Logo AND Algorithmique Numérique Distribuée

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