Logo AND Algorithmique Numérique Distribuée

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