Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
668bd417c14a70bc8d7079796a86c26bc329f70c
[simgrid.git] / src / simix / smx_global.c
1 /*      $Id$     */
2
3 /* Copyright (c) 2007 Arnaud Legrand, Bruno Donassolo.
4    All rights reserved.                                          */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "private.h"
10 #include "xbt/sysdep.h"
11 #include "xbt/log.h"
12 #include "xbt/str.h"
13 #include "xbt/ex.h"             /* ex_backtrace_display */
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix,
15                                 "Logging specific to SIMIX (kernel)");
16
17 SIMIX_Global_t simix_global = NULL;
18
19 /********************************* SIMIX **************************************/
20 static void __simix_config_helper(const char *name, ...)
21 {
22   va_list pa;
23   va_start(pa, name);
24
25   SIMIX_config(name, pa);
26
27   va_end(pa);
28 }
29
30 static void simix_cfg_control_set(const char *control_string)
31 {
32   /* To split the string in commands, and the cursors */
33   xbt_dynar_t set_strings;
34   char *str;
35   unsigned int cpt;
36
37   if (!control_string)
38     return;
39   DEBUG1("Parse log settings '%s'", control_string);
40
41   /* split the string, and remove empty entries */
42   set_strings = xbt_str_split_quoted(control_string);
43
44   if (xbt_dynar_length(set_strings) == 0) {     /* vicious user! */
45     xbt_dynar_free(&set_strings);
46     return;
47   }
48   /* Parse each entry and either use it right now (if the category was already
49      created), or store it for further use */
50   xbt_dynar_foreach(set_strings, cpt, str) {
51     char *control_string, *control_string_sav, *name, *value;
52
53
54     control_string = control_string_sav = strdup(str);
55     control_string += strspn(control_string, " ");
56     name = control_string;
57     control_string += strcspn(str, ":=");
58     value = control_string;
59     *value = 0;
60     value++;
61
62     xbt_assert1(strlen(name) != 0, "Invalid name for configuration: '%s'",
63                 name);
64     xbt_assert1(strlen(value) != 0,
65                 "Invalid value for configuration: '%s'", value);
66     INFO2("setting '%s' to '%s'", name, value);
67
68     __simix_config_helper(name, value);
69
70     free(control_string_sav);
71   }
72   xbt_dynar_free(&set_strings);
73 }
74
75 static void simix_cfg_init(int *argc, char **argv)
76 {
77   int i, j;
78   char *opt;
79
80   for (i = 1; i < *argc; i++) {
81     if (!strncmp(argv[i], "--cfg=", strlen("--cfg="))) {
82       opt = strchr(argv[i], '=');
83       opt++;
84
85       simix_cfg_control_set(opt);
86       DEBUG1("Did apply '%s' as config setting", opt);
87       /*remove this from argv */
88
89       for (j = i + 1; j < *argc; j++) {
90         argv[j - 1] = argv[j];
91       }
92
93       argv[j - 1] = NULL;
94       (*argc)--;
95       i--;                      /* compensate effect of next loop incrementation */
96     }
97   }
98 }
99
100 /**
101  * \brief Initialize some SIMIX internal data.
102  *
103  * \param argc Argc
104  * \param argv Argv
105  */
106 void SIMIX_global_init(int *argc, char **argv)
107 {
108   s_smx_process_t proc;
109
110   if (!simix_global) {
111     surf_init(argc, argv);      /* Initialize some common structures. Warning, it sets simix_global=NULL */
112     simix_cfg_init(argc, argv);
113
114     simix_global = xbt_new0(s_SIMIX_Global_t, 1);
115
116     simix_global->host = xbt_dict_new();
117     simix_global->process_to_run =
118         xbt_swag_new(xbt_swag_offset(proc, synchro_hookup));
119     simix_global->process_list =
120         xbt_swag_new(xbt_swag_offset(proc, process_hookup));
121     simix_global->current_process = NULL;
122     simix_global->registered_functions = xbt_dict_new();
123         
124     simix_global->create_process_function = NULL;
125     simix_global->kill_process_function = NULL;
126     simix_global->cleanup_process_function = SIMIX_process_cleanup;
127   }
128 }
129
130 /* Debug purpose, incomplete */
131 void SIMIX_display_process_status(void)
132 {
133   smx_process_t process = NULL;
134   xbt_fifo_item_t item = NULL;
135   smx_action_t act;
136   int nbprocess = xbt_swag_size(simix_global->process_list);
137
138   INFO1("%d processes are still running, waiting for something.",
139         nbprocess);
140   /*  List the process and their state */
141   INFO0
142       ("Legend of the following listing: \"<process> on <host>: <status>.\"");
143   xbt_swag_foreach(process, simix_global->process_list) {
144     smx_simdata_process_t p_simdata =
145         (smx_simdata_process_t) process->simdata;
146     // simdata_host_t h_simdata=(simdata_host_t)p_simdata->host->simdata;
147     char *who, *who2;
148
149     asprintf(&who, "%s on %s: %s",
150              process->name,
151              p_simdata->smx_host->name,
152              (process->simdata->blocked) ? "[BLOCKED] "
153              : ((process->simdata->suspended) ? "[SUSPENDED] " : ""));
154
155     if (p_simdata->mutex) {
156                 who2 = bprintf("%s Blocked on mutex %#x", who, (XBT_LOG_ISENABLED(simix_kernel,xbt_log_priority_verbose))?p_simdata->mutex:(void*)0xdead);
157       free(who);
158       who = who2;
159     } else if (p_simdata->cond) {
160       who2 =
161           bprintf
162           ("%s Blocked on condition %#x; Waiting for the following actions:",
163            who, (XBT_LOG_ISENABLED(simix_kernel,xbt_log_priority_verbose))?p_simdata->cond:(void*)0xdead);
164       free(who);
165       who = who2;
166       xbt_fifo_foreach(p_simdata->cond->actions, item, act, smx_action_t) {
167                   who2 = bprintf("%s '%s'(%#x)", who, act->name,(XBT_LOG_ISENABLED(simix_kernel,xbt_log_priority_verbose))?act:(void*)0xdead);
168         free(who);
169         who = who2;
170       }
171     } else {
172       who2 =
173           bprintf
174           ("%s Blocked in an unknown status (please report this bug)",
175            who);
176       free(who);
177       who = who2;
178     }
179     INFO1("%s.", who);
180     free(who);
181   }
182 }
183
184 /* FIXME: Yeah, I'll do it in a portable maner one day [Mt] */
185 #include <signal.h>
186
187 static void _XBT_CALL inthandler(int ignored)
188 {
189   INFO0("CTRL-C pressed. Displaying status and bailing out");
190   SIMIX_display_process_status();
191   exit(1);
192 }
193
194 /**
195  * \brief Launch the SIMIX simulation, debug purpose
196  */
197 void __SIMIX_main(void)
198 {
199   smx_process_t process = NULL;
200   smx_cond_t cond = NULL;
201   smx_action_t smx_action;
202   xbt_fifo_t actions_done = xbt_fifo_new();
203   xbt_fifo_t actions_failed = xbt_fifo_new();
204
205   /* Prepare to display some more info when dying on Ctrl-C pressing */
206   signal(SIGINT, inthandler);
207
208   /* Clean IO before the run */
209   fflush(stdout);
210   fflush(stderr);
211
212   //surf_solve(); /* Takes traces into account. Returns 0.0 */
213   /* xbt_fifo_size(msg_global->process_to_run) */
214
215   while (SIMIX_solve(actions_done, actions_failed) != -1.0) {
216
217     while ((smx_action = xbt_fifo_pop(actions_failed))) {
218
219       xbt_fifo_item_t _cursor;
220
221       DEBUG1("** %s failed **", smx_action->name);
222       xbt_fifo_foreach(smx_action->cond_list, _cursor, cond, smx_cond_t) {
223         xbt_swag_foreach(process, cond->sleeping) {
224           DEBUG2("\t preparing to wake up %s on %s",
225                  process->name, process->simdata->smx_host->name);
226         }
227         SIMIX_cond_broadcast(cond);
228         /* remove conditional from action */
229         SIMIX_unregister_action_to_condition(smx_action, cond);
230       }
231     }
232
233     while ((smx_action = xbt_fifo_pop(actions_done))) {
234       xbt_fifo_item_t _cursor;
235
236       DEBUG1("** %s done **", smx_action->name);
237       xbt_fifo_foreach(smx_action->cond_list, _cursor, cond, smx_cond_t) {
238         xbt_swag_foreach(process, cond->sleeping) {
239           DEBUG2("\t preparing to wake up %s on %s",
240                  process->name, process->simdata->smx_host->name);
241         }
242         SIMIX_cond_broadcast(cond);
243         /* remove conditional from action */
244         SIMIX_unregister_action_to_condition(smx_action, cond);
245       }
246     }
247   }
248   return;
249 }
250
251 /**
252  * \brief Kill all running process
253  *
254  */
255 void SIMIX_process_killall()
256 {
257   smx_process_t p = NULL;
258   smx_process_t self = SIMIX_process_self();
259
260   while ((p = xbt_swag_extract(simix_global->process_list))) {
261     if (p != self)
262       SIMIX_process_kill(p);
263   }
264
265   xbt_context_empty_trash();
266
267   if (self) {
268     xbt_context_yield();
269   }
270
271   return;
272 }
273
274 /** 
275  * \brief Clean the SIMIX simulation
276  *
277  * This functions remove all memories needed to the SIMIX execution
278  */
279 void SIMIX_clean(void)
280 {
281   smx_process_t p = NULL;
282
283   while ((p = xbt_swag_extract(simix_global->process_list))) {
284     SIMIX_process_kill(p);
285   }
286
287   xbt_dict_free(&(simix_global->host));
288   xbt_swag_free(simix_global->process_to_run);
289   xbt_swag_free(simix_global->process_list);
290   xbt_dict_free(&(simix_global->registered_functions));
291   simix_config_finalize();
292   free(simix_global);
293   simix_global = NULL;
294   
295   surf_exit();
296
297   return;
298 }
299
300
301 /**
302  * \brief A clock (in second).
303  *
304  * \return Return the clock.
305  */
306 double SIMIX_get_clock(void)
307 {
308   return surf_get_clock();
309 }
310
311 /**
312  *      \brief Finish the simulation initialization 
313  * 
314  *      Must be called before the first call to SIMIX_solve()
315  */
316 void SIMIX_init(void) {
317     surf_presolve();
318 }
319
320 /**
321  *      \brief Does a turn of the simulation
322  *
323  *      Executes a step in the surf simulation, adding to the two lists all the actions that finished on this turn. Schedules all processus in the process_to_run list.         
324  *      \param actions_done List of actions done
325  *      \param actions_failed List of actions failed
326  *      \return The time spent to execute the simulation or -1 if the simulation ended
327  */
328 double SIMIX_solve(xbt_fifo_t actions_done, xbt_fifo_t actions_failed)
329 {
330
331   smx_process_t process = NULL;
332   unsigned int iter;
333   double elapsed_time = 0.0;
334   static int state_modifications = 1;
335
336   xbt_context_empty_trash();
337   if (xbt_swag_size(simix_global->process_to_run) && (elapsed_time > 0)) {
338     DEBUG0("**************************************************");
339   }
340  
341   while ((process = xbt_swag_extract(simix_global->process_to_run))) {
342     DEBUG2("Scheduling %s on %s",
343            process->name, process->simdata->smx_host->name);
344     simix_global->current_process = process;
345     xbt_context_schedule(process->simdata->context);
346     /*       fflush(NULL); */
347     simix_global->current_process = NULL;
348   }
349
350   {
351     surf_action_t action = NULL;
352     surf_model_t model = NULL;
353     smx_action_t smx_action = NULL;
354
355     void *fun = NULL;
356     void *arg = NULL;
357
358     xbt_dynar_foreach(model_list, iter, model) {
359       if (xbt_swag_size(model->common_public->states.failed_action_set)
360           || xbt_swag_size(model->common_public->states.
361                            done_action_set)) {
362         state_modifications = 1;
363          break;
364       }
365     }
366
367     if (!state_modifications) {
368       DEBUG1("%f : Calling surf_solve", SIMIX_get_clock());
369       elapsed_time = surf_solve();
370       DEBUG1("Elapsed_time %f", elapsed_time);
371     }
372
373     while (surf_timer_model->extension_public->get(&fun, (void *) &arg)) {
374       DEBUG2("got %p %p", fun, arg);
375       if (fun == SIMIX_process_create) {
376         smx_process_arg_t args = arg;
377         DEBUG2("Launching %s on %s", args->name, args->hostname);
378         process = SIMIX_process_create(args->name, args->code,
379                                        args->data, args->hostname,
380                                        args->argc, args->argv, args->properties);
381         if (args->kill_time > SIMIX_get_clock()) {
382           surf_timer_model->extension_public->set(args->kill_time,
383                                                      (void *)
384                                                      &SIMIX_process_kill,
385                                                      (void *) process);
386         }
387         xbt_free(args);
388       }
389       if (fun == SIMIX_process_kill) {
390         process = arg;
391         DEBUG2("Killing %s on %s", process->name,
392                process->simdata->smx_host->name);
393         SIMIX_process_kill(process);
394       }
395     }
396
397     /* Wake up all process waiting for the action finish */
398     xbt_dynar_foreach(model_list, iter, model) {
399       while ((action =
400               xbt_swag_extract(model->common_public->states.
401                                failed_action_set))) {
402         smx_action = action->data;
403         if (smx_action) {
404           xbt_fifo_unshift(actions_failed, smx_action);
405         }
406       }
407       while ((action =
408               xbt_swag_extract(model->common_public->states.
409                                done_action_set))) {
410         smx_action = action->data;
411         if (smx_action) {
412           xbt_fifo_unshift(actions_done, smx_action);
413         }
414       }
415     }
416   }
417   state_modifications = 0;
418
419   if (elapsed_time == -1) {
420     if (xbt_swag_size(simix_global->process_list) == 0) {
421 /*                      INFO0("Congratulations ! Simulation terminated : all processes are over"); */
422     } else {
423       INFO0("Oops ! Deadlock or code not perfectly clean.");
424       SIMIX_display_process_status();
425       if (XBT_LOG_ISENABLED(simix, xbt_log_priority_debug) ||
426           XBT_LOG_ISENABLED(simix_kernel, xbt_log_priority_debug)) {
427         DEBUG0("Aborting!");
428         xbt_abort();
429       }
430       INFO0("Return a Warning.");
431     }
432   }
433   return elapsed_time;
434 }
435
436 /**
437  *      \brief Set the date to execute a function
438  *
439  * Set the date to execute the function on the surf.
440  *      \param date Date to execute function
441  *      \param function Function to be executed
442  *      \param arg Parameters of the function
443  *
444  */
445 void SIMIX_timer_set(double date, void *function, void *arg)
446 {
447   surf_timer_model->extension_public->set(date, function, arg);
448 }
449
450 int SIMIX_timer_get(void **function, void **arg)
451 {
452   return surf_timer_model->extension_public->get(function, arg);
453 }
454
455 /**
456  *      \brief Registers a function to create a process.
457  *
458  *      This function registers an user function to be called when a new process is created. The user function have to call the SIMIX_create_process function.
459  *      \param function Create process function
460  *
461  */
462 void SIMIX_function_register_process_create(smx_creation_func_t function)
463 {
464   xbt_assert0((simix_global->create_process_function == NULL),
465               "Data already set");
466
467   simix_global->create_process_function = function;
468 }
469
470 /**
471  *      \brief Registers a function to kill a process.
472  *
473  *      This function registers an user function to be called when a new process is killed. The user function have to call the SIMIX_kill_process function.
474  *      \param function Kill process function
475  *
476  */
477 void SIMIX_function_register_process_kill(void_f_pvoid_t function)
478 {
479   xbt_assert0((simix_global->kill_process_function == NULL),
480               "Data already set");
481
482   simix_global->kill_process_function = function;
483 }
484
485 /**
486  *      \brief Registers a function to cleanup a process.
487  *
488  *      This function registers an user function to be called when a new process ends properly.
489  *      \param function cleanup process function
490  *
491  */
492 void SIMIX_function_register_process_cleanup(void_f_pvoid_t function)
493 {
494   simix_global->cleanup_process_function = function;
495 }