Logo AND Algorithmique Numérique Distribuée

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