Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge cpu and network
[simgrid.git] / src / surf / surf.c
1 /* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011. 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 <ctype.h>
8
9 #include "surf_private.h"
10 #include "xbt/module.h"
11 #include "mc/mc.h"
12 #include "surf/surf_resource.h"
13 #include "xbt/xbt_os_thread.h"
14
15 XBT_LOG_NEW_CATEGORY(surf, "All SURF categories");
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_kernel, surf,
17                                 "Logging specific to SURF (kernel)");
18
19 /* Additional declarations for Windows portability. */
20
21 #ifndef MAX_DRIVE
22 #define MAX_DRIVE 26
23 #endif
24
25 #ifdef _XBT_WIN32
26 #include <windows.h>
27 static const char *disk_drives_letter_table[MAX_DRIVE] = {
28   "A:\\",
29   "B:\\",
30   "C:\\",
31   "D:\\",
32   "E:\\",
33   "F:\\",
34   "G:\\",
35   "H:\\",
36   "I:\\",
37   "J:\\",
38   "K:\\",
39   "L:\\",
40   "M:\\",
41   "N:\\",
42   "O:\\",
43   "P:\\",
44   "Q:\\",
45   "R:\\",
46   "S:\\",
47   "T:\\",
48   "U:\\",
49   "V:\\",
50   "W:\\",
51   "X:\\",
52   "Y:\\",
53   "Z:\\"
54 };
55 #endif                          /* #ifdef _XBT_WIN32 */
56
57 /*
58  * Returns the initial path. On Windows the initial path is
59  * the current directory for the current process in the other
60  * case the function returns "./" that represents the current
61  * directory on Unix/Linux platforms.
62  */
63
64 const char *__surf_get_initial_path(void)
65 {
66
67 #ifdef _XBT_WIN32
68   unsigned i;
69   char current_directory[MAX_PATH + 1] = { 0 };
70   unsigned int len = GetCurrentDirectory(MAX_PATH + 1, current_directory);
71   char root[4] = { 0 };
72
73   if (!len)
74     return NULL;
75
76   strncpy(root, current_directory, 3);
77
78   for (i = 0; i < MAX_DRIVE; i++) {
79     if (toupper(root[0]) == disk_drives_letter_table[i][0])
80       return disk_drives_letter_table[i];
81   }
82
83   return NULL;
84 #else
85   return "./";
86 #endif
87 }
88
89 /* The __surf_is_absolute_file_path() returns 1 if
90  * file_path is a absolute file path, in the other
91  * case the function returns 0.
92  */
93 int __surf_is_absolute_file_path(const char *file_path)
94 {
95 #ifdef _XBT_WIN32
96   WIN32_FIND_DATA wfd = { 0 };
97   HANDLE hFile = FindFirstFile(file_path, &wfd);
98
99   if (INVALID_HANDLE_VALUE == hFile)
100     return 0;
101
102   FindClose(hFile);
103   return 1;
104 #else
105   return (file_path[0] == '/');
106 #endif
107 }
108
109 double NOW = 0;
110
111 xbt_dynar_t model_list = NULL;
112 tmgr_history_t history = NULL;
113 lmm_system_t maxmin_system = NULL;
114 xbt_dynar_t surf_path = NULL;
115
116 /* Don't forget to update the option description in smx_config when you change this */
117 s_surf_model_description_t surf_network_model_description[] = {
118   {"LV08",
119    "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). ",
120    surf_network_model_init_LegrandVelho},
121   {"Constant",
122    "Simplistic network model where all communication take a constant time (one second). This model provides the lowest realism, but is (marginally) faster.",
123    surf_network_model_init_Constant},
124   {"SMPI",
125    "Realistic network model specifically tailored for HPC settings (accurate modeling of slow start with correction factors on three intervals: < 1KiB, < 64 KiB, >= 64 KiB)",
126    surf_network_model_init_SMPI},
127   {"CM02",
128    "Legacy network analytic model (Very similar to LV08, but without corrective factors. The timings of small messages are thus poorly modeled).",
129    surf_network_model_init_CM02},
130 #ifdef HAVE_GTNETS
131   {"GTNets",
132    "Network pseudo-model using the GTNets simulator instead of an analytic model",
133    surf_network_model_init_GTNETS},
134 #endif
135 #ifdef HAVE_NS3
136   {"NS3",
137    "Network pseudo-model using the NS3 tcp model instead of an analytic model",
138         surf_network_model_init_NS3},
139 #endif
140   {"Reno",
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_Reno},
143   {"Reno2",
144    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
145    surf_network_model_init_Reno2},
146   {"Vegas",
147    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
148    surf_network_model_init_Vegas},
149   {NULL, NULL, NULL}      /* this array must be NULL terminated */
150 };
151
152 s_surf_model_description_t surf_cpu_model_description[] = {
153   {"Cas01",
154    "Simplistic CPU model (time=size/power).",
155    surf_cpu_model_init_Cas01},
156   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
157 };
158
159 s_surf_model_description_t surf_workstation_model_description[] = {
160   {"default",
161    "Default workstation model. Currently, CPU:Cas01 and network:LV08 (with cross traffic enabled)",
162    surf_workstation_model_init_current_default},
163   {"compound",
164    "Workstation model that is automatically chosen if you change the network and CPU models",
165    surf_workstation_model_init_compound},
166   {"ptask_L07", "Workstation model somehow similar to Cas01+CM02 but allowing parallel tasks",
167    surf_workstation_model_init_ptask_L07},
168   {NULL, NULL, NULL}      /* this array must be NULL terminated */
169 };
170
171 s_surf_model_description_t surf_optimization_mode_description[] = {
172   {"Lazy",
173    "Lazy action management (partial invalidation in lmm + heap in action remaining).",
174    NULL},
175   {"TI",
176    "Trace integration. Highly optimized mode when using availability traces (only available for the Cas01 CPU model for now).",
177     NULL},
178   {"Full",
179    "Full update of remaining and variables. Slow but may be useful when debugging.",
180    NULL},
181   {NULL, NULL, NULL}      /* this array must be NULL terminated */
182 };
183
184 s_surf_model_description_t surf_storage_model_description[] = {
185   {"default",
186    "Simplistic storage model.",
187    surf_storage_model_init_default},
188   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
189 };
190
191 #ifdef CONTEXT_THREADS
192 static xbt_parmap_t surf_parmap = NULL; /* parallel map on models */
193 #endif
194
195 static int surf_nthreads = 1;    /* number of threads of the parmap (1 means no parallelism) */
196 static double *surf_mins = NULL; /* return value of share_resources for each model */
197 static int surf_min_index;       /* current index in surf_mins */
198 static double min;               /* duration determined by surf_solve */
199
200 static void surf_share_resources(surf_model_t model);
201 static void surf_update_actions_state(surf_model_t model);
202
203 /** Displays the long description of all registered models, and quit */
204 void model_help(const char *category, s_surf_model_description_t * table)
205 {
206   int i;
207   printf("Long description of the %s models accepted by this simulator:\n",
208          category);
209   for (i = 0; table[i].name; i++)
210     printf("  %s: %s\n", table[i].name, table[i].description);
211 }
212
213 int find_model_description(s_surf_model_description_t * table,
214                            const char *name)
215 {
216   int i;
217   char *name_list = NULL;
218
219   for (i = 0; table[i].name; i++)
220     if (!strcmp(name, table[i].name)) {
221       return i;
222     }
223   name_list = strdup(table[0].name);
224   for (i = 1; table[i].name; i++) {
225     name_list =
226         xbt_realloc(name_list,
227                     strlen(name_list) + strlen(table[i].name) + 3);
228     strcat(name_list, ", ");
229     strcat(name_list, table[i].name);
230   }
231   xbt_die("Model '%s' is invalid! Valid models are: %s.", name, name_list);
232   return -1;
233 }
234
235 double generic_maxmin_share_resources(xbt_swag_t running_actions,
236                                       size_t offset,
237                                       lmm_system_t sys,
238                                       void (*solve) (lmm_system_t))
239 {
240   surf_action_t action = NULL;
241   double min = -1;
242   double value = -1;
243 #define VARIABLE(action) (*((lmm_variable_t*)(((char *) (action)) + (offset))))
244
245   solve(sys);
246
247   xbt_swag_foreach(action, running_actions) {
248     value = lmm_variable_getvalue(VARIABLE(action));
249     if ((value > 0) || (action->max_duration >= 0))
250       break;
251   }
252
253   if (!action)
254     return -1.0;
255
256   if (value > 0) {
257     if (action->remains > 0)
258       min = action->remains / value;
259     else
260       min = 0.0;
261     if ((action->max_duration >= 0) && (action->max_duration < min))
262       min = action->max_duration;
263   } else
264     min = action->max_duration;
265
266
267   for (action = xbt_swag_getNext(action, running_actions->offset);
268        action;
269        action = xbt_swag_getNext(action, running_actions->offset)) {
270     value = lmm_variable_getvalue(VARIABLE(action));
271     if (value > 0) {
272       if (action->remains > 0)
273         value = action->remains / value;
274       else
275         value = 0.0;
276       if (value < min) {
277         min = value;
278         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
279       }
280     }
281     if ((action->max_duration >= 0) && (action->max_duration < min)) {
282       min = action->max_duration;
283       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
284     }
285   }
286   XBT_DEBUG("min value : %f", min);
287
288 #undef VARIABLE
289   return min;
290 }
291
292 double generic_share_resources_lazy(double now, surf_model_t model)
293 {
294   surf_action_lmm_t action = NULL;
295   double min = -1;
296   double value;
297
298   XBT_DEBUG
299       ("Before share resources, the size of modified actions set is %d",
300        xbt_swag_size(model->model_private->modified_set));
301
302   lmm_solve(model->model_private->maxmin_system);
303
304   XBT_DEBUG
305       ("After share resources, The size of modified actions set is %d",
306        xbt_swag_size(model->model_private->modified_set));
307
308   while((action = xbt_swag_extract(model->model_private->modified_set))) {
309     int max_dur_flag = 0;
310
311     if (action->generic_action.state_set !=
312         model->states.running_action_set)
313       continue;
314
315     /* bogus priority, skip it */
316     if (action->generic_action.priority <= 0)
317       continue;
318
319     generic_update_action_remaining_lazy(action,now);
320
321     min = -1;
322     value = lmm_variable_getvalue(action->variable);
323     if (value > 0) {
324       if (action->generic_action.remains > 0) {
325         value = action->generic_action.remains / value;
326         min = now + value;
327       } else {
328         value = 0.0;
329         min = now;
330       }
331     }
332
333     if ((action->generic_action.max_duration != NO_MAX_DURATION)
334         && (min == -1
335             || action->generic_action.start +
336             action->generic_action.max_duration < min)) {
337       min = action->generic_action.start +
338           action->generic_action.max_duration;
339       max_dur_flag = 1;
340     }
341
342     XBT_DEBUG("Action(%p) Start %lf Finish %lf Max_duration %lf", action,
343         action->generic_action.start, now + value,
344         action->generic_action.max_duration);
345
346     if (min != -1) {
347       surf_action_lmm_heap_remove(model->model_private->action_heap,action);
348       surf_action_lmm_heap_insert(model->model_private->action_heap,action, min, max_dur_flag ? MAX_DURATION : NORMAL);
349       XBT_DEBUG("Insert at heap action(%p) min %lf now %lf", action, min,
350                 now);
351     } else DIE_IMPOSSIBLE;
352   }
353
354   //hereafter must have already the min value for this resource model
355   if (xbt_heap_size(model->model_private->action_heap) > 0)
356     min = xbt_heap_maxkey(model->model_private->action_heap) - now;
357   else
358     min = -1;
359
360   XBT_DEBUG("The minimum with the HEAP %lf", min);
361
362   return min;
363 }
364 static XBT_INLINE void routing_asr_host_free(void *p)
365 {
366   sg_routing_edge_t elm = p;
367   free(elm->name);
368   xbt_free(elm);
369 }
370
371 void surf_init(int *argc, char **argv)
372 {
373   XBT_DEBUG("Create all Libs");
374   host_lib = xbt_lib_new();
375   link_lib = xbt_lib_new();
376   as_router_lib = xbt_lib_new();
377   storage_lib = xbt_lib_new();
378   storage_type_lib = xbt_lib_new();
379
380   XBT_DEBUG("ADD ROUTING LEVEL");
381   ROUTING_HOST_LEVEL = xbt_lib_add_level(host_lib,routing_asr_host_free);
382   ROUTING_ASR_LEVEL  = xbt_lib_add_level(as_router_lib,routing_asr_host_free);
383
384   XBT_DEBUG("ADD SURF LEVELS");
385   SURF_CPU_LEVEL = xbt_lib_add_level(host_lib,surf_resource_free);
386   SURF_WKS_LEVEL = xbt_lib_add_level(host_lib,surf_resource_free);
387   SURF_LINK_LEVEL = xbt_lib_add_level(link_lib,surf_resource_free);
388
389   xbt_init(argc, argv);
390   if (!model_list)
391     model_list = xbt_dynar_new(sizeof(surf_model_private_t), NULL);
392   if (!history)
393     history = tmgr_history_new();
394
395   surf_config_init(argc, argv);
396   surf_action_init();
397   if (MC_IS_ENABLED)
398     MC_memory_init();
399 }
400
401 #ifdef _XBT_WIN32
402 # define FILE_DELIM "\\"
403 #else
404 # define FILE_DELIM "/"         /* FIXME: move to better location */
405 #endif
406
407 FILE *surf_fopen(const char *name, const char *mode)
408 {
409   unsigned int cpt;
410   char *path_elm = NULL;
411   char *buff;
412   FILE *file = NULL;
413
414   xbt_assert(name);
415
416   if (__surf_is_absolute_file_path(name))       /* don't mess with absolute file names */
417     return fopen(name, mode);
418
419   /* search relative files in the path */
420   xbt_dynar_foreach(surf_path, cpt, path_elm) {
421     buff = bprintf("%s" FILE_DELIM "%s", path_elm, name);
422     file = fopen(buff, mode);
423     free(buff);
424
425     if (file)
426       return file;
427   }
428   return NULL;
429 }
430
431 void surf_exit(void)
432 {
433   unsigned int iter;
434   surf_model_t model = NULL;
435
436   surf_config_finalize();
437
438   xbt_dynar_foreach(model_list, iter, model)
439       model->model_private->finalize();
440   xbt_dynar_free(&model_list);
441   routing_exit();
442
443   if (maxmin_system) {
444     lmm_system_free(maxmin_system);
445     maxmin_system = NULL;
446   }
447   if (history) {
448     tmgr_history_free(history);
449     history = NULL;
450   }
451   surf_action_exit();
452
453 #ifdef CONTEXT_THREADS
454   xbt_parmap_destroy(surf_parmap);
455   xbt_free(surf_mins);
456   surf_mins = NULL;
457 #endif
458
459   xbt_dynar_free(&surf_path);
460
461   xbt_lib_free(&host_lib);
462   xbt_lib_free(&link_lib);
463   xbt_lib_free(&as_router_lib);
464   xbt_lib_free(&storage_lib);
465   xbt_lib_free(&storage_type_lib);
466
467   tmgr_finalize();
468   surf_parse_lex_destroy();
469   surf_parse_free_callbacks();
470
471   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
472 }
473
474 void surf_presolve(void)
475 {
476   double next_event_date = -1.0;
477   tmgr_trace_event_t event = NULL;
478   double value = -1.0;
479   surf_resource_t resource = NULL;
480   surf_model_t model = NULL;
481   unsigned int iter;
482
483   XBT_DEBUG
484       ("First Run! Let's \"purge\" events and put models in the right state");
485   while ((next_event_date = tmgr_history_next_date(history)) != -1.0) {
486     if (next_event_date > NOW)
487       break;
488     while ((event =
489             tmgr_history_get_next_event_leq(history, next_event_date,
490                                             &value,
491                                             (void **) &resource))) {
492       resource->model->model_private->update_resource_state(resource,
493                                                             event, value,
494                                                             NOW);
495     }
496   }
497   xbt_dynar_foreach(model_list, iter, model)
498       model->model_private->update_actions_state(NOW, 0.0);
499 }
500
501 double surf_solve(double max_date)
502 {
503   min = -1.0; /* duration */
504   double next_event_date = -1.0;
505   double model_next_action_end = -1.0;
506   double value = -1.0;
507   surf_resource_t resource = NULL;
508   surf_model_t model = NULL;
509   tmgr_trace_event_t event = NULL;
510   unsigned int iter;
511
512   if (max_date != -1.0 && max_date != NOW) {
513     min = max_date - NOW;
514   }
515
516   XBT_DEBUG("Looking for next action end for all models except NS3");
517
518   if (surf_mins == NULL) {
519     surf_mins = xbt_new(double, xbt_dynar_length(model_list));
520   }
521   surf_min_index = 0;
522
523
524   if (surf_get_nthreads() > 1) {
525     /* parallel version */
526 #ifdef CONTEXT_THREADS
527     xbt_parmap_apply(surf_parmap, (void_f_pvoid_t) surf_share_resources, model_list);
528 #endif
529   }
530   else {
531     /* sequential version */
532     xbt_dynar_foreach(model_list, iter, model) {
533       surf_share_resources(model);
534     }
535   }
536
537   unsigned i;
538   for (i = 0; i < xbt_dynar_length(model_list); i++) {
539     if ((min < 0.0 || surf_mins[i] < min)
540         && surf_mins[i] >= 0.0) {
541       min = surf_mins[i];
542     }
543   }
544
545   XBT_DEBUG("Min for resources (remember that NS3 dont update that value) : %f", min);
546
547   XBT_DEBUG("Looking for next trace event");
548
549   do {
550     XBT_DEBUG("Next TRACE event : %f", next_event_date);
551
552     next_event_date = tmgr_history_next_date(history);
553
554     if(surf_network_model->name && !strcmp(surf_network_model->name,"network NS3")){
555       if(next_event_date!=-1.0 && min!=-1.0) {
556         min = MIN(next_event_date - NOW, min);
557       } else{
558         min = MAX(next_event_date - NOW, min);
559       }
560
561       XBT_DEBUG("Run for NS3 at most %f", min);
562       // run until min or next flow
563       model_next_action_end = surf_network_model->model_private->share_resources(min);
564
565       XBT_DEBUG("Min for NS3 : %f", model_next_action_end);
566       if(model_next_action_end>=0.0)
567         min = model_next_action_end;
568     }
569
570     if (next_event_date == -1.0) {
571         XBT_DEBUG("no next TRACE event. Stop searching for it");
572         break;
573     }
574
575     if ((min != -1.0) && (next_event_date > NOW + min)) break;
576
577     XBT_DEBUG("Updating models");
578     while ((event =
579             tmgr_history_get_next_event_leq(history, next_event_date,
580                                             &value,
581                                             (void **) &resource))) {
582       if (resource->model->model_private->resource_used(resource)) {
583         min = next_event_date - NOW;
584         XBT_DEBUG
585             ("This event will modify model state. Next event set to %f",
586              min);
587       }
588       /* update state of model_obj according to new value. Does not touch lmm.
589          It will be modified if needed when updating actions */
590       XBT_DEBUG("Calling update_resource_state for resource %s with min %lf",
591              resource->model->name, min);
592       resource->model->model_private->update_resource_state(resource,
593                                                             event, value,
594                                                             NOW + min);
595     }
596   } while (1);
597
598   /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are with availability = 0.
599    * This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a trace with periodicity > 0.
600    * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed */
601   if (min == -1.0) {
602         XBT_DEBUG("No next event at all. Bail out now.");
603     return -1.0;
604   }
605
606   XBT_DEBUG("Duration set to %f", min);
607
608   NOW = NOW + min;
609
610   if (surf_get_nthreads() > 1) {
611     /* parallel version */
612 #ifdef CONTEXT_THREADS
613     xbt_parmap_apply(surf_parmap, (void_f_pvoid_t) surf_update_actions_state, model_list);
614 #endif
615   }
616   else {
617     /* sequential version */
618     xbt_dynar_foreach(model_list, iter, model) {
619       surf_update_actions_state(model);
620     }
621   }
622
623 #ifdef HAVE_TRACING
624   TRACE_paje_dump_buffer (0);
625 #endif
626
627   return min;
628 }
629
630 XBT_INLINE double surf_get_clock(void)
631 {
632   return NOW;
633 }
634
635 static void surf_share_resources(surf_model_t model)
636 {
637   double next_action_end = -1.0;
638   int i = __sync_fetch_and_add(&surf_min_index, 1);
639   if (strcmp(model->name,"network NS3")) {
640     XBT_DEBUG("Running for Resource [%s]", model->name);
641     next_action_end = model->model_private->share_resources(NOW);
642     XBT_DEBUG("Resource [%s] : next action end = %f",
643         model->name, next_action_end);
644   }
645   surf_mins[i] = next_action_end;
646 }
647
648 static void surf_update_actions_state(surf_model_t model)
649 {
650   model->model_private->update_actions_state(NOW, min);
651 }
652
653 /**
654  * \brief Returns the number of parallel threads used to update the models.
655  * \return the number of threads (1 means no parallelism)
656  */
657 int surf_get_nthreads(void) {
658   return surf_nthreads;
659 }
660
661 /**
662  * \brief Sets the number of parallel threads used to update the models.
663  *
664  * A value of 1 means no parallelism.
665  *
666  * \param nb_threads the number of threads to use
667  */
668 void surf_set_nthreads(int nthreads) {
669
670   if (nthreads<=0) {
671      nthreads = xbt_os_get_numcores();
672      XBT_INFO("Auto-setting surf/nthreads to %d",nthreads);
673   }
674
675 #ifdef CONTEXT_THREADS
676   xbt_parmap_destroy(surf_parmap);
677   surf_parmap = NULL;
678 #endif
679
680   if (nthreads > 1) {
681 #ifdef CONTEXT_THREADS
682     surf_parmap = xbt_parmap_new(nthreads, XBT_PARMAP_DEFAULT);
683 #else
684     THROWF(arg_error, 0, "Cannot activate parallel threads in Surf: your architecture does not support threads");
685 #endif
686   }
687
688   surf_nthreads = nthreads;
689 }