Logo AND Algorithmique Numérique Distribuée

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