Logo AND Algorithmique Numérique Distribuée

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