Logo AND Algorithmique Numérique Distribuée

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