1 /* Copyright (c) 2007-2015. The SimGrid Team.
2 * All rights reserved. */
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. */
8 #include <sys/ptrace.h>
10 #include "smx_private.h"
12 #include "xbt/sysdep.h"
15 #include "xbt/ex.h" /* ex_backtrace_display */
17 #include "src/mc/mc_replay.h"
18 #include "simgrid/sg_config.h"
21 #include "src/mc/mc_private.h"
22 #include "src/mc/mc_protocol.h"
23 #include "src/mc/mc_client.h"
28 #include "src/mc/mc_protocol.h"
31 #include "src/mc/mc_record.h"
34 #include "src/smpi/private.h"
37 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
38 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix,
39 "Logging specific to SIMIX (kernel)");
41 smx_global_t simix_global = NULL;
42 static xbt_heap_t simix_timers = NULL;
44 static void* SIMIX_synchro_mallocator_new_f(void);
45 static void SIMIX_synchro_mallocator_free_f(void* synchro);
46 static void SIMIX_synchro_mallocator_reset_f(void* synchro);
48 /* FIXME: Yeah, I'll do it in a portable maner one day [Mt] */
51 int _sg_do_verbose_exit = 1;
52 static void _XBT_CALL inthandler(int ignored)
54 if ( _sg_do_verbose_exit ) {
55 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option 'verbose-exit').");
56 SIMIX_display_process_status();
59 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'verbose-exit' is set to false.");
65 static void _XBT_CALL segvhandler(int signum, siginfo_t *siginfo, void *context)
67 if (siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) {
69 "Access violation detected.\n"
70 "This can result from a programming error in your code or, although less likely,\n"
71 "from a bug in SimGrid itself. This can also be the sign of a bug in the OS or\n"
72 "in third-party libraries. Failing hardware can sometimes generate such errors\n"
74 "Finally, if nothing of the above applies, this can result from a stack overflow.\n"
75 "Try to increase stack size with --cfg=contexts/stack_size (current size is %d KiB).\n",
76 smx_context_stack_size / 1024);
77 if (XBT_LOG_ISENABLED(simix_kernel, xbt_log_priority_debug)) {
79 "siginfo = {si_signo = %d, si_errno = %d, si_code = %d, si_addr = %p}\n",
80 siginfo->si_signo, siginfo->si_errno, siginfo->si_code, siginfo->si_addr);
82 } else if (siginfo->si_signo == SIGSEGV) {
83 fprintf(stderr, "Segmentation fault.\n");
85 if (smpi_enabled() && !smpi_privatize_global_variables) {
87 "Try to enable SMPI variable privatization with --cfg=smpi/privatize_global_variables:yes.\n");
94 char sigsegv_stack[SIGSTKSZ]; /* alternate stack for SIGSEGV handler */
97 * Install signal handler for SIGSEGV. Check that nobody has already installed
98 * its own handler. For example, the Java VM does this.
100 static void install_segvhandler(void)
102 stack_t stack, old_stack;
103 stack.ss_sp = sigsegv_stack;
104 stack.ss_size = sizeof sigsegv_stack;
107 if (sigaltstack(&stack, &old_stack) == -1) {
108 XBT_WARN("Failed to register alternate signal stack: %s",
112 if (!(old_stack.ss_flags & SS_DISABLE)) {
113 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zd, flags=%x). Restore it.",
114 old_stack.ss_sp, old_stack.ss_size, old_stack.ss_flags);
115 sigaltstack(&old_stack, NULL);
118 struct sigaction action, old_action;
119 action.sa_sigaction = segvhandler;
120 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
121 sigemptyset(&action.sa_mask);
123 if (sigaction(SIGSEGV, &action, &old_action) == -1) {
124 XBT_WARN("Failed to register signal handler for SIGSEGV: %s",
128 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
129 XBT_DEBUG("A signal handler was already installed for SIGSEGV (%p). Restore it.",
130 (old_action.sa_flags & SA_SIGINFO) ?
131 (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
132 sigaction(SIGSEGV, &old_action, NULL);
137 /********************************* SIMIX **************************************/
139 XBT_INLINE double SIMIX_timer_next(void)
141 return xbt_heap_size(simix_timers) > 0 ? xbt_heap_maxkey(simix_timers) : -1.0;
146 * \brief Initialize SIMIX internal data.
151 void SIMIX_global_init(int *argc, char **argv)
154 _sg_do_model_check = getenv(MC_ENV_VARIABLE) != NULL;
157 s_smx_process_t proc;
160 simix_global = xbt_new0(s_smx_global_t, 1);
162 #ifdef TIME_BENCH_AMDAHL
163 simix_global->timer_seq = xbt_os_timer_new();
164 simix_global->timer_par = xbt_os_timer_new();
165 xbt_os_cputimer_start(simix_global->timer_seq);
167 simix_global->process_to_run = xbt_dynar_new(sizeof(smx_process_t), NULL);
168 simix_global->process_that_ran = xbt_dynar_new(sizeof(smx_process_t), NULL);
169 simix_global->process_list =
170 xbt_swag_new(xbt_swag_offset(proc, process_hookup));
171 simix_global->process_to_destroy =
172 xbt_swag_new(xbt_swag_offset(proc, destroy_hookup));
174 simix_global->maestro_process = NULL;
175 simix_global->registered_functions = xbt_dict_new_homogeneous(NULL);
177 simix_global->create_process_function = SIMIX_process_create;
178 simix_global->kill_process_function = SIMIX_process_kill;
179 simix_global->cleanup_process_function = SIMIX_process_cleanup;
180 simix_global->synchro_mallocator = xbt_mallocator_new(65536,
181 SIMIX_synchro_mallocator_new_f, SIMIX_synchro_mallocator_free_f,
182 SIMIX_synchro_mallocator_reset_f);
183 simix_global->autorestart = SIMIX_host_restart_processes;
184 simix_global->mutex = xbt_os_mutex_init();
186 surf_init(argc, argv); /* Initialize SURF structures */
187 SIMIX_context_mod_init();
188 SIMIX_create_maestro_process();
190 /* context exception handlers */
191 __xbt_running_ctx_fetch = SIMIX_process_get_running_context;
192 __xbt_ex_terminate = SIMIX_process_exception_terminate;
194 SIMIX_network_init();
196 /* Prepare to display some more info when dying on Ctrl-C pressing */
197 signal(SIGINT, inthandler);
200 /* Install SEGV handler */
201 install_segvhandler();
203 /* register a function to be called by SURF after the environment creation */
205 sg_platf_postparse_add_cb(SIMIX_post_create_environment);
209 simix_timers = xbt_heap_new(8, &free);
212 SIMIX_STORAGE_LEVEL = xbt_lib_add_level(storage_lib, SIMIX_storage_destroy);
214 if (sg_cfg_get_boolean("clean_atexit"))
218 // The communication initialization is done ASAP.
219 // We need to communicate initialization of the different layers to the model-checker.
220 if (mc_mode == MC_MODE_NONE) {
221 if (getenv(MC_ENV_SOCKET_FD)) {
223 mc_mode = MC_MODE_CLIENT;
226 // Waiting for the model-checker:
227 if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) == -1 || raise(SIGSTOP) != 0)
228 xbt_die("Could not wait for the model-checker");
230 MC_client_handle_messages();
235 if (_sg_cfg_exit_asap)
242 * \brief Clean the SIMIX simulation
244 * This functions remove the memory used by SIMIX
246 void SIMIX_clean(void)
248 #ifdef TIME_BENCH_PER_SR
249 smx_ctx_raw_new_sr();
251 if (smx_cleaned) return; // to avoid double cleaning by java and C
253 XBT_DEBUG("SIMIX_clean called. Simulation's over.");
254 if (!xbt_dynar_is_empty(simix_global->process_to_run) && SIMIX_get_clock() == 0.0) {
256 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
257 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
258 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
260 /* Kill all processes (but maestro) */
261 SIMIX_process_killall(simix_global->maestro_process, 1);
263 /* Exit the SIMIX network module */
264 SIMIX_network_exit();
266 xbt_heap_free(simix_timers);
268 /* Free the remaining data structures */
269 xbt_dynar_free(&simix_global->process_to_run);
270 xbt_dynar_free(&simix_global->process_that_ran);
271 xbt_swag_free(simix_global->process_to_destroy);
272 xbt_swag_free(simix_global->process_list);
273 simix_global->process_list = NULL;
274 simix_global->process_to_destroy = NULL;
275 xbt_dict_free(&(simix_global->registered_functions));
277 xbt_os_mutex_destroy(simix_global->mutex);
278 simix_global->mutex = NULL;
280 /* Let's free maestro now */
281 SIMIX_context_free(simix_global->maestro_process->context);
282 xbt_free(simix_global->maestro_process->running_ctx);
283 xbt_free(simix_global->maestro_process);
284 simix_global->maestro_process = NULL;
286 /* Restore the default exception setup */
287 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
288 __xbt_ex_terminate = &__xbt_ex_terminate_default;
290 /* Finish context module and SURF */
291 SIMIX_context_mod_exit();
295 #ifdef TIME_BENCH_AMDAHL
296 xbt_os_cputimer_stop(simix_global->timer_seq);
297 XBT_INFO("Amdahl timing informations. Sequential time: %f; Parallel time: %f",
298 xbt_os_timer_elapsed(simix_global->timer_seq),
299 xbt_os_timer_elapsed(simix_global->timer_par));
300 xbt_os_timer_free(simix_global->timer_seq);
301 xbt_os_timer_free(simix_global->timer_par);
304 xbt_mallocator_free(simix_global->synchro_mallocator);
305 xbt_free(simix_global);
314 * \brief A clock (in second).
316 * \return Return the clock.
318 XBT_INLINE double SIMIX_get_clock(void)
320 if(MC_is_active() || MC_record_replay_is_active()){
321 return MC_process_clock_get(SIMIX_process_self());
323 return surf_get_clock();
327 static int process_syscall_color(void *p)
329 switch ((*(smx_process_t *)p)->simcall.call) {
331 case SIMCALL_PROCESS_KILL:
333 case SIMCALL_PROCESS_RESUME:
342 * \brief Run the main simulation loop.
347 MC_record_replay_init();
348 MC_record_replay_from_string(MC_record_path);
353 smx_process_t process;
354 surf_action_t action;
360 XBT_DEBUG("New Schedule Round; size(queue)=%lu",
361 xbt_dynar_length(simix_global->process_to_run));
362 #ifdef TIME_BENCH_PER_SR
363 smx_ctx_raw_new_sr();
365 while (!xbt_dynar_is_empty(simix_global->process_to_run)) {
366 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%lu",
367 xbt_dynar_length(simix_global->process_to_run));
369 /* Run all processes that are ready to run, possibly in parallel */
370 #ifdef TIME_BENCH_AMDAHL
371 xbt_os_cputimer_stop(simix_global->timer_seq);
372 xbt_os_cputimer_resume(simix_global->timer_par);
374 SIMIX_process_runall();
375 #ifdef TIME_BENCH_AMDAHL
376 xbt_os_cputimer_stop(simix_global->timer_par);
377 xbt_os_cputimer_resume(simix_global->timer_seq);
380 /* Move all killer processes to the end of the list, because killing a process that have an ongoing simcall is a bad idea */
381 xbt_dynar_three_way_partition(simix_global->process_that_ran, process_syscall_color);
383 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
385 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
387 /* Here, the order is ok because:
389 * Short proof: only maestro adds stuff to the process_to_run array, so the execution order of user contexts do not impact its order.
391 * Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
393 * - if there is no kill during the simulation, processes remain sorted according by their PID.
394 * rational: This can be proved inductively.
395 * Assume that process_to_run is sorted at a beginning of one round (it is at round 0: the deployment file is parsed linearly).
396 * Let's show that it is still so at the end of this round.
397 * - if a process is added when being created, that's from maestro. It can be either at startup
398 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
399 * in arbitrary order (inductive hypothesis), we are fine.
400 * - If a process is added because it's getting killed, its subsequent actions shouldn't matter
401 * - If a process gets added to process_to_run because one of their blocking action constituting the meat
402 * of a simcall terminates, we're still good. Proof:
403 * - You are added from SIMIX_simcall_answer() only. When this function is called depends on the resource
404 * kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an example.
405 * - For communications, this function is called from SIMIX_comm_finish().
406 * This function itself don't mess with the order since simcalls are handled in FIFO order.
407 * The function is called:
408 * - before the comm starts (invalid parameters, or resource already dead or whatever).
409 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
410 * - because the communication failed or were canceled after startup. In this case, it's called from the function
411 * we are in, by the chunk:
412 * set = model->states.failed_action_set;
413 * while ((synchro = xbt_swag_extract(set)))
414 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
415 * This order is also fixed because it depends of the order in which the surf actions were
416 * added to the system, and only maestro can add stuff this way, through simcalls.
417 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
418 * poped out of the swag does not depend on the user code's execution order.
419 * - because the communication terminated. In this case, synchros are served in the order given by
420 * set = model->states.done_action_set;
421 * while ((synchro = xbt_swag_extract(set)))
422 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
423 * and the argument is very similar to the previous one.
424 * So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user processes are executed.
425 * 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.
426 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
427 * - If there is some process killings, the order is changed by this decision that comes from user-land
428 * But this decision may not have been motivated by a situation that were different because the simulation is not reproducible.
429 * So, even the order change induced by the process killing is perfectly reproducible.
431 * So science works, bitches [http://xkcd.com/54/].
433 * We could sort the process_that_ran array completely so that we can describe the order in which simcalls are handled
434 * (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if unfriendly).
435 * That would thus be a pure waste of time.
438 xbt_dynar_foreach(simix_global->process_that_ran, iter, process) {
439 if (process->simcall.call != SIMCALL_NONE) {
440 SIMIX_simcall_handle(&process->simcall, 0);
443 /* Wake up all processes waiting for a Surf action to finish */
444 xbt_dynar_foreach(model_list, iter, model) {
445 XBT_DEBUG("Handling process whose action failed");
446 while ((action = surf_model_extract_failed_action_set(model))) {
447 XBT_DEBUG(" Handling Action %p",action);
448 SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
450 XBT_DEBUG("Handling process whose action terminated normally");
451 while ((action = surf_model_extract_done_action_set(model))) {
452 XBT_DEBUG(" Handling Action %p",action);
453 if (surf_action_get_data(action) == NULL)
454 XBT_DEBUG("probably vcpu's action %p, skip", action);
456 SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
461 time = SIMIX_timer_next();
462 if (time != -1.0 || xbt_swag_size(simix_global->process_list) != 0) {
463 XBT_DEBUG("Calling surf_solve");
464 time = surf_solve(time);
465 XBT_DEBUG("Moving time ahead : %g", time);
467 /* Notify all the hosts that have failed */
468 /* FIXME: iterate through the list of failed host and mark each of them */
469 /* as failed. On each host, signal all the running processes with host_fail */
471 /* Handle any pending timer */
472 while (xbt_heap_size(simix_timers) > 0 && SIMIX_get_clock() >= SIMIX_timer_next()) {
473 //FIXME: make the timers being real callbacks
474 // (i.e. provide dispatchers that read and expand the args)
475 timer = xbt_heap_pop(simix_timers);
477 ((void (*)(void*))timer->func)(timer->args);
481 /* Wake up all processes waiting for a Surf action to finish */
482 xbt_dynar_foreach(model_list, iter, model) {
483 XBT_DEBUG("Handling process whose action failed");
484 while ((action = surf_model_extract_failed_action_set(model))) {
485 XBT_DEBUG(" Handling Action %p",action);
486 SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
488 XBT_DEBUG("Handling process whose action terminated normally");
489 while ((action = surf_model_extract_done_action_set(model))) {
490 XBT_DEBUG(" Handling Action %p",action);
491 if (surf_action_get_data(action) == NULL)
492 XBT_DEBUG("probably vcpu's action %p, skip", action);
494 SIMIX_simcall_exit((smx_synchro_t) surf_action_get_data(action));
498 /* Autorestart all process */
499 if(host_that_restart) {
500 char *hostname = NULL;
501 xbt_dynar_foreach(host_that_restart,iter,hostname) {
502 XBT_INFO("Restart processes on host: %s",hostname);
503 SIMIX_host_autorestart(sg_host_by_name(hostname));
505 xbt_dynar_reset(host_that_restart);
508 /* Clean processes to destroy */
509 SIMIX_process_empty_trash();
512 XBT_DEBUG("### time %f, empty %d", time, xbt_dynar_is_empty(simix_global->process_to_run));
514 } while (time != -1.0 || !xbt_dynar_is_empty(simix_global->process_to_run));
516 if (xbt_swag_size(simix_global->process_list) != 0) {
520 XBT_CRITICAL("Oops ! Deadlock or code not perfectly clean.");
521 SIMIX_display_process_status();
527 * \brief Set the date to execute a function
529 * Set the date to execute the function on the surf.
530 * \param date Date to execute function
531 * \param function Function to be executed
532 * \param arg Parameters of the function
535 XBT_INLINE smx_timer_t SIMIX_timer_set(double date, void *function, void *arg)
537 smx_timer_t timer = xbt_new0(s_smx_timer_t, 1);
540 timer->func = function;
542 xbt_heap_push(simix_timers, timer, date);
545 /** @brief cancels a timer that was added earlier */
546 XBT_INLINE void SIMIX_timer_remove(smx_timer_t timer) {
547 xbt_heap_rm_elm(simix_timers, timer, timer->date);
550 /** @brief Returns the date at which the timer will trigger (or 0 if NULL timer) */
551 XBT_INLINE double SIMIX_timer_get_date(smx_timer_t timer) {
552 return timer?timer->date:0;
556 * \brief Registers a function to create a process.
558 * This function registers a function to be called
559 * when a new process is created. The function has
560 * to call SIMIX_process_create().
561 * \param function create process function
563 XBT_INLINE void SIMIX_function_register_process_create(smx_creation_func_t
566 simix_global->create_process_function = function;
570 * \brief Registers a function to kill a process.
572 * This function registers a function to be called when a
573 * process is killed. The function has to call the SIMIX_process_kill().
575 * \param function Kill process function
577 XBT_INLINE void SIMIX_function_register_process_kill(void_pfn_smxprocess_t_smxprocess_t
580 simix_global->kill_process_function = function;
584 * \brief Registers a function to cleanup a process.
586 * This function registers a user function to be called when
587 * a process ends properly.
589 * \param function cleanup process function
591 XBT_INLINE void SIMIX_function_register_process_cleanup(void_pfn_smxprocess_t
594 simix_global->cleanup_process_function = function;
598 void SIMIX_display_process_status(void)
600 if (simix_global->process_list == NULL) {
604 smx_process_t process = NULL;
605 int nbprocess = xbt_swag_size(simix_global->process_list);
607 XBT_INFO("%d processes are still running, waiting for something.", nbprocess);
608 /* List the process and their state */
610 ("Legend of the following listing: \"Process <pid> (<name>@<host>): <status>\"");
611 xbt_swag_foreach(process, simix_global->process_list) {
613 if (process->waiting_synchro) {
615 const char* synchro_description = "unknown";
616 switch (process->waiting_synchro->type) {
618 case SIMIX_SYNC_EXECUTE:
619 synchro_description = "execution";
622 case SIMIX_SYNC_PARALLEL_EXECUTE:
623 synchro_description = "parallel execution";
626 case SIMIX_SYNC_COMMUNICATE:
627 synchro_description = "communication";
630 case SIMIX_SYNC_SLEEP:
631 synchro_description = "sleeping";
634 case SIMIX_SYNC_JOIN:
635 synchro_description = "joining";
638 case SIMIX_SYNC_SYNCHRO:
639 synchro_description = "synchronization";
643 synchro_description = "I/O";
646 XBT_INFO("Process %lu (%s@%s): waiting for %s synchro %p (%s) in state %d to finish",
647 process->pid, process->name, sg_host_get_name(process->host),
648 synchro_description, process->waiting_synchro,
649 process->waiting_synchro->name, (int)process->waiting_synchro->state);
652 XBT_INFO("Process %lu (%s@%s)", process->pid, process->name, sg_host_get_name(process->host));
657 static void* SIMIX_synchro_mallocator_new_f(void) {
658 smx_synchro_t synchro = xbt_new(s_smx_synchro_t, 1);
659 synchro->simcalls = xbt_fifo_new();
663 static void SIMIX_synchro_mallocator_free_f(void* synchro) {
664 xbt_fifo_free(((smx_synchro_t) synchro)->simcalls);
668 static void SIMIX_synchro_mallocator_reset_f(void* synchro) {
670 // we also recycle the simcall list
671 xbt_fifo_t fifo = ((smx_synchro_t) synchro)->simcalls;
672 xbt_fifo_reset(fifo);
673 memset(synchro, 0, sizeof(s_smx_synchro_t));
674 ((smx_synchro_t) synchro)->simcalls = fifo;
677 xbt_dict_t simcall_HANDLER_asr_get_properties(smx_simcall_t simcall, const char *name){
678 return SIMIX_asr_get_properties(name);
680 xbt_dict_t SIMIX_asr_get_properties(const char *name)
682 return xbt_lib_get_or_null(as_router_lib, name, ROUTING_PROP_ASR_LEVEL);