Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Leak-- (seen in maestro-set).
[simgrid.git] / src / surf / 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 "maxmin_private.hpp"
9 #include "xbt/log.h"
10 #include "xbt/mallocator.h"
11 #include "xbt/sysdep.h"
12 #include <cmath>
13 #include <cstdlib>
14 #include <cxxabi.h>
15 #include <limits>
16
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_maxmin, surf, "Logging specific to SURF (maxmin)");
18
19 typedef struct s_dyn_light {
20   int *data;
21   int pos;
22   int size;
23 } s_dyn_light_t;
24 typedef s_dyn_light_t* dyn_light_t;
25
26 double sg_maxmin_precision = 0.00001; /* Change this with --cfg=maxmin/precision:VALUE */
27 double sg_surf_precision   = 0.00001; /* Change this with --cfg=surf/precision:VALUE */
28 int sg_concurrency_limit   = -1;      /* Change this with --cfg=maxmin/concurrency-limit:VALUE */
29
30 static void *lmm_variable_mallocator_new_f();
31 static void lmm_variable_mallocator_free_f(void *var);
32 #define lmm_variable_mallocator_reset_f ((void_f_pvoid_t)nullptr)
33 static void lmm_update_modified_set(lmm_system_t sys, lmm_constraint_t cnst);
34 static void lmm_remove_all_modified_set(lmm_system_t sys);
35 static int Global_debug_id = 1;
36 static int Global_const_debug_id = 1;
37
38 static inline void lmm_cnst_free(lmm_system_t sys, lmm_constraint_t cnst);
39
40 static void lmm_on_disabled_var(lmm_system_t sys, lmm_constraint_t cnstr);
41 static void lmm_enable_var(lmm_system_t sys, lmm_variable_t var);
42 static int lmm_can_enable_var(lmm_variable_t var);
43 static void lmm_disable_var(lmm_system_t sys, lmm_variable_t var);
44 static int lmm_concurrency_slack(lmm_constraint_t cnstr);
45 static int lmm_cnstrs_min_concurrency_slack(lmm_variable_t var);
46
47 inline int lmm_element_concurrency(lmm_element_t elem) {
48   //Ignore element with weight less than one (e.g. cross-traffic)
49   return (elem->consumption_weight >= 1) ? 1 : 0;
50   //There are other alternatives, but they will change the behaviour of the model..
51   //So do not use it unless you want to make a new model.
52   //If you do, remember to change the variables concurrency share to reflect it.
53   //Potential examples are:
54   //return (elem->weight>0)?1:0;//Include element as soon  as weight is non-zero
55   //return (int)ceil(elem->weight);//Include element as the rounded-up integer value of the element weight
56 }
57
58 inline void lmm_decrease_concurrency(lmm_element_t elem) {
59   xbt_assert(elem->constraint->concurrency_current>=lmm_element_concurrency(elem));
60   elem->constraint->concurrency_current-=lmm_element_concurrency(elem);
61 }
62
63 inline void lmm_increase_concurrency(lmm_element_t elem) {
64   elem->constraint->concurrency_current+= lmm_element_concurrency(elem);
65
66   lmm_constraint_t cnstr=elem->constraint;
67
68   if(cnstr->concurrency_current > cnstr->concurrency_maximum)
69     cnstr->concurrency_maximum= cnstr->concurrency_current;
70
71   xbt_assert(cnstr->concurrency_limit<0 || cnstr->concurrency_current<=cnstr->concurrency_limit,
72              "Concurrency limit overflow!");
73 }
74
75 static void lmm_check_concurrency(lmm_system_t sys)
76 {
77   // These checks are very expensive, so do them only if we want to debug SURF LMM
78   if (not XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug))
79     return;
80
81   void* cnstIt;
82   xbt_swag_foreach(cnstIt, &(sys->constraint_set))
83   {
84     lmm_constraint_t cnst = (lmm_constraint_t)cnstIt;
85     int concurrency       = 0;
86     void* elemIt;
87     xbt_swag_foreach(elemIt, &(cnst->enabled_element_set))
88     {
89       lmm_element_t elem = (lmm_element_t)elemIt;
90       xbt_assert(elem->variable->sharing_weight > 0);
91       concurrency += lmm_element_concurrency(elem);
92     }
93
94     xbt_swag_foreach(elemIt, &(cnst->disabled_element_set))
95     {
96       lmm_element_t elem = (lmm_element_t)elemIt;
97       // We should have staged variables only if concurrency is reached in some constraint
98       xbt_assert(cnst->concurrency_limit < 0 || elem->variable->staged_weight == 0 ||
99                      lmm_cnstrs_min_concurrency_slack(elem->variable) < elem->variable->concurrency_share,
100                  "should not have staged variable!");
101     }
102
103     xbt_assert(cnst->concurrency_limit < 0 || cnst->concurrency_limit >= concurrency, "concurrency check failed!");
104     xbt_assert(cnst->concurrency_current == concurrency, "concurrency_current is out-of-date!");
105   }
106
107   // Check that for each variable, all corresponding elements are in the same state (i.e. same element sets)
108   void* varIt;
109   xbt_swag_foreach(varIt, &(sys->variable_set))
110   {
111     lmm_variable_t var = (lmm_variable_t)varIt;
112
113     if (not var->cnsts_number)
114       continue;
115
116     lmm_element_t elem     = &var->cnsts[0];
117     int belong_to_enabled  = xbt_swag_belongs(elem, &(elem->constraint->enabled_element_set));
118     int belong_to_disabled = xbt_swag_belongs(elem, &(elem->constraint->disabled_element_set));
119     int belong_to_active   = xbt_swag_belongs(elem, &(elem->constraint->active_element_set));
120
121     for (int i = 1; i < var->cnsts_number; i++) {
122       elem = &var->cnsts[i];
123       xbt_assert(belong_to_enabled == xbt_swag_belongs(elem, &(elem->constraint->enabled_element_set)),
124                  "Variable inconsistency (1): enabled_element_set");
125       xbt_assert(belong_to_disabled == xbt_swag_belongs(elem, &(elem->constraint->disabled_element_set)),
126                  "Variable inconsistency (2): disabled_element_set");
127       xbt_assert(belong_to_active == xbt_swag_belongs(elem, &(elem->constraint->active_element_set)),
128                  "Variable inconsistency (3): active_element_set");
129     }
130   }
131 }
132
133 static inline void lmm_variable_remove(lmm_system_t sys, lmm_variable_t var)
134 {
135   XBT_IN("(sys=%p, var=%p)", sys, var);
136   sys->modified = 1;
137
138   // TODOLATER Can do better than that by leaving only the variable in only one enabled_element_set, call
139   // lmm_update_modified_set, and then remove it..
140   if (var->cnsts_number)
141     lmm_update_modified_set(sys, var->cnsts[0].constraint);
142
143   for (int i = 0; i < var->cnsts_number; i++) {
144     lmm_element_t elem = &var->cnsts[i];
145     if (var->sharing_weight > 0)
146       lmm_decrease_concurrency(elem);
147     xbt_swag_remove(elem, &(elem->constraint->enabled_element_set));
148     xbt_swag_remove(elem, &(elem->constraint->disabled_element_set));
149     xbt_swag_remove(elem, &(elem->constraint->active_element_set));
150     int nelements = xbt_swag_size(&(elem->constraint->enabled_element_set)) +
151                     xbt_swag_size(&(elem->constraint->disabled_element_set));
152     if (nelements == 0)
153       make_constraint_inactive(sys, elem->constraint);
154     else
155       lmm_on_disabled_var(sys, elem->constraint);
156   }
157
158   // Check if we can enable new variables going through the constraints where var was.
159   // Do it after removing all elements, so he first disabled variables get priority over those with smaller requirement
160   for (int i = 0; i < var->cnsts_number; i++) {
161     lmm_element_t elem = &var->cnsts[i];
162     if (xbt_swag_size(&(elem->constraint->disabled_element_set)))
163       lmm_on_disabled_var(sys, elem->constraint);
164   }
165
166   var->cnsts_number = 0;
167
168   lmm_check_concurrency(sys);
169
170   XBT_OUT();
171 }
172
173 static void lmm_var_free(lmm_system_t sys, lmm_variable_t var)
174 {
175   lmm_variable_remove(sys, var);
176   xbt_mallocator_release(sys->variable_mallocator, var);
177 }
178
179 lmm_system_t lmm_system_new(bool selective_update)
180 {
181   s_lmm_variable_t var;
182   s_lmm_constraint_t cnst;
183
184   lmm_system_t l = xbt_new0(s_lmm_system_t, 1);
185
186   l->modified = 0;
187   l->selective_update_active = selective_update;
188   l->visited_counter = 1;
189
190   XBT_DEBUG("Setting selective_update_active flag to %d", l->selective_update_active);
191
192   xbt_swag_init(&(l->variable_set), xbt_swag_offset(var, variable_set_hookup));
193   xbt_swag_init(&(l->constraint_set), xbt_swag_offset(cnst, constraint_set_hookup));
194
195   xbt_swag_init(&(l->active_constraint_set), xbt_swag_offset(cnst, active_constraint_set_hookup));
196
197   xbt_swag_init(&(l->modified_constraint_set), xbt_swag_offset(cnst, modified_constraint_set_hookup));
198   xbt_swag_init(&(l->saturated_variable_set), xbt_swag_offset(var, saturated_variable_set_hookup));
199   xbt_swag_init(&(l->saturated_constraint_set), xbt_swag_offset(cnst, saturated_constraint_set_hookup));
200
201   l->variable_mallocator = xbt_mallocator_new(65536,
202                                               lmm_variable_mallocator_new_f,
203                                               lmm_variable_mallocator_free_f,
204                                               lmm_variable_mallocator_reset_f);
205
206   l->solve_fun = &lmm_solve;
207
208   return l;
209 }
210
211 void lmm_system_free(lmm_system_t sys)
212 {
213   lmm_variable_t var = nullptr;
214   lmm_constraint_t cnst = nullptr;
215
216   if (sys == nullptr)
217     return;
218
219   while ((var = (lmm_variable_t) extract_variable(sys))) {
220     int status;
221     char* demangled = abi::__cxa_demangle(typeid(*var->id).name(), 0, 0, &status);
222
223     XBT_WARN("Probable bug: a %s variable (#%d) not removed before the LMM system destruction.", demangled,
224              var->id_int);
225     xbt_free(demangled);
226     lmm_var_free(sys, var);
227   }
228   while ((cnst = (lmm_constraint_t) extract_constraint(sys)))
229     lmm_cnst_free(sys, cnst);
230
231   xbt_mallocator_free(sys->variable_mallocator);
232   free(sys);
233 }
234
235 static inline void lmm_cnst_free(lmm_system_t sys, lmm_constraint_t cnst)
236 {
237   make_constraint_inactive(sys, cnst);
238   free(cnst);
239 }
240
241 lmm_constraint_t lmm_constraint_new(lmm_system_t sys, void *id, double bound_value)
242 {
243   lmm_constraint_t cnst = nullptr;
244   s_lmm_element_t elem;
245
246   cnst = xbt_new0(s_lmm_constraint_t, 1);
247   cnst->id = id;
248   cnst->id_int = Global_const_debug_id++;
249   xbt_swag_init(&(cnst->enabled_element_set), xbt_swag_offset(elem, enabled_element_set_hookup));
250   xbt_swag_init(&(cnst->disabled_element_set), xbt_swag_offset(elem, disabled_element_set_hookup));
251   xbt_swag_init(&(cnst->active_element_set), xbt_swag_offset(elem, active_element_set_hookup));
252
253   cnst->bound = bound_value;
254   cnst->concurrency_maximum=0;
255   cnst->concurrency_current=0;
256   cnst->concurrency_limit  = sg_concurrency_limit;
257   cnst->usage = 0;
258   cnst->sharing_policy = 1; /* FIXME: don't hardcode the value */
259   insert_constraint(sys, cnst);
260
261   return cnst;
262 }
263
264 int lmm_constraint_concurrency_limit_get(lmm_constraint_t cnst)
265 {
266  return cnst->concurrency_limit;
267 }
268
269 void lmm_constraint_concurrency_limit_set(lmm_constraint_t cnst, int concurrency_limit)
270 {
271   xbt_assert(concurrency_limit<0 || cnst->concurrency_maximum<=concurrency_limit,
272              "New concurrency limit should be larger than observed concurrency maximum. Maybe you want to call"
273              " lmm_constraint_concurrency_maximum_reset() to reset the maximum?");
274   cnst->concurrency_limit = concurrency_limit;
275 }
276
277 void lmm_constraint_concurrency_maximum_reset(lmm_constraint_t cnst)
278 {
279   cnst->concurrency_maximum = 0;
280 }
281
282 int lmm_constraint_concurrency_maximum_get(lmm_constraint_t cnst)
283 {
284  xbt_assert(cnst->concurrency_limit<0 || cnst->concurrency_maximum<=cnst->concurrency_limit,
285             "Very bad: maximum observed concurrency is higher than limit. This is a bug of SURF, please report it.");
286   return cnst->concurrency_maximum;
287 }
288
289 void lmm_constraint_shared(lmm_constraint_t cnst)
290 {
291   cnst->sharing_policy = 0;
292 }
293
294 /** Return true if the constraint is shared, and false if it's FATPIPE */
295 int lmm_constraint_sharing_policy(lmm_constraint_t cnst)
296 {
297   return (cnst->sharing_policy);
298 }
299
300 /* @brief Remove a constraint
301  * Currently this is dead code, but it is exposed in maxmin.h
302  * Apparently, this call was designed assuming that constraint would no more have elements in it.
303  * If not the case, assertion will fail, and you need to add calls e.g. to lmm_shrink before effectively removing it.
304  */
305 inline void lmm_constraint_free(lmm_system_t sys,lmm_constraint_t cnst)
306 {
307   xbt_assert(not xbt_swag_size(&(cnst->active_element_set)), "Removing constraint but it still has active elements");
308   xbt_assert(not xbt_swag_size(&(cnst->enabled_element_set)), "Removing constraint but it still has enabled elements");
309   xbt_assert(not xbt_swag_size(&(cnst->disabled_element_set)),
310              "Removing constraint but it still has disabled elements");
311   remove_constraint(sys, cnst);
312   lmm_cnst_free(sys, cnst);
313 }
314
315 static void *lmm_variable_mallocator_new_f()
316 {
317   lmm_variable_t var = xbt_new(s_lmm_variable_t, 1);
318   var->cnsts = nullptr; /* will be created by realloc */
319   return var;
320 }
321
322 static void lmm_variable_mallocator_free_f(void *var)
323 {
324   xbt_free(((lmm_variable_t) var)->cnsts);
325   xbt_free(var);
326 }
327
328 lmm_variable_t lmm_variable_new(lmm_system_t sys, simgrid::surf::Action* id, double sharing_weight, double bound,
329                                 int number_of_constraints)
330 {
331   XBT_IN("(sys=%p, id=%p, weight=%f, bound=%f, num_cons =%d)", sys, id, sharing_weight, bound, number_of_constraints);
332
333   lmm_variable_t var = (lmm_variable_t)xbt_mallocator_get(sys->variable_mallocator);
334   var->id = id;
335   var->id_int = Global_debug_id++;
336   var->cnsts = (s_lmm_element_t *) xbt_realloc(var->cnsts, number_of_constraints * sizeof(s_lmm_element_t));
337   for (int i = 0; i < number_of_constraints; i++) {
338     var->cnsts[i].enabled_element_set_hookup.next = nullptr;
339     var->cnsts[i].enabled_element_set_hookup.prev = nullptr;
340     var->cnsts[i].disabled_element_set_hookup.next = nullptr;
341     var->cnsts[i].disabled_element_set_hookup.prev = nullptr;
342     var->cnsts[i].active_element_set_hookup.next = nullptr;
343     var->cnsts[i].active_element_set_hookup.prev = nullptr;
344     var->cnsts[i].constraint = nullptr;
345     var->cnsts[i].variable = nullptr;
346     var->cnsts[i].consumption_weight               = 0.0;
347   }
348   var->cnsts_size = number_of_constraints;
349   var->cnsts_number = 0;
350   var->sharing_weight    = sharing_weight;
351   var->staged_weight = 0.0;
352   var->bound = bound;
353   var->concurrency_share = 1;
354   var->value = 0.0;
355   var->visited = sys->visited_counter - 1;
356   var->mu = 0.0;
357   var->new_mu = 0.0;
358   var->func_f = func_f_def;
359   var->func_fp = func_fp_def;
360   var->func_fpi = func_fpi_def;
361
362   var->variable_set_hookup.next = nullptr;
363   var->variable_set_hookup.prev = nullptr;
364   var->saturated_variable_set_hookup.next = nullptr;
365   var->saturated_variable_set_hookup.prev = nullptr;
366
367   if (sharing_weight)
368     xbt_swag_insert_at_head(var, &(sys->variable_set));
369   else
370     xbt_swag_insert_at_tail(var, &(sys->variable_set));
371
372   XBT_OUT(" returns %p", var);
373   return var;
374 }
375
376 void lmm_variable_free(lmm_system_t sys, lmm_variable_t var)
377 {
378   remove_variable(sys, var);
379   lmm_var_free(sys, var);
380 }
381
382 double lmm_variable_getvalue(lmm_variable_t var)
383 {
384   return (var->value);
385 }
386
387 void lmm_variable_concurrency_share_set(lmm_variable_t var, short int concurrency_share)
388 {
389   var->concurrency_share=concurrency_share;
390 }
391
392 double lmm_variable_getbound(lmm_variable_t var)
393 {
394   return (var->bound);
395 }
396
397 void lmm_shrink(lmm_system_t sys, lmm_constraint_t cnst, lmm_variable_t var)
398 {
399   lmm_element_t elem = nullptr;
400   int found = 0;
401
402   for (int i = 0; i < var->cnsts_number; i++) {
403     elem = &(var->cnsts[i]);
404     if (elem->constraint == cnst) {
405       found = 1;
406       break;
407     }
408   }
409
410   if (not found) {
411     XBT_DEBUG("cnst %p is not found in var %p", cnst, var);
412     return;
413   }
414
415   sys->modified = 1;
416
417   XBT_DEBUG("remove elem(value %f, cnst %p, var %p) in var %p", elem->consumption_weight, elem->constraint,
418             elem->variable, var);
419
420   /* We are going to change the constraint object and the variable object.
421    * Propagate this change to other objects. Calling here before removing variable from not active elements
422    * (inactive elements are not visited)
423    */
424   lmm_update_modified_set(sys, cnst);
425   //Useful in case var was already removed from the constraint
426   lmm_update_modified_set(sys, var->cnsts[0].constraint); // will look up enabled_element_set of this constraint, and
427                                                      //then each var in the enabled_element_set, and each var->cnsts[i].
428
429   if(xbt_swag_remove(elem, &(elem->constraint->enabled_element_set)))
430     lmm_decrease_concurrency(elem);
431
432   xbt_swag_remove(elem, &(elem->constraint->active_element_set));
433   elem->constraint = nullptr;
434   elem->variable = nullptr;
435   elem->consumption_weight = 0;
436
437   var->cnsts_number -= 1;
438
439   //No variable in this constraint -> make it inactive
440   if (xbt_swag_size(&(cnst->enabled_element_set))+xbt_swag_size(&(cnst->disabled_element_set)) == 0)
441     make_constraint_inactive(sys, cnst);
442   else {
443     //Check maxconcurrency to see if we can enable new variables
444     lmm_on_disabled_var(sys,elem->constraint);
445   }
446
447   lmm_check_concurrency(sys);
448 }
449
450 void lmm_expand(lmm_system_t sys, lmm_constraint_t cnst, lmm_variable_t var, double consumption_weight)
451 {
452   sys->modified = 1;
453
454   //Check if this variable already has an active element in this constraint
455   //If it does, substract it from the required slack
456   int current_share = 0;
457   if(var->concurrency_share>1){
458     for (int i = 0; i < var->cnsts_number; i++) {
459       if(var->cnsts[i].constraint==cnst &&
460          xbt_swag_belongs(&var->cnsts[i],&(var->cnsts[i].constraint->enabled_element_set)))
461          current_share+=lmm_element_concurrency(&(var->cnsts[i]));
462     }
463   }
464
465   //Check if we need to disable the variable
466   if (var->sharing_weight > 0 && var->concurrency_share - current_share > lmm_concurrency_slack(cnst)) {
467     double weight = var->sharing_weight;
468     lmm_disable_var(sys,var);
469     for (int i = 0; i < var->cnsts_number; i++)
470       lmm_on_disabled_var(sys,var->cnsts[i].constraint);
471     consumption_weight = 0;
472     var->staged_weight=weight;
473     xbt_assert(not var->sharing_weight);
474   }
475
476   xbt_assert(var->cnsts_number < var->cnsts_size, "Too much constraints");
477
478   lmm_element_t elem = &(var->cnsts[var->cnsts_number++]);
479
480   elem->consumption_weight = consumption_weight;
481   elem->constraint = cnst;
482   elem->variable = var;
483
484   if (var->sharing_weight) {
485     xbt_swag_insert_at_head(elem, &(elem->constraint->enabled_element_set));
486     lmm_increase_concurrency(elem);
487   } else
488     xbt_swag_insert_at_tail(elem, &(elem->constraint->disabled_element_set));
489
490   if (not sys->selective_update_active) {
491     make_constraint_active(sys, cnst);
492   } else if (elem->consumption_weight > 0 || var->sharing_weight > 0) {
493     make_constraint_active(sys, cnst);
494     lmm_update_modified_set(sys, cnst);
495     //TODOLATER: Why do we need this second call?
496     if (var->cnsts_number > 1)
497       lmm_update_modified_set(sys, var->cnsts[0].constraint);
498   }
499
500   lmm_check_concurrency(sys);
501 }
502
503 void lmm_expand_add(lmm_system_t sys, lmm_constraint_t cnst, lmm_variable_t var, double value)
504 {
505   int i;
506   sys->modified = 1;
507
508   lmm_check_concurrency(sys);
509
510   //BEWARE: In case you have multiple elements in one constraint, this will always add value to the first element.
511   for (i = 0; i < var->cnsts_number; i++)
512     if (var->cnsts[i].constraint == cnst)
513       break;
514
515   if (i < var->cnsts_number) {
516     if (var->sharing_weight)
517       lmm_decrease_concurrency(&var->cnsts[i]);
518
519     if (cnst->sharing_policy)
520       var->cnsts[i].consumption_weight += value;
521     else
522       var->cnsts[i].consumption_weight = MAX(var->cnsts[i].consumption_weight, value);
523
524     //We need to check that increasing value of the element does not cross the concurrency limit
525     if (var->sharing_weight) {
526       if(lmm_concurrency_slack(cnst)<lmm_element_concurrency(&var->cnsts[i])){
527         double weight = var->sharing_weight;
528         lmm_disable_var(sys,var);
529         for (int j = 0; j < var->cnsts_number; j++)
530           lmm_on_disabled_var(sys,var->cnsts[j].constraint);
531         var->staged_weight=weight;
532         xbt_assert(not var->sharing_weight);
533       }
534       lmm_increase_concurrency(&var->cnsts[i]);
535     }
536     lmm_update_modified_set(sys, cnst);
537   } else
538     lmm_expand(sys, cnst, var, value);
539
540   lmm_check_concurrency(sys);
541 }
542
543 lmm_constraint_t lmm_get_cnst_from_var(lmm_system_t /*sys*/, lmm_variable_t var, int num)
544 {
545   if (num < var->cnsts_number)
546     return (var->cnsts[num].constraint);
547   else
548     return nullptr;
549 }
550
551 double lmm_get_cnst_weight_from_var(lmm_system_t /*sys*/, lmm_variable_t var, int num)
552 {
553   if (num < var->cnsts_number)
554     return (var->cnsts[num].consumption_weight);
555   else
556     return 0.0;
557 }
558
559 int lmm_get_number_of_cnst_from_var(lmm_system_t /*sys*/, lmm_variable_t var)
560 {
561   return (var->cnsts_number);
562 }
563
564 lmm_variable_t lmm_get_var_from_cnst(lmm_system_t /*sys*/, lmm_constraint_t cnst, lmm_element_t * elem)
565 {
566   if (*elem == nullptr) {
567     // That is the first call, pick the first element among enabled_element_set (or disabled_element_set if
568     // enabled_element_set is empty)
569     *elem = (lmm_element_t) xbt_swag_getFirst(&(cnst->enabled_element_set));
570     if (*elem == nullptr)
571       *elem = (lmm_element_t) xbt_swag_getFirst(&(cnst->disabled_element_set));
572   } else {
573     //elem is not null, so we carry on
574     if(xbt_swag_belongs(*elem,&(cnst->enabled_element_set))){
575       //Look at enabled_element_set, and jump to disabled_element_set when finished
576       *elem = (lmm_element_t) xbt_swag_getNext(*elem, cnst->enabled_element_set.offset);
577       if (*elem == nullptr)
578         *elem = (lmm_element_t) xbt_swag_getFirst(&(cnst->disabled_element_set));
579     } else {
580       *elem = (lmm_element_t) xbt_swag_getNext(*elem, cnst->disabled_element_set.offset);
581     }
582   }
583   if (*elem)
584     return (*elem)->variable;
585   else
586     return nullptr;
587 }
588
589 //if we modify the swag between calls, normal version may loop forever
590 //this safe version ensures that we browse the swag elements only once
591 lmm_variable_t lmm_get_var_from_cnst_safe(lmm_system_t /*sys*/, lmm_constraint_t cnst, lmm_element_t * elem,
592                                           lmm_element_t * nextelem, int * numelem)
593 {
594   if (*elem == nullptr) {
595     *elem = (lmm_element_t) xbt_swag_getFirst(&(cnst->enabled_element_set));
596     *numelem = xbt_swag_size(&(cnst->enabled_element_set))+xbt_swag_size(&(cnst->disabled_element_set))-1;
597     if (*elem == nullptr)
598       *elem = (lmm_element_t) xbt_swag_getFirst(&(cnst->disabled_element_set));
599   }else{
600     *elem = *nextelem;
601     if(*numelem>0){
602      (*numelem) --;
603     }else
604       return nullptr;
605   }
606   if (*elem){
607     //elem is not null, so we carry on
608     if(xbt_swag_belongs(*elem,&(cnst->enabled_element_set))){
609       //Look at enabled_element_set, and jump to disabled_element_set when finished
610       *nextelem = (lmm_element_t) xbt_swag_getNext(*elem, cnst->enabled_element_set.offset);
611       if (*nextelem == nullptr)
612         *nextelem = (lmm_element_t) xbt_swag_getFirst(&(cnst->disabled_element_set));
613     } else {
614       *nextelem = (lmm_element_t) xbt_swag_getNext(*elem, cnst->disabled_element_set.offset);
615     }
616     return (*elem)->variable;
617   }else
618     return nullptr;
619 }
620
621 void *lmm_constraint_id(lmm_constraint_t cnst)
622 {
623   return cnst->id;
624 }
625
626 void *lmm_variable_id(lmm_variable_t var)
627 {
628   return var->id;
629 }
630
631 static inline void saturated_constraint_set_update(double usage, int cnst_light_num,
632                                                    dyn_light_t saturated_constraint_set, double *min_usage)
633 {
634   xbt_assert(usage > 0,"Impossible");
635
636   if (*min_usage < 0 || *min_usage > usage) {
637     *min_usage = usage;
638     XBT_HERE(" min_usage=%f (cnst->remaining / cnst->usage =%f)", *min_usage, usage);
639     saturated_constraint_set->data[0] = cnst_light_num;
640     saturated_constraint_set->pos = 1;
641   } else if (*min_usage == usage) {
642     if(saturated_constraint_set->pos == saturated_constraint_set->size) { // realloc the size
643       saturated_constraint_set->size *= 2;
644       saturated_constraint_set->data =
645         (int*) xbt_realloc(saturated_constraint_set->data, (saturated_constraint_set->size) * sizeof(int));
646     }
647     saturated_constraint_set->data[saturated_constraint_set->pos] = cnst_light_num;
648     saturated_constraint_set->pos++;
649   }
650 }
651
652 static inline void saturated_variable_set_update(s_lmm_constraint_light_t *cnst_light_tab,
653                                                  dyn_light_t saturated_constraint_set, lmm_system_t sys)
654 {
655   /* Add active variables (i.e. variables that need to be set) from the set of constraints to saturate (cnst_light_tab)*/
656   lmm_constraint_light_t cnst = nullptr;
657   void *_elem;
658   lmm_element_t elem = nullptr;
659   xbt_swag_t elem_list = nullptr;
660   int i;
661   for(i = 0; i< saturated_constraint_set->pos; i++){
662     cnst = &cnst_light_tab[saturated_constraint_set->data[i]];
663     elem_list = &(cnst->cnst->active_element_set);
664     xbt_swag_foreach(_elem, elem_list) {
665       elem = (lmm_element_t)_elem;
666       //Visiting active_element_set, so, by construction, should never get a zero weight, correct?
667       xbt_assert(elem->variable->sharing_weight > 0);
668       if (elem->consumption_weight > 0)
669         xbt_swag_insert(elem->variable, &(sys->saturated_variable_set));
670     }
671   }
672 }
673
674 void lmm_print(lmm_system_t sys)
675 {
676   std::string buf       = std::string("MAX-MIN ( ");
677   void* _var;
678
679   /* Printing Objective */
680   xbt_swag_t var_list = &(sys->variable_set);
681   xbt_swag_foreach(_var, var_list) {
682     lmm_variable_t var = (lmm_variable_t)_var;
683     buf = buf + "'" + std::to_string(var->id_int) + "'(" + std::to_string(var->sharing_weight) + ") ";
684   }
685   buf += ")";
686   XBT_DEBUG("%20s", buf.c_str());
687   buf.clear();
688
689   XBT_DEBUG("Constraints");
690   /* Printing Constraints */
691   void* _cnst;
692   xbt_swag_t cnst_list = &(sys->active_constraint_set);
693   xbt_swag_foreach(_cnst, cnst_list) {
694     lmm_constraint_t cnst = (lmm_constraint_t)_cnst;
695     double sum = 0.0;
696     //Show  the enabled variables
697     void* _elem;
698     xbt_swag_t elem_list = &(cnst->enabled_element_set);
699     buf += "\t";
700     buf += ((cnst->sharing_policy) ? "(" : "max(");
701     xbt_swag_foreach(_elem, elem_list) {
702       lmm_element_t elem = (lmm_element_t)_elem;
703       buf  = buf + std::to_string(elem->consumption_weight) + ".'" + std::to_string(elem->variable->id_int) + "'(" +
704             std::to_string(elem->variable->value) + ")" + ((cnst->sharing_policy) ? " + " : " , ");
705       if(cnst->sharing_policy)
706         sum += elem->consumption_weight * elem->variable->value;
707       else
708         sum = MAX(sum, elem->consumption_weight * elem->variable->value);
709     }
710     //TODO: Adding disabled elements only for test compatibility, but do we really want them to be printed?
711     elem_list = &(cnst->disabled_element_set);
712     xbt_swag_foreach(_elem, elem_list) {
713       lmm_element_t elem = (lmm_element_t)_elem;
714       buf  = buf + std::to_string(elem->consumption_weight) + ".'" + std::to_string(elem->variable->id_int) + "'(" +
715             std::to_string(elem->variable->value) + ")" + ((cnst->sharing_policy) ? " + " : " , ");
716       if(cnst->sharing_policy)
717         sum += elem->consumption_weight * elem->variable->value;
718       else
719         sum = MAX(sum, elem->consumption_weight * elem->variable->value);
720     }
721
722     buf = buf + "0) <= " + std::to_string(cnst->bound) + " ('" + std::to_string(cnst->id_int) + "')";
723
724     if (not cnst->sharing_policy) {
725       buf += " [MAX-Constraint]";
726     }
727     XBT_DEBUG("%s", buf.c_str());
728     buf.clear();
729     xbt_assert(not double_positive(sum - cnst->bound, cnst->bound * sg_maxmin_precision),
730                "Incorrect value (%f is not smaller than %f): %g", sum, cnst->bound, sum - cnst->bound);
731   }
732
733   XBT_DEBUG("Variables");
734   /* Printing Result */
735   xbt_swag_foreach(_var, var_list) {
736     lmm_variable_t var = (lmm_variable_t)_var;
737     if (var->bound > 0) {
738       XBT_DEBUG("'%d'(%f) : %f (<=%f)", var->id_int, var->sharing_weight, var->value, var->bound);
739       xbt_assert(not double_positive(var->value - var->bound, var->bound * sg_maxmin_precision),
740                  "Incorrect value (%f is not smaller than %f", var->value, var->bound);
741     } else {
742       XBT_DEBUG("'%d'(%f) : %f", var->id_int, var->sharing_weight, var->value);
743     }
744   }
745 }
746
747 void lmm_solve(lmm_system_t sys)
748 {
749   void* _cnst;
750   void* _cnst_next;
751   void* _elem;
752   double min_usage = -1;
753   double min_bound = -1;
754
755   if (not sys->modified)
756     return;
757
758   XBT_IN("(sys=%p)", sys);
759
760   /* Compute Usage and store the variables that reach the maximum. If selective_update_active is true, only constraints
761    * that changed are considered. Otherwise all constraints with active actions are considered.
762    */
763   xbt_swag_t cnst_list = sys->selective_update_active ? &(sys->modified_constraint_set) : &(sys->active_constraint_set);
764
765   XBT_DEBUG("Active constraints : %d", xbt_swag_size(cnst_list));
766   /* Init: Only modified code portions: reset the value of active variables */
767   xbt_swag_foreach(_cnst, cnst_list) {
768     lmm_constraint_t cnst = (lmm_constraint_t)_cnst;
769     xbt_swag_t elem_list  = &(cnst->enabled_element_set);
770     //XBT_DEBUG("Variable set : %d", xbt_swag_size(elem_list));
771     xbt_swag_foreach(_elem, elem_list) {
772       lmm_variable_t var = ((lmm_element_t)_elem)->variable;
773       xbt_assert(var->sharing_weight > 0.0);
774       var->value = 0.0;
775     }
776   }
777
778   s_lmm_constraint_light_t *cnst_light_tab =
779      (s_lmm_constraint_light_t *)xbt_malloc0(xbt_swag_size(cnst_list)*sizeof(s_lmm_constraint_light_t));
780   int cnst_light_num = 0;
781   dyn_light_t saturated_constraint_set = xbt_new0(s_dyn_light_t,1);
782   saturated_constraint_set->size = 5;
783   saturated_constraint_set->data = xbt_new0(int, saturated_constraint_set->size);
784
785   xbt_swag_foreach_safe(_cnst, _cnst_next, cnst_list) {
786     lmm_constraint_t cnst = (lmm_constraint_t)_cnst;
787     /* INIT: Collect constraints that actually need to be saturated (i.e remaining  and usage are strictly positive)
788      * into cnst_light_tab. */
789     cnst->remaining = cnst->bound;
790     if (not double_positive(cnst->remaining, cnst->bound * sg_maxmin_precision))
791       continue;
792     cnst->usage = 0;
793     xbt_swag_t elem_list = &(cnst->enabled_element_set);
794     xbt_swag_foreach(_elem, elem_list) {
795       lmm_element_t elem = (lmm_element_t)_elem;
796       xbt_assert(elem->variable->sharing_weight > 0);
797       if (elem->consumption_weight > 0) {
798         if (cnst->sharing_policy)
799           cnst->usage += elem->consumption_weight / elem->variable->sharing_weight;
800         else if (cnst->usage < elem->consumption_weight / elem->variable->sharing_weight)
801           cnst->usage = elem->consumption_weight / elem->variable->sharing_weight;
802
803         make_elem_active(elem);
804         simgrid::surf::Action *action = static_cast<simgrid::surf::Action*>(elem->variable->id);
805         if (sys->keep_track && not action->is_linked())
806           sys->keep_track->push_back(*action);
807       }
808     }
809     XBT_DEBUG("Constraint '%d' usage: %f remaining: %f concurrency: %i<=%i<=%i", cnst->id_int, cnst->usage,
810               cnst->remaining,cnst->concurrency_current,cnst->concurrency_maximum,cnst->concurrency_limit);
811     /* Saturated constraints update */
812
813     if(cnst->usage > 0) {
814       cnst_light_tab[cnst_light_num].cnst = cnst;
815       cnst->cnst_light = &(cnst_light_tab[cnst_light_num]);
816       cnst_light_tab[cnst_light_num].remaining_over_usage = cnst->remaining / cnst->usage;
817       saturated_constraint_set_update(cnst_light_tab[cnst_light_num].remaining_over_usage,
818         cnst_light_num, saturated_constraint_set, &min_usage);
819       xbt_assert(cnst->active_element_set.count>0, "There is no sense adding a constraint that has no active element!");
820       cnst_light_num++;
821     }
822   }
823
824   saturated_variable_set_update(  cnst_light_tab, saturated_constraint_set, sys);
825
826   /* Saturated variables update */
827   do {
828     /* Fix the variables that have to be */
829     xbt_swag_t var_list = &(sys->saturated_variable_set);
830     void* _var;
831     lmm_variable_t var = nullptr;
832     xbt_swag_foreach(_var, var_list) {
833       var = (lmm_variable_t)_var;
834       if (var->sharing_weight <= 0.0)
835         DIE_IMPOSSIBLE;
836       /* First check if some of these variables could reach their upper bound and update min_bound accordingly. */
837       XBT_DEBUG("var=%d, var->bound=%f, var->weight=%f, min_usage=%f, var->bound*var->weight=%f", var->id_int,
838                 var->bound, var->sharing_weight, min_usage, var->bound * var->sharing_weight);
839       if ((var->bound > 0) && (var->bound * var->sharing_weight < min_usage)) {
840         if (min_bound < 0)
841           min_bound = var->bound * var->sharing_weight;
842         else
843           min_bound = MIN(min_bound, (var->bound * var->sharing_weight));
844         XBT_DEBUG("Updated min_bound=%f", min_bound);
845       }
846     }
847
848     while ((var = (lmm_variable_t)xbt_swag_getFirst(var_list))) {
849       int i;
850
851       if (min_bound < 0) {
852         //If no variable could reach its bound, deal iteratively the constraints usage ( at worst one constraint is
853         // saturated at each cycle)
854         var->value = min_usage / var->sharing_weight;
855         // XBT_DEBUG("Setting %p (%d) value to %f\n", var, var->id_int, var->value);
856         XBT_DEBUG("Setting var (%d) value to %f\n", var->id_int, var->value);
857       } else {
858          //If there exist a variable that can reach its bound, only update it (and other with the same bound) for now.
859          if (double_equals(min_bound, var->bound * var->sharing_weight, sg_maxmin_precision)) {
860            var->value = var->bound;
861            XBT_DEBUG("Setting %p (%d) value to %f\n", var, var->id_int, var->value);
862          } else {
863            // Variables which bound is different are not considered for this cycle, but they will be afterwards.
864            XBT_DEBUG("Do not consider %p (%d) \n", var, var->id_int);
865            xbt_swag_remove(var, var_list);
866            continue;
867          }
868       }
869       XBT_DEBUG("Min usage: %f, Var(%d)->weight: %f, Var(%d)->value: %f ", min_usage, var->id_int, var->sharing_weight,
870                 var->id_int, var->value);
871
872       /* Update the usage of contraints where this variable is involved */
873       for (i = 0; i < var->cnsts_number; i++) {
874         lmm_element_t elem    = &var->cnsts[i];
875         lmm_constraint_t cnst = elem->constraint;
876         if (cnst->sharing_policy) {
877           //Remember: shared constraints require that sum(elem->value * var->value) < cnst->bound
878           double_update(&(cnst->remaining), elem->consumption_weight * var->value, cnst->bound * sg_maxmin_precision);
879           double_update(&(cnst->usage), elem->consumption_weight / var->sharing_weight, sg_maxmin_precision);
880           //If the constraint is saturated, remove it from the set of active constraints (light_tab)
881           if (not double_positive(cnst->usage, sg_maxmin_precision) ||
882               not double_positive(cnst->remaining, cnst->bound * sg_maxmin_precision)) {
883             if (cnst->cnst_light) {
884               int index = (cnst->cnst_light-cnst_light_tab);
885               XBT_DEBUG("index: %d \t cnst_light_num: %d \t || usage: %f remaining: %f bound: %f  ",
886                          index,cnst_light_num, cnst->usage, cnst->remaining, cnst->bound);
887               //XBT_DEBUG("index: %d \t cnst_light_num: %d \t || \t cnst: %p \t cnst->cnst_light: %p "
888               //          "\t cnst_light_tab: %p usage: %f remaining: %f bound: %f  ", index,cnst_light_num,
889               //          cnst, cnst->cnst_light, cnst_light_tab, cnst->usage, cnst->remaining, cnst->bound);
890               cnst_light_tab[index]=cnst_light_tab[cnst_light_num-1];
891               cnst_light_tab[index].cnst->cnst_light = &cnst_light_tab[index];
892               cnst_light_num--;
893               cnst->cnst_light = nullptr;
894             }
895           } else {
896             cnst->cnst_light->remaining_over_usage = cnst->remaining / cnst->usage;
897           }
898           make_elem_inactive(elem);
899         } else {
900           //Remember: non-shared constraints only require that max(elem->value * var->value) < cnst->bound
901           cnst->usage = 0.0;
902           make_elem_inactive(elem);
903           xbt_swag_t elem_list = &(cnst->enabled_element_set);
904           xbt_swag_foreach(_elem, elem_list) {
905             elem = (lmm_element_t)_elem;
906             xbt_assert(elem->variable->sharing_weight > 0);
907             if (elem->variable->value > 0) continue;
908             if (elem->consumption_weight > 0)
909               cnst->usage = MAX(cnst->usage, elem->consumption_weight / elem->variable->sharing_weight);
910           }
911           //If the constraint is saturated, remove it from the set of active constraints (light_tab)
912           if (not double_positive(cnst->usage, sg_maxmin_precision) ||
913               not double_positive(cnst->remaining, cnst->bound * sg_maxmin_precision)) {
914             if(cnst->cnst_light) {
915               int index = (cnst->cnst_light-cnst_light_tab);
916               XBT_DEBUG("index: %d \t cnst_light_num: %d \t || \t cnst: %p \t cnst->cnst_light: %p "
917                         "\t cnst_light_tab: %p usage: %f remaining: %f bound: %f  ", index,cnst_light_num, cnst,
918                         cnst->cnst_light, cnst_light_tab, cnst->usage, cnst->remaining, cnst->bound);
919               cnst_light_tab[index]=cnst_light_tab[cnst_light_num-1];
920               cnst_light_tab[index].cnst->cnst_light = &cnst_light_tab[index];
921               cnst_light_num--;
922               cnst->cnst_light = nullptr;
923             }
924           } else {
925             cnst->cnst_light->remaining_over_usage = cnst->remaining / cnst->usage;
926             xbt_assert(cnst->active_element_set.count>0, "Should not keep a maximum constraint that has no active"
927                        " element! You want to check the maxmin precision and possible rounding effects." );
928           }
929         }
930       }
931       xbt_swag_remove(var, var_list);
932     }
933
934     /* Find out which variables reach the maximum */
935     min_usage = -1;
936     min_bound = -1;
937     saturated_constraint_set->pos = 0;
938     int pos;
939     for(pos=0; pos<cnst_light_num; pos++){
940       xbt_assert(cnst_light_tab[pos].cnst->active_element_set.count>0, "Cannot saturate more a constraint that has"
941                  " no active element! You may want to change the maxmin precision (--cfg=maxmin/precision:<new_value>)"
942                  " because of possible rounding effects.\n\tFor the record, the usage of this constraint is %g while "
943                  "the maxmin precision to which it is compared is %g.\n\tThe usage of the previous constraint is %g.",
944                  cnst_light_tab[pos].cnst->usage, sg_maxmin_precision, cnst_light_tab[pos-1].cnst->usage);
945       saturated_constraint_set_update(cnst_light_tab[pos].remaining_over_usage, pos, saturated_constraint_set,
946                                       &min_usage);
947     }
948
949     saturated_variable_set_update(cnst_light_tab, saturated_constraint_set, sys);
950
951   } while (cnst_light_num > 0);
952
953   sys->modified = 0;
954   if (sys->selective_update_active)
955     lmm_remove_all_modified_set(sys);
956
957   if (XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug)) {
958     lmm_print(sys);
959   }
960
961   lmm_check_concurrency(sys);
962
963   xbt_free(saturated_constraint_set->data);
964   xbt_free(saturated_constraint_set);
965   xbt_free(cnst_light_tab);
966   XBT_OUT();
967 }
968
969 /** \brief Attribute the value bound to var->bound.
970  *
971  *  \param sys the lmm_system_t
972  *  \param var the lmm_variable_t
973  *  \param bound the new bound to associate with var
974  *
975  *  Makes var->bound equal to bound. Whenever this function is called a change is  signed in the system. To
976  *  avoid false system changing detection it is a good idea to test (bound != 0) before calling it.
977  */
978 void lmm_update_variable_bound(lmm_system_t sys, lmm_variable_t var, double bound)
979 {
980   sys->modified = 1;
981   var->bound = bound;
982
983   if (var->cnsts_number)
984     lmm_update_modified_set(sys, var->cnsts[0].constraint);
985 }
986
987 int lmm_concurrency_slack(lmm_constraint_t cnstr){
988   //FIXME MARTIN: Replace by infinite value std::numeric_limits<int>::(max)(), or something better within Simgrid?
989   if(cnstr->concurrency_limit<0)
990     return 666;
991
992   return  cnstr->concurrency_limit - cnstr->concurrency_current;
993 }
994
995 /** \brief Measure the minimum concurrency slack across all constraints where the given var is involved */
996 int lmm_cnstrs_min_concurrency_slack(lmm_variable_t var){
997   int minslack = std::numeric_limits<int>::max();
998   for (int i = 0; i < var->cnsts_number; i++) {
999     int slack = lmm_concurrency_slack(var->cnsts[i].constraint);
1000
1001     //This is only an optimization, to avoid looking at more constraints when slack is already zero
1002     //Disable it when debugging to let lmm_concurrency_slack catch nasty things
1003     if (not slack && not XBT_LOG_ISENABLED(surf_maxmin, xbt_log_priority_debug))
1004       return 0;
1005
1006     if(minslack>slack)
1007       minslack=slack;
1008   }
1009
1010   return minslack;
1011 }
1012
1013 /* /Check if a variable can be enabled
1014  *
1015  * Make sure to set staged_weight before, if your intent is only to check concurrency
1016  */
1017 int lmm_can_enable_var(lmm_variable_t var){
1018   return var->staged_weight>0 && lmm_cnstrs_min_concurrency_slack(var)>=var->concurrency_share;
1019 }
1020
1021 //Small remark: In this implementation of lmm_enable_var and lmm_disable_var, we will meet multiple times with var when
1022 // running lmm_update_modified_set.
1023 //A priori not a big performance issue, but we might do better by calling lmm_update_modified_set within the for loops
1024 // (after doing the first for enabling==1, and before doing the last for disabling==1)
1025 void lmm_enable_var(lmm_system_t sys, lmm_variable_t var){
1026   xbt_assert(lmm_can_enable_var(var));
1027
1028   var->sharing_weight = var->staged_weight;
1029   var->staged_weight = 0;
1030
1031   // Enabling the variable, move to var to list head. Subtlety is: here, we need to call lmm_update_modified_set AFTER
1032   // moving at least one element of var.
1033
1034   xbt_swag_remove(var, &(sys->variable_set));
1035   xbt_swag_insert_at_head(var, &(sys->variable_set));
1036   for (int i = 0; i < var->cnsts_number; i++) {
1037     lmm_element_t elem = &var->cnsts[i];
1038     xbt_swag_remove(elem, &(elem->constraint->disabled_element_set));
1039     xbt_swag_insert_at_head(elem, &(elem->constraint->enabled_element_set));
1040     lmm_increase_concurrency(elem);
1041   }
1042   if (var->cnsts_number)
1043     lmm_update_modified_set(sys, var->cnsts[0].constraint);
1044
1045   //When used within lmm_on_disabled_var, we would get an assertion fail, because transiently there can be variables
1046   // that are staged and could be activated.
1047   //Anyway, caller functions all call lmm_check_concurrency() in the end.
1048   //  lmm_check_concurrency(sys);
1049 }
1050
1051 void lmm_disable_var(lmm_system_t sys, lmm_variable_t var){
1052   xbt_assert(not var->staged_weight, "Staged weight should have been cleared");
1053   // Disabling the variable, move to var to list tail. Subtlety is: here, we need to call lmm_update_modified_set BEFORE
1054   // moving the last element of var.
1055   xbt_swag_remove(var, &(sys->variable_set));
1056   xbt_swag_insert_at_tail(var, &(sys->variable_set));
1057   if (var->cnsts_number)
1058     lmm_update_modified_set(sys, var->cnsts[0].constraint);
1059   for (int i = 0; i < var->cnsts_number; i++) {
1060     lmm_element_t elem = &var->cnsts[i];
1061     xbt_swag_remove(elem, &(elem->constraint->enabled_element_set));
1062     xbt_swag_insert_at_tail(elem, &(elem->constraint->disabled_element_set));
1063
1064     xbt_swag_remove(elem, &(elem->constraint->active_element_set));
1065
1066     lmm_decrease_concurrency(elem);
1067   }
1068
1069   var->sharing_weight = 0.0;
1070   var->staged_weight=0.0;
1071   var->value = 0.0;
1072   lmm_check_concurrency(sys);
1073 }
1074
1075 /* /brief Find variables that can be enabled and enable them.
1076  *
1077  * Assuming that the variable has already been removed from non-zero weights
1078  * Can we find a staged variable to add?
1079  * If yes, check that none of the constraints that this variable is involved in is at the limit of its concurrency
1080  * And then add it to enabled variables
1081  */
1082 void lmm_on_disabled_var(lmm_system_t sys, lmm_constraint_t cnstr){
1083
1084   if(cnstr->concurrency_limit<0)
1085     return;
1086
1087   int numelem = xbt_swag_size(&(cnstr->disabled_element_set));
1088   if (not numelem)
1089     return;
1090
1091   lmm_element_t elem = (lmm_element_t)xbt_swag_getFirst(&(cnstr->disabled_element_set));
1092
1093   //Cannot use xbt_swag_foreach, because lmm_enable_var will modify disabled_element_set.. within the loop
1094   while (numelem-- && elem) {
1095
1096     lmm_element_t nextelem = (lmm_element_t)xbt_swag_getNext(elem, cnstr->disabled_element_set.offset);
1097
1098     if (elem->variable->staged_weight>0 ){
1099       //Found a staged variable
1100       //TODOLATER: Add random timing function to model reservation protocol fuzziness? Then how to make sure that
1101       //staged variables will eventually be called?
1102       if(lmm_can_enable_var(elem->variable)){
1103         lmm_enable_var(sys,elem->variable);
1104       }
1105     }
1106
1107     xbt_assert(cnstr->concurrency_current<=cnstr->concurrency_limit,"Concurrency overflow!");
1108     if(cnstr->concurrency_current==cnstr->concurrency_limit)
1109       break;
1110
1111     elem = nextelem;
1112   }
1113
1114   //We could get an assertion fail, because transiently there can be variables that are staged and could be activated.
1115   //And we need to go through all constraints of the disabled var before getting back a coherent state.
1116   //Anyway, caller functions all call lmm_check_concurrency() in the end.
1117   //  lmm_check_concurrency(sys);
1118 }
1119
1120 /* \brief update the weight of a variable, and enable/disable it.
1121  * @return Returns whether a change was made
1122  */
1123 void lmm_update_variable_weight(lmm_system_t sys, lmm_variable_t var, double weight)
1124 {
1125   xbt_assert(weight>=0,"Variable weight should not be negative!");
1126
1127   if (weight == var->sharing_weight)
1128     return;
1129
1130   int enabling_var  = (weight > 0 && var->sharing_weight <= 0);
1131   int disabling_var = (weight <= 0 && var->sharing_weight > 0);
1132
1133   XBT_IN("(sys=%p, var=%p, weight=%f)", sys, var, weight);
1134
1135   sys->modified = 1;
1136
1137   //Are we enabling this variable?
1138   if (enabling_var){
1139     var->staged_weight = weight;
1140     int minslack       = lmm_cnstrs_min_concurrency_slack(var);
1141     if (minslack < var->concurrency_share) {
1142       XBT_DEBUG("Staging var (instead of enabling) because min concurrency slack %i, with weight %f and concurrency"
1143                 " share %i", minslack, weight, var->concurrency_share);
1144       return;
1145     }
1146     XBT_DEBUG("Enabling var with min concurrency slack %i", minslack);
1147     lmm_enable_var(sys,var);
1148   } else if (disabling_var){
1149     //Are we disabling this variable?
1150     lmm_disable_var(sys,var);
1151   } else {
1152     var->sharing_weight = weight;
1153   }
1154
1155   lmm_check_concurrency(sys);
1156
1157   XBT_OUT();
1158 }
1159
1160 double lmm_get_variable_weight(lmm_variable_t var)
1161 {
1162   return var->sharing_weight;
1163 }
1164
1165 void lmm_update_constraint_bound(lmm_system_t sys, lmm_constraint_t cnst, double bound)
1166 {
1167   sys->modified = 1;
1168   lmm_update_modified_set(sys, cnst);
1169   cnst->bound = bound;
1170 }
1171
1172 int lmm_constraint_used(lmm_system_t sys, lmm_constraint_t cnst)
1173 {
1174   return xbt_swag_belongs(cnst, &(sys->active_constraint_set));
1175 }
1176
1177 inline lmm_constraint_t lmm_get_first_active_constraint(lmm_system_t sys)
1178 {
1179   return (lmm_constraint_t)xbt_swag_getFirst(&(sys->active_constraint_set));
1180 }
1181
1182 inline lmm_constraint_t lmm_get_next_active_constraint(lmm_system_t sys, lmm_constraint_t cnst)
1183 {
1184   return (lmm_constraint_t)xbt_swag_getNext(cnst, (sys->active_constraint_set).offset);
1185 }
1186
1187 /** \brief Update the constraint set propagating recursively to other constraints so the system should not be entirely
1188  *  computed.
1189  *
1190  *  \param sys the lmm_system_t
1191  *  \param cnst the lmm_constraint_t affected by the change
1192  *
1193  *  A recursive algorithm to optimize the system recalculation selecting only constraints that have changed. Each
1194  *  constraint change is propagated to the list of constraints for each variable.
1195  */
1196 static void lmm_update_modified_set_rec(lmm_system_t sys, lmm_constraint_t cnst)
1197 {
1198   void* _elem;
1199
1200   //TODOLATER: Why lmm_modified_set has been changed in git version 2392B5157...? Looks equivalent logically and less obvious..
1201   xbt_swag_foreach(_elem, &cnst->enabled_element_set) {
1202     lmm_variable_t var = ((lmm_element_t)_elem)->variable;
1203     s_lmm_element_t *cnsts = var->cnsts;
1204     int i;
1205     for (i = 0; var->visited != sys->visited_counter && i < var->cnsts_number ; i++) {
1206       if (cnsts[i].constraint != cnst && not xbt_swag_belongs(cnsts[i].constraint, &sys->modified_constraint_set)) {
1207         xbt_swag_insert(cnsts[i].constraint, &sys->modified_constraint_set);
1208         lmm_update_modified_set_rec(sys, cnsts[i].constraint);
1209       }
1210     }
1211     //var will be ignored in later visits as long as sys->visited_counter does not move
1212     var->visited = sys->visited_counter;
1213   }
1214 }
1215
1216 static void lmm_update_modified_set(lmm_system_t sys, lmm_constraint_t cnst)
1217 {
1218   /* nothing to do if selective update isn't active */
1219   if (sys->selective_update_active && not xbt_swag_belongs(cnst, &sys->modified_constraint_set)) {
1220     xbt_swag_insert(cnst, &sys->modified_constraint_set);
1221     lmm_update_modified_set_rec(sys, cnst);
1222   }
1223 }
1224
1225 /** \brief Remove all constraints of the modified_constraint_set.
1226  *
1227  *  \param sys the lmm_system_t
1228  */
1229 static void lmm_remove_all_modified_set(lmm_system_t sys)
1230 {
1231   //We cleverly un-flag all variables just by incrementing sys->visited_counter
1232   //In effect, the var->visited value will no more be equal to sys->visited counter
1233   //To be clean, when visited counter has wrapped around, we force these var->visited values so that variables that
1234   //were in the modified a long (long long) time ago are not wrongly skipped here, which would lead to very nasty bugs
1235   //(i.e. not readibily reproducible, and requiring a lot of run time before happening).
1236   if (++sys->visited_counter == 1) {
1237     /* the counter wrapped around, reset each variable->visited */
1238   void *_var;
1239     xbt_swag_foreach(_var, &sys->variable_set)
1240       ((lmm_variable_t)_var)->visited = 0;
1241   }
1242   xbt_swag_reset(&sys->modified_constraint_set);
1243 }
1244
1245 /**
1246  * Returns resource load (in flop per second, or byte per second, or similar)
1247  *
1248  * If the resource is shared (the default case), the load is sum of resource usage made by every variables located on
1249  * this resource.
1250  *
1251  * If the resource is not shared (ie in FATPIPE mode), then the load is the max (not the sum) of all resource usages
1252  * located on this resource.
1253  *
1254  * \param cnst the lmm_constraint_t associated to the resource
1255  */
1256 double lmm_constraint_get_usage(lmm_constraint_t cnst) {
1257   double usage         = 0.0;
1258   xbt_swag_t elem_list = &(cnst->enabled_element_set);
1259   void* _elem;
1260
1261   xbt_swag_foreach(_elem, elem_list)
1262   {
1263     lmm_element_t elem = (lmm_element_t)_elem;
1264     if (elem->consumption_weight > 0) {
1265       if (cnst->sharing_policy)
1266         usage += elem->consumption_weight * elem->variable->value;
1267       else if (usage < elem->consumption_weight * elem->variable->value)
1268         usage = std::max(usage, elem->consumption_weight * elem->variable->value);
1269     }
1270   }
1271   return usage;
1272 }
1273
1274 int lmm_constraint_get_variable_amount(lmm_constraint_t cnst) {
1275   int usage = 0;
1276   xbt_swag_t elem_list = &(cnst->enabled_element_set);
1277   void *_elem;
1278
1279   xbt_swag_foreach(_elem, elem_list) {
1280     lmm_element_t elem = (lmm_element_t)_elem;
1281     if (elem->consumption_weight > 0)
1282       usage++;
1283   }
1284  return usage;
1285 }