Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
b87f73c348fc554e30937f087f2b80472dc0040e
[simgrid.git] / src / surf / surf_interface.cpp
1 #include "surf_private.h"
2 #include "surf_interface.hpp"
3 #include "network_interface.hpp"
4 #include "cpu_interface.hpp"
5 #include "workstation_interface.hpp"
6 #include "vm_workstation_interface.hpp"
7 #include "simix/smx_host_private.h"
8 #include "surf_routing.hpp"
9 #include "simgrid/sg_config.h"
10 #include "mc/mc.h"
11
12 extern "C" {
13 XBT_LOG_NEW_CATEGORY(surf, "All SURF categories");
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_kernel, surf,
15                                 "Logging specific to SURF (kernel)");
16 }
17
18
19
20 /*********
21  * Utils *
22  *********/
23
24 /* This function is a pimple that we ought to fix. But it won't be easy.
25  *
26  * The surf_solve() function does properly return the set of actions that changed.
27  * Instead, each model change a global data, and then the caller of surf_solve must
28  * pick into these sets of action_failed and action_done.
29  *
30  * This was not clean but ok as long as we didn't had to restart the processes when the resource comes back up.
31  * We worked by putting sentinel actions on every resources we are interested in,
32  * so that surf informs us if/when the corresponding resource fails.
33  *
34  * But this does not work to get Simix informed of when a resource comes back up, and this is where this pimple comes.
35  * We have a set of resources that are currently down and for which simix needs to know when it comes back up.
36  * And the current function is called *at every simulation step* to sweep over that set, searching for a resource
37  * that was turned back up in the meanwhile. This is UGLY and slow.
38  *
39  * The proper solution would be to not rely on globals for the action_failed and action_done swags.
40  * They must be passed as parameter by the caller (the handling of these actions in simix may let you
41  * think that these two sets can be merged, but their handling in SimDag induce the contrary unless this
42  * simdag code can check by itself whether the action is done of failed -- seems very doable, but yet more
43  * cleanup to do).
44  *
45  * Once surf_solve() is passed the set of actions that changed, you want to add a new set of resources back up
46  * as parameter to this function. You also want to add a boolean field "restart_watched" to each resource, and
47  * make sure that whenever a resource with this field enabled comes back up, it's added to that set so that Simix
48  * sees it and react accordingly. This would kill that need for surf to call simix.
49  *
50  */
51
52 static void remove_watched_host(void *key)
53 {
54   xbt_dict_remove(watched_hosts_lib, *(char**)key);
55 }
56
57 /*void surf_watched_hosts(void)
58 {
59   char *key;
60   void *host;
61   xbt_dict_cursor_t cursor;
62   xbt_dynar_t hosts = xbt_dynar_new(sizeof(char*), NULL);
63
64   XBT_DEBUG("Check for host SURF_RESOURCE_ON on watched_hosts_lib");
65   xbt_dict_foreach(watched_hosts_lib, cursor, key, host)
66   {
67     if(SIMIX_host_get_state((smx_host_t)host) == SURF_RESOURCE_ON){
68       XBT_INFO("Restart processes on host: %s", SIMIX_host_get_name((smx_host_t)host));
69       SIMIX_host_autorestart((smx_host_t)host);
70       xbt_dynar_push_as(hosts, char*, key);
71     }
72     else
73       XBT_DEBUG("See SURF_RESOURCE_OFF on host: %s",key);
74   }
75   xbt_dynar_map(hosts, remove_watched_host);
76   xbt_dynar_free(&hosts);
77 }*/
78
79 /* model_list_invoke contains only surf_workstation and surf_vm_workstation.
80  * The callback functions of cpu_model and network_model will be called from
81  * those of these workstation models. */
82 xbt_dynar_t model_list = NULL; /* for destroying all models correctly */
83 xbt_dynar_t model_list_invoke = NULL;  /* for invoking callbacks */
84
85 tmgr_history_t history = NULL;
86 lmm_system_t maxmin_system = NULL;
87 xbt_dynar_t surf_path = NULL;
88 xbt_dynar_t host_that_restart = NULL;
89 xbt_dict_t watched_hosts_lib;
90
91 /* Don't forget to update the option description in smx_config when you change this */
92 s_surf_model_description_t surf_network_model_description[] = {
93   {"LV08",
94    "Realistic network analytic model (slow-start modeled by multiplying latency by 10.4, bandwidth by .92; bottleneck sharing uses a payload of S=8775 for evaluating RTT). ",
95    surf_network_model_init_LegrandVelho},
96   {"Constant",
97    "Simplistic network model where all communication take a constant time (one second). This model provides the lowest realism, but is (marginally) faster.",
98    surf_network_model_init_Constant},
99   {"SMPI",
100    "Realistic network model specifically tailored for HPC settings (accurate modeling of slow start with correction factors on three intervals: < 1KiB, < 64 KiB, >= 64 KiB)",
101    surf_network_model_init_SMPI},
102   {"CM02",
103    "Legacy network analytic model (Very similar to LV08, but without corrective factors. The timings of small messages are thus poorly modeled).",
104    surf_network_model_init_CM02},
105 #ifdef HAVE_GTNETS
106   {"GTNets",
107    "Network pseudo-model using the GTNets simulator instead of an analytic model",
108    surf_network_model_init_GTNETS},
109 #endif
110 #ifdef HAVE_NS3
111   {"NS3",
112    "Network pseudo-model using the NS3 tcp model instead of an analytic model",
113   surf_network_model_init_NS3},
114 #endif
115   {"Reno",
116    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
117    surf_network_model_init_Reno},
118   {"Reno2",
119    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
120    surf_network_model_init_Reno2},
121   {"Vegas",
122    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
123    surf_network_model_init_Vegas},
124   {NULL, NULL, NULL}      /* this array must be NULL terminated */
125 };
126
127 s_surf_model_description_t surf_cpu_model_description[] = {
128   {"Cas01",
129    "Simplistic CPU model (time=size/power).",
130    surf_cpu_model_init_Cas01},
131   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
132 };
133
134 s_surf_model_description_t surf_workstation_model_description[] = {
135   {"default",
136    "Default workstation model. Currently, CPU:Cas01 and network:LV08 (with cross traffic enabled)",
137    surf_workstation_model_init_current_default},
138   {"compound",
139    "Workstation model that is automatically chosen if you change the network and CPU models",
140    surf_workstation_model_init_compound},
141   {"ptask_L07", "Workstation model somehow similar to Cas01+CM02 but allowing parallel tasks",
142    surf_workstation_model_init_ptask_L07},
143   {NULL, NULL, NULL}      /* this array must be NULL terminated */
144 };
145
146 s_surf_model_description_t surf_vm_workstation_model_description[] = {
147   {"default",
148    "Default vm workstation model.)",
149    surf_vm_workstation_model_init_current_default},
150   {NULL, NULL, NULL}      /* this array must be NULL terminated */
151 };
152
153 s_surf_model_description_t surf_optimization_mode_description[] = {
154   {"Lazy",
155    "Lazy action management (partial invalidation in lmm + heap in action remaining).",
156    NULL},
157   {"TI",
158    "Trace integration. Highly optimized mode when using availability traces (only available for the Cas01 CPU model for now).",
159     NULL},
160   {"Full",
161    "Full update of remaining and variables. Slow but may be useful when debugging.",
162    NULL},
163   {NULL, NULL, NULL}      /* this array must be NULL terminated */
164 };
165
166 s_surf_model_description_t surf_storage_model_description[] = {
167   {"default",
168    "Simplistic storage model.",
169    surf_storage_model_init_default},
170   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
171 };
172
173 #ifdef CONTEXT_THREADS
174 static xbt_parmap_t surf_parmap = NULL; /* parallel map on models */
175 #endif
176
177 double NOW = 0;
178 double *surf_mins = NULL; /* return value of share_resources for each model */
179 int surf_min_index;       /* current index in surf_mins */
180 double surf_min;               /* duration determined by surf_solve */
181
182 double surf_get_clock(void)
183 {
184   return NOW;
185 }
186
187 #ifdef _XBT_WIN32
188 # define FILE_DELIM "\\"
189 #else
190 # define FILE_DELIM "/"         /* FIXME: move to better location */
191 #endif
192
193 FILE *surf_fopen(const char *name, const char *mode)
194 {
195   unsigned int cpt;
196   char *path_elm = NULL;
197   char *buff;
198   FILE *file = NULL;
199
200   xbt_assert(name);
201
202   if (__surf_is_absolute_file_path(name))       /* don't mess with absolute file names */
203     return fopen(name, mode);
204
205   /* search relative files in the path */
206   xbt_dynar_foreach(surf_path, cpt, path_elm) {
207     buff = bprintf("%s" FILE_DELIM "%s", path_elm, name);
208     file = fopen(buff, mode);
209     free(buff);
210
211     if (file)
212       return file;
213   }
214   return NULL;
215 }
216
217 /*
218  * Returns the initial path. On Windows the initial path is
219  * the current directory for the current process in the other
220  * case the function returns "./" that represents the current
221  * directory on Unix/Linux platforms.
222  */
223
224 const char *__surf_get_initial_path(void)
225 {
226
227 #ifdef _XBT_WIN32
228   unsigned i;
229   char current_directory[MAX_PATH + 1] = { 0 };
230   unsigned int len = GetCurrentDirectory(MAX_PATH + 1, current_directory);
231   char root[4] = { 0 };
232
233   if (!len)
234     return NULL;
235
236   strncpy(root, current_directory, 3);
237
238   for (i = 0; i < MAX_DRIVE; i++) {
239     if (toupper(root[0]) == disk_drives_letter_table[i][0])
240       return disk_drives_letter_table[i];
241   }
242
243   return NULL;
244 #else
245   return "./";
246 #endif
247 }
248
249 /* The __surf_is_absolute_file_path() returns 1 if
250  * file_path is a absolute file path, in the other
251  * case the function returns 0.
252  */
253 int __surf_is_absolute_file_path(const char *file_path)
254 {
255 #ifdef _XBT_WIN32
256   WIN32_FIND_DATA wfd = { 0 };
257   HANDLE hFile = FindFirstFile(file_path, &wfd);
258
259   if (INVALID_HANDLE_VALUE == hFile)
260     return 0;
261
262   FindClose(hFile);
263   return 1;
264 #else
265   return (file_path[0] == '/');
266 #endif
267 }
268
269 /** Displays the long description of all registered models, and quit */
270 void model_help(const char *category, s_surf_model_description_t * table)
271 {
272   int i;
273   printf("Long description of the %s models accepted by this simulator:\n",
274          category);
275   for (i = 0; table[i].name; i++)
276     printf("  %s: %s\n", table[i].name, table[i].description);
277 }
278
279 int find_model_description(s_surf_model_description_t * table,
280                            const char *name)
281 {
282   int i;
283   char *name_list = NULL;
284
285   for (i = 0; table[i].name; i++)
286     if (!strcmp(name, table[i].name)) {
287       return i;
288     }
289   name_list = strdup(table[0].name);
290   for (i = 1; table[i].name; i++) {
291     name_list = (char *) xbt_realloc(name_list, strlen(name_list) + strlen(table[i].name) + 3);
292     strcat(name_list, ", ");
293     strcat(name_list, table[i].name);
294   }
295   xbt_die("Model '%s' is invalid! Valid models are: %s.", name, name_list);
296   return -1;
297 }
298
299 static XBT_INLINE void routing_asr_host_free(void *p)
300 {
301   delete ((RoutingEdgePtr) p);
302 }
303
304 static XBT_INLINE void routing_asr_prop_free(void *p)
305 {
306   xbt_dict_t elm = (xbt_dict_t) p;
307   xbt_dict_free(&elm);
308 }
309
310 static XBT_INLINE void surf_cpu_free(void *r)
311 {
312   delete dynamic_cast<CpuPtr>(static_cast<ResourcePtr>(r));
313 }
314
315 static XBT_INLINE void surf_link_free(void *r)
316 {
317   delete dynamic_cast<NetworkLinkPtr>(static_cast<ResourcePtr>(r));
318 }
319
320 static XBT_INLINE void surf_workstation_free(void *r)
321 {
322   delete dynamic_cast<WorkstationPtr>(static_cast<ResourcePtr>(r));
323 }
324
325
326 void sg_version(int *ver_major,int *ver_minor,int *ver_patch) {
327   *ver_major = SIMGRID_VERSION_MAJOR;
328   *ver_minor = SIMGRID_VERSION_MINOR;
329   *ver_patch = SIMGRID_VERSION_PATCH;
330 }
331
332 void surf_init(int *argc, char **argv)
333 {
334   XBT_DEBUG("Create all Libs");
335   host_lib = xbt_lib_new();
336   link_lib = xbt_lib_new();
337   as_router_lib = xbt_lib_new();
338   storage_lib = xbt_lib_new();
339   storage_type_lib = xbt_lib_new();
340   watched_hosts_lib = xbt_dict_new_homogeneous(NULL);
341
342   XBT_DEBUG("Add routing levels");
343   ROUTING_HOST_LEVEL = xbt_lib_add_level(host_lib,routing_asr_host_free);
344   ROUTING_ASR_LEVEL  = xbt_lib_add_level(as_router_lib,routing_asr_host_free);
345   ROUTING_PROP_ASR_LEVEL = xbt_lib_add_level(as_router_lib,routing_asr_prop_free);
346
347   XBT_DEBUG("Add SURF levels");
348   SURF_CPU_LEVEL = xbt_lib_add_level(host_lib,surf_cpu_free);
349   SURF_WKS_LEVEL = xbt_lib_add_level(host_lib,surf_workstation_free);
350   SURF_LINK_LEVEL = xbt_lib_add_level(link_lib,surf_link_free);
351
352   xbt_init(argc, argv);
353   if (!model_list)
354     model_list = xbt_dynar_new(sizeof(ModelPtr), NULL);
355   if (!model_list_invoke)
356     model_list_invoke = xbt_dynar_new(sizeof(ModelPtr), NULL);
357   if (!history)
358     history = tmgr_history_new();
359
360 #ifdef HAVE_TRACING
361   TRACE_add_start_function(TRACE_surf_alloc);
362   TRACE_add_end_function(TRACE_surf_release);
363 #endif
364
365   sg_config_init(argc, argv);
366
367   if (MC_is_active())
368     MC_memory_init();
369 }
370
371 void surf_exit(void)
372 {
373   unsigned int iter;
374   ModelPtr model = NULL;
375
376 #ifdef HAVE_TRACING
377   TRACE_end();                  /* Just in case it was not called by the upper
378                                  * layer (or there is no upper layer) */
379 #endif
380
381   sg_config_finalize();
382
383   xbt_dynar_foreach(model_list, iter, model)
384     delete model;
385   xbt_dynar_free(&model_list);
386   xbt_dynar_free(&model_list_invoke);
387   routing_exit();
388
389   if (maxmin_system) {
390     lmm_system_free(maxmin_system);
391     maxmin_system = NULL;
392   }
393   if (history) {
394     tmgr_history_free(history);
395     history = NULL;
396   }
397
398 #ifdef CONTEXT_THREADS
399   xbt_parmap_destroy(surf_parmap);
400 #endif
401
402   xbt_free(surf_mins);
403   surf_mins = NULL;
404
405   xbt_dynar_free(&host_that_restart);
406   xbt_dynar_free(&surf_path);
407
408   xbt_lib_free(&host_lib);
409   xbt_lib_free(&link_lib);
410   xbt_lib_free(&as_router_lib);
411   xbt_lib_free(&storage_lib);
412   xbt_lib_free(&storage_type_lib);
413
414   xbt_dict_free(&watched_hosts_lib);
415
416   tmgr_finalize();
417   surf_parse_lex_destroy();
418   surf_parse_free_callbacks();
419
420   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
421 }
422 /*********
423  * Model *
424  *********/
425
426 Model::Model(string name)
427   : p_maxminSystem(0),  m_name(name),
428     m_resOnCB(0), m_resOffCB(0),
429     m_actCancelCB(0), m_actSuspendCB(0), m_actResumeCB(0)
430 {
431   ActionPtr action = NULL;
432   p_readyActionSet = xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
433   p_runningActionSet = xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
434   p_failedActionSet = xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
435   p_doneActionSet = xbt_swag_new(xbt_swag_offset(*action, p_stateHookup));
436
437   p_modifiedSet = NULL;
438   p_actionHeap = NULL;
439   p_updateMechanism = UM_UNDEFINED;
440   m_selectiveUpdate = 0;
441 }
442
443 Model::~Model(){
444 xbt_swag_free(p_readyActionSet);
445 xbt_swag_free(p_runningActionSet);
446 xbt_swag_free(p_failedActionSet);
447 xbt_swag_free(p_doneActionSet);
448 }
449
450 double Model::shareResources(double now)
451 {
452   //FIXME: set the good function once and for all
453   if (p_updateMechanism == UM_LAZY)
454         return shareResourcesLazy(now);
455   else if (p_updateMechanism == UM_FULL)
456         return shareResourcesFull(now);
457   else
458         xbt_die("Invalid cpu update mechanism!");
459 }
460
461 double Model::shareResourcesLazy(double now)
462 {
463   ActionLmmPtr action = NULL;
464   double min = -1;
465   double value;
466
467   XBT_DEBUG
468       ("Before share resources, the size of modified actions set is %d",
469        xbt_swag_size(p_modifiedSet));
470
471   lmm_solve(p_maxminSystem);
472
473   XBT_DEBUG
474       ("After share resources, The size of modified actions set is %d",
475        xbt_swag_size(p_modifiedSet));
476
477   while((action = static_cast<ActionLmmPtr>(xbt_swag_extract(p_modifiedSet)))) {
478     int max_dur_flag = 0;
479
480     if (action->p_stateSet != p_runningActionSet)
481       continue;
482
483     /* bogus priority, skip it */
484     if (action->m_priority <= 0)
485       continue;
486
487     action->updateRemainingLazy(now);
488
489     min = -1;
490     value = lmm_variable_getvalue(action->p_variable);
491     if (value > 0) {
492       if (action->m_remains > 0) {
493         value = action->m_remains / value;
494         min = now + value;
495       } else {
496         value = 0.0;
497         min = now;
498       }
499     }
500
501     if ((action->m_maxDuration != NO_MAX_DURATION)
502         && (min == -1
503             || action->m_start +
504             action->m_maxDuration < min)) {
505       min = action->m_start +
506           action->m_maxDuration;
507       max_dur_flag = 1;
508     }
509
510     XBT_DEBUG("Action(%p) Start %lf Finish %lf Max_duration %lf", action,
511         action->m_start, now + value,
512         action->m_maxDuration);
513
514     if (min != -1) {
515       action->heapRemove(p_actionHeap);
516       action->heapInsert(p_actionHeap, min, max_dur_flag ? MAX_DURATION : NORMAL);
517       XBT_DEBUG("Insert at heap action(%p) min %lf now %lf", action, min,
518                 now);
519     } else DIE_IMPOSSIBLE;
520   }
521
522   //hereafter must have already the min value for this resource model
523   if (xbt_heap_size(p_actionHeap) > 0)
524     min = xbt_heap_maxkey(p_actionHeap) - now;
525   else
526     min = -1;
527
528   XBT_DEBUG("The minimum with the HEAP %lf", min);
529
530   return min;
531 }
532
533 double Model::shareResourcesFull(double /*now*/) {
534   THROW_UNIMPLEMENTED;
535 }
536
537
538 double Model::shareResourcesMaxMin(xbt_swag_t running_actions,
539                           lmm_system_t sys,
540                           void (*solve) (lmm_system_t))
541 {
542   void *_action = NULL;
543   ActionLmmPtr action = NULL;
544   double min = -1;
545   double value = -1;
546
547   solve(sys);
548
549   xbt_swag_foreach(_action, running_actions) {
550     action = dynamic_cast<ActionLmmPtr>(static_cast<ActionPtr>(_action));
551     value = lmm_variable_getvalue(action->p_variable);
552     if ((value > 0) || (action->m_maxDuration >= 0))
553       break;
554   }
555
556   if (!_action)
557     return -1.0;
558
559   if (value > 0) {
560     if (action->m_remains > 0)
561       min = action->m_remains / value;
562     else
563       min = 0.0;
564     if ((action->m_maxDuration >= 0) && (action->m_maxDuration < min))
565       min = action->m_maxDuration;
566   } else
567     min = action->m_maxDuration;
568
569
570   for (_action = xbt_swag_getNext(static_cast<ActionPtr>(action), running_actions->offset);
571        _action;
572        _action = xbt_swag_getNext(static_cast<ActionPtr>(action), running_actions->offset)) {
573         action = dynamic_cast<ActionLmmPtr>(static_cast<ActionPtr>(_action));
574     value = lmm_variable_getvalue(action->p_variable);
575     if (value > 0) {
576       if (action->m_remains > 0)
577         value = action->m_remains / value;
578       else
579         value = 0.0;
580       if (value < min) {
581         min = value;
582         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
583       }
584     }
585     if ((action->m_maxDuration >= 0) && (action->m_maxDuration < min)) {
586       min = action->m_maxDuration;
587       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
588     }
589   }
590   XBT_DEBUG("min value : %f", min);
591
592   return min;
593 }
594
595 void Model::updateActionsState(double now, double delta)
596 {
597   if (p_updateMechanism == UM_FULL)
598         updateActionsStateFull(now, delta);
599   else if (p_updateMechanism == UM_LAZY)
600         updateActionsStateLazy(now, delta);
601   else
602         xbt_die("Invalid cpu update mechanism!");
603 }
604
605 void Model::updateActionsStateLazy(double /*now*/, double /*delta*/)
606 {
607
608 }
609
610 void Model::updateActionsStateFull(double /*now*/, double /*delta*/)
611 {
612
613 }
614
615
616 void Model::addTurnedOnCallback(ResourceCallback rc)
617 {
618   m_resOnCB = rc;
619 }
620
621 void Model::notifyResourceTurnedOn(ResourcePtr r)
622 {
623   m_resOnCB(r);
624 }
625
626 void Model::addTurnedOffCallback(ResourceCallback rc)
627 {
628   m_resOffCB = rc;
629 }
630
631 void Model::notifyResourceTurnedOff(ResourcePtr r)
632 {
633   m_resOffCB(r);
634 }
635
636 void Model::addActionCancelCallback(ActionCallback ac)
637 {
638   m_actCancelCB = ac;
639 }
640
641 void Model::notifyActionCancel(ActionPtr a)
642 {
643   m_actCancelCB(a);
644 }
645
646 void Model::addActionResumeCallback(ActionCallback ac)
647 {
648   m_actResumeCB = ac;
649 }
650
651 void Model::notifyActionResume(ActionPtr a)
652 {
653   m_actResumeCB(a);
654 }
655
656 void Model::addActionSuspendCallback(ActionCallback ac)
657 {
658   m_actSuspendCB = ac;
659 }
660
661 void Model::notifyActionSuspend(ActionPtr a)
662 {
663   m_actSuspendCB(a);
664 }
665
666
667 /************
668  * Resource *
669  ************/
670
671 Resource::Resource(surf_model_t model, const char *name, xbt_dict_t props)
672   : m_name(xbt_strdup(name)), m_properties(props), p_model(model), m_running(true)
673 {}
674
675 Resource::Resource()
676 : m_name(NULL), m_properties(NULL), p_model(NULL)
677 {}
678
679 const char *Resource::getName()
680 {
681   return m_name;
682 }
683
684 xbt_dict_t Resource::getProperties()
685 {
686   return m_properties;
687 }
688
689 e_surf_resource_state_t Resource::getState()
690 {
691   return p_stateCurrent;
692 }
693
694 void Resource::setState(e_surf_resource_state_t state)
695 {
696   p_stateCurrent = state;
697 }
698
699 bool Resource::isOn()
700 {
701   return m_running;
702 }
703
704 void Resource::turnOn()
705 {
706   if (!m_running) {
707     m_running = true;
708     p_model->notifyResourceTurnedOn(this);
709   }
710 }
711
712 void Resource::turnOff()
713 {
714   if (m_running) {
715     m_running = false;
716     p_model->notifyResourceTurnedOff(this);
717   }
718 }
719
720 ResourceLmm::ResourceLmm(lmm_system_t system,
721                          double constraint_value,
722                          tmgr_history_t history,
723                          e_surf_resource_state_t state_init,
724                          tmgr_trace_t state_trace,
725                          double metric_peak,
726                          tmgr_trace_t metric_trace)
727 {
728   p_constraint = lmm_constraint_new(system, this, constraint_value);
729   p_stateCurrent = state_init;
730   if (state_trace)
731     p_stateEvent = tmgr_history_add_trace(history, state_trace, 0.0, 0, static_cast<ResourcePtr>(this));
732   p_power.scale = 1.0;
733   p_power.peak = metric_peak;
734   if (metric_trace)
735     p_power.event = tmgr_history_add_trace(history, metric_trace, 0.0, 0, static_cast<ResourcePtr>(this));
736   else
737     p_power.event = NULL;
738 }
739
740 /**********
741  * Action *
742  **********/
743
744 const char *surf_action_state_names[6] = {
745   "SURF_ACTION_READY",
746   "SURF_ACTION_RUNNING",
747   "SURF_ACTION_FAILED",
748   "SURF_ACTION_DONE",
749   "SURF_ACTION_TO_FREE",
750   "SURF_ACTION_NOT_IN_THE_SYSTEM"
751 };
752
753 Action::Action()
754 : m_refcount(1)
755 {}
756
757 Action::Action(ModelPtr model, double cost, bool failed)
758  : m_priority(1.0)
759  , m_failed(failed)
760  , m_start(surf_get_clock()), m_finish(-1.0)
761  , m_remains(cost)
762  , m_maxDuration(NO_MAX_DURATION)
763  , m_cost(cost)
764  , p_model(model)
765  , m_refcount(1)
766  , p_data(NULL)
767 {
768   #ifdef HAVE_TRACING
769     p_category = NULL;
770   #endif
771   p_stateHookup.prev = 0;
772   p_stateHookup.next = 0;
773   if (failed)
774     p_stateSet = p_model->p_failedActionSet;
775   else
776     p_stateSet = p_model->p_runningActionSet;
777
778   xbt_swag_insert(this, p_stateSet);
779 }
780
781 Action::~Action() {}
782
783 int Action::unref(){
784   DIE_IMPOSSIBLE;
785 }
786
787 void Action::cancel(){
788   DIE_IMPOSSIBLE;
789 }
790
791 void Action::recycle(){
792   DIE_IMPOSSIBLE;
793 }
794
795 e_surf_action_state_t Action::getState()
796 {
797   if (p_stateSet ==  p_model->p_readyActionSet)
798     return SURF_ACTION_READY;
799   if (p_stateSet ==  p_model->p_runningActionSet)
800     return SURF_ACTION_RUNNING;
801   if (p_stateSet ==  p_model->p_failedActionSet)
802     return SURF_ACTION_FAILED;
803   if (p_stateSet ==  p_model->p_doneActionSet)
804     return SURF_ACTION_DONE;
805   return SURF_ACTION_NOT_IN_THE_SYSTEM;
806 }
807
808 void Action::setState(e_surf_action_state_t state)
809 {
810   //surf_action_state_t action_state = &(action->model_type->states);
811   XBT_IN("(%p,%s)", this, surf_action_state_names[state]);
812   xbt_swag_remove(this, p_stateSet);
813
814   if (state == SURF_ACTION_READY)
815     p_stateSet = p_model->p_readyActionSet;
816   else if (state == SURF_ACTION_RUNNING)
817     p_stateSet = p_model->p_runningActionSet;
818   else if (state == SURF_ACTION_FAILED)
819     p_stateSet = p_model->p_failedActionSet;
820   else if (state == SURF_ACTION_DONE)
821     p_stateSet = p_model->p_doneActionSet;
822   else
823     p_stateSet = NULL;
824
825   if (p_stateSet)
826     xbt_swag_insert(this, p_stateSet);
827   XBT_OUT();
828 }
829
830 double Action::getStartTime()
831 {
832   return m_start;
833 }
834
835 double Action::getFinishTime()
836 {
837   /* keep the function behavior, some models (cpu_ti) change the finish time before the action end */
838   return m_remains == 0 ? m_finish : -1;
839 }
840
841 double Action::getRemains()
842 {
843   XBT_IN("(%p)", this);
844   XBT_OUT();
845   return m_remains;
846 }
847
848 void Action::setData(void* data)
849 {
850   p_data = data;
851 }
852
853 #ifdef HAVE_TRACING
854 void Action::setCategory(const char *category)
855 {
856   XBT_IN("(%p,%s)", this, category);
857   p_category = xbt_strdup(category);
858   XBT_OUT();
859 }
860 #endif
861
862 void Action::ref(){
863   m_refcount++;
864 }
865
866 void ActionLmm::setMaxDuration(double duration)
867 {
868   XBT_IN("(%p,%g)", this, duration);
869   m_maxDuration = duration;
870   if (p_model->p_updateMechanism == UM_LAZY)      // remove action from the heap
871     heapRemove(p_model->p_actionHeap);
872   XBT_OUT();
873 }
874
875 void ActionLmm::gapRemove() {}
876
877 void ActionLmm::setPriority(double priority)
878 {
879   XBT_IN("(%p,%g)", this, priority);
880   m_priority = priority;
881   lmm_update_variable_weight(p_model->p_maxminSystem, p_variable, priority);
882
883   if (p_model->p_updateMechanism == UM_LAZY)
884         heapRemove(p_model->p_actionHeap);
885   XBT_OUT();
886 }
887
888 void ActionLmm::cancel(){
889   setState(SURF_ACTION_FAILED);
890   if (p_model->p_updateMechanism == UM_LAZY) {
891     xbt_swag_remove(this, p_model->p_modifiedSet);
892     heapRemove(p_model->p_actionHeap);
893   }
894 }
895
896 int ActionLmm::unref(){
897   m_refcount--;
898   if (!m_refcount) {
899         xbt_swag_remove(static_cast<ActionPtr>(this), p_stateSet);
900         if (p_variable)
901           lmm_variable_free(p_model->p_maxminSystem, p_variable);
902         if (p_model->p_updateMechanism == UM_LAZY) {
903           /* remove from heap */
904           heapRemove(p_model->p_actionHeap);
905           xbt_swag_remove(this, p_model->p_modifiedSet);
906     }
907 #ifdef HAVE_TRACING
908     xbt_free(p_category);
909 #endif
910         delete this;
911         return 1;
912   }
913   return 0;
914 }
915
916 void ActionLmm::suspend()
917 {
918   XBT_IN("(%p)", this);
919   if (m_suspended != 2) {
920     lmm_update_variable_weight(p_model->p_maxminSystem, p_variable, 0.0);
921     m_suspended = 1;
922     if (p_model->p_updateMechanism == UM_LAZY)
923       heapRemove(p_model->p_actionHeap);
924   }
925   XBT_OUT();
926 }
927
928 void ActionLmm::resume()
929 {
930   XBT_IN("(%p)", this);
931   if (m_suspended != 2) {
932     lmm_update_variable_weight(p_model->p_maxminSystem, p_variable, m_priority);
933     m_suspended = 0;
934     if (p_model->p_updateMechanism == UM_LAZY)
935       heapRemove(p_model->p_actionHeap);
936   }
937   XBT_OUT();
938 }
939
940 bool ActionLmm::isSuspended()
941 {
942   return m_suspended == 1;
943 }
944 /* insert action on heap using a given key and a hat (heap_action_type)
945  * a hat can be of three types for communications:
946  *
947  * NORMAL = this is a normal heap entry stating the date to finish transmitting
948  * LATENCY = this is a heap entry to warn us when the latency is payed
949  * MAX_DURATION =this is a heap entry to warn us when the max_duration limit is reached
950  */
951 void ActionLmm::heapInsert(xbt_heap_t heap, double key, enum heap_action_type hat)
952 {
953   m_hat = hat;
954   xbt_heap_push(heap, this, key);
955 }
956
957 void ActionLmm::heapRemove(xbt_heap_t heap)
958 {
959   m_hat = NOTSET;
960   if (m_indexHeap >= 0) {
961     xbt_heap_remove(heap, m_indexHeap);
962   }
963 }
964
965 /* added to manage the communication action's heap */
966 void surf_action_lmm_update_index_heap(void *action, int i) {
967   ((ActionLmmPtr)action)->updateIndexHeap(i);
968 }
969
970 void ActionLmm::updateIndexHeap(int i) {
971   m_indexHeap = i;
972 }
973
974 double ActionLmm::getRemains()
975 {
976   XBT_IN("(%p)", this);
977   /* update remains before return it */
978   if (p_model->p_updateMechanism == UM_LAZY)      /* update remains before return it */
979     updateRemainingLazy(surf_get_clock());
980   XBT_OUT();
981   return m_remains;
982 }
983
984 //FIXME split code in the right places
985 void ActionLmm::updateRemainingLazy(double now)
986 {
987   double delta = 0.0;
988
989   if(p_model == static_cast<ModelPtr>(surf_network_model))
990   {
991     if (m_suspended != 0)
992       return;
993   }
994   else
995   {
996     xbt_assert(p_stateSet == p_model->p_runningActionSet,
997         "You're updating an action that is not running.");
998
999       /* bogus priority, skip it */
1000     xbt_assert(m_priority > 0,
1001         "You're updating an action that seems suspended.");
1002   }
1003
1004   delta = now - m_lastUpdate;
1005
1006   if (m_remains > 0) {
1007     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
1008     double_update(&m_remains, m_lastValue * delta);
1009
1010 #ifdef HAVE_TRACING
1011     if (p_model == static_cast<ModelPtr>(surf_cpu_model_pm) && TRACE_is_enabled()) {
1012       ResourcePtr cpu = static_cast<ResourcePtr>(lmm_constraint_id(lmm_get_cnst_from_var(p_model->p_maxminSystem, p_variable, 0)));
1013       TRACE_surf_host_set_utilization(cpu->m_name, p_category, m_lastValue, m_lastUpdate, now - m_lastUpdate);
1014     }
1015 #endif
1016     XBT_DEBUG("Updating action(%p): remains is now %f", this, m_remains);
1017   }
1018
1019   if(p_model == static_cast<ModelPtr>(surf_network_model))
1020   {
1021     if (m_maxDuration != NO_MAX_DURATION)
1022       double_update(&m_maxDuration, delta);
1023
1024     //FIXME: duplicated code
1025     if ((m_remains <= 0) &&
1026         (lmm_get_variable_weight(p_variable) > 0)) {
1027       m_finish = surf_get_clock();
1028       setState(SURF_ACTION_DONE);
1029       heapRemove(p_model->p_actionHeap);
1030     } else if (((m_maxDuration != NO_MAX_DURATION)
1031         && (m_maxDuration <= 0))) {
1032       m_finish = surf_get_clock();
1033       setState(SURF_ACTION_DONE);
1034       heapRemove(p_model->p_actionHeap);
1035     }
1036   }
1037
1038   m_lastUpdate = now;
1039   m_lastValue = lmm_variable_getvalue(p_variable);
1040 }
1041
1042 /*void Action::cancel()
1043 {
1044   p_model->notifyActionCancel(this);
1045 }
1046
1047 void Action::suspend()
1048 {
1049   p_model->notifyActionSuspend(this);
1050 }
1051
1052 void Action::resume()
1053 {
1054   p_model->notifyActionResume(this);
1055 }
1056
1057 bool Action::isSuspended()
1058 {
1059   return false;
1060 }*/
1061