Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
5aa108295a2a66aea48b79c79602f310c37d7fa5
[simgrid.git] / src / kernel / lmm / System.cpp
1 /* Copyright (c) 2004-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/kernel/lmm/fair_bottleneck.hpp"
7 #include "src/kernel/lmm/maxmin.hpp"
8 #if SIMGRID_HAVE_EIGEN3
9 #include "src/kernel/lmm/bmf.hpp"
10 #endif
11 #include <boost/core/demangle.hpp>
12 #include <typeinfo>
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_lmm, kernel, "Kernel Linear Max-Min solver");
15
16 double sg_maxmin_precision = 1E-5; /* Change this with --cfg=maxmin/precision:VALUE */
17 double sg_surf_precision   = 1E-9; /* Change this with --cfg=surf/precision:VALUE */
18 int sg_concurrency_limit   = -1;      /* Change this with --cfg=maxmin/concurrency-limit:VALUE */
19
20 namespace simgrid::kernel::lmm {
21
22 int Variable::next_rank_   = 1;
23 int Constraint::next_rank_ = 1;
24
25 Element::Element(Constraint* constraint, Variable* variable, double cweight)
26     : constraint(constraint), variable(variable), consumption_weight(cweight), max_consumption_weight(cweight)
27 {
28 }
29
30 int Element::get_concurrency() const
31 {
32   // just to try having the computation of the concurrency
33   if (constraint->get_sharing_policy() == Constraint::SharingPolicy::WIFI) {
34     return 1;
35   }
36
37   // Ignore element with weight less than one (e.g. cross-traffic)
38   return (consumption_weight >= 1) ? 1 : 0;
39   // There are other alternatives, but they will change the behavior of the model..
40   // So do not use it unless you want to make a new model.
41   // If you do, remember to change the variables concurrency share to reflect it.
42   // Potential examples are:
43   // return (elem->weight>0)?1:0;//Include element as soon  as weight is non-zero
44   // return (int)ceil(elem->weight);//Include element as the rounded-up integer value of the element weight
45 }
46
47 void Element::decrease_concurrency()
48 {
49   xbt_assert(constraint->concurrency_current_ >= get_concurrency());
50   constraint->concurrency_current_ -= get_concurrency();
51 }
52
53 void Element::increase_concurrency(bool check_limit)
54 {
55   constraint->concurrency_current_ += get_concurrency();
56
57   if (constraint->concurrency_current_ > constraint->concurrency_maximum_)
58     constraint->concurrency_maximum_ = constraint->concurrency_current_;
59
60   xbt_assert(not check_limit || constraint->get_concurrency_limit() < 0 ||
61                  constraint->concurrency_current_ <= constraint->get_concurrency_limit(),
62              "Concurrency limit overflow!");
63 }
64
65 System* System::build(std::string_view solver_name, bool selective_update)
66 {
67   System* system = nullptr;
68   if (solver_name == "bmf") {
69 #if SIMGRID_HAVE_EIGEN3
70     system = new BmfSystem(selective_update);
71 #endif
72   } else if (solver_name == "fairbottleneck") {
73     system = new FairBottleneck(selective_update);
74   } else {
75     system = new MaxMin(selective_update);
76   }
77   return system;
78 }
79
80 void System::validate_solver(const std::string& solver_name)
81 {
82   static const std::vector<std::string> opts{"bmf", "maxmin", "fairbottleneck"};
83   if (solver_name == "bmf") {
84 #if !SIMGRID_HAVE_EIGEN3
85     xbt_die("Cannot use the BMF solver without installing Eigen3.");
86 #endif
87   }
88   if (std::find(opts.begin(), opts.end(), solver_name) == std::end(opts)) {
89     xbt_die("Invalid system solver, it should be one of: \"maxmin\", \"fairbottleneck\" or \"bmf\"");
90   }
91 }
92
93 void System::check_concurrency() const
94 {
95   // These checks are very expensive, so do them only if we want to debug SURF LMM
96   if (not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug))
97     return;
98
99   for (Constraint const& cnst : constraint_set) {
100     int concurrency       = 0;
101     for (Element const& elem : cnst.enabled_element_set_) {
102       xbt_assert(elem.variable->sharing_penalty_ > 0);
103       concurrency += elem.get_concurrency();
104     }
105
106     for (Element const& elem : cnst.disabled_element_set_) {
107       // We should have staged variables only if concurrency is reached in some constraint
108       xbt_assert(cnst.get_concurrency_limit() < 0 || elem.variable->staged_sharing_penalty_ == 0 ||
109                      elem.variable->get_min_concurrency_slack() == 0,
110                  "should not have staged variable!");
111     }
112
113     xbt_assert(cnst.get_concurrency_limit() < 0 || cnst.get_concurrency_limit() >= concurrency,
114                "concurrency check failed!");
115     xbt_assert(cnst.concurrency_current_ == concurrency, "concurrency_current is out-of-date!");
116   }
117
118   // Check that for each variable, all corresponding elements are in the same state (i.e. same element sets)
119   for (Variable const& var : variable_set) {
120     if (var.cnsts_.empty())
121       continue;
122
123     const Element& elem    = var.cnsts_[0];
124     bool belong_to_enabled  = elem.enabled_element_set_hook.is_linked();
125     bool belong_to_disabled = elem.disabled_element_set_hook.is_linked();
126     bool belong_to_active   = elem.active_element_set_hook.is_linked();
127
128     for (Element const& elem2 : var.cnsts_) {
129       xbt_assert(belong_to_enabled == elem2.enabled_element_set_hook.is_linked(),
130                  "Variable inconsistency (1): enabled_element_set");
131       xbt_assert(belong_to_disabled == elem2.disabled_element_set_hook.is_linked(),
132                  "Variable inconsistency (2): disabled_element_set");
133       xbt_assert(belong_to_active == elem2.active_element_set_hook.is_linked(),
134                  "Variable inconsistency (3): active_element_set");
135     }
136   }
137 }
138
139 void System::var_free(Variable* var)
140 {
141   XBT_IN("(sys=%p, var=%p)", this, var);
142   modified_ = true;
143
144   // TODOLATER Can do better than that by leaving only the variable in only one enabled_element_set, call
145   // update_modified_set, and then remove it..
146   update_modified_cnst_set_from_variable(var);
147
148   for (Element& elem : var->cnsts_) {
149     if (var->sharing_penalty_ > 0)
150       elem.decrease_concurrency();
151     if (elem.enabled_element_set_hook.is_linked())
152       simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
153     if (elem.disabled_element_set_hook.is_linked())
154       simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
155     if (elem.active_element_set_hook.is_linked())
156       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
157     if (elem.constraint->enabled_element_set_.empty() && elem.constraint->disabled_element_set_.empty())
158       make_constraint_inactive(elem.constraint);
159     else
160       on_disabled_var(elem.constraint);
161   }
162
163   var->cnsts_.clear();
164
165   check_concurrency();
166
167   xbt_mallocator_release(variable_mallocator_, var);
168   XBT_OUT();
169 }
170
171 System::System(bool selective_update) : selective_update_active(selective_update)
172 {
173   XBT_DEBUG("Setting selective_update_active flag to %d", selective_update_active);
174
175   if (selective_update)
176     modified_set_ = std::make_unique<kernel::resource::Action::ModifiedSet>();
177 }
178
179 System::~System()
180 {
181   while (Variable* var = extract_variable()) {
182     const char* name = var->id_ ? typeid(*var->id_).name() : "(unidentified)";
183     boost::core::scoped_demangled_name demangled(name);
184     XBT_WARN("Probable bug: a %s variable (#%d) not removed before the LMM system destruction.",
185              demangled.get() ? demangled.get() : name, var->rank_);
186     var_free(var);
187   }
188   while (Constraint* cnst = extract_constraint())
189     cnst_free(cnst);
190
191   xbt_mallocator_free(variable_mallocator_);
192 }
193
194 void System::cnst_free(Constraint* cnst)
195 {
196   make_constraint_inactive(cnst);
197   delete cnst;
198 }
199
200 Constraint::Constraint(resource::Resource* id_value, double bound_value) : bound_(bound_value), id_(id_value)
201 {
202   rank_ = next_rank_++;
203 }
204
205 Constraint* System::constraint_new(resource::Resource* id, double bound_value)
206 {
207   auto* cnst = new Constraint(id, bound_value);
208   insert_constraint(cnst);
209   return cnst;
210 }
211
212 void* System::variable_mallocator_new_f()
213 {
214   return new Variable;
215 }
216
217 void System::variable_mallocator_free_f(void* var)
218 {
219   delete static_cast<Variable*>(var);
220 }
221
222 Variable* System::variable_new(resource::Action* id, double sharing_penalty, double bound, size_t number_of_constraints)
223 {
224   XBT_IN("(sys=%p, id=%p, penalty=%f, bound=%f, num_cons =%zu)", this, id, sharing_penalty, bound,
225          number_of_constraints);
226
227   auto* var = static_cast<Variable*>(xbt_mallocator_get(variable_mallocator_));
228   var->initialize(id, sharing_penalty, bound, number_of_constraints, visited_counter_ - 1);
229   if (sharing_penalty > 0)
230     variable_set.push_front(*var);
231   else
232     variable_set.push_back(*var);
233
234   XBT_OUT(" returns %p", var);
235   return var;
236 }
237
238 void System::variable_free(Variable* var)
239 {
240   remove_variable(var);
241   var_free(var);
242 }
243
244 void System::variable_free_all()
245 {
246   while (Variable* var = extract_variable())
247     variable_free(var);
248 }
249
250 Element& System::expand_create_elem(Constraint* cnst, Variable* var, double consumption_weight)
251 {
252   xbt_assert(var->cnsts_.size() < var->cnsts_.capacity(), "Too much constraints");
253
254   var->cnsts_.emplace_back(cnst, var, consumption_weight);
255   Element& elem = var->cnsts_.back();
256
257   if (var->sharing_penalty_ != 0.0) {
258     elem.constraint->enabled_element_set_.push_front(elem);
259   } else
260     elem.constraint->disabled_element_set_.push_back(elem);
261
262   if (elem.consumption_weight > 0 || var->sharing_penalty_ > 0) {
263     make_constraint_active(cnst);
264   }
265   return elem;
266 }
267
268 Element& System::expand_add_to_elem(Element& elem, const Constraint* cnst, double consumption_weight) const
269 {
270   elem.max_consumption_weight = std::max(elem.max_consumption_weight, consumption_weight);
271   if (cnst->sharing_policy_ != Constraint::SharingPolicy::FATPIPE)
272     elem.consumption_weight += consumption_weight;
273   else
274     elem.consumption_weight = std::max(elem.consumption_weight, consumption_weight);
275   return elem;
276 }
277
278 void System::expand(Constraint* cnst, Variable* var, double consumption_weight, bool force_creation)
279 {
280   modified_ = true;
281
282   auto elem_it =
283       std::find_if(begin(var->cnsts_), end(var->cnsts_), [&cnst](Element const& x) { return x.constraint == cnst; });
284
285   bool reuse_elem = elem_it != end(var->cnsts_) && not force_creation;
286   if (reuse_elem && var->sharing_penalty_ != 0.0) {
287     /* before changing it, decreases concurrency on constraint, it'll be added back later */
288     elem_it->decrease_concurrency();
289   }
290   Element& elem = reuse_elem ? expand_add_to_elem(*elem_it, cnst, consumption_weight)
291                              : expand_create_elem(cnst, var, consumption_weight);
292
293   // Check if we need to disable the variable
294   if (var->sharing_penalty_ != 0) {
295     /* increase concurrency in constraint that this element uses.
296      * as we don't check if constraint has reached its limit before increasing,
297      * we can't check the correct state at increase_concurrency, anyway
298      * it'll check if the slack is smaller than 0 just below */
299     elem.increase_concurrency(false);
300     if (cnst->get_concurrency_slack() < 0) {
301       double penalty = var->sharing_penalty_;
302       disable_var(var);
303       for (Element const& elem2 : var->cnsts_)
304         on_disabled_var(elem2.constraint);
305       var->staged_sharing_penalty_ = penalty;
306       xbt_assert(not var->sharing_penalty_);
307     }
308   }
309
310   /* update modified constraint set accordingly */
311   if (elem.consumption_weight > 0 || var->sharing_penalty_ > 0)
312     update_modified_cnst_set(cnst);
313
314   check_concurrency();
315 }
316
317 Variable* Constraint::get_variable(const Element** elem) const
318 {
319   if (*elem == nullptr) {
320     // That is the first call, pick the first element among enabled_element_set (or disabled_element_set if
321     // enabled_element_set is empty)
322     if (not enabled_element_set_.empty())
323       *elem = &enabled_element_set_.front();
324     else if (not disabled_element_set_.empty())
325       *elem = &disabled_element_set_.front();
326   } else {
327     // elem is not null, so we carry on
328     if ((*elem)->enabled_element_set_hook.is_linked()) {
329       // Look at enabled_element_set, and jump to disabled_element_set when finished
330       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
331       if (iter != std::end(enabled_element_set_))
332         *elem = &*iter;
333       else if (not disabled_element_set_.empty())
334         *elem = &disabled_element_set_.front();
335       else
336         *elem = nullptr;
337     } else {
338       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
339       *elem     = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
340     }
341   }
342   if (*elem)
343     return (*elem)->variable;
344   else
345     return nullptr;
346 }
347
348 // if we modify the list between calls, normal version may loop forever
349 // this safe version ensures that we browse the list elements only once
350 Variable* Constraint::get_variable_safe(const Element** elem, const Element** nextelem, size_t* numelem) const
351 {
352   if (*elem == nullptr) {
353     *numelem = enabled_element_set_.size() + disabled_element_set_.size() - 1;
354     if (not enabled_element_set_.empty())
355       *elem = &enabled_element_set_.front();
356     else if (not disabled_element_set_.empty())
357       *elem = &disabled_element_set_.front();
358   } else {
359     *elem = *nextelem;
360     if (*numelem > 0) {
361       (*numelem)--;
362     } else
363       return nullptr;
364   }
365   if (*elem) {
366     // elem is not null, so we carry on
367     if ((*elem)->enabled_element_set_hook.is_linked()) {
368       // Look at enabled_element_set, and jump to disabled_element_set when finished
369       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
370       if (iter != std::end(enabled_element_set_))
371         *nextelem = &*iter;
372       else if (not disabled_element_set_.empty())
373         *nextelem = &disabled_element_set_.front();
374       else
375         *nextelem = nullptr;
376     } else {
377       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
378       *nextelem = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
379     }
380     return (*elem)->variable;
381   } else
382     return nullptr;
383 }
384
385 template <class ElemList>
386 static void format_element_list(const ElemList& elem_list, Constraint::SharingPolicy sharing_policy, double& sum,
387                                 std::string& buf)
388 {
389   for (Element const& elem : elem_list) {
390     buf += std::to_string(elem.consumption_weight) + ".'" + std::to_string(elem.variable->rank_) + "'(" +
391            std::to_string(elem.variable->value_) + ")" +
392            (sharing_policy != Constraint::SharingPolicy::FATPIPE ? " + " : " , ");
393     if (sharing_policy != Constraint::SharingPolicy::FATPIPE)
394       sum += elem.consumption_weight * elem.variable->value_;
395     else
396       sum = std::max(sum, elem.consumption_weight * elem.variable->value_);
397   }
398 }
399
400 void System::print() const
401 {
402   std::string buf = "MAX-MIN ( ";
403
404   /* Printing Objective */
405   for (Variable const& var : variable_set)
406     buf += "'" + std::to_string(var.rank_) + "'(" + std::to_string(var.sharing_penalty_) + ") ";
407   buf += ")";
408   XBT_DEBUG("%20s", buf.c_str());
409   buf.clear();
410
411   XBT_DEBUG("Constraints");
412   /* Printing Constraints */
413   for (Constraint const& cnst : active_constraint_set) {
414     double sum            = 0.0;
415     // Show  the enabled variables
416     buf += "\t";
417     buf += cnst.sharing_policy_ != Constraint::SharingPolicy::FATPIPE ? "(" : "max(";
418     format_element_list(cnst.enabled_element_set_, cnst.sharing_policy_, sum, buf);
419     // TODO: Adding disabled elements only for test compatibility, but do we really want them to be printed?
420     format_element_list(cnst.disabled_element_set_, cnst.sharing_policy_, sum, buf);
421
422     buf += "0) <= " + std::to_string(cnst.bound_) + " ('" + std::to_string(cnst.rank_) + "')";
423
424     if (cnst.sharing_policy_ == Constraint::SharingPolicy::FATPIPE) {
425       buf += " [MAX-Constraint]";
426     }
427     XBT_DEBUG("%s", buf.c_str());
428     buf.clear();
429     xbt_assert(not double_positive(sum - cnst.bound_, cnst.bound_ * sg_maxmin_precision),
430                "Incorrect value (%f is not smaller than %f): %g", sum, cnst.bound_, sum - cnst.bound_);
431   }
432
433   XBT_DEBUG("Variables");
434   /* Printing Result */
435   for (Variable const& var : variable_set) {
436     if (var.bound_ > 0) {
437       XBT_DEBUG("'%d'(%f) : %f (<=%f)", var.rank_, var.sharing_penalty_, var.value_, var.bound_);
438       xbt_assert(not double_positive(var.value_ - var.bound_, var.bound_ * sg_maxmin_precision),
439                  "Incorrect value (%f is not smaller than %f", var.value_, var.bound_);
440     } else {
441       XBT_DEBUG("'%d'(%f) : %f", var.rank_, var.sharing_penalty_, var.value_);
442     }
443   }
444 }
445
446 resource::Action::ModifiedSet* System::get_modified_action_set() const
447 {
448   return modified_set_.get();
449 }
450
451 void System::solve()
452 {
453   if (not modified_)
454     return;
455
456   do_solve();
457
458   modified_ = false;
459   if (selective_update_active) {
460     /* update list of modified variables */
461     for (const Constraint& cnst : modified_constraint_set) {
462       for (const Element& elem : cnst.enabled_element_set_) {
463         if (elem.consumption_weight > 0) {
464           resource::Action* action = elem.variable->id_;
465           if (not action->is_within_modified_set())
466             modified_set_->push_back(*action);
467         }
468       }
469     }
470     /* clear list of modified constraint */
471     remove_all_modified_cnst_set();
472   }
473
474   if (XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug)) {
475     print();
476   }
477
478   check_concurrency();
479 }
480
481 /** @brief Attribute the value bound to var->bound.
482  *
483  *  @param var the Variable*
484  *  @param bound the new bound to associate with var
485  *
486  *  Makes var->bound equal to bound. Whenever this function is called a change is  signed in the system. To
487  *  avoid false system changing detection it is a good idea to test (bound != 0) before calling it.
488  */
489 void System::update_variable_bound(Variable* var, double bound)
490 {
491   modified_  = true;
492   var->bound_ = bound;
493
494   if (not var->cnsts_.empty()) {
495     for (Element const& elem : var->cnsts_) {
496       update_modified_cnst_set(elem.constraint);
497     }
498   }
499 }
500
501 void Variable::initialize(resource::Action* id_value, double sharing_penalty, double bound_value,
502                           size_t number_of_constraints, unsigned visited_value)
503 {
504   id_     = id_value;
505   rank_   = next_rank_++;
506   cnsts_.reserve(number_of_constraints);
507   sharing_penalty_   = sharing_penalty;
508   staged_sharing_penalty_ = 0.0;
509   bound_             = bound_value;
510   value_             = 0.0;
511   visited_           = visited_value;
512   mu_                = 0.0;
513
514   xbt_assert(not variable_set_hook_.is_linked());
515   xbt_assert(not saturated_variable_set_hook_.is_linked());
516 }
517
518 int Variable::get_min_concurrency_slack() const
519 {
520   int minslack = std::numeric_limits<int>::max();
521   for (Element const& elem : cnsts_) {
522     int slack = elem.constraint->get_concurrency_slack();
523     if (slack < minslack) {
524       // This is only an optimization, to avoid looking at more constraints when slack is already zero
525       if (slack == 0)
526         return 0;
527       minslack = slack;
528     }
529   }
530   return minslack;
531 }
532
533 // Small remark: In this implementation of System::enable_var() and System::disable_var(), we will meet multiple times
534 // with var when running System::update_modified_cnst_set().
535 // A priori not a big performance issue, but we might do better by calling System::update_modified_cnst_set() within the
536 // for loops (after doing the first for enabling==1, and before doing the last for disabling==1)
537 void System::enable_var(Variable* var)
538 {
539   xbt_assert(not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug) || var->can_enable());
540
541   var->sharing_penalty_        = var->staged_sharing_penalty_;
542   var->staged_sharing_penalty_ = 0;
543
544   // Enabling the variable, move var to list head. Subtlety is: here, we need to call update_modified_cnst_set AFTER
545   // moving at least one element of var.
546
547   simgrid::xbt::intrusive_erase(variable_set, *var);
548   variable_set.push_front(*var);
549   for (Element& elem : var->cnsts_) {
550     simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
551     elem.constraint->enabled_element_set_.push_front(elem);
552     elem.increase_concurrency();
553   }
554   update_modified_cnst_set_from_variable(var);
555
556   // When used within on_disabled_var, we would get an assertion fail, because transiently there can be variables
557   // that are staged and could be activated.
558   // Anyway, caller functions all call check_concurrency() in the end.
559 }
560
561 void System::disable_var(Variable* var)
562 {
563   xbt_assert(not var->staged_sharing_penalty_, "Staged penalty should have been cleared");
564   // Disabling the variable, move to var to list tail. Subtlety is: here, we need to call update_modified_cnst_set
565   // BEFORE moving the last element of var.
566   simgrid::xbt::intrusive_erase(variable_set, *var);
567   variable_set.push_back(*var);
568   update_modified_cnst_set_from_variable(var);
569   for (Element& elem : var->cnsts_) {
570     simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
571     elem.constraint->disabled_element_set_.push_back(elem);
572     if (elem.active_element_set_hook.is_linked())
573       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
574     elem.decrease_concurrency();
575   }
576
577   var->sharing_penalty_ = 0.0;
578   var->staged_sharing_penalty_ = 0.0;
579   var->value_          = 0.0;
580   check_concurrency();
581 }
582
583 /* /brief Find variables that can be enabled and enable them.
584  *
585  * Assuming that the variable has already been removed from non-zero penalties
586  * Can we find a staged variable to add?
587  * If yes, check that none of the constraints that this variable is involved in is at the limit of its concurrency
588  * And then add it to enabled variables
589  */
590 void System::on_disabled_var(Constraint* cnstr)
591 {
592   if (cnstr->get_concurrency_limit() < 0)
593     return;
594
595   size_t numelem = cnstr->disabled_element_set_.size();
596   if (numelem == 0)
597     return;
598
599   Element* elem = &cnstr->disabled_element_set_.front();
600
601   // Cannot use foreach loop, because System::enable_var() will modify disabled_element_set.. within the loop
602   while (numelem-- && elem) {
603     Element* nextelem;
604     if (elem->disabled_element_set_hook.is_linked()) {
605       auto iter = std::next(cnstr->disabled_element_set_.iterator_to(*elem));
606       nextelem  = iter != std::end(cnstr->disabled_element_set_) ? &*iter : nullptr;
607     } else {
608       nextelem = nullptr;
609     }
610
611     if (elem->variable->staged_sharing_penalty_ > 0 && elem->variable->can_enable()) {
612       // Found a staged variable
613       // TODOLATER: Add random timing function to model reservation protocol fuzziness? Then how to make sure that
614       // staged variables will eventually be called?
615       enable_var(elem->variable);
616     }
617
618     xbt_assert(cnstr->concurrency_current_ <= cnstr->get_concurrency_limit(), "Concurrency overflow!");
619     if (cnstr->concurrency_current_ == cnstr->get_concurrency_limit())
620       break;
621
622     elem = nextelem;
623   }
624
625   // We could get an assertion fail, because transiently there can be variables that are staged and could be activated.
626   // And we need to go through all constraints of the disabled var before getting back a coherent state.
627   // Anyway, caller functions all call check_concurrency() in the end.
628 }
629
630 /** @brief update the penalty of a variable (disable it by passing 0 as a penalty) */
631 void System::update_variable_penalty(Variable* var, double penalty)
632 {
633   xbt_assert(penalty >= 0, "Variable penalty should not be negative!");
634   if (penalty == var->sharing_penalty_)
635     return;
636
637   bool enabling_var  = (penalty > 0 && var->sharing_penalty_ <= 0);
638   bool disabling_var = (penalty <= 0 && var->sharing_penalty_ > 0);
639
640   XBT_IN("(sys=%p, var=%p, var->sharing_penalty = %f, penalty=%f)", this, var, var->sharing_penalty_, penalty);
641
642   modified_ = true;
643
644   // Are we enabling this variable?
645   if (enabling_var) {
646     var->staged_sharing_penalty_ = penalty;
647     int minslack       = var->get_min_concurrency_slack();
648     if (minslack == 0) {
649       XBT_DEBUG("Staging var (instead of enabling) because min concurrency slack is 0");
650       return;
651     }
652     XBT_DEBUG("Enabling var with min concurrency slack %i", minslack);
653     enable_var(var);
654   } else if (disabling_var) {
655     disable_var(var);
656   } else {
657     var->sharing_penalty_ = penalty;
658     update_modified_cnst_set_from_variable(var);
659   }
660
661   check_concurrency();
662
663   XBT_OUT();
664 }
665
666 void System::update_constraint_bound(Constraint* cnst, double bound)
667 {
668   modified_ = true;
669   update_modified_cnst_set(cnst);
670   cnst->bound_ = bound;
671 }
672
673 /** @brief Update the constraint set propagating recursively to other constraints so the system should not be entirely
674  *  computed.
675  *
676  *  @param cnst the Constraint* affected by the change
677  *
678  *  A recursive algorithm to optimize the system recalculation selecting only constraints that have changed. Each
679  *  constraint change is propagated to the list of constraints for each variable.
680  */
681 void System::update_modified_cnst_set_rec(const Constraint* cnst)
682 {
683   for (Element const& elem : cnst->enabled_element_set_) {
684     Variable* var = elem.variable;
685     for (Element const& elem2 : var->cnsts_) {
686       if (var->visited_ == visited_counter_)
687         break;
688       if (elem2.constraint != cnst && not elem2.constraint->modified_constraint_set_hook_.is_linked()) {
689         modified_constraint_set.push_back(*elem2.constraint);
690         update_modified_cnst_set_rec(elem2.constraint);
691       }
692     }
693     // var will be ignored in later visits as long as sys->visited_counter does not move
694     var->visited_ = visited_counter_;
695   }
696 }
697
698 void System::update_modified_cnst_set_from_variable(const Variable* var)
699 {
700   /* nothing to update in these cases:
701    * - selective update not active, all variables are active
702    * - variable doesn't use any constraint
703    * - variable is disabled (sharing penalty <= 0): we iterate only through the enabled_variables in
704    * update_modified_cnst_set_rec */
705   if (not selective_update_active || var->cnsts_.empty() || var->sharing_penalty_ <= 0)
706     return;
707
708   /* Normally, if the conditions above are true, specially variable is enabled, we can call
709    * modified_set over the first contraint only, since the recursion in update_modified_cnst_set_rec
710    * will iterate over the other constraints of this variable */
711   update_modified_cnst_set(var->cnsts_[0].constraint);
712 }
713
714 void System::update_modified_cnst_set(Constraint* cnst)
715 {
716   /* nothing to do if selective update isn't active */
717   if (selective_update_active && not cnst->modified_constraint_set_hook_.is_linked()) {
718     modified_constraint_set.push_back(*cnst);
719     update_modified_cnst_set_rec(cnst);
720   }
721 }
722
723 void System::remove_all_modified_cnst_set()
724 {
725   // We cleverly un-flag all variables just by incrementing visited_counter
726   // In effect, the var->visited value will no more be equal to visited counter
727   // To be clean, when visited counter has wrapped around, we force these var->visited values so that variables that
728   // were in the modified a long long time ago are not wrongly skipped here, which would lead to very nasty bugs
729   // (i.e. not readily reproducible, and requiring a lot of run time before happening).
730   if (++visited_counter_ == 1) {
731     /* the counter wrapped around, reset each variable->visited */
732     for (Variable& var : variable_set)
733       var.visited_ = 0;
734   }
735   modified_constraint_set.clear();
736 }
737
738 /**
739  * Returns resource load (in flop per second, or byte per second, or similar)
740  *
741  * If the resource is shared (the default case), the load is sum of resource usage made by
742  * every variables located on this resource.
743  *
744  * If the resource is not shared (ie in FATPIPE mode), then the load is the max (not the sum)
745  * of all resource usages located on this resource.
746  */
747 double Constraint::get_usage() const
748 {
749   double result              = 0.0;
750   if (sharing_policy_ != SharingPolicy::FATPIPE) {
751     for (Element const& elem : enabled_element_set_)
752       if (elem.consumption_weight > 0)
753         result += elem.consumption_weight * elem.variable->value_;
754   } else {
755     for (Element const& elem : enabled_element_set_)
756       if (elem.consumption_weight > 0)
757         result = std::max(result, elem.consumption_weight * elem.variable->value_);
758   }
759   return result;
760 }
761
762 void Constraint::set_sharing_policy(SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
763 {
764   xbt_assert(policy == SharingPolicy::NONLINEAR || policy == SharingPolicy::WIFI || not cb,
765              "Invalid sharing policy for constraint. Callback should be used with NONLINEAR sharing policy");
766   sharing_policy_    = policy;
767   dyn_constraint_cb_ = cb;
768 }
769
770 } // namespace simgrid::kernel::lmm