Logo AND Algorithmique Numérique Distribuée

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