Logo AND Algorithmique Numérique Distribuée

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