Logo AND Algorithmique Numérique Distribuée

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