Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6e3dac7a8f6774d55223885994418e2e9e52bcb1
[simgrid.git] / src / simix / smx_global.c
1 /* Copyright (c) 2007-2014. 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 #include "simgrid/sg_config.h"
15
16 #ifdef HAVE_MC
17 #include "mc/mc_private.h"
18 #endif
19 #include "mc/mc_record.h"
20
21 #ifdef HAVE_SMPI
22 #include "smpi/private.h"
23 #endif
24
25 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix,
27                                 "Logging specific to SIMIX (kernel)");
28
29 smx_global_t simix_global = NULL;
30 static xbt_heap_t simix_timers = NULL;
31
32 static void* SIMIX_synchro_mallocator_new_f(void);
33 static void SIMIX_synchro_mallocator_free_f(void* synchro);
34 static void SIMIX_synchro_mallocator_reset_f(void* synchro);
35
36 /* FIXME: Yeah, I'll do it in a portable maner one day [Mt] */
37 #include <signal.h>
38
39 int _sg_do_verbose_exit = 1;
40 static void _XBT_CALL inthandler(int ignored)
41 {
42   if ( _sg_do_verbose_exit ) {
43      XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option 'verbose-exit').");
44      SIMIX_display_process_status();
45   }
46   else {
47      XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'verbose-exit' is set to false.");
48   }
49   exit(1);
50 }
51
52 #ifndef WIN32
53 static void _XBT_CALL segvhandler(int signum, siginfo_t *siginfo, void *context)
54 {
55   if (siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) {
56     fprintf(stderr,
57             "Access violation detected.\n"
58             "This can result from a programming error in your code or, although less likely,\n"
59             "from a bug in SimGrid itself.  This can also be the sign of a bug in the OS or\n"
60             "in third-party libraries.  Failing hardware can sometimes generate such errors\n"
61             "too.\n"
62             "Finally, if nothing of the above applies, this can result from a stack overflow.\n"
63             "Try to increase stack size with --cfg=contexts/stack_size (current size is %d KiB).\n",
64             smx_context_stack_size / 1024);
65     if (XBT_LOG_ISENABLED(simix_kernel, xbt_log_priority_debug)) {
66       fprintf(stderr,
67               "siginfo = {si_signo = %d, si_errno = %d, si_code = %d, si_addr = %p}\n",
68               siginfo->si_signo, siginfo->si_errno, siginfo->si_code, siginfo->si_addr);
69     }
70   } else  if (siginfo->si_signo == SIGSEGV) {
71     fprintf(stderr, "Segmentation fault.\n");
72 #ifdef HAVE_SMPI
73     if (smpi_enabled() && !smpi_privatize_global_variables) {
74       fprintf(stderr,
75         "Try to enable SMPI variable privatization with --cfg=smpi/privatize_global_variables:yes.\n");
76     }
77 #endif
78   }
79 #ifdef HAVE_MC
80   if (MC_is_active()) {
81     if (mc_stack) {
82       MC_dump_stack_safety(mc_stack);
83     }
84     MC_print_statistics(mc_stats);
85   }
86 #endif
87   raise(signum);
88 }
89
90 char sigsegv_stack[SIGSTKSZ];   /* alternate stack for SIGSEGV handler */
91
92 /**
93  * Install signal handler for SIGSEGV.  Check that nobody has already installed
94  * its own handler.  For example, the Java VM does this.
95  */
96 static void install_segvhandler(void)
97 {
98   stack_t stack, old_stack;
99   stack.ss_sp = sigsegv_stack;
100   stack.ss_size = sizeof sigsegv_stack;
101   stack.ss_flags = 0;
102
103   if (sigaltstack(&stack, &old_stack) == -1) {
104     XBT_WARN("Failed to register alternate signal stack: %s",
105              strerror(errno));
106     return;
107   }
108   if (!(old_stack.ss_flags & SS_DISABLE)) {
109     XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zd, flags=%x). Restore it.",
110               old_stack.ss_sp, old_stack.ss_size, old_stack.ss_flags);
111     sigaltstack(&old_stack, NULL);
112   }
113
114   struct sigaction action, old_action;
115   action.sa_sigaction = segvhandler;
116   action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
117   sigemptyset(&action.sa_mask);
118
119   if (sigaction(SIGSEGV, &action, &old_action) == -1) {
120     XBT_WARN("Failed to register signal handler for SIGSEGV: %s",
121              strerror(errno));
122     return;
123   }
124   if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
125     XBT_DEBUG("A signal handler was already installed for SIGSEGV (%p). Restore it.",
126              (old_action.sa_flags & SA_SIGINFO) ?
127              (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
128     sigaction(SIGSEGV, &old_action, NULL);
129   }
130 }
131
132 #endif
133 /********************************* SIMIX **************************************/
134
135 XBT_INLINE double SIMIX_timer_next(void)
136 {
137   return xbt_heap_size(simix_timers) > 0 ? xbt_heap_maxkey(simix_timers) : -1.0;
138 }
139
140 /**
141  * \ingroup SIMIX_API
142  * \brief Initialize SIMIX internal data.
143  *
144  * \param argc Argc
145  * \param argv Argv
146  */
147 void SIMIX_global_init(int *argc, char **argv)
148 {
149   s_smx_process_t proc;
150
151   if (!simix_global) {
152     simix_global = xbt_new0(s_smx_global_t, 1);
153
154 #ifdef TIME_BENCH_AMDAHL
155     simix_global->timer_seq = xbt_os_timer_new();
156     simix_global->timer_par = xbt_os_timer_new();
157     xbt_os_cputimer_start(simix_global->timer_seq);
158 #endif
159     simix_global->process_to_run = xbt_dynar_new(sizeof(smx_process_t), NULL);
160     simix_global->process_that_ran = xbt_dynar_new(sizeof(smx_process_t), NULL);
161     simix_global->process_list =
162         xbt_swag_new(xbt_swag_offset(proc, process_hookup));
163     simix_global->process_to_destroy =
164         xbt_swag_new(xbt_swag_offset(proc, destroy_hookup));
165
166     simix_global->maestro_process = NULL;
167     simix_global->registered_functions = xbt_dict_new_homogeneous(NULL);
168
169     simix_global->create_process_function = SIMIX_process_create;
170     simix_global->kill_process_function = SIMIX_process_kill;
171     simix_global->cleanup_process_function = SIMIX_process_cleanup;
172     simix_global->synchro_mallocator = xbt_mallocator_new(65536,
173         SIMIX_synchro_mallocator_new_f, SIMIX_synchro_mallocator_free_f,
174         SIMIX_synchro_mallocator_reset_f);
175     simix_global->autorestart = SIMIX_host_restart_processes;
176
177     surf_init(argc, argv);      /* Initialize SURF structures */
178     SIMIX_context_mod_init();
179     SIMIX_create_maestro_process();
180
181     /* context exception handlers */
182     __xbt_running_ctx_fetch = SIMIX_process_get_running_context;
183     __xbt_ex_terminate = SIMIX_process_exception_terminate;
184
185     SIMIX_network_init();
186
187     /* Prepare to display some more info when dying on Ctrl-C pressing */
188     signal(SIGINT, inthandler);
189
190 #ifndef WIN32
191     /* Install SEGV handler */
192     install_segvhandler();
193 #endif
194     /* register a function to be called by SURF after the environment creation */
195     sg_platf_init();
196     sg_platf_postparse_add_cb(SIMIX_post_create_environment);
197
198   }
199   if (!simix_timers) {
200     simix_timers = xbt_heap_new(8, &free);
201   }
202
203   SIMIX_HOST_LEVEL = xbt_lib_add_level(host_lib,SIMIX_host_destroy);
204   SIMIX_STORAGE_LEVEL = xbt_lib_add_level(storage_lib, SIMIX_storage_destroy);
205
206   if (sg_cfg_get_boolean("clean_atexit"))
207     atexit(SIMIX_clean);
208
209   if (_sg_cfg_exit_asap)
210     exit(0);
211 }
212
213 /**
214  * \ingroup SIMIX_API
215  * \brief Clean the SIMIX simulation
216  *
217  * This functions remove the memory used by SIMIX
218  */
219 void SIMIX_clean(void)
220 {
221   static int cleaned = 0;
222 #ifdef TIME_BENCH_PER_SR
223   smx_ctx_raw_new_sr();
224 #endif
225   if (cleaned) return; // to avoid double cleaning by java and C
226   cleaned = 1;
227   /* Kill everyone (except maestro) */
228   SIMIX_process_killall(simix_global->maestro_process, 1);
229
230   /* Exit the SIMIX network module */
231   SIMIX_network_exit();
232
233   xbt_heap_free(simix_timers);
234   simix_timers = NULL;
235   /* Free the remaining data structures */
236   xbt_dynar_free(&simix_global->process_to_run);
237   xbt_dynar_free(&simix_global->process_that_ran);
238   xbt_swag_free(simix_global->process_to_destroy);
239   xbt_swag_free(simix_global->process_list);
240   simix_global->process_list = NULL;
241   simix_global->process_to_destroy = NULL;
242   xbt_dict_free(&(simix_global->registered_functions));
243
244   /* Let's free maestro now */
245   SIMIX_context_free(simix_global->maestro_process->context);
246   xbt_free(simix_global->maestro_process->running_ctx);
247   xbt_free(simix_global->maestro_process);
248   simix_global->maestro_process = NULL;
249
250   /* Restore the default exception setup */
251   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
252   __xbt_ex_terminate = &__xbt_ex_terminate_default;
253
254   /* Finish context module and SURF */
255   SIMIX_context_mod_exit();
256
257   surf_exit();
258
259 #ifdef TIME_BENCH_AMDAHL
260   xbt_os_cputimer_stop(simix_global->timer_seq);
261   XBT_INFO("Amdahl timing informations. Sequential time: %f; Parallel time: %f",
262            xbt_os_timer_elapsed(simix_global->timer_seq),
263            xbt_os_timer_elapsed(simix_global->timer_par));
264   xbt_os_timer_free(simix_global->timer_seq);
265   xbt_os_timer_free(simix_global->timer_par);
266 #endif
267
268   xbt_mallocator_free(simix_global->synchro_mallocator);
269   xbt_free(simix_global);
270   simix_global = NULL;
271
272   return;
273 }
274
275
276 /**
277  * \ingroup SIMIX_API
278  * \brief A clock (in second).
279  *
280  * \return Return the clock.
281  */
282 XBT_INLINE double SIMIX_get_clock(void)
283 {
284   if(MC_is_active() || MC_record_replay_is_active()){
285     return MC_process_clock_get(SIMIX_process_self());
286   }else{
287     return surf_get_clock();
288   }
289 }
290
291 static int process_syscall_color(void *p)
292 {
293   switch ((*(smx_process_t *)p)->simcall.call) {
294   case SIMCALL_NONE:
295   case SIMCALL_PROCESS_KILL:
296     return 2;
297   case SIMCALL_PROCESS_RESUME:
298     return 1;
299   default:
300     return 0;
301   }
302 }
303
304 /**
305  * \ingroup SIMIX_API
306  * \brief Run the main simulation loop.
307  */
308 void SIMIX_run(void)
309 {
310   if(MC_record_path) {
311     MC_record_replay_init();
312     MC_record_replay_from_string(MC_record_path);
313     return;
314   }
315
316   double time = 0;
317   smx_process_t process;
318   surf_action_t action;
319   smx_timer_t timer;
320   surf_model_t model;
321   unsigned int iter;
322
323   do {
324     XBT_DEBUG("New Schedule Round; size(queue)=%lu",
325         xbt_dynar_length(simix_global->process_to_run));
326 #ifdef TIME_BENCH_PER_SR
327     smx_ctx_raw_new_sr();
328 #endif
329     while (!xbt_dynar_is_empty(simix_global->process_to_run)) {
330       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%lu",
331               xbt_dynar_length(simix_global->process_to_run));
332
333       /* Run all processes that are ready to run, possibly in parallel */
334 #ifdef TIME_BENCH_AMDAHL
335       xbt_os_cputimer_stop(simix_global->timer_seq);
336       xbt_os_cputimer_resume(simix_global->timer_par);
337 #endif
338       SIMIX_process_runall();
339 #ifdef TIME_BENCH_AMDAHL
340       xbt_os_cputimer_stop(simix_global->timer_par);
341       xbt_os_cputimer_resume(simix_global->timer_seq);
342 #endif
343
344       /* Move all killing processes to the end of the list, because killing a process that have an ongoing simcall is a bad idea */
345       xbt_dynar_three_way_partition(simix_global->process_that_ran, process_syscall_color);
346
347       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
348
349       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
350
351       /* Here, the order is ok because:
352        *
353        *   Short proof: only maestro adds stuff to the process_to_run array, so the execution order of user contexts do not impact its order.
354        *
355        *   Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
356        *
357        *   - if there is no kill during the simulation, processes remain sorted according by their PID.
358        *     rational: This can be proved inductively.
359        *        Assume that process_to_run is sorted at a beginning of one round (it is at round 0: the deployment file is parsed linearly).
360        *        Let's show that it is still so at the end of this round.
361        *        - if a process is added when being created, that's from maestro. It can be either at startup
362        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
363        *          in arbitrary order (inductive hypothesis), we are fine.
364        *        - If a process is added because it's getting killed, its subsequent actions shouldn't matter
365        *        - If a process gets added to process_to_run because one of their blocking action constituting the meat
366        *          of a simcall terminates, we're still good. Proof:
367        *          - You are added from SIMIX_simcall_answer() only. When this function is called depends on the resource
368        *            kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an example.
369        *          - For communications, this function is called from SIMIX_comm_finish().
370        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
371        *            The function is called:
372        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
373        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
374        *            - because the communication failed or were canceled after startup. In this case, it's called from the function
375        *              we are in, by the chunk:
376        *                       set = model->states.failed_action_set;
377        *                       while ((synchro = xbt_swag_extract(set)))
378        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
379        *              This order is also fixed because it depends of the order in which the surf actions were
380        *              added to the system, and only maestro can add stuff this way, through simcalls.
381        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
382        *              poped out of the swag does not depend on the user code's execution order.
383        *            - because the communication terminated. In this case, synchros are served in the order given by
384        *                       set = model->states.done_action_set;
385        *                       while ((synchro = xbt_swag_extract(set)))
386        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
387        *              and the argument is very similar to the previous one.
388        *            So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user processes are executed.
389        *          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.
390        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
391        *   - If there is some process killings, the order is changed by this decision that comes from user-land
392        *     But this decision may not have been motivated by a situation that were different because the simulation is not reproducible.
393        *     So, even the order change induced by the process killing is perfectly reproducible.
394        *
395        *   So science works, bitches [http://xkcd.com/54/].
396        *
397        *   We could sort the process_that_ran array completely so that we can describe the order in which simcalls are handled
398        *   (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if unfriendly).
399        *   That would thus be a pure waste of time.
400        */
401
402       xbt_dynar_foreach(simix_global->process_that_ran, iter, process) {
403         if (process->simcall.call != SIMCALL_NONE) {
404           SIMIX_simcall_handle(&process->simcall, 0);
405         }
406       }
407     }
408
409     time = SIMIX_timer_next();
410     if (time != -1.0 || xbt_swag_size(simix_global->process_list) != 0)
411       time = surf_solve(time);
412
413     /* Notify all the hosts that have failed */
414     /* FIXME: iterate through the list of failed host and mark each of them */
415     /* as failed. On each host, signal all the running processes with host_fail */
416
417     /* Handle any pending timer */
418     while (xbt_heap_size(simix_timers) > 0 && SIMIX_get_clock() >= SIMIX_timer_next()) {
419        //FIXME: make the timers being real callbacks
420        // (i.e. provide dispatchers that read and expand the args)
421        timer = xbt_heap_pop(simix_timers);
422        if (timer->func)
423          ((void (*)(void*))timer->func)(timer->args);
424        xbt_free(timer);
425     }
426
427     /* Wake up all processes waiting for a Surf action to finish */
428     xbt_dynar_foreach(model_list, iter, model) {
429       while ((action = surf_model_extract_failed_action_set(model)))
430         SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
431
432       while ((action = surf_model_extract_done_action_set(model)))
433         if (surf_action_get_data(action) == NULL)
434           XBT_DEBUG("probably vcpu's action %p, skip", action);
435         else
436           SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
437     }
438
439     /* Autorestart all process */
440     if(host_that_restart) {
441       char *hostname = NULL;
442       xbt_dynar_foreach(host_that_restart,iter,hostname) {
443         XBT_INFO("Restart processes on host: %s",hostname);
444         SIMIX_host_autorestart(SIMIX_host_get_by_name(hostname));
445       }
446       xbt_dynar_reset(host_that_restart);
447     }
448
449     /* Clean processes to destroy */
450     SIMIX_process_empty_trash();
451
452
453     XBT_DEBUG("### time %f, empty %d", time, xbt_dynar_is_empty(simix_global->process_to_run));
454
455   } while (time != -1.0 || !xbt_dynar_is_empty(simix_global->process_to_run));
456
457   if (xbt_swag_size(simix_global->process_list) != 0) {
458
459 #ifdef HAVE_TRACING
460     TRACE_end();
461 #endif
462
463     XBT_CRITICAL("Oops ! Deadlock or code not perfectly clean.");
464     SIMIX_display_process_status();
465     xbt_abort();
466   }
467 }
468
469 /**
470  *   \brief Set the date to execute a function
471  *
472  * Set the date to execute the function on the surf.
473  *   \param date Date to execute function
474  *   \param function Function to be executed
475  *   \param arg Parameters of the function
476  *
477  */
478 XBT_INLINE void SIMIX_timer_set(double date, void *function, void *arg)
479 {
480   smx_timer_t timer = xbt_new0(s_smx_timer_t, 1);
481
482   timer->date = date;
483   timer->func = function;
484   timer->args = arg;
485   xbt_heap_push(simix_timers, timer, date);
486 }
487
488 /**
489  * \brief Registers a function to create a process.
490  *
491  * This function registers a function to be called
492  * when a new process is created. The function has
493  * to call SIMIX_process_create().
494  * \param function create process function
495  */
496 XBT_INLINE void SIMIX_function_register_process_create(smx_creation_func_t
497                                                        function)
498 {
499   simix_global->create_process_function = function;
500 }
501
502 /**
503  * \brief Registers a function to kill a process.
504  *
505  * This function registers a function to be called when a
506  * process is killed. The function has to call the SIMIX_process_kill().
507  *
508  * \param function Kill process function
509  */
510 XBT_INLINE void SIMIX_function_register_process_kill(void_pfn_smxprocess_t_smxprocess_t
511                                                      function)
512 {
513   simix_global->kill_process_function = function;
514 }
515
516 /**
517  * \brief Registers a function to cleanup a process.
518  *
519  * This function registers a user function to be called when
520  * a process ends properly.
521  *
522  * \param function cleanup process function
523  */
524 XBT_INLINE void SIMIX_function_register_process_cleanup(void_pfn_smxprocess_t
525                                                         function)
526 {
527   simix_global->cleanup_process_function = function;
528 }
529
530
531 void SIMIX_display_process_status(void)
532 {
533   if (simix_global->process_list == NULL) {
534     return;
535   }
536
537   smx_process_t process = NULL;
538   int nbprocess = xbt_swag_size(simix_global->process_list);
539
540   XBT_INFO("%d processes are still running, waiting for something.", nbprocess);
541   /*  List the process and their state */
542   XBT_INFO
543     ("Legend of the following listing: \"Process <pid> (<name>@<host>): <status>\"");
544   xbt_swag_foreach(process, simix_global->process_list) {
545
546     if (process->waiting_synchro) {
547
548       const char* synchro_description = "unknown";
549       switch (process->waiting_synchro->type) {
550
551       case SIMIX_SYNC_EXECUTE:
552         synchro_description = "execution";
553         break;
554
555       case SIMIX_SYNC_PARALLEL_EXECUTE:
556         synchro_description = "parallel execution";
557         break;
558
559       case SIMIX_SYNC_COMMUNICATE:
560         synchro_description = "communication";
561         break;
562
563       case SIMIX_SYNC_SLEEP:
564         synchro_description = "sleeping";
565         break;
566
567       case SIMIX_SYNC_JOIN:
568         synchro_description = "joining";
569         break;
570
571       case SIMIX_SYNC_SYNCHRO:
572         synchro_description = "synchronization";
573         break;
574
575       case SIMIX_SYNC_IO:
576         synchro_description = "I/O";
577         break;
578       }
579       XBT_INFO("Process %lu (%s@%s): waiting for %s synchro %p (%s) in state %d to finish",
580           process->pid, process->name, sg_host_name(process->smx_host),
581           synchro_description, process->waiting_synchro,
582           process->waiting_synchro->name, (int)process->waiting_synchro->state);
583     }
584     else {
585       XBT_INFO("Process %lu (%s@%s)", process->pid, process->name, sg_host_name(process->smx_host));
586     }
587   }
588 }
589
590 static void* SIMIX_synchro_mallocator_new_f(void) {
591   smx_synchro_t synchro = xbt_new(s_smx_synchro_t, 1);
592   synchro->simcalls = xbt_fifo_new();
593   return synchro;
594 }
595
596 static void SIMIX_synchro_mallocator_free_f(void* synchro) {
597   xbt_fifo_free(((smx_synchro_t) synchro)->simcalls);
598   xbt_free(synchro);
599 }
600
601 static void SIMIX_synchro_mallocator_reset_f(void* synchro) {
602
603   // we also recycle the simcall list
604   xbt_fifo_t fifo = ((smx_synchro_t) synchro)->simcalls;
605   xbt_fifo_reset(fifo);
606   memset(synchro, 0, sizeof(s_smx_synchro_t));
607   ((smx_synchro_t) synchro)->simcalls = fifo;
608 }
609
610 xbt_dict_t simcall_HANDLER_asr_get_properties(smx_simcall_t simcall, const char *name){
611   return SIMIX_asr_get_properties(name);
612 }
613 xbt_dict_t SIMIX_asr_get_properties(const char *name)
614 {
615   return xbt_lib_get_or_null(as_router_lib, name, ROUTING_PROP_ASR_LEVEL);
616 }