Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Rename NetworkLink type to Link
[simgrid.git] / src / surf / surf_interface.cpp
1 /* Copyright (c) 2004-2014. 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 "surf_private.h"
8 #include "surf_interface.hpp"
9 #include "network_interface.hpp"
10 #include "cpu_interface.hpp"
11 #include "host_interface.hpp"
12 #include "simix/smx_host_private.h"
13 #include "surf_routing.hpp"
14 #include "simgrid/sg_config.h"
15 #include "mc/mc.h"
16 #include "vm_interface.hpp"
17
18 XBT_LOG_NEW_CATEGORY(surf, "All SURF categories");
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_kernel, surf,
20                                 "Logging specific to SURF (kernel)");
21
22 /*********
23  * Utils *
24  *********/
25
26 /* This function is a pimple that we ought to fix. But it won't be easy.
27  *
28  * The surf_solve() function does properly return the set of actions that
29  * changed. Instead, each model change a global data, and then the caller of
30  * surf_solve must pick into these sets of action_failed and action_done.
31  *
32  * This was not clean but ok as long as we didn't had to restart the processes
33  * when the resource comes back up.
34  * We worked by putting sentinel actions on every resources we are interested
35  * in, so that surf informs us if/when the corresponding resource fails.
36  *
37  * But this does not work to get Simix informed of when a resource comes back
38  * up, and this is where this pimple comes. We have a set of resources that are
39  * currently down and for which simix needs to know when it comes back up.
40  * And the current function is called *at every simulation step* to sweep over
41  * that set, searching for a resource that was turned back up in the meanwhile.
42  * This is UGLY and slow.
43  *
44  * The proper solution would be to not rely on globals for the action_failed and
45  * action_done swags. They must be passed as parameter by the caller (the
46  * handling of these actions in simix may let you think that these two sets can
47  * be merged, but their handling in SimDag induce the contrary unless this
48  * simdag code can check by itself whether the action is done of failed -- seems
49  * very doable, but yet more cleanup to do).
50  *
51  * Once surf_solve() is passed the set of actions that changed, you want to add
52  * a new set of resources back up as parameter to this function. You also want
53  * to add a boolean field "restart_watched" to each resource, and make sure that
54  * whenever a resource with this field enabled comes back up, it's added to that
55  * set so that Simix sees it and react accordingly. This would kill that need
56  * for surf to call simix.
57  *
58  */
59
60 /*static void remove_watched_host(void *key)
61 {
62   xbt_dict_remove(watched_hosts_lib, *(char**)key);
63 }*/
64
65 /*void surf_watched_hosts(void)
66 {
67   char *key;
68   void *host;
69   xbt_dict_cursor_t cursor;
70   xbt_dynar_t hosts = xbt_dynar_new(sizeof(char*), NULL);
71
72   XBT_DEBUG("Check for host SURF_RESOURCE_ON on watched_hosts_lib");
73   xbt_dict_foreach(watched_hosts_lib, cursor, key, host)
74   {
75     if(SIMIX_host_get_state((smx_host_t)host) == SURF_RESOURCE_ON){
76       XBT_INFO("Restart processes on host: %s", SIMIX_host_get_name((smx_host_t)host));
77       SIMIX_host_autorestart((smx_host_t)host);
78       xbt_dynar_push_as(hosts, char*, key);
79     }
80     else
81       XBT_DEBUG("See SURF_RESOURCE_OFF on host: %s",key);
82   }
83   xbt_dynar_map(hosts, remove_watched_host);
84   xbt_dynar_free(&hosts);
85 }*/
86
87 /* model_list_invoke contains only surf_host and surf_vm.
88  * The callback functions of cpu_model and network_model will be called from
89  * those of these host models. */
90 xbt_dynar_t model_list = NULL; /* for destroying all models correctly */
91 xbt_dynar_t model_list_invoke = NULL;  /* for invoking callbacks */
92
93 tmgr_history_t history = NULL;
94 lmm_system_t maxmin_system = NULL;
95 xbt_dynar_t surf_path = NULL;
96 xbt_dynar_t host_that_restart = NULL;
97 xbt_dict_t watched_hosts_lib;
98
99 surf_callback(void, void) surfExitCallbacks;
100
101 s_surf_model_description_t surf_plugin_description[] = {
102     {"Energy", "Cpu energy consumption.", sg_energy_plugin_init},
103      {NULL, NULL,  NULL}      /* this array must be NULL terminated */
104 };
105
106 /* Don't forget to update the option description in smx_config when you change
107    this */
108 s_surf_model_description_t surf_network_model_description[] = {
109   {"LV08",
110    "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). ",
111    surf_network_model_init_LegrandVelho},
112   {"Constant",
113    "Simplistic network model where all communication take a constant time (one second). This model provides the lowest realism, but is (marginally) faster.",
114    surf_network_model_init_Constant},
115   {"SMPI",
116    "Realistic network model specifically tailored for HPC settings (accurate modeling of slow start with correction factors on three intervals: < 1KiB, < 64 KiB, >= 64 KiB)",
117    surf_network_model_init_SMPI},
118   {"IB",
119    "Realistic network model specifically tailored for HPC settings, with Infiniband contention model",
120    surf_network_model_init_IB},
121   {"CM02",
122    "Legacy network analytic model (Very similar to LV08, but without corrective factors. The timings of small messages are thus poorly modeled).",
123    surf_network_model_init_CM02},
124 #ifdef HAVE_GTNETS
125   {"GTNets",
126    "Network pseudo-model using the GTNets simulator instead of an analytic model",
127    surf_network_model_init_GTNETS},
128 #endif
129 #ifdef HAVE_NS3
130   {"NS3",
131    "Network pseudo-model using the NS3 tcp model instead of an analytic model",
132   surf_network_model_init_NS3},
133 #endif
134   {"Reno",
135    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
136    surf_network_model_init_Reno},
137   {"Reno2",
138    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
139    surf_network_model_init_Reno2},
140   {"Vegas",
141    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
142    surf_network_model_init_Vegas},
143   {NULL, NULL, NULL}      /* this array must be NULL terminated */
144 };
145
146 s_surf_model_description_t surf_cpu_model_description[] = {
147   {"Cas01",
148    "Simplistic CPU model (time=size/power).",
149    surf_cpu_model_init_Cas01},
150   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
151 };
152
153 s_surf_model_description_t surf_host_model_description[] = {
154   {"default",
155    "Default host model. Currently, CPU:Cas01 and network:LV08 (with cross traffic enabled)",
156    surf_host_model_init_current_default},
157   {"compound",
158    "Host model that is automatically chosen if you change the network and CPU models",
159    surf_host_model_init_compound},
160   {"ptask_L07", "Host model somehow similar to Cas01+CM02 but allowing parallel tasks",
161    surf_host_model_init_ptask_L07},
162   {NULL, NULL, NULL}      /* this array must be NULL terminated */
163 };
164
165 s_surf_model_description_t surf_vm_model_description[] = {
166   {"default",
167    "Default vm model.",
168    surf_vm_model_init_HL13},
169   {NULL, NULL, NULL}      /* this array must be NULL terminated */
170 };
171
172 s_surf_model_description_t surf_optimization_mode_description[] = {
173   {"Lazy",
174    "Lazy action management (partial invalidation in lmm + heap in action remaining).",
175    NULL},
176   {"TI",
177    "Trace integration. Highly optimized mode when using availability traces (only available for the Cas01 CPU model for now).",
178     NULL},
179   {"Full",
180    "Full update of remaining and variables. Slow but may be useful when debugging.",
181    NULL},
182   {NULL, NULL, NULL}      /* this array must be NULL terminated */
183 };
184
185 s_surf_model_description_t surf_storage_model_description[] = {
186   {"default",
187    "Simplistic storage model.",
188    surf_storage_model_init_default},
189   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
190 };
191
192 #ifdef CONTEXT_THREADS
193 static xbt_parmap_t surf_parmap = NULL; /* parallel map on models */
194 #endif
195
196 double NOW = 0;
197 double *surf_mins = NULL; /* return value of share_resources for each model */
198 int surf_min_index;       /* current index in surf_mins */
199 double surf_min;               /* duration determined by surf_solve */
200
201 double surf_get_clock(void)
202 {
203   return NOW;
204 }
205
206 #ifdef _XBT_WIN32
207 # define FILE_DELIM "\\"
208 #else
209 # define FILE_DELIM "/"         /* FIXME: move to better location */
210 #endif
211
212 FILE *surf_fopen(const char *name, const char *mode)
213 {
214   unsigned int cpt;
215   char *path_elm = NULL;
216   char *buff;
217   FILE *file = NULL;
218
219   xbt_assert(name);
220
221   if (__surf_is_absolute_file_path(name))       /* don't mess with absolute file names */
222     return fopen(name, mode);
223
224   /* search relative files in the path */
225   xbt_dynar_foreach(surf_path, cpt, path_elm) {
226     buff = bprintf("%s" FILE_DELIM "%s", path_elm, name);
227     file = fopen(buff, mode);
228     free(buff);
229
230     if (file)
231       return file;
232   }
233   return NULL;
234 }
235
236
237 #ifndef MAX_DRIVE
238 #define MAX_DRIVE 26
239 #endif
240
241 #ifdef _XBT_WIN32
242 #include <windows.h>
243 static const char *disk_drives_letter_table[MAX_DRIVE] = {
244   "A:\\",
245   "B:\\",
246   "C:\\",
247   "D:\\",
248   "E:\\",
249   "F:\\",
250   "G:\\",
251   "H:\\",
252   "I:\\",
253   "J:\\",
254   "K:\\",
255   "L:\\",
256   "M:\\",
257   "N:\\",
258   "O:\\",
259   "P:\\",
260   "Q:\\",
261   "R:\\",
262   "S:\\",
263   "T:\\",
264   "U:\\",
265   "V:\\",
266   "W:\\",
267   "X:\\",
268   "Y:\\",
269   "Z:\\"
270 };
271 #endif
272
273 /*
274  * Returns the initial path. On Windows the initial path is
275  * the current directory for the current process in the other
276  * case the function returns "./" that represents the current
277  * directory on Unix/Linux platforms.
278  */
279
280 const char *__surf_get_initial_path(void)
281 {
282
283 #ifdef _XBT_WIN32
284   unsigned i;
285   char current_directory[MAX_PATH + 1] = { 0 };
286   unsigned int len = GetCurrentDirectory(MAX_PATH + 1, current_directory);
287   char root[4] = { 0 };
288
289   if (!len)
290     return NULL;
291
292   strncpy(root, current_directory, 3);
293
294   for (i = 0; i < MAX_DRIVE; i++) {
295     if (toupper(root[0]) == disk_drives_letter_table[i][0])
296       return disk_drives_letter_table[i];
297   }
298
299   return NULL;
300 #else
301   return "./";
302 #endif
303 }
304
305 /* The __surf_is_absolute_file_path() returns 1 if
306  * file_path is a absolute file path, in the other
307  * case the function returns 0.
308  */
309 int __surf_is_absolute_file_path(const char *file_path)
310 {
311 #ifdef _XBT_WIN32
312   WIN32_FIND_DATA wfd = { 0 };
313   HANDLE hFile = FindFirstFile(file_path, &wfd);
314
315   if (INVALID_HANDLE_VALUE == hFile)
316     return 0;
317
318   FindClose(hFile);
319   return 1;
320 #else
321   return (file_path[0] == '/');
322 #endif
323 }
324
325 /** Displays the long description of all registered models, and quit */
326 void model_help(const char *category, s_surf_model_description_t * table)
327 {
328   int i;
329   printf("Long description of the %s models accepted by this simulator:\n",
330          category);
331   for (i = 0; table[i].name; i++)
332     printf("  %s: %s\n", table[i].name, table[i].description);
333 }
334
335 int find_model_description(s_surf_model_description_t * table,
336                            const char *name)
337 {
338   int i;
339   char *name_list = NULL;
340
341   for (i = 0; table[i].name; i++)
342     if (!strcmp(name, table[i].name)) {
343       return i;
344     }
345   if (!table[0].name)
346     xbt_die("No model is valid! This is a bug.");
347   name_list = xbt_strdup(table[0].name);
348   for (i = 1; table[i].name; i++) {
349     name_list = (char *) xbt_realloc(name_list, strlen(name_list) + strlen(table[i].name) + 3);
350     strcat(name_list, ", ");
351     strcat(name_list, table[i].name);
352   }
353   xbt_die("Model '%s' is invalid! Valid models are: %s.", name, name_list);
354   return -1;
355 }
356
357 static XBT_INLINE void routing_asr_prop_free(void *p)
358 {
359   //xbt_dict_t elm = (xbt_dict_t) p;
360   //xbt_dict_free(&elm); FIXME: leaking in some case? That's a sometimes double-free with AsCluster::~AsCluster
361 }
362
363 static XBT_INLINE void surf_link_free(void *r)
364 {
365   delete static_cast<LinkPtr>(r);
366 }
367
368 static XBT_INLINE void surf_host_free(void *r)
369 {
370   delete static_cast<HostPtr>(r);
371 }
372
373 static XBT_INLINE void surf_storage_free(void *r)
374 {
375   delete static_cast<StoragePtr>(r);
376 }
377
378
379 void sg_version(int *ver_major,int *ver_minor,int *ver_patch) {
380   *ver_major = SIMGRID_VERSION_MAJOR;
381   *ver_minor = SIMGRID_VERSION_MINOR;
382   *ver_patch = SIMGRID_VERSION_PATCH;
383 }
384
385 void surf_init(int *argc, char **argv)
386 {
387   XBT_DEBUG("Create all Libs");
388   host_lib = xbt_lib_new();
389   link_lib = xbt_lib_new();
390   as_router_lib = xbt_lib_new();
391   storage_lib = xbt_lib_new();
392   storage_type_lib = xbt_lib_new();
393   file_lib = xbt_lib_new();
394   watched_hosts_lib = xbt_dict_new_homogeneous(NULL);
395
396   sg_host_init();
397
398   XBT_DEBUG("Add routing levels");
399   ROUTING_PROP_ASR_LEVEL = xbt_lib_add_level(as_router_lib,routing_asr_prop_free);
400
401   XBT_DEBUG("Add SURF levels");
402   SURF_HOST_LEVEL = xbt_lib_add_level(host_lib,surf_host_free);
403   SURF_LINK_LEVEL = xbt_lib_add_level(link_lib,surf_link_free);
404   SURF_STORAGE_LEVEL = xbt_lib_add_level(storage_lib,surf_storage_free);
405
406   xbt_init(argc, argv);
407   if (!model_list)
408     model_list = xbt_dynar_new(sizeof(ModelPtr), NULL);
409   if (!model_list_invoke)
410     model_list_invoke = xbt_dynar_new(sizeof(ModelPtr), NULL);
411   if (!history)
412     history = tmgr_history_new();
413
414   TRACE_add_start_function(TRACE_surf_alloc);
415   TRACE_add_end_function(TRACE_surf_release);
416
417   sg_config_init(argc, argv);
418
419   if (MC_is_active())
420     MC_memory_init();
421 }
422
423 void surf_exit(void)
424 {
425   unsigned int iter;
426   ModelPtr model = NULL;
427
428   TRACE_end();                  /* Just in case it was not called by the upper
429                                  * layer (or there is no upper layer) */
430
431   sg_config_finalize();
432
433   xbt_dynar_free(&host_that_restart);
434   xbt_dynar_free(&surf_path);
435
436   xbt_lib_free(&host_lib);
437   xbt_lib_free(&link_lib);
438   xbt_lib_free(&as_router_lib);
439   xbt_lib_free(&storage_lib);
440   xbt_lib_free(&storage_type_lib);
441   xbt_lib_free(&file_lib);
442   xbt_dict_free(&watched_hosts_lib);
443
444   xbt_dynar_foreach(model_list, iter, model)
445     delete model;
446   xbt_dynar_free(&model_list);
447   xbt_dynar_free(&model_list_invoke);
448   routing_exit();
449
450   surf_callback_emit(surfExitCallbacks);
451
452   if (maxmin_system) {
453     lmm_system_free(maxmin_system);
454     maxmin_system = NULL;
455   }
456   if (history) {
457     tmgr_history_free(history);
458     history = NULL;
459   }
460
461 #ifdef CONTEXT_THREADS
462   xbt_parmap_destroy(surf_parmap);
463 #endif
464
465   xbt_free(surf_mins);
466   surf_mins = NULL;
467
468   tmgr_finalize();
469   surf_parse_lex_destroy();
470   surf_parse_free_callbacks();
471
472   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
473 }
474
475 /*********
476  * Model *
477  *********/
478
479 Model::Model(const char *name)
480   : p_maxminSystem(NULL)
481   , p_name(name)
482 {
483   p_readyActionSet = new ActionList();
484   p_runningActionSet = new ActionList();
485   p_failedActionSet = new ActionList();
486   p_doneActionSet = new ActionList();
487
488   p_modifiedSet = NULL;
489   p_actionHeap = NULL;
490   p_updateMechanism = UM_UNDEFINED;
491   m_selectiveUpdate = 0;
492 }
493
494 Model::~Model(){
495   delete p_readyActionSet;
496   delete p_runningActionSet;
497   delete p_failedActionSet;
498   delete p_doneActionSet;
499 }
500
501 double Model::shareResources(double now)
502 {
503   //FIXME: set the good function once and for all
504   if (p_updateMechanism == UM_LAZY)
505     return shareResourcesLazy(now);
506   else if (p_updateMechanism == UM_FULL)
507     return shareResourcesFull(now);
508   else
509     xbt_die("Invalid cpu update mechanism!");
510 }
511
512 double Model::shareResourcesLazy(double now)
513 {
514   ActionPtr action = NULL;
515   double min = -1;
516   double share;
517
518   XBT_DEBUG
519       ("Before share resources, the size of modified actions set is %zd",
520        p_modifiedSet->size());
521
522   lmm_solve(p_maxminSystem);
523
524   XBT_DEBUG
525       ("After share resources, The size of modified actions set is %zd",
526        p_modifiedSet->size());
527
528   while(!p_modifiedSet->empty()) {
529     action = &(p_modifiedSet->front());
530     p_modifiedSet->pop_front();
531     int max_dur_flag = 0;
532
533     if (action->getStateSet() != p_runningActionSet)
534       continue;
535
536     /* bogus priority, skip it */
537     if (action->getPriority() <= 0 || action->getHat()==LATENCY)
538       continue;
539
540     action->updateRemainingLazy(now);
541
542     min = -1;
543     share = lmm_variable_getvalue(action->getVariable());
544
545     if (share > 0) {
546       double time_to_completion;
547       if (action->getRemains() > 0) {
548         time_to_completion = action->getRemainsNoUpdate() / share;
549       } else {
550         time_to_completion = 0.0;
551       }
552       min = now + time_to_completion; // when the task will complete if nothing changes
553     }
554
555     if ((action->getMaxDuration() != NO_MAX_DURATION)
556         && (min == -1
557             || action->getStartTime() +
558             action->getMaxDuration() < min)) {
559       min = action->getStartTime() +
560           action->getMaxDuration();  // when the task will complete anyway because of the deadline if any
561       max_dur_flag = 1;
562     }
563
564
565     XBT_DEBUG("Action(%p) corresponds to variable %d", action, action->getVariable()->id_int);
566
567     XBT_DEBUG("Action(%p) Start %f. May finish at %f (got a share of %f). Max_duration %f", action,
568         action->getStartTime(), min, share,
569         action->getMaxDuration());
570
571     if (min != -1) {
572       action->heapUpdate(p_actionHeap, min, max_dur_flag ? MAX_DURATION : NORMAL);
573       XBT_DEBUG("Insert at heap action(%p) min %f now %f", action, min,
574                 now);
575     } else DIE_IMPOSSIBLE;
576   }
577
578   //hereafter must have already the min value for this resource model
579   if (xbt_heap_size(p_actionHeap) > 0)
580     min = xbt_heap_maxkey(p_actionHeap) - now;
581   else
582     min = -1;
583
584   XBT_DEBUG("The minimum with the HEAP %f", min);
585
586   return min;
587 }
588
589 double Model::shareResourcesFull(double /*now*/) {
590   THROW_UNIMPLEMENTED;
591 }
592
593 double Model::shareResourcesMaxMin(ActionListPtr running_actions,
594                           lmm_system_t sys,
595                           void (*solve) (lmm_system_t))
596 {
597   ActionPtr action = NULL;
598   double min = -1;
599   double value = -1;
600
601   solve(sys);
602
603   ActionList::iterator it(running_actions->begin()), itend(running_actions->end());
604   for(; it != itend ; ++it) {
605     action = &*it;
606     value = lmm_variable_getvalue(action->getVariable());
607     if ((value > 0) || (action->getMaxDuration() >= 0))
608       break;
609   }
610
611   if (!action)
612     return -1.0;
613
614   if (value > 0) {
615     if (action->getRemains() > 0)
616       min = action->getRemainsNoUpdate() / value;
617     else
618       min = 0.0;
619     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min))
620       min = action->getMaxDuration();
621   } else
622     min = action->getMaxDuration();
623
624
625   for (++it; it != itend; ++it) {
626         action = &*it;
627     value = lmm_variable_getvalue(action->getVariable());
628     if (value > 0) {
629       if (action->getRemains() > 0)
630         value = action->getRemainsNoUpdate() / value;
631       else
632         value = 0.0;
633       if (value < min) {
634         min = value;
635         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
636       }
637     }
638     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min)) {
639       min = action->getMaxDuration();
640       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
641     }
642   }
643   XBT_DEBUG("min value : %f", min);
644
645   return min;
646 }
647
648 void Model::updateActionsState(double now, double delta)
649 {
650   if (p_updateMechanism == UM_FULL)
651         updateActionsStateFull(now, delta);
652   else if (p_updateMechanism == UM_LAZY)
653         updateActionsStateLazy(now, delta);
654   else
655         xbt_die("Invalid cpu update mechanism!");
656 }
657
658 void Model::updateActionsStateLazy(double /*now*/, double /*delta*/)
659 {
660  THROW_UNIMPLEMENTED;
661 }
662
663 void Model::updateActionsStateFull(double /*now*/, double /*delta*/)
664 {
665   THROW_UNIMPLEMENTED;
666 }
667
668 /************
669  * Resource *
670  ************/
671
672 Resource::Resource()
673 : p_name(NULL), p_properties(NULL), p_model(NULL)
674 {}
675
676 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props)
677   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
678   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON)
679 {}
680
681 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, lmm_constraint_t constraint)
682   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
683   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON), p_constraint(constraint)
684 {}
685
686 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, e_surf_resource_state_t stateInit)
687   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
688   , m_running(true), m_stateCurrent(stateInit)
689 {}
690
691 Resource::~Resource() {
692   xbt_free((void*)p_name);
693   xbt_dict_free(&p_properties);
694 }
695
696 e_surf_resource_state_t Resource::getState()
697 {
698   return m_stateCurrent;
699 }
700
701 void Resource::setState(e_surf_resource_state_t state)
702 {
703   m_stateCurrent = state;
704 }
705
706 bool Resource::isOn()
707 {
708   return m_running;
709 }
710
711 void Resource::turnOn()
712 {
713   if (!m_running) {
714     m_running = true;
715   }
716 }
717
718 void Resource::turnOff()
719 {
720   if (m_running) {
721     m_running = false;
722   }
723 }
724
725 ModelPtr Resource::getModel() {
726   return p_model;
727 }
728
729 const char *Resource::getName() {
730   return p_name;
731 }
732
733 xbt_dict_t Resource::getProperties() {
734   if (p_properties==NULL)
735     p_properties = xbt_dict_new();
736   return p_properties;
737 }
738
739 lmm_constraint_t Resource::getConstraint() {
740   return p_constraint;
741 }
742
743 /**********
744  * Action *
745  **********/
746
747 const char *surf_action_state_names[6] = {
748   "SURF_ACTION_READY",
749   "SURF_ACTION_RUNNING",
750   "SURF_ACTION_FAILED",
751   "SURF_ACTION_DONE",
752   "SURF_ACTION_TO_FREE",
753   "SURF_ACTION_NOT_IN_THE_SYSTEM"
754 };
755
756 void Action::initialize(ModelPtr model, double cost, bool failed,
757                         lmm_variable_t var)
758 {
759   m_priority = 1.0;
760   m_refcount = 1;
761   m_remains = cost;
762   m_maxDuration = NO_MAX_DURATION;
763   m_finish = -1.0;
764   m_failed = failed;
765   m_start = surf_get_clock();
766   m_cost = cost;
767   p_model = model;
768   p_data = NULL;
769   p_variable = var;
770   m_lastValue = 0;
771   m_lastUpdate = 0;
772   m_suspended = false;
773   m_hat = NOTSET;
774 }
775
776 Action::Action(ModelPtr model, double cost, bool failed)
777 {
778   initialize(model, cost, failed);
779   p_category = NULL;
780   p_stateHookup.prev = 0;
781   p_stateHookup.next = 0;
782   if (failed)
783     p_stateSet = getModel()->getFailedActionSet();
784   else
785     p_stateSet = getModel()->getRunningActionSet();
786
787   p_stateSet->push_back(*this);
788 }
789
790 Action::Action(ModelPtr model, double cost, bool failed, lmm_variable_t var)
791 {
792   initialize(model, cost, failed, var);
793   p_category = NULL;
794   p_stateHookup.prev = 0;
795   p_stateHookup.next = 0;
796   if (failed)
797     p_stateSet = getModel()->getFailedActionSet();
798   else
799     p_stateSet = getModel()->getRunningActionSet();
800
801   p_stateSet->push_back(*this);
802 }
803
804 Action::~Action() {
805   xbt_free(p_category);
806 }
807
808 void Action::finish() {
809     m_finish = surf_get_clock();
810 }
811
812 e_surf_action_state_t Action::getState()
813 {
814   if (p_stateSet ==  getModel()->getReadyActionSet())
815     return SURF_ACTION_READY;
816   if (p_stateSet ==  getModel()->getRunningActionSet())
817     return SURF_ACTION_RUNNING;
818   if (p_stateSet ==  getModel()->getFailedActionSet())
819     return SURF_ACTION_FAILED;
820   if (p_stateSet ==  getModel()->getDoneActionSet())
821     return SURF_ACTION_DONE;
822   return SURF_ACTION_NOT_IN_THE_SYSTEM;
823 }
824
825 void Action::setState(e_surf_action_state_t state)
826 {
827   //surf_action_state_t action_state = &(action->model_type->states);
828   XBT_IN("(%p,%s)", this, surf_action_state_names[state]);
829   p_stateSet->erase(p_stateSet->iterator_to(*this));
830   if (state == SURF_ACTION_READY)
831     p_stateSet = getModel()->getReadyActionSet();
832   else if (state == SURF_ACTION_RUNNING)
833     p_stateSet = getModel()->getRunningActionSet();
834   else if (state == SURF_ACTION_FAILED)
835     p_stateSet = getModel()->getFailedActionSet();
836   else if (state == SURF_ACTION_DONE)
837     p_stateSet = getModel()->getDoneActionSet();
838   else
839     p_stateSet = NULL;
840
841   if (p_stateSet)
842     p_stateSet->push_back(*this);
843   XBT_OUT();
844 }
845
846 double Action::getBound()
847 {
848   return (p_variable) ? lmm_variable_getbound(p_variable) : 0;
849 }
850
851 void Action::setBound(double bound)
852 {
853   XBT_IN("(%p,%g)", this, bound);
854   if (p_variable)
855     lmm_update_variable_bound(getModel()->getMaxminSystem(), p_variable, bound);
856
857   if (getModel()->getUpdateMechanism() == UM_LAZY && getLastUpdate()!=surf_get_clock())
858     heapRemove(getModel()->getActionHeap());
859   XBT_OUT();
860 }
861
862 double Action::getStartTime()
863 {
864   return m_start;
865 }
866
867 double Action::getFinishTime()
868 {
869   /* keep the function behavior, some models (cpu_ti) change the finish time before the action end */
870   return m_remains == 0 ? m_finish : -1;
871 }
872
873 void Action::setData(void* data)
874 {
875   p_data = data;
876 }
877
878 void Action::setCategory(const char *category)
879 {
880   XBT_IN("(%p,%s)", this, category);
881   p_category = xbt_strdup(category);
882   XBT_OUT();
883 }
884
885 void Action::ref(){
886   m_refcount++;
887 }
888
889 void Action::setMaxDuration(double duration)
890 {
891   XBT_IN("(%p,%g)", this, duration);
892   m_maxDuration = duration;
893   if (getModel()->getUpdateMechanism() == UM_LAZY)      // remove action from the heap
894     heapRemove(getModel()->getActionHeap());
895   XBT_OUT();
896 }
897
898 void Action::gapRemove() {}
899
900 void Action::setPriority(double priority)
901 {
902   XBT_IN("(%p,%g)", this, priority);
903   m_priority = priority;
904   lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), priority);
905
906   if (getModel()->getUpdateMechanism() == UM_LAZY)
907         heapRemove(getModel()->getActionHeap());
908   XBT_OUT();
909 }
910
911 void Action::cancel(){
912   setState(SURF_ACTION_FAILED);
913   if (getModel()->getUpdateMechanism() == UM_LAZY) {
914     if (actionLmmHook::is_linked())
915       getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
916     heapRemove(getModel()->getActionHeap());
917   }
918 }
919
920 int Action::unref(){
921   m_refcount--;
922   if (!m_refcount) {
923     if (actionHook::is_linked())
924       p_stateSet->erase(p_stateSet->iterator_to(*this));
925     if (getVariable())
926       lmm_variable_free(getModel()->getMaxminSystem(), getVariable());
927     if (getModel()->getUpdateMechanism() == UM_LAZY) {
928       /* remove from heap */
929       heapRemove(getModel()->getActionHeap());
930       if (actionLmmHook::is_linked())
931         getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
932     }
933     delete this;
934     return 1;
935   }
936   return 0;
937 }
938
939 void Action::suspend()
940 {
941   XBT_IN("(%p)", this);
942   if (m_suspended != 2) {
943     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), 0.0);
944     m_suspended = 1;
945     if (getModel()->getUpdateMechanism() == UM_LAZY)
946       heapRemove(getModel()->getActionHeap());
947   }
948   XBT_OUT();
949 }
950
951 void Action::resume()
952 {
953   XBT_IN("(%p)", this);
954   if (m_suspended != 2) {
955     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), m_priority);
956     m_suspended = 0;
957     if (getModel()->getUpdateMechanism() == UM_LAZY)
958       heapRemove(getModel()->getActionHeap());
959   }
960   XBT_OUT();
961 }
962
963 bool Action::isSuspended()
964 {
965   return m_suspended == 1;
966 }
967 /* insert action on heap using a given key and a hat (heap_action_type)
968  * a hat can be of three types for communications:
969  *
970  * NORMAL = this is a normal heap entry stating the date to finish transmitting
971  * LATENCY = this is a heap entry to warn us when the latency is payed
972  * MAX_DURATION =this is a heap entry to warn us when the max_duration limit is reached
973  */
974 void Action::heapInsert(xbt_heap_t heap, double key, enum heap_action_type hat)
975 {
976   m_hat = hat;
977   xbt_heap_push(heap, this, key);
978 }
979
980 void Action::heapRemove(xbt_heap_t heap)
981 {
982   m_hat = NOTSET;
983   if (m_indexHeap >= 0) {
984     xbt_heap_remove(heap, m_indexHeap);
985   }
986 }
987
988 void Action::heapUpdate(xbt_heap_t heap, double key, enum heap_action_type hat)
989 {
990   m_hat = hat;
991   if (m_indexHeap >= 0) {
992     xbt_heap_update(heap, m_indexHeap, key);
993   }else{
994     xbt_heap_push(heap, this, key);
995   }
996 }
997
998 /* added to manage the communication action's heap */
999 void surf_action_lmm_update_index_heap(void *action, int i) {
1000   ((ActionPtr)action)->updateIndexHeap(i);
1001 }
1002
1003 void Action::updateIndexHeap(int i) {
1004   m_indexHeap = i;
1005 }
1006
1007 double Action::getRemains()
1008 {
1009   XBT_IN("(%p)", this);
1010   /* update remains before return it */
1011   if (getModel()->getUpdateMechanism() == UM_LAZY)      /* update remains before return it */
1012     updateRemainingLazy(surf_get_clock());
1013   XBT_OUT();
1014   return m_remains;
1015 }
1016
1017 double Action::getRemainsNoUpdate()
1018 {
1019   return m_remains;
1020 }
1021
1022 //FIXME split code in the right places
1023 void Action::updateRemainingLazy(double now)
1024 {
1025   double delta = 0.0;
1026
1027   if(getModel() == surf_network_model)
1028   {
1029     if (m_suspended != 0)
1030       return;
1031   }
1032   else
1033   {
1034     xbt_assert(p_stateSet == getModel()->getRunningActionSet(),
1035         "You're updating an action that is not running.");
1036
1037       /* bogus priority, skip it */
1038     xbt_assert(m_priority > 0,
1039         "You're updating an action that seems suspended.");
1040   }
1041
1042   delta = now - m_lastUpdate;
1043
1044   if (m_remains > 0) {
1045     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
1046     double_update(&m_remains, m_lastValue * delta, sg_surf_precision*sg_maxmin_precision);
1047
1048     if (getModel() == surf_cpu_model_pm && TRACE_is_enabled()) {
1049       ResourcePtr cpu = static_cast<ResourcePtr>(lmm_constraint_id(lmm_get_cnst_from_var(getModel()->getMaxminSystem(), getVariable(), 0)));
1050       TRACE_surf_host_set_utilization(cpu->getName(), getCategory(), m_lastValue, m_lastUpdate, now - m_lastUpdate);
1051     }
1052     XBT_DEBUG("Updating action(%p): remains is now %f", this, m_remains);
1053   }
1054
1055   if(getModel() == surf_network_model)
1056   {
1057     if (m_maxDuration != NO_MAX_DURATION)
1058       double_update(&m_maxDuration, delta, sg_surf_precision);
1059
1060     //FIXME: duplicated code
1061     if ((m_remains <= 0) &&
1062         (lmm_get_variable_weight(getVariable()) > 0)) {
1063       finish();
1064       setState(SURF_ACTION_DONE);
1065       heapRemove(getModel()->getActionHeap());
1066     } else if (((m_maxDuration != NO_MAX_DURATION)
1067         && (m_maxDuration <= 0))) {
1068       finish();
1069       setState(SURF_ACTION_DONE);
1070       heapRemove(getModel()->getActionHeap());
1071     }
1072   }
1073
1074   m_lastUpdate = now;
1075   m_lastValue = lmm_variable_getvalue(getVariable());
1076 }