Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
kill the portable header
[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/internal_config.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 #if 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 #if 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 _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 _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 _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 _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 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   if (host_list != nullptr) // Already initialized
270     return;
271
272   XBT_DEBUG("Create all Libs");
273   host_list = xbt_dict_new_homogeneous([](void*p) {
274     simgrid::s4u::Host* host = static_cast<simgrid::s4u::Host*>(p);
275     simgrid::s4u::Host::onDestruction(*host);
276     delete host;
277   });
278   USER_HOST_LEVEL = simgrid::s4u::Host::extension_create(NULL);
279
280   as_router_lib = xbt_lib_new();
281   storage_lib = xbt_lib_new();
282   storage_type_lib = xbt_lib_new();
283   file_lib = xbt_lib_new();
284   watched_hosts_lib = xbt_dict_new_homogeneous(NULL);
285
286
287   XBT_DEBUG("Add routing levels");
288   ROUTING_PROP_ASR_LEVEL = xbt_lib_add_level(as_router_lib, NULL);
289
290   XBT_DEBUG("Add SURF levels");
291   simgrid::surf::HostImpl::classInit();
292   SURF_STORAGE_LEVEL = xbt_lib_add_level(storage_lib,surf_storage_free);
293
294   xbt_init(argc, argv);
295   if (!all_existing_models)
296     all_existing_models = xbt_dynar_new(sizeof(simgrid::surf::Model*), NULL);
297   if (!model_list_invoke)
298     model_list_invoke = xbt_dynar_new(sizeof(simgrid::surf::Model*), NULL);
299   if (!future_evt_set)
300     future_evt_set = new simgrid::trace_mgr::future_evt_set();
301
302   TRACE_add_start_function(TRACE_surf_alloc);
303   TRACE_add_end_function(TRACE_surf_release);
304
305   sg_config_init(argc, argv);
306
307   if (MC_is_active())
308     MC_memory_init();
309 }
310
311 void surf_exit(void)
312 {
313   unsigned int iter;
314   simgrid::surf::Model *model = NULL;
315
316   TRACE_end();                  /* Just in case it was not called by the upper
317                                  * layer (or there is no upper layer) */
318
319   sg_config_finalize();
320
321   xbt_dynar_free(&host_that_restart);
322   xbt_dynar_free(&surf_path);
323
324   xbt_dict_free(&host_list);
325   xbt_lib_free(&as_router_lib);
326   xbt_lib_free(&storage_lib);
327   sg_link_exit();
328   xbt_lib_free(&storage_type_lib);
329   xbt_lib_free(&file_lib);
330   xbt_dict_free(&watched_hosts_lib);
331
332   xbt_dynar_foreach(all_existing_models, iter, model)
333     delete model;
334   xbt_dynar_free(&all_existing_models);
335   xbt_dynar_free(&model_list_invoke);
336   routing_exit();
337
338   simgrid::surf::surfExitCallbacks();
339
340   if (future_evt_set) {
341     delete future_evt_set;
342     future_evt_set = nullptr;
343   }
344
345 #if HAVE_THREAD_CONTEXTS
346   xbt_parmap_destroy(surf_parmap);
347 #endif
348
349   tmgr_finalize();
350   sg_platf_exit();
351
352   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
353 }
354
355 /*********
356  * Model *
357  *********/
358
359 namespace simgrid {
360 namespace surf {
361
362 Model::Model()
363   : maxminSystem_(NULL)
364 {
365   readyActionSet_ = new ActionList();
366   runningActionSet_ = new ActionList();
367   failedActionSet_ = new ActionList();
368   doneActionSet_ = new ActionList();
369
370   modifiedSet_ = NULL;
371   actionHeap_ = NULL;
372   updateMechanism_ = UM_UNDEFINED;
373   selectiveUpdate_ = 0;
374 }
375
376 Model::~Model(){
377   delete readyActionSet_;
378   delete runningActionSet_;
379   delete failedActionSet_;
380   delete doneActionSet_;
381 }
382
383 double Model::next_occuring_event(double now)
384 {
385   //FIXME: set the good function once and for all
386   if (updateMechanism_ == UM_LAZY)
387     return next_occuring_event_lazy(now);
388   else if (updateMechanism_ == UM_FULL)
389     return next_occuring_event_full(now);
390   else
391     xbt_die("Invalid cpu update mechanism!");
392 }
393
394 double Model::next_occuring_event_lazy(double now)
395 {
396   Action *action = NULL;
397   double min = -1;
398   double share;
399
400   XBT_DEBUG
401       ("Before share resources, the size of modified actions set is %zd",
402        modifiedSet_->size());
403
404   lmm_solve(maxminSystem_);
405
406   XBT_DEBUG
407       ("After share resources, The size of modified actions set is %zd",
408        modifiedSet_->size());
409
410   while(!modifiedSet_->empty()) {
411     action = &(modifiedSet_->front());
412     modifiedSet_->pop_front();
413     int max_dur_flag = 0;
414
415     if (action->getStateSet() != runningActionSet_)
416       continue;
417
418     /* bogus priority, skip it */
419     if (action->getPriority() <= 0 || action->getHat()==LATENCY)
420       continue;
421
422     action->updateRemainingLazy(now);
423
424     min = -1;
425     share = lmm_variable_getvalue(action->getVariable());
426
427     if (share > 0) {
428       double time_to_completion;
429       if (action->getRemains() > 0) {
430         time_to_completion = action->getRemainsNoUpdate() / share;
431       } else {
432         time_to_completion = 0.0;
433       }
434       min = now + time_to_completion; // when the task will complete if nothing changes
435     }
436
437     if ((action->getMaxDuration() != NO_MAX_DURATION)
438         && (min == -1
439             || action->getStartTime() +
440             action->getMaxDuration() < min)) {
441       min = action->getStartTime() +
442           action->getMaxDuration();  // when the task will complete anyway because of the deadline if any
443       max_dur_flag = 1;
444     }
445
446
447     XBT_DEBUG("Action(%p) corresponds to variable %d", action, action->getVariable()->id_int);
448
449     XBT_DEBUG("Action(%p) Start %f. May finish at %f (got a share of %f). Max_duration %f", action,
450         action->getStartTime(), min, share,
451         action->getMaxDuration());
452
453     if (min != -1) {
454       action->heapUpdate(actionHeap_, min, max_dur_flag ? MAX_DURATION : NORMAL);
455       XBT_DEBUG("Insert at heap action(%p) min %f now %f", action, min,
456                 now);
457     } else DIE_IMPOSSIBLE;
458   }
459
460   //hereafter must have already the min value for this resource model
461   if (xbt_heap_size(actionHeap_) > 0)
462     min = xbt_heap_maxkey(actionHeap_) - now;
463   else
464     min = -1;
465
466   XBT_DEBUG("The minimum with the HEAP %f", min);
467
468   return min;
469 }
470
471 double Model::next_occuring_event_full(double /*now*/) {
472   THROW_UNIMPLEMENTED;
473 }
474
475 double Model::shareResourcesMaxMin(ActionList *running_actions,
476                           lmm_system_t sys,
477                           void (*solve) (lmm_system_t))
478 {
479   Action *action = NULL;
480   double min = -1;
481   double value = -1;
482
483   solve(sys);
484
485   ActionList::iterator it(running_actions->begin()), itend(running_actions->end());
486   for(; it != itend ; ++it) {
487     action = &*it;
488     value = lmm_variable_getvalue(action->getVariable());
489     if ((value > 0) || (action->getMaxDuration() >= 0))
490       break;
491   }
492
493   if (!action)
494     return -1.0;
495
496   if (value > 0) {
497     if (action->getRemains() > 0)
498       min = action->getRemainsNoUpdate() / value;
499     else
500       min = 0.0;
501     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min))
502       min = action->getMaxDuration();
503   } else
504     min = action->getMaxDuration();
505
506
507   for (++it; it != itend; ++it) {
508   action = &*it;
509     value = lmm_variable_getvalue(action->getVariable());
510     if (value > 0) {
511       if (action->getRemains() > 0)
512         value = action->getRemainsNoUpdate() / value;
513       else
514         value = 0.0;
515       if (value < min) {
516         min = value;
517         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
518       }
519     }
520     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min)) {
521       min = action->getMaxDuration();
522       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
523     }
524   }
525   XBT_DEBUG("min value : %f", min);
526
527   return min;
528 }
529
530 void Model::updateActionsState(double now, double delta)
531 {
532   if (updateMechanism_ == UM_FULL)
533   updateActionsStateFull(now, delta);
534   else if (updateMechanism_ == UM_LAZY)
535   updateActionsStateLazy(now, delta);
536   else
537   xbt_die("Invalid cpu update mechanism!");
538 }
539
540 void Model::updateActionsStateLazy(double /*now*/, double /*delta*/)
541 {
542  THROW_UNIMPLEMENTED;
543 }
544
545 void Model::updateActionsStateFull(double /*now*/, double /*delta*/)
546 {
547   THROW_UNIMPLEMENTED;
548 }
549
550 }
551 }
552
553 /************
554  * Resource *
555  ************/
556
557 namespace simgrid {
558 namespace surf {
559
560 Resource::Resource(Model *model, const char *name)
561   : Resource(model, name, 1/*ON*/)
562 {}
563
564 Resource::Resource(Model *model, const char *name, lmm_constraint_t constraint)
565   : Resource(model, name, constraint, 1/*ON*/)
566 {}
567   
568 Resource::Resource(Model *model, const char *name, lmm_constraint_t constraint, int initiallyOn)
569   : p_name(xbt_strdup(name))
570   , p_model(model)
571   , m_isOn(initiallyOn)
572   , p_constraint(constraint)
573 {}
574
575 Resource::Resource(Model *model, const char *name, int initiallyOn)
576   : p_name(xbt_strdup(name))
577   , p_model(model)
578   , m_isOn(initiallyOn)
579 {}
580
581
582 Resource::~Resource() {
583   xbt_free((void*)p_name);
584 }
585
586 bool Resource::isOn() {
587   return m_isOn;
588 }
589 bool Resource::isOff() {
590   return ! m_isOn;
591 }
592
593 void Resource::turnOn()
594 {
595   if (!m_isOn) {
596     m_isOn = true;
597   }
598 }
599
600 void Resource::turnOff()
601 {
602   if (m_isOn) {
603     m_isOn = false;
604   }
605 }
606
607 Model *Resource::getModel() {
608   return p_model;
609 }
610
611 const char *Resource::getName() {
612   return p_name;
613 }
614
615 lmm_constraint_t Resource::getConstraint() {
616   return p_constraint;
617 }
618
619 }
620 }
621
622 /**********
623  * Action *
624  **********/
625
626 const char *surf_action_state_names[6] = {
627   "SURF_ACTION_READY",
628   "SURF_ACTION_RUNNING",
629   "SURF_ACTION_FAILED",
630   "SURF_ACTION_DONE",
631   "SURF_ACTION_TO_FREE",
632   "SURF_ACTION_NOT_IN_THE_SYSTEM"
633 };
634
635 /* added to manage the communication action's heap */
636 void surf_action_lmm_update_index_heap(void *action, int i) {
637   static_cast<simgrid::surf::Action*>(action)->updateIndexHeap(i);
638 }
639
640 namespace simgrid {
641 namespace surf {
642
643 void Action::initialize(simgrid::surf::Model *model, double cost, bool failed,
644                         lmm_variable_t var)
645 {
646   m_remains = cost;
647   m_start = surf_get_clock();
648   m_cost = cost;
649   p_model = model;
650   p_variable = var;
651   if (failed)
652     p_stateSet = getModel()->getFailedActionSet();
653   else
654     p_stateSet = getModel()->getRunningActionSet();
655
656   p_stateSet->push_back(*this);
657 }
658
659 Action::Action(simgrid::surf::Model *model, double cost, bool failed)
660 {
661   initialize(model, cost, failed);
662 }
663
664 Action::Action(simgrid::surf::Model *model, double cost, bool failed, lmm_variable_t var)
665 {
666   initialize(model, cost, failed, var);
667 }
668
669 Action::~Action() {
670   xbt_free(p_category);
671 }
672
673 void Action::finish() {
674     m_finish = surf_get_clock();
675 }
676
677 e_surf_action_state_t Action::getState()
678 {
679   if (p_stateSet ==  getModel()->getReadyActionSet())
680     return SURF_ACTION_READY;
681   if (p_stateSet ==  getModel()->getRunningActionSet())
682     return SURF_ACTION_RUNNING;
683   if (p_stateSet ==  getModel()->getFailedActionSet())
684     return SURF_ACTION_FAILED;
685   if (p_stateSet ==  getModel()->getDoneActionSet())
686     return SURF_ACTION_DONE;
687   return SURF_ACTION_NOT_IN_THE_SYSTEM;
688 }
689
690 void Action::setState(e_surf_action_state_t state)
691 {
692   //surf_action_state_t action_state = &(action->model_type->states);
693   XBT_IN("(%p,%s)", this, surf_action_state_names[state]);
694   p_stateSet->erase(p_stateSet->iterator_to(*this));
695   if (state == SURF_ACTION_READY)
696     p_stateSet = getModel()->getReadyActionSet();
697   else if (state == SURF_ACTION_RUNNING)
698     p_stateSet = getModel()->getRunningActionSet();
699   else if (state == SURF_ACTION_FAILED)
700     p_stateSet = getModel()->getFailedActionSet();
701   else if (state == SURF_ACTION_DONE)
702     p_stateSet = getModel()->getDoneActionSet();
703   else
704     p_stateSet = NULL;
705
706   if (p_stateSet)
707     p_stateSet->push_back(*this);
708   XBT_OUT();
709 }
710
711 double Action::getBound()
712 {
713   return (p_variable) ? lmm_variable_getbound(p_variable) : 0;
714 }
715
716 void Action::setBound(double bound)
717 {
718   XBT_IN("(%p,%g)", this, bound);
719   if (p_variable)
720     lmm_update_variable_bound(getModel()->getMaxminSystem(), p_variable, bound);
721
722   if (getModel()->getUpdateMechanism() == UM_LAZY && getLastUpdate()!=surf_get_clock())
723     heapRemove(getModel()->getActionHeap());
724   XBT_OUT();
725 }
726
727 double Action::getStartTime()
728 {
729   return m_start;
730 }
731
732 double Action::getFinishTime()
733 {
734   /* keep the function behavior, some models (cpu_ti) change the finish time before the action end */
735   return m_remains == 0 ? m_finish : -1;
736 }
737
738 void Action::setData(void* data)
739 {
740   p_data = data;
741 }
742
743 void Action::setCategory(const char *category)
744 {
745   XBT_IN("(%p,%s)", this, category);
746   p_category = xbt_strdup(category);
747   XBT_OUT();
748 }
749
750 void Action::ref(){
751   m_refcount++;
752 }
753
754 void Action::setMaxDuration(double duration)
755 {
756   XBT_IN("(%p,%g)", this, duration);
757   m_maxDuration = duration;
758   if (getModel()->getUpdateMechanism() == UM_LAZY)      // remove action from the heap
759     heapRemove(getModel()->getActionHeap());
760   XBT_OUT();
761 }
762
763 void Action::gapRemove() {}
764
765 void Action::setPriority(double priority)
766 {
767   XBT_IN("(%p,%g)", this, priority);
768   m_priority = priority;
769   lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), priority);
770
771   if (getModel()->getUpdateMechanism() == UM_LAZY)
772     heapRemove(getModel()->getActionHeap());
773   XBT_OUT();
774 }
775
776 void Action::cancel(){
777   setState(SURF_ACTION_FAILED);
778   if (getModel()->getUpdateMechanism() == UM_LAZY) {
779     if (action_lmm_hook.is_linked())
780       getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
781     heapRemove(getModel()->getActionHeap());
782   }
783 }
784
785 int Action::unref(){
786   m_refcount--;
787   if (!m_refcount) {
788     if (action_hook.is_linked())
789       p_stateSet->erase(p_stateSet->iterator_to(*this));
790     if (getVariable())
791       lmm_variable_free(getModel()->getMaxminSystem(), getVariable());
792     if (getModel()->getUpdateMechanism() == UM_LAZY) {
793       /* remove from heap */
794       heapRemove(getModel()->getActionHeap());
795       if (action_lmm_hook.is_linked())
796         getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
797     }
798     delete this;
799     return 1;
800   }
801   return 0;
802 }
803
804 void Action::suspend()
805 {
806   XBT_IN("(%p)", this);
807   if (m_suspended != 2) {
808     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), 0.0);
809     m_suspended = 1;
810     if (getModel()->getUpdateMechanism() == UM_LAZY)
811       heapRemove(getModel()->getActionHeap());
812   }
813   XBT_OUT();
814 }
815
816 void Action::resume()
817 {
818   XBT_IN("(%p)", this);
819   if (m_suspended != 2) {
820     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), m_priority);
821     m_suspended = 0;
822     if (getModel()->getUpdateMechanism() == UM_LAZY)
823       heapRemove(getModel()->getActionHeap());
824   }
825   XBT_OUT();
826 }
827
828 bool Action::isSuspended()
829 {
830   return m_suspended == 1;
831 }
832 /* insert action on heap using a given key and a hat (heap_action_type)
833  * a hat can be of three types for communications:
834  *
835  * NORMAL = this is a normal heap entry stating the date to finish transmitting
836  * LATENCY = this is a heap entry to warn us when the latency is payed
837  * MAX_DURATION =this is a heap entry to warn us when the max_duration limit is reached
838  */
839 void Action::heapInsert(xbt_heap_t heap, double key, enum heap_action_type hat)
840 {
841   m_hat = hat;
842   xbt_heap_push(heap, this, key);
843 }
844
845 void Action::heapRemove(xbt_heap_t heap)
846 {
847   m_hat = NOTSET;
848   if (m_indexHeap >= 0) {
849     xbt_heap_remove(heap, m_indexHeap);
850   }
851 }
852
853 void Action::heapUpdate(xbt_heap_t heap, double key, enum heap_action_type hat)
854 {
855   m_hat = hat;
856   if (m_indexHeap >= 0) {
857     xbt_heap_update(heap, m_indexHeap, key);
858   }else{
859     xbt_heap_push(heap, this, key);
860   }
861 }
862
863 void Action::updateIndexHeap(int i) {
864   m_indexHeap = i;
865 }
866
867 double Action::getRemains()
868 {
869   XBT_IN("(%p)", this);
870   /* update remains before return it */
871   if (getModel()->getUpdateMechanism() == UM_LAZY)      /* update remains before return it */
872     updateRemainingLazy(surf_get_clock());
873   XBT_OUT();
874   return m_remains;
875 }
876
877 double Action::getRemainsNoUpdate()
878 {
879   return m_remains;
880 }
881
882 //FIXME split code in the right places
883 void Action::updateRemainingLazy(double now)
884 {
885   double delta = 0.0;
886
887   if(getModel() == surf_network_model)
888   {
889     if (m_suspended != 0)
890       return;
891   }
892   else
893   {
894     xbt_assert(p_stateSet == getModel()->getRunningActionSet(),
895         "You're updating an action that is not running.");
896
897       /* bogus priority, skip it */
898     xbt_assert(m_priority > 0,
899         "You're updating an action that seems suspended.");
900   }
901
902   delta = now - m_lastUpdate;
903
904   if (m_remains > 0) {
905     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
906     double_update(&m_remains, m_lastValue * delta, sg_surf_precision*sg_maxmin_precision);
907
908     if (getModel() == surf_cpu_model_pm && TRACE_is_enabled()) {
909       simgrid::surf::Resource *cpu = static_cast<simgrid::surf::Resource*>(
910         lmm_constraint_id(lmm_get_cnst_from_var(getModel()->getMaxminSystem(), getVariable(), 0)));
911       TRACE_surf_host_set_utilization(cpu->getName(), getCategory(), m_lastValue, m_lastUpdate, now - m_lastUpdate);
912     }
913     XBT_DEBUG("Updating action(%p): remains is now %f", this, m_remains);
914   }
915
916   if(getModel() == surf_network_model)
917   {
918     if (m_maxDuration != NO_MAX_DURATION)
919       double_update(&m_maxDuration, delta, sg_surf_precision);
920
921     //FIXME: duplicated code
922     if ((m_remains <= 0) &&
923         (lmm_get_variable_weight(getVariable()) > 0)) {
924       finish();
925       setState(SURF_ACTION_DONE);
926       heapRemove(getModel()->getActionHeap());
927     } else if (((m_maxDuration != NO_MAX_DURATION)
928         && (m_maxDuration <= 0))) {
929       finish();
930       setState(SURF_ACTION_DONE);
931       heapRemove(getModel()->getActionHeap());
932     }
933   }
934
935   m_lastUpdate = now;
936   m_lastValue = lmm_variable_getvalue(getVariable());
937 }
938
939 }
940 }