Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a86ef6b347dab959362f6c5dbbd56fdbe68ec95d
[simgrid.git] / src / kernel / lmm / maxmin.cpp
1 /* Copyright (c) 2004-2021. 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/maxmin.hpp"
7 #include "xbt/backtrace.hpp"
8
9 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_maxmin, surf, "Logging specific to SURF (maxmin)");
10
11 double sg_maxmin_precision = 1E-5; /* Change this with --cfg=maxmin/precision:VALUE */
12 double sg_surf_precision   = 1E-9; /* Change this with --cfg=surf/precision:VALUE */
13 int sg_concurrency_limit   = -1;      /* Change this with --cfg=maxmin/concurrency-limit:VALUE */
14
15 namespace simgrid {
16 namespace kernel {
17 namespace lmm {
18
19 using dyn_light_t = std::vector<int>;
20
21 int Variable::next_rank_   = 1;
22 int Constraint::next_rank_ = 1;
23
24 int Element::get_concurrency() const
25 {
26   // Ignore element with weight less than one (e.g. cross-traffic)
27   return (consumption_weight >= 1) ? 1 : 0;
28   // There are other alternatives, but they will change the behavior of the model..
29   // So do not use it unless you want to make a new model.
30   // If you do, remember to change the variables concurrency share to reflect it.
31   // Potential examples are:
32   // return (elem->weight>0)?1:0;//Include element as soon  as weight is non-zero
33   // return (int)ceil(elem->weight);//Include element as the rounded-up integer value of the element weight
34 }
35
36 void Element::decrease_concurrency()
37 {
38   xbt_assert(constraint->concurrency_current_ >= get_concurrency());
39   constraint->concurrency_current_ -= get_concurrency();
40 }
41
42 void Element::increase_concurrency()
43 {
44   constraint->concurrency_current_ += get_concurrency();
45
46   if (constraint->concurrency_current_ > constraint->concurrency_maximum_)
47     constraint->concurrency_maximum_ = constraint->concurrency_current_;
48
49   xbt_assert(constraint->get_concurrency_limit() < 0 ||
50                  constraint->concurrency_current_ <= constraint->get_concurrency_limit(),
51              "Concurrency limit overflow!");
52 }
53
54 void System::check_concurrency() const
55 {
56   // These checks are very expensive, so do them only if we want to debug SURF LMM
57   if (not XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug))
58     return;
59
60   for (Constraint const& cnst : constraint_set) {
61     int concurrency       = 0;
62     for (Element const& elem : cnst.enabled_element_set_) {
63       xbt_assert(elem.variable->sharing_penalty_ > 0);
64       concurrency += elem.get_concurrency();
65     }
66
67     for (Element const& elem : cnst.disabled_element_set_) {
68       // We should have staged variables only if concurrency is reached in some constraint
69       xbt_assert(cnst.get_concurrency_limit() < 0 || elem.variable->staged_penalty_ == 0 ||
70                      elem.variable->get_min_concurrency_slack() < elem.variable->concurrency_share_,
71                  "should not have staged variable!");
72     }
73
74     xbt_assert(cnst.get_concurrency_limit() < 0 || cnst.get_concurrency_limit() >= concurrency,
75                "concurrency check failed!");
76     xbt_assert(cnst.concurrency_current_ == concurrency, "concurrency_current is out-of-date!");
77   }
78
79   // Check that for each variable, all corresponding elements are in the same state (i.e. same element sets)
80   for (Variable const& var : variable_set) {
81     if (var.cnsts_.empty())
82       continue;
83
84     const Element& elem    = var.cnsts_[0];
85     bool belong_to_enabled  = elem.enabled_element_set_hook.is_linked();
86     bool belong_to_disabled = elem.disabled_element_set_hook.is_linked();
87     bool belong_to_active   = elem.active_element_set_hook.is_linked();
88
89     for (Element const& elem2 : var.cnsts_) {
90       xbt_assert(belong_to_enabled == elem2.enabled_element_set_hook.is_linked(),
91                  "Variable inconsistency (1): enabled_element_set");
92       xbt_assert(belong_to_disabled == elem2.disabled_element_set_hook.is_linked(),
93                  "Variable inconsistency (2): disabled_element_set");
94       xbt_assert(belong_to_active == elem2.active_element_set_hook.is_linked(),
95                  "Variable inconsistency (3): active_element_set");
96     }
97   }
98 }
99
100 void System::var_free(Variable* var)
101 {
102   XBT_IN("(sys=%p, var=%p)", this, var);
103   modified_ = true;
104
105   // TODOLATER Can do better than that by leaving only the variable in only one enabled_element_set, call
106   // update_modified_set, and then remove it..
107   if (not var->cnsts_.empty())
108     update_modified_set(var->cnsts_[0].constraint);
109
110   for (Element& elem : var->cnsts_) {
111     if (var->sharing_penalty_ > 0)
112       elem.decrease_concurrency();
113     if (elem.enabled_element_set_hook.is_linked())
114       simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
115     if (elem.disabled_element_set_hook.is_linked())
116       simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
117     if (elem.active_element_set_hook.is_linked())
118       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
119     int nelements = elem.constraint->enabled_element_set_.size() + elem.constraint->disabled_element_set_.size();
120     if (nelements == 0)
121       make_constraint_inactive(elem.constraint);
122     else
123       on_disabled_var(elem.constraint);
124   }
125
126   var->cnsts_.clear();
127
128   check_concurrency();
129
130   xbt_mallocator_release(variable_mallocator_, var);
131   XBT_OUT();
132 }
133
134 System::System(bool selective_update) : selective_update_active(selective_update)
135 {
136   XBT_DEBUG("Setting selective_update_active flag to %d", selective_update_active);
137
138   if (selective_update)
139     modified_set_ = std::make_unique<kernel::resource::Action::ModifiedSet>();
140 }
141
142 System::~System()
143 {
144   Variable* var;
145   Constraint* cnst;
146
147   while ((var = extract_variable())) {
148     auto demangled = simgrid::xbt::demangle(var->id_ ? typeid(*var->id_).name() : "(unidentified)");
149     XBT_WARN("Probable bug: a %s variable (#%d) not removed before the LMM system destruction.", demangled.get(),
150              var->rank_);
151     var_free(var);
152   }
153   while ((cnst = extract_constraint()))
154     cnst_free(cnst);
155
156   xbt_mallocator_free(variable_mallocator_);
157 }
158
159 void System::cnst_free(Constraint* cnst)
160 {
161   make_constraint_inactive(cnst);
162   delete cnst;
163 }
164
165 Constraint::Constraint(resource::Resource* id_value, double bound_value) : bound_(bound_value), id_(id_value)
166 {
167   rank_ = next_rank_++;
168 }
169
170 Constraint* System::constraint_new(resource::Resource* id, double bound_value)
171 {
172   auto* cnst = new Constraint(id, bound_value);
173   insert_constraint(cnst);
174   return cnst;
175 }
176
177 void* System::variable_mallocator_new_f()
178 {
179   return new Variable;
180 }
181
182 void System::variable_mallocator_free_f(void* var)
183 {
184   delete static_cast<Variable*>(var);
185 }
186
187 Variable* System::variable_new(resource::Action* id, double sharing_penalty, double bound, size_t number_of_constraints)
188 {
189   XBT_IN("(sys=%p, id=%p, penalty=%f, bound=%f, num_cons =%zu)", this, id, sharing_penalty, bound,
190          number_of_constraints);
191
192   auto* var = static_cast<Variable*>(xbt_mallocator_get(variable_mallocator_));
193   var->initialize(id, sharing_penalty, bound, number_of_constraints, visited_counter_ - 1);
194   if (sharing_penalty > 0)
195     variable_set.push_front(*var);
196   else
197     variable_set.push_back(*var);
198
199   XBT_OUT(" returns %p", var);
200   return var;
201 }
202
203 void System::variable_free(Variable* var)
204 {
205   remove_variable(var);
206   var_free(var);
207 }
208
209 void System::variable_free_all()
210 {
211   Variable* var;
212   while ((var = extract_variable()))
213     variable_free(var);
214 }
215
216 void System::expand(Constraint* cnst, Variable* var, double consumption_weight)
217 {
218   modified_ = true;
219
220   // Check if this variable already has an active element in this constraint
221   // If it does, subtract it from the required slack
222   int current_share = 0;
223   if (var->concurrency_share_ > 1) {
224     for (const Element& elem : var->cnsts_) {
225       if (elem.constraint == cnst && elem.enabled_element_set_hook.is_linked())
226         current_share += elem.get_concurrency();
227     }
228   }
229
230   // Check if we need to disable the variable
231   if (var->sharing_penalty_ > 0 && var->concurrency_share_ - current_share > cnst->get_concurrency_slack()) {
232     double penalty = var->sharing_penalty_;
233     disable_var(var);
234     for (Element const& elem : var->cnsts_)
235       on_disabled_var(elem.constraint);
236     consumption_weight = 0;
237     var->staged_penalty_ = penalty;
238     xbt_assert(not var->sharing_penalty_);
239   }
240
241   xbt_assert(var->cnsts_.size() < var->cnsts_.capacity(), "Too much constraints");
242
243   var->cnsts_.resize(var->cnsts_.size() + 1);
244   Element& elem = var->cnsts_.back();
245
246   elem.consumption_weight = consumption_weight;
247   elem.constraint         = cnst;
248   elem.variable           = var;
249
250   if (var->sharing_penalty_ != 0.0) {
251     elem.constraint->enabled_element_set_.push_front(elem);
252     elem.increase_concurrency();
253   } else
254     elem.constraint->disabled_element_set_.push_back(elem);
255
256   if (not selective_update_active) {
257     make_constraint_active(cnst);
258   } else if (elem.consumption_weight > 0 || var->sharing_penalty_ > 0) {
259     make_constraint_active(cnst);
260     update_modified_set(cnst);
261     // TODOLATER: Why do we need this second call?
262     if (var->cnsts_.size() > 1)
263       update_modified_set(var->cnsts_[0].constraint);
264   }
265
266   check_concurrency();
267 }
268
269 void System::expand_add(Constraint* cnst, Variable* var, double value)
270 {
271   modified_ = true;
272
273   check_concurrency();
274
275   // BEWARE: In case you have multiple elements in one constraint, this will always add value to the first element.
276   auto elem_it =
277       std::find_if(begin(var->cnsts_), end(var->cnsts_), [&cnst](Element const& x) { return x.constraint == cnst; });
278   if (elem_it != end(var->cnsts_)) {
279     Element& elem = *elem_it;
280     if (var->sharing_penalty_ != 0.0)
281       elem.decrease_concurrency();
282
283     if (cnst->sharing_policy_ != s4u::Link::SharingPolicy::FATPIPE)
284       elem.consumption_weight += value;
285     else
286       elem.consumption_weight = std::max(elem.consumption_weight, value);
287
288     // We need to check that increasing value of the element does not cross the concurrency limit
289     if (var->sharing_penalty_ != 0.0) {
290       if (cnst->get_concurrency_slack() < elem.get_concurrency()) {
291         double penalty = var->sharing_penalty_;
292         disable_var(var);
293         for (Element const& elem2 : var->cnsts_)
294           on_disabled_var(elem2.constraint);
295         var->staged_penalty_ = penalty;
296         xbt_assert(not var->sharing_penalty_);
297       }
298       elem.increase_concurrency();
299     }
300     update_modified_set(cnst);
301   } else
302     expand(cnst, var, value);
303
304   check_concurrency();
305 }
306
307 Variable* Constraint::get_variable(const Element** elem) const
308 {
309   if (*elem == nullptr) {
310     // That is the first call, pick the first element among enabled_element_set (or disabled_element_set if
311     // enabled_element_set is empty)
312     if (not enabled_element_set_.empty())
313       *elem = &enabled_element_set_.front();
314     else if (not disabled_element_set_.empty())
315       *elem = &disabled_element_set_.front();
316     else
317       *elem = nullptr;
318   } else {
319     // elem is not null, so we carry on
320     if ((*elem)->enabled_element_set_hook.is_linked()) {
321       // Look at enabled_element_set, and jump to disabled_element_set when finished
322       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
323       if (iter != std::end(enabled_element_set_))
324         *elem = &*iter;
325       else if (not disabled_element_set_.empty())
326         *elem = &disabled_element_set_.front();
327       else
328         *elem = nullptr;
329     } else {
330       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
331       *elem     = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
332     }
333   }
334   if (*elem)
335     return (*elem)->variable;
336   else
337     return nullptr;
338 }
339
340 // if we modify the list between calls, normal version may loop forever
341 // this safe version ensures that we browse the list elements only once
342 Variable* Constraint::get_variable_safe(const Element** elem, const Element** nextelem, int* numelem) const
343 {
344   if (*elem == nullptr) {
345     *numelem = enabled_element_set_.size() + disabled_element_set_.size() - 1;
346     if (not enabled_element_set_.empty())
347       *elem = &enabled_element_set_.front();
348     else if (not disabled_element_set_.empty())
349       *elem = &disabled_element_set_.front();
350     else
351       *elem = nullptr;
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 static inline void saturated_constraints_update(double usage, int cnst_light_num, dyn_light_t& saturated_constraints,
380                                                 double* min_usage)
381 {
382   xbt_assert(usage > 0, "Impossible");
383
384   if (*min_usage < 0 || *min_usage > usage) {
385     *min_usage = usage;
386     XBT_HERE(" min_usage=%f (cnst->remaining / cnst->usage =%f)", *min_usage, usage);
387     saturated_constraints.assign(1, cnst_light_num);
388   } else if (*min_usage == usage) {
389     saturated_constraints.emplace_back(cnst_light_num);
390   }
391 }
392
393 static inline void saturated_variable_set_update(const ConstraintLight* cnst_light_tab,
394                                                  const dyn_light_t& saturated_constraints, System* sys)
395 {
396   /* Add active variables (i.e. variables that need to be set) from the set of constraints to saturate
397    * (cnst_light_tab)*/
398   for (int const& saturated_cnst : saturated_constraints) {
399     const ConstraintLight& cnst = cnst_light_tab[saturated_cnst];
400     for (Element const& elem : cnst.cnst->active_element_set_) {
401       xbt_assert(elem.variable->sharing_penalty_ > 0); // All elements of active_element_set should be active
402       if (elem.consumption_weight > 0 && not elem.variable->saturated_variable_set_hook_.is_linked())
403         sys->saturated_variable_set.push_back(*elem.variable);
404     }
405   }
406 }
407
408 template <class ElemList>
409 static void format_element_list(const ElemList& elem_list, s4u::Link::SharingPolicy sharing_policy, double& sum,
410                                 std::string& buf)
411 {
412   for (Element const& elem : elem_list) {
413     buf += std::to_string(elem.consumption_weight) + ".'" + std::to_string(elem.variable->rank_) + "'(" +
414            std::to_string(elem.variable->value_) + ")" +
415            (sharing_policy != s4u::Link::SharingPolicy::FATPIPE ? " + " : " , ");
416     if (sharing_policy != s4u::Link::SharingPolicy::FATPIPE)
417       sum += elem.consumption_weight * elem.variable->value_;
418     else
419       sum = std::max(sum, elem.consumption_weight * elem.variable->value_);
420   }
421 }
422
423 void System::print() const
424 {
425   std::string buf = "MAX-MIN ( ";
426
427   /* Printing Objective */
428   for (Variable const& var : variable_set)
429     buf += "'" + std::to_string(var.rank_) + "'(" + std::to_string(var.sharing_penalty_) + ") ";
430   buf += ")";
431   XBT_DEBUG("%20s", buf.c_str());
432   buf.clear();
433
434   XBT_DEBUG("Constraints");
435   /* Printing Constraints */
436   for (Constraint const& cnst : active_constraint_set) {
437     double sum            = 0.0;
438     // Show  the enabled variables
439     buf += "\t";
440     buf += cnst.sharing_policy_ != s4u::Link::SharingPolicy::FATPIPE ? "(" : "max(";
441     format_element_list(cnst.enabled_element_set_, cnst.sharing_policy_, sum, buf);
442     // TODO: Adding disabled elements only for test compatibility, but do we really want them to be printed?
443     format_element_list(cnst.disabled_element_set_, cnst.sharing_policy_, sum, buf);
444
445     buf += "0) <= " + std::to_string(cnst.bound_) + " ('" + std::to_string(cnst.rank_) + "')";
446
447     if (cnst.sharing_policy_ == s4u::Link::SharingPolicy::FATPIPE) {
448       buf += " [MAX-Constraint]";
449     }
450     XBT_DEBUG("%s", buf.c_str());
451     buf.clear();
452     xbt_assert(not double_positive(sum - cnst.bound_, cnst.bound_ * sg_maxmin_precision),
453                "Incorrect value (%f is not smaller than %f): %g", sum, cnst.bound_, sum - cnst.bound_);
454   }
455
456   XBT_DEBUG("Variables");
457   /* Printing Result */
458   for (Variable const& var : variable_set) {
459     if (var.bound_ > 0) {
460       XBT_DEBUG("'%d'(%f) : %f (<=%f)", var.rank_, var.sharing_penalty_, var.value_, var.bound_);
461       xbt_assert(not double_positive(var.value_ - var.bound_, var.bound_ * sg_maxmin_precision),
462                  "Incorrect value (%f is not smaller than %f", var.value_, var.bound_);
463     } else {
464       XBT_DEBUG("'%d'(%f) : %f", var.rank_, var.sharing_penalty_, var.value_);
465     }
466   }
467 }
468
469 void System::lmm_solve()
470 {
471   if (modified_) {
472     XBT_IN("(sys=%p)", this);
473     /* Compute Usage and store the variables that reach the maximum. If selective_update_active is true, only
474      * constraints that changed are considered. Otherwise all constraints with active actions are considered.
475      */
476     if (selective_update_active)
477       lmm_solve(modified_constraint_set);
478     else
479       lmm_solve(active_constraint_set);
480     XBT_OUT();
481   }
482 }
483
484 template <class CnstList> void System::lmm_solve(CnstList& cnst_list)
485 {
486   double min_usage = -1;
487   double min_bound = -1;
488
489   XBT_DEBUG("Active constraints : %zu", cnst_list.size());
490   cnst_light_vec.reserve(cnst_list.size());
491   ConstraintLight* cnst_light_tab = cnst_light_vec.data();
492   int cnst_light_num              = 0;
493
494   for (Constraint& cnst : cnst_list) {
495     /* INIT: Collect constraints that actually need to be saturated (i.e remaining  and usage are strictly positive)
496      * into cnst_light_tab. */
497     cnst.remaining_ = cnst.bound_;
498     if (not double_positive(cnst.remaining_, cnst.bound_ * sg_maxmin_precision))
499       continue;
500     cnst.usage_ = 0;
501     for (Element& elem : cnst.enabled_element_set_) {
502       xbt_assert(elem.variable->sharing_penalty_ > 0.0);
503       elem.variable->value_ = 0.0;
504       if (elem.consumption_weight > 0) {
505         if (cnst.sharing_policy_ != s4u::Link::SharingPolicy::FATPIPE)
506           cnst.usage_ += elem.consumption_weight / elem.variable->sharing_penalty_;
507         else if (cnst.usage_ < elem.consumption_weight / elem.variable->sharing_penalty_)
508           cnst.usage_ = elem.consumption_weight / elem.variable->sharing_penalty_;
509
510         elem.make_active();
511         resource::Action* action = elem.variable->id_;
512         if (modified_set_ && not action->is_within_modified_set())
513           modified_set_->push_back(*action);
514       }
515     }
516     XBT_DEBUG("Constraint '%d' usage: %f remaining: %f concurrency: %i<=%i<=%i", cnst.rank_, cnst.usage_,
517               cnst.remaining_, cnst.concurrency_current_, cnst.concurrency_maximum_, cnst.get_concurrency_limit());
518     /* Saturated constraints update */
519
520     if (cnst.usage_ > 0) {
521       cnst_light_tab[cnst_light_num].cnst                 = &cnst;
522       cnst.cnst_light_                                    = &cnst_light_tab[cnst_light_num];
523       cnst_light_tab[cnst_light_num].remaining_over_usage = cnst.remaining_ / cnst.usage_;
524       saturated_constraints_update(cnst_light_tab[cnst_light_num].remaining_over_usage, cnst_light_num,
525                                    saturated_constraints, &min_usage);
526       xbt_assert(not cnst.active_element_set_.empty(),
527                  "There is no sense adding a constraint that has no active element!");
528       cnst_light_num++;
529     }
530   }
531
532   saturated_variable_set_update(cnst_light_tab, saturated_constraints, this);
533
534   /* Saturated variables update */
535   do {
536     /* Fix the variables that have to be */
537     auto& var_list = saturated_variable_set;
538     for (Variable const& var : var_list) {
539       if (var.sharing_penalty_ <= 0.0)
540         DIE_IMPOSSIBLE;
541       /* First check if some of these variables could reach their upper bound and update min_bound accordingly. */
542       XBT_DEBUG("var=%d, var.bound=%f, var.penalty=%f, min_usage=%f, var.bound*var.penalty=%f", var.rank_, var.bound_,
543                 var.sharing_penalty_, min_usage, var.bound_ * var.sharing_penalty_);
544       if ((var.bound_ > 0) && (var.bound_ * var.sharing_penalty_ < min_usage)) {
545         if (min_bound < 0)
546           min_bound = var.bound_ * var.sharing_penalty_;
547         else
548           min_bound = std::min(min_bound, (var.bound_ * var.sharing_penalty_));
549         XBT_DEBUG("Updated min_bound=%f", min_bound);
550       }
551     }
552
553     while (not var_list.empty()) {
554       Variable& var = var_list.front();
555       if (min_bound < 0) {
556         // If no variable could reach its bound, deal iteratively the constraints usage ( at worst one constraint is
557         // saturated at each cycle)
558         var.value_ = min_usage / var.sharing_penalty_;
559         XBT_DEBUG("Setting var (%d) value to %f\n", var.rank_, var.value_);
560       } else {
561         // If there exist a variable that can reach its bound, only update it (and other with the same bound) for now.
562         if (double_equals(min_bound, var.bound_ * var.sharing_penalty_, sg_maxmin_precision)) {
563           var.value_ = var.bound_;
564           XBT_DEBUG("Setting %p (%d) value to %f\n", &var, var.rank_, var.value_);
565         } else {
566           // Variables which bound is different are not considered for this cycle, but they will be afterwards.
567           XBT_DEBUG("Do not consider %p (%d) \n", &var, var.rank_);
568           var_list.pop_front();
569           continue;
570         }
571       }
572       XBT_DEBUG("Min usage: %f, Var(%d).penalty: %f, Var(%d).value: %f ", min_usage, var.rank_, var.sharing_penalty_,
573                 var.rank_, var.value_);
574
575       /* Update the usage of constraints where this variable is involved */
576       for (Element& elem : var.cnsts_) {
577         Constraint* cnst = elem.constraint;
578         if (cnst->sharing_policy_ != s4u::Link::SharingPolicy::FATPIPE) {
579           // Remember: shared constraints require that sum(elem.value * var.value) < cnst->bound
580           double_update(&(cnst->remaining_), elem.consumption_weight * var.value_, cnst->bound_ * sg_maxmin_precision);
581           double_update(&(cnst->usage_), elem.consumption_weight / var.sharing_penalty_, sg_maxmin_precision);
582           // If the constraint is saturated, remove it from the set of active constraints (light_tab)
583           if (not double_positive(cnst->usage_, sg_maxmin_precision) ||
584               not double_positive(cnst->remaining_, cnst->bound_ * sg_maxmin_precision)) {
585             if (cnst->cnst_light_) {
586               int index = (cnst->cnst_light_ - cnst_light_tab);
587               XBT_DEBUG("index: %d \t cnst_light_num: %d \t || usage: %f remaining: %f bound: %f  ", index,
588                         cnst_light_num, cnst->usage_, cnst->remaining_, cnst->bound_);
589               cnst_light_tab[index]                  = cnst_light_tab[cnst_light_num - 1];
590               cnst_light_tab[index].cnst->cnst_light_ = &cnst_light_tab[index];
591               cnst_light_num--;
592               cnst->cnst_light_ = nullptr;
593             }
594           } else {
595             if (cnst->cnst_light_) {
596               cnst->cnst_light_->remaining_over_usage = cnst->remaining_ / cnst->usage_;
597             }
598           }
599           elem.make_inactive();
600         } else {
601           // Remember: non-shared constraints only require that max(elem.value * var.value) < cnst->bound
602           cnst->usage_ = 0.0;
603           elem.make_inactive();
604           for (const Element& elem2 : cnst->enabled_element_set_) {
605             xbt_assert(elem2.variable->sharing_penalty_ > 0);
606             if (elem2.variable->value_ > 0)
607               continue;
608             if (elem2.consumption_weight > 0)
609               cnst->usage_ = std::max(cnst->usage_, elem2.consumption_weight / elem2.variable->sharing_penalty_);
610           }
611           // If the constraint is saturated, remove it from the set of active constraints (light_tab)
612           if (not double_positive(cnst->usage_, sg_maxmin_precision) ||
613               not double_positive(cnst->remaining_, cnst->bound_ * sg_maxmin_precision)) {
614             if (cnst->cnst_light_) {
615               int index = (cnst->cnst_light_ - cnst_light_tab);
616               XBT_DEBUG("index: %d \t cnst_light_num: %d \t || \t cnst: %p \t cnst->cnst_light: %p "
617                         "\t cnst_light_tab: %p usage: %f remaining: %f bound: %f  ",
618                         index, cnst_light_num, cnst, cnst->cnst_light_, cnst_light_tab, cnst->usage_, cnst->remaining_,
619                         cnst->bound_);
620               cnst_light_tab[index]                  = cnst_light_tab[cnst_light_num - 1];
621               cnst_light_tab[index].cnst->cnst_light_ = &cnst_light_tab[index];
622               cnst_light_num--;
623               cnst->cnst_light_ = nullptr;
624             }
625           } else {
626             if (cnst->cnst_light_) {
627               cnst->cnst_light_->remaining_over_usage = cnst->remaining_ / cnst->usage_;
628               xbt_assert(not cnst->active_element_set_.empty(),
629                          "Should not keep a maximum constraint that has no active"
630                          " element! You want to check the maxmin precision and possible rounding effects.");
631             }
632           }
633         }
634       }
635       var_list.pop_front();
636     }
637
638     /* Find out which variables reach the maximum */
639     min_usage = -1;
640     min_bound = -1;
641     saturated_constraints.clear();
642     for (int pos = 0; pos < cnst_light_num; pos++) {
643       xbt_assert(not cnst_light_tab[pos].cnst->active_element_set_.empty(),
644                  "Cannot saturate more a constraint that has"
645                  " no active element! You may want to change the maxmin precision (--cfg=maxmin/precision:<new_value>)"
646                  " because of possible rounding effects.\n\tFor the record, the usage of this constraint is %g while "
647                  "the maxmin precision to which it is compared is %g.\n\tThe usage of the previous constraint is %g.",
648                  cnst_light_tab[pos].cnst->usage_, sg_maxmin_precision, cnst_light_tab[pos - 1].cnst->usage_);
649       saturated_constraints_update(cnst_light_tab[pos].remaining_over_usage, pos, saturated_constraints, &min_usage);
650     }
651
652     saturated_variable_set_update(cnst_light_tab, saturated_constraints, this);
653   } while (cnst_light_num > 0);
654
655   modified_ = false;
656   if (selective_update_active)
657     remove_all_modified_set();
658
659   if (XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug)) {
660     print();
661   }
662
663   check_concurrency();
664 }
665
666 /** @brief Attribute the value bound to var->bound.
667  *
668  *  @param var the Variable*
669  *  @param bound the new bound to associate with var
670  *
671  *  Makes var->bound equal to bound. Whenever this function is called a change is  signed in the system. To
672  *  avoid false system changing detection it is a good idea to test (bound != 0) before calling it.
673  */
674 void System::update_variable_bound(Variable* var, double bound)
675 {
676   modified_  = true;
677   var->bound_ = bound;
678
679   if (not var->cnsts_.empty())
680     update_modified_set(var->cnsts_[0].constraint);
681 }
682
683 void Variable::initialize(resource::Action* id_value, double sharing_penalty, double bound_value,
684                           int number_of_constraints, unsigned visited_value)
685 {
686   id_     = id_value;
687   rank_   = next_rank_++;
688   cnsts_.reserve(number_of_constraints);
689   sharing_penalty_   = sharing_penalty;
690   staged_penalty_    = 0.0;
691   bound_             = bound_value;
692   concurrency_share_ = 1;
693   value_             = 0.0;
694   visited_           = visited_value;
695   mu_                = 0.0;
696
697   xbt_assert(not variable_set_hook_.is_linked());
698   xbt_assert(not saturated_variable_set_hook_.is_linked());
699 }
700
701 int Variable::get_min_concurrency_slack() const
702 {
703   int minslack = std::numeric_limits<int>::max();
704   for (Element const& elem : cnsts_) {
705     int slack = elem.constraint->get_concurrency_slack();
706     if (slack < minslack) {
707       // This is only an optimization, to avoid looking at more constraints when slack is already zero
708       if (slack == 0)
709         return 0;
710       minslack = slack;
711     }
712   }
713   return minslack;
714 }
715
716 // Small remark: In this implementation of System::enable_var() and System::disable_var(), we will meet multiple times
717 // with var when running System::update_modified_set().
718 // A priori not a big performance issue, but we might do better by calling System::update_modified_set() within the for
719 // loops (after doing the first for enabling==1, and before doing the last for disabling==1)
720 void System::enable_var(Variable* var)
721 {
722   xbt_assert(not XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug) || var->can_enable());
723
724   var->sharing_penalty_ = var->staged_penalty_;
725   var->staged_penalty_  = 0;
726
727   // Enabling the variable, move var to list head. Subtlety is: here, we need to call update_modified_set AFTER
728   // moving at least one element of var.
729
730   simgrid::xbt::intrusive_erase(variable_set, *var);
731   variable_set.push_front(*var);
732   for (Element& elem : var->cnsts_) {
733     simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
734     elem.constraint->enabled_element_set_.push_front(elem);
735     elem.increase_concurrency();
736   }
737   if (not var->cnsts_.empty())
738     update_modified_set(var->cnsts_[0].constraint);
739
740   // When used within on_disabled_var, we would get an assertion fail, because transiently there can be variables
741   // that are staged and could be activated.
742   // Anyway, caller functions all call check_concurrency() in the end.
743 }
744
745 void System::disable_var(Variable* var)
746 {
747   xbt_assert(not var->staged_penalty_, "Staged penalty should have been cleared");
748   // Disabling the variable, move to var to list tail. Subtlety is: here, we need to call update_modified_set
749   // BEFORE moving the last element of var.
750   simgrid::xbt::intrusive_erase(variable_set, *var);
751   variable_set.push_back(*var);
752   if (not var->cnsts_.empty())
753     update_modified_set(var->cnsts_[0].constraint);
754   for (Element& elem : var->cnsts_) {
755     simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
756     elem.constraint->disabled_element_set_.push_back(elem);
757     if (elem.active_element_set_hook.is_linked())
758       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
759     elem.decrease_concurrency();
760   }
761
762   var->sharing_penalty_ = 0.0;
763   var->staged_penalty_  = 0.0;
764   var->value_          = 0.0;
765   check_concurrency();
766 }
767
768 /* /brief Find variables that can be enabled and enable them.
769  *
770  * Assuming that the variable has already been removed from non-zero penalties
771  * Can we find a staged variable to add?
772  * If yes, check that none of the constraints that this variable is involved in is at the limit of its concurrency
773  * And then add it to enabled variables
774  */
775 void System::on_disabled_var(Constraint* cnstr)
776 {
777   if (cnstr->get_concurrency_limit() < 0)
778     return;
779
780   int numelem = cnstr->disabled_element_set_.size();
781   if (not numelem)
782     return;
783
784   Element* elem = &cnstr->disabled_element_set_.front();
785
786   // Cannot use foreach loop, because System::enable_var() will modify disabled_element_set.. within the loop
787   while (numelem-- && elem) {
788     Element* nextelem;
789     if (elem->disabled_element_set_hook.is_linked()) {
790       auto iter = std::next(cnstr->disabled_element_set_.iterator_to(*elem));
791       nextelem  = iter != std::end(cnstr->disabled_element_set_) ? &*iter : nullptr;
792     } else {
793       nextelem = nullptr;
794     }
795
796     if (elem->variable->staged_penalty_ > 0 && elem->variable->can_enable()) {
797       // Found a staged variable
798       // TODOLATER: Add random timing function to model reservation protocol fuzziness? Then how to make sure that
799       // staged variables will eventually be called?
800       enable_var(elem->variable);
801     }
802
803     xbt_assert(cnstr->concurrency_current_ <= cnstr->get_concurrency_limit(), "Concurrency overflow!");
804     if (cnstr->concurrency_current_ == cnstr->get_concurrency_limit())
805       break;
806
807     elem = nextelem;
808   }
809
810   // We could get an assertion fail, because transiently there can be variables that are staged and could be activated.
811   // And we need to go through all constraints of the disabled var before getting back a coherent state.
812   // Anyway, caller functions all call check_concurrency() in the end.
813 }
814
815 /** @brief update the penalty of a variable (disable it by passing 0 as a penalty) */
816 void System::update_variable_penalty(Variable* var, double penalty)
817 {
818   xbt_assert(penalty >= 0, "Variable penalty should not be negative!");
819
820   if (penalty == var->sharing_penalty_)
821     return;
822
823   bool enabling_var  = (penalty > 0 && var->sharing_penalty_ <= 0);
824   bool disabling_var = (penalty <= 0 && var->sharing_penalty_ > 0);
825
826   XBT_IN("(sys=%p, var=%p, penalty=%f)", this, var, penalty);
827
828   modified_ = true;
829
830   // Are we enabling this variable?
831   if (enabling_var) {
832     var->staged_penalty_ = penalty;
833     int minslack       = var->get_min_concurrency_slack();
834     if (minslack < var->concurrency_share_) {
835       XBT_DEBUG("Staging var (instead of enabling) because min concurrency slack %i, with penalty %f and concurrency"
836                 " share %i",
837                 minslack, penalty, var->concurrency_share_);
838       return;
839     }
840     XBT_DEBUG("Enabling var with min concurrency slack %i", minslack);
841     enable_var(var);
842   } else if (disabling_var) {
843     disable_var(var);
844   } else {
845     var->sharing_penalty_ = penalty;
846   }
847
848   check_concurrency();
849
850   XBT_OUT();
851 }
852
853 void System::update_constraint_bound(Constraint* cnst, double bound)
854 {
855   modified_ = true;
856   update_modified_set(cnst);
857   cnst->bound_ = bound;
858 }
859
860 /** @brief Update the constraint set propagating recursively to other constraints so the system should not be entirely
861  *  computed.
862  *
863  *  @param cnst the Constraint* affected by the change
864  *
865  *  A recursive algorithm to optimize the system recalculation selecting only constraints that have changed. Each
866  *  constraint change is propagated to the list of constraints for each variable.
867  */
868 void System::update_modified_set_rec(const Constraint* cnst)
869 {
870   for (Element const& elem : cnst->enabled_element_set_) {
871     Variable* var = elem.variable;
872     for (Element const& elem2 : var->cnsts_) {
873       if (var->visited_ == visited_counter_)
874         break;
875       if (elem2.constraint != cnst && not elem2.constraint->modified_constraint_set_hook_.is_linked()) {
876         modified_constraint_set.push_back(*elem2.constraint);
877         update_modified_set_rec(elem2.constraint);
878       }
879     }
880     // var will be ignored in later visits as long as sys->visited_counter does not move
881     var->visited_ = visited_counter_;
882   }
883 }
884
885 void System::update_modified_set(Constraint* cnst)
886 {
887   /* nothing to do if selective update isn't active */
888   if (selective_update_active && not cnst->modified_constraint_set_hook_.is_linked()) {
889     modified_constraint_set.push_back(*cnst);
890     update_modified_set_rec(cnst);
891   }
892 }
893
894 void System::remove_all_modified_set()
895 {
896   // We cleverly un-flag all variables just by incrementing visited_counter
897   // In effect, the var->visited value will no more be equal to visited counter
898   // To be clean, when visited counter has wrapped around, we force these var->visited values so that variables that
899   // were in the modified a long long time ago are not wrongly skipped here, which would lead to very nasty bugs
900   // (i.e. not readily reproducible, and requiring a lot of run time before happening).
901   if (++visited_counter_ == 1) {
902     /* the counter wrapped around, reset each variable->visited */
903     for (Variable& var : variable_set)
904       var.visited_ = 0;
905   }
906   modified_constraint_set.clear();
907 }
908
909 /**
910  * Returns resource load (in flop per second, or byte per second, or similar)
911  *
912  * If the resource is shared (the default case), the load is sum of resource usage made by
913  * every variables located on this resource.
914  *
915  * If the resource is not shared (ie in FATPIPE mode), then the load is the max (not the sum)
916  * of all resource usages located on this resource.
917  */
918 double Constraint::get_usage() const
919 {
920   double result              = 0.0;
921   if (sharing_policy_ != s4u::Link::SharingPolicy::FATPIPE) {
922     for (Element const& elem : enabled_element_set_)
923       if (elem.consumption_weight > 0)
924         result += elem.consumption_weight * elem.variable->value_;
925   } else {
926     for (Element const& elem : enabled_element_set_)
927       if (elem.consumption_weight > 0)
928         result = std::max(result, elem.consumption_weight * elem.variable->value_);
929   }
930   return result;
931 }
932
933 int Constraint::get_variable_amount() const
934 {
935   return static_cast<int>(std::count_if(std::begin(enabled_element_set_), std::end(enabled_element_set_),
936                                         [](const Element& elem) { return elem.consumption_weight > 0; }));
937 }
938
939 } // namespace lmm
940 } // namespace kernel
941 } // namespace simgrid