Logo AND Algorithmique Numérique Distribuée

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