Logo AND Algorithmique Numérique Distribuée

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