Logo AND Algorithmique Numérique Distribuée

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