Logo AND Algorithmique Numérique Distribuée

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