Logo AND Algorithmique Numérique Distribuée

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