Logo AND Algorithmique Numérique Distribuée

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