Logo AND Algorithmique Numérique Distribuée

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