Logo AND Algorithmique Numérique Distribuée

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