Logo AND Algorithmique Numérique Distribuée

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