Logo AND Algorithmique Numérique Distribuée

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