Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Move SIMIX_process_on_exit functions to public
[simgrid.git] / src / simix / smx_global.c
1 /* Copyright (c) 2007, 2008, 2009, 2010. 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 "smx_private.h"
8 #include "xbt/heap.h"
9 #include "xbt/sysdep.h"
10 #include "xbt/log.h"
11 #include "xbt/str.h"
12 #include "xbt/ex.h"             /* ex_backtrace_display */
13 #include "mc/mc.h"
14
15 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix,
17                                 "Logging specific to SIMIX (kernel)");
18
19 smx_global_t simix_global = NULL;
20 static xbt_heap_t simix_timers = NULL;
21
22 static void* SIMIX_action_mallocator_new_f(void);
23 static void SIMIX_action_mallocator_free_f(void* action);
24 static void SIMIX_action_mallocator_reset_f(void* action);
25
26 extern void smx_ctx_raw_new_sr(void);
27
28 /* FIXME: Yeah, I'll do it in a portable maner one day [Mt] */
29 #include <signal.h>
30
31 int _surf_do_verbose_exit = 1;
32 static void _XBT_CALL inthandler(int ignored)
33 {
34   if ( _surf_do_verbose_exit ) {
35      XBT_INFO("CTRL-C pressed. Displaying status and bailing out");
36      SIMIX_display_process_status();
37   }
38   else {
39      XBT_INFO("CTRL-C pressed. bailing out without displaying because verbose-exit is disabled");
40   }
41   exit(1);
42 }
43
44 /********************************* SIMIX **************************************/
45
46 XBT_INLINE double SIMIX_timer_next(void)
47 {
48   return xbt_heap_size(simix_timers) > 0 ? xbt_heap_maxkey(simix_timers) : -1.0;
49 }
50
51 /**
52  * \ingroup SIMIX_API
53  * \brief Initialize SIMIX internal data.
54  *
55  * \param argc Argc
56  * \param argv Argv
57  */
58 void SIMIX_global_init(int *argc, char **argv)
59 {
60   s_smx_process_t proc;
61
62   if (!simix_global) {
63     simix_global = xbt_new0(s_smx_global_t, 1);
64
65     simix_global->process_to_run = xbt_dynar_new(sizeof(smx_process_t), NULL);
66     simix_global->process_that_ran = xbt_dynar_new(sizeof(smx_process_t), NULL);
67     simix_global->process_list =
68         xbt_swag_new(xbt_swag_offset(proc, process_hookup));
69     simix_global->process_to_destroy =
70         xbt_swag_new(xbt_swag_offset(proc, destroy_hookup));
71
72     simix_global->maestro_process = NULL;
73     simix_global->registered_functions = xbt_dict_new_homogeneous(NULL);
74
75     simix_global->create_process_function = SIMIX_process_create;
76     simix_global->kill_process_function = SIMIX_process_kill;
77     simix_global->cleanup_process_function = SIMIX_process_cleanup;
78     simix_global->action_mallocator = xbt_mallocator_new(65536,
79         SIMIX_action_mallocator_new_f, SIMIX_action_mallocator_free_f,
80         SIMIX_action_mallocator_reset_f);
81
82     surf_init(argc, argv);      /* Initialize SURF structures */
83     SIMIX_context_mod_init();
84     SIMIX_create_maestro_process();
85
86     /* context exception handlers */
87     __xbt_running_ctx_fetch = SIMIX_process_get_running_context;
88     __xbt_ex_terminate = SIMIX_process_exception_terminate;
89
90     /* Initialize the SIMIX network module */
91     SIMIX_network_init();
92
93     /* Prepare to display some more info when dying on Ctrl-C pressing */
94     signal(SIGINT, inthandler);
95   }
96   if (!simix_timers) {
97     simix_timers = xbt_heap_new(8, &free);
98   }
99
100   XBT_DEBUG("ADD SIMIX LEVELS");
101   SIMIX_HOST_LEVEL = xbt_lib_add_level(host_lib,SIMIX_host_destroy);
102 }
103
104 /**
105  * \ingroup SIMIX_API
106  * \brief Clean the SIMIX simulation
107  *
108  * This functions remove the memory used by SIMIX
109  */
110 void SIMIX_clean(void)
111 {
112 #ifdef TIME_BENCH
113   smx_ctx_raw_new_sr();
114 #endif
115
116   /* Kill everyone (except maestro) */
117   SIMIX_process_killall(simix_global->maestro_process);
118
119   /* Exit the SIMIX network module */
120   SIMIX_network_exit();
121
122   xbt_heap_free(simix_timers);
123   simix_timers = NULL;
124   /* Free the remaining data structures */
125   xbt_dynar_free(&simix_global->process_to_run);
126   xbt_dynar_free(&simix_global->process_that_ran);
127   xbt_swag_free(simix_global->process_to_destroy);
128   xbt_swag_free(simix_global->process_list);
129   simix_global->process_list = NULL;
130   simix_global->process_to_destroy = NULL;
131   xbt_dict_free(&(simix_global->registered_functions));
132
133   /* Let's free maestro now */
134   SIMIX_context_free(simix_global->maestro_process->context);
135   xbt_free(simix_global->maestro_process->running_ctx);
136   xbt_free(simix_global->maestro_process);
137   simix_global->maestro_process = NULL;
138
139   /* Restore the default exception setup */
140   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
141   __xbt_ex_terminate = &__xbt_ex_terminate_default;
142
143   /* Finish context module and SURF */
144   SIMIX_context_mod_exit();
145
146   surf_exit();
147
148   xbt_mallocator_free(simix_global->action_mallocator);
149   xbt_free(simix_global);
150   simix_global = NULL;
151
152   return;
153 }
154
155
156 /**
157  * \ingroup SIMIX_API
158  * \brief A clock (in second).
159  *
160  * \return Return the clock.
161  */
162 XBT_INLINE double SIMIX_get_clock(void)
163 {
164   if(MC_IS_ENABLED){
165     return MC_process_clock_get(SIMIX_process_self());
166   }else{
167     return surf_get_clock();
168   }
169 }
170
171 static int process_syscall_color(void *p)
172 {
173   switch ((*(smx_process_t *)p)->simcall.call) {
174   case SIMCALL_NONE:
175   case SIMCALL_PROCESS_KILL:
176     return 2;
177   case SIMCALL_PROCESS_RESUME:
178     return 1;
179   default:
180     return 0;
181   }
182 }
183
184 /**
185  * \ingroup SIMIX_API
186  * \brief Run the main simulation loop.
187  */
188 void SIMIX_run(void)
189 {
190   double time = 0;
191   smx_process_t process;
192   xbt_swag_t set;
193   surf_action_t action;
194   smx_timer_t timer;
195   surf_model_t model;
196   unsigned int iter;
197
198   do {
199     XBT_DEBUG("New Schedule Round; size(queue)=%lu",
200         xbt_dynar_length(simix_global->process_to_run));
201 #ifdef TIME_BENCH
202     smx_ctx_raw_new_sr();
203 #endif
204     while (!xbt_dynar_is_empty(simix_global->process_to_run)) {
205       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%lu",
206               xbt_dynar_length(simix_global->process_to_run));
207
208       /* Run all processes that are ready to run, possibly in parallel */
209       SIMIX_process_runall();
210
211       /* Move all killing processes to the end of the list, because killing a process that have an ongoing simcall is a bad idea */
212       xbt_dynar_three_way_partition(simix_global->process_that_ran, process_syscall_color);
213
214       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
215
216       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
217
218       /* Here, the order is ok because:
219        *
220        *   Short proof: only maestro adds stuff to the process_to_run array, so the execution order of user contexts do not impact its order.
221        *
222        *   Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
223        *
224        *   - if there is no kill during the simulation, processes remain sorted according by their PID.
225        *     rational: This can be proved inductively.
226        *        Assume that process_to_run is sorted at a beginning of one round (it is at round 0: the deployment file is parsed linearly).
227        *        Let's show that it is still so at the end of this round.
228        *        - if a process is added when being created, that's from maestro. It can be either at startup
229        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
230        *          in arbitrary order (inductive hypothesis), we are fine.
231        *        - If a process is added because it's getting killed, its subsequent actions shouldn't matter
232        *        - If a process gets added to process_to_run because one of their blocking action constituting the meat
233        *          of a simcall terminates, we're still good. Proof:
234        *          - You are added from SIMIX_simcall_answer() only. When this function is called depends on the resource
235        *            kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an example.
236        *          - For communications, this function is called from SIMIX_comm_finish().
237        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
238        *            The function is called:
239        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
240        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
241        *            - because the communication failed or were canceled after startup. In this case, it's called from the function
242        *              we are in, by the chunk:
243        *                       set = model->states.failed_action_set;
244        *                       while ((action = xbt_swag_extract(set)))
245        *                          SIMIX_simcall_post((smx_action_t) action->data);
246        *              This order is also fixed because it depends of the order in which the surf actions were
247        *              added to the system, and only maestro can add stuff this way, through simcalls.
248        *              We thus use the inductive hypothesis once again to conclude that the order in which actions are
249        *              poped out of the swag does not depend on the user code's execution order.
250        *            - because the communication terminated. In this case, actions are served in the order given by
251        *                       set = model->states.done_action_set;
252        *                       while ((action = xbt_swag_extract(set)))
253        *                          SIMIX_simcall_post((smx_action_t) action->data);
254        *              and the argument is very similar to the previous one.
255        *            So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user processes are executed.
256        *          So, in any cases, the orders of processes within process_to_run do not depend on the order in which user processes were executed previously.
257        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
258        *   - If there is some process killings, the order is changed by this decision that comes from user-land
259        *     But this decision may not have been motivated by a situation that were different because the simulation is not reproducible.
260        *     So, even the order change induced by the process killing is perfectly reproducible.
261        *
262        *   So science works, bitches [http://xkcd.com/54/].
263        *
264        *   We could sort the process_that_ran array completely so that we can describe the order in which simcalls are handled
265        *   (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if unfriendly).
266        *   That would thus be a pure waste of time.
267        */
268
269       xbt_dynar_foreach(simix_global->process_that_ran, iter, process) {
270         if (process->simcall.call != SIMCALL_NONE) {
271           SIMIX_simcall_pre(&process->simcall, 0);
272         }
273       }
274     }
275
276     time = SIMIX_timer_next();
277     if (time != -1.0 || xbt_swag_size(simix_global->process_list) != 0)
278       time = surf_solve(time);
279
280     /* Notify all the hosts that have failed */
281     /* FIXME: iterate through the list of failed host and mark each of them */
282     /* as failed. On each host, signal all the running processes with host_fail */
283
284     /* Handle any pending timer */
285     while (xbt_heap_size(simix_timers) > 0 && SIMIX_get_clock() >= SIMIX_timer_next()) {
286        //FIXME: make the timers being real callbacks
287        // (i.e. provide dispatchers that read and expand the args) 
288        timer = xbt_heap_pop(simix_timers);
289        if (timer->func)
290          ((void (*)(void*))timer->func)(timer->args);
291     }
292     /* Wake up all processes waiting for a Surf action to finish */
293     xbt_dynar_foreach(model_list, iter, model) {
294       set = model->states.failed_action_set;
295       while ((action = xbt_swag_extract(set)))
296         SIMIX_simcall_post((smx_action_t) action->data);
297       set = model->states.done_action_set;
298       while ((action = xbt_swag_extract(set)))
299         SIMIX_simcall_post((smx_action_t) action->data);
300     }
301
302     /* Clean processes to destroy */
303     SIMIX_process_empty_trash();
304
305   } while (time != -1.0 || !xbt_dynar_is_empty(simix_global->process_to_run));
306
307   if (xbt_swag_size(simix_global->process_list) != 0) {
308
309 #ifdef HAVE_TRACING
310     TRACE_end();
311 #endif
312
313     XBT_WARN("Oops ! Deadlock or code not perfectly clean.");
314     SIMIX_display_process_status();
315     xbt_abort();
316   }
317 }
318
319 /**
320  *   \brief Set the date to execute a function
321  *
322  * Set the date to execute the function on the surf.
323  *   \param date Date to execute function
324  *   \param function Function to be executed
325  *   \param arg Parameters of the function
326  *
327  */
328 XBT_INLINE void SIMIX_timer_set(double date, void *function, void *arg)
329 {
330   smx_timer_t timer = xbt_new0(s_smx_timer_t, 1);
331
332   timer->date = date;
333   timer->func = function;
334   timer->args = arg;
335   xbt_heap_push(simix_timers, timer, date);
336 }
337
338 /**
339  * \brief Registers a function to create a process.
340  *
341  * This function registers a function to be called
342  * when a new process is created. The function has
343  * to call SIMIX_process_create().
344  * \param function create process function
345  */
346 XBT_INLINE void SIMIX_function_register_process_create(smx_creation_func_t
347                                                        function)
348 {
349   simix_global->create_process_function = function;
350 }
351
352 /**
353  * \brief Registers a function to kill a process.
354  *
355  * This function registers a function to be called when a
356  * process is killed. The function has to call the SIMIX_process_kill().
357  *
358  * \param function Kill process function
359  */
360 XBT_INLINE void SIMIX_function_register_process_kill(void_pfn_smxprocess_t
361                                                      function)
362 {
363   simix_global->kill_process_function = function;
364 }
365
366 /**
367  * \brief Registers a function to cleanup a process.
368  *
369  * This function registers a user function to be called when
370  * a process ends properly.
371  *
372  * \param function cleanup process function
373  */
374 XBT_INLINE void SIMIX_function_register_process_cleanup(void_pfn_smxprocess_t
375                                                         function)
376 {
377   simix_global->cleanup_process_function = function;
378 }
379
380
381 void SIMIX_display_process_status(void)
382 {
383   if (simix_global->process_list == NULL) {
384     return;
385   }
386
387   smx_process_t process = NULL;
388   int nbprocess = xbt_swag_size(simix_global->process_list);
389
390   XBT_INFO("%d processes are still running, waiting for something.", nbprocess);
391   /*  List the process and their state */
392   XBT_INFO
393     ("Legend of the following listing: \"Process <pid> (<name>@<host>): <status>\"");
394   xbt_swag_foreach(process, simix_global->process_list) {
395
396     if (process->waiting_action) {
397
398       const char* action_description = "unknown";
399       switch (process->waiting_action->type) {
400
401       case SIMIX_ACTION_EXECUTE:
402         action_description = "execution";
403         break;
404
405       case SIMIX_ACTION_PARALLEL_EXECUTE:
406         action_description = "parallel execution";
407         break;
408
409       case SIMIX_ACTION_COMMUNICATE:
410         action_description = "communication";
411         break;
412
413       case SIMIX_ACTION_SLEEP:
414         action_description = "sleeping";
415         break;
416
417       case SIMIX_ACTION_SYNCHRO:
418         action_description = "synchronization";
419         break;
420
421       case SIMIX_ACTION_IO:
422         action_description = "I/O";
423         break;
424       }
425       XBT_INFO("Process %lu (%s@%s): waiting for %s action %p (%s) in state %d to finish",
426           process->pid, process->name, process->smx_host->name,
427           action_description, process->waiting_action,
428           process->waiting_action->name, (int)process->waiting_action->state);
429     }
430     else {
431       XBT_INFO("Process %lu (%s@%s)", process->pid, process->name, process->smx_host->name);
432     }
433   }
434 }
435
436 static void* SIMIX_action_mallocator_new_f(void) {
437   smx_action_t action = xbt_new(s_smx_action_t, 1);
438   action->simcalls = xbt_fifo_new();
439   return action;
440 }
441
442 static void SIMIX_action_mallocator_free_f(void* action) {
443   xbt_fifo_free(((smx_action_t) action)->simcalls);
444   xbt_free(action);
445 }
446
447 static void SIMIX_action_mallocator_reset_f(void* action) {
448
449   // we also recycle the simcall list
450   xbt_fifo_t fifo = ((smx_action_t) action)->simcalls;
451   xbt_fifo_reset(fifo);
452   memset(action, 0, sizeof(s_smx_action_t));
453   ((smx_action_t) action)->simcalls = fifo;
454 }