Logo AND Algorithmique Numérique Distribuée

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