1 /* Copyright (c) 2007-2017. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
10 #include "src/internal_config.h"
11 #include <csignal> /* Signal handling */
14 #include <xbt/algorithm.hpp>
15 #include <xbt/functional.hpp>
17 #include "simgrid/s4u/Engine.hpp"
18 #include "simgrid/s4u/Host.hpp"
20 #include "smx_private.hpp"
21 #include "src/surf/surf_interface.hpp"
22 #include "src/surf/xml/platf.hpp"
23 #include "xbt/ex.h" /* ex_backtrace_display */
26 #include "simgrid/sg_config.h"
27 #include "src/mc/mc_replay.hpp"
28 #include "src/surf/StorageImpl.hpp"
30 #include "src/smpi/include/smpi_process.hpp"
32 #include "src/kernel/activity/CommImpl.hpp"
33 #include "src/kernel/activity/ExecImpl.hpp"
34 #include "src/kernel/activity/SleepImpl.hpp"
35 #include "src/kernel/activity/SynchroIo.hpp"
36 #include "src/kernel/activity/SynchroRaw.hpp"
39 #include "src/mc/mc_private.hpp"
40 #include "src/mc/remote/Client.hpp"
41 #include "src/mc/remote/mc_protocol.h"
44 #include "src/mc/mc_record.hpp"
47 #include "src/smpi/include/private.hpp"
50 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
51 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix, "Logging specific to SIMIX (kernel)");
53 std::unique_ptr<simgrid::simix::Global> simix_global;
55 /** @brief Timer datatype */
60 simgrid::xbt::Task<void()> callback;
61 void disable() { date = -1.0; }
62 bool isDisabled() { return date == -1.0; }
63 double getDate() { return date; }
64 s_smx_timer_t(double date, simgrid::xbt::Task<void()> callback) : date(date), callback(std::move(callback)) {}
68 typedef std::pair<double, smx_timer_t> TimerQelt;
69 std::priority_queue<TimerQelt, std::vector<TimerQelt>, std::greater<TimerQelt>> simix_timers;
70 void SIMIX_timer_flush()
72 while (not simix_timers.empty() && simix_timers.top().second->isDisabled()) {
73 delete simix_timers.top().second;
79 void (*SMPI_switch_data_segment)(int) = nullptr;
81 int _sg_do_verbose_exit = 1;
82 static void inthandler(int)
84 if ( _sg_do_verbose_exit ) {
85 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option 'verbose-exit').");
86 SIMIX_display_process_status();
89 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'verbose-exit' is set to false.");
95 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
97 if (siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) {
98 fprintf(stderr, "Access violation detected.\n"
99 "This probably comes from a programming error in your code, or from a stack\n"
100 "overflow. If you are certain of your code, try increasing the stack size\n"
101 " --cfg=contexts/stack-size=XXX (current size is %u KiB).\n"
103 "If it does not help, this may have one of the following causes:\n"
104 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
105 "Failing hardware can sometimes generate such errors too.\n"
107 "If you think you've found a bug in SimGrid, please report it along with a\n"
108 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
109 "of the fault captured with gdb or valgrind.\n",
110 smx_context_stack_size / 1024);
111 } else if (siginfo->si_signo == SIGSEGV) {
112 fprintf(stderr, "Segmentation fault.\n");
114 if (smpi_enabled() && smpi_privatize_global_variables == SMPI_PRIVATIZE_NONE) {
115 #if HAVE_PRIVATIZATION
116 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
118 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
119 #endif /* HAVE_PRIVATIZATION */
121 #endif /* HAVE_SMPI */
126 char sigsegv_stack[SIGSTKSZ]; /* alternate stack for SIGSEGV handler */
129 * Install signal handler for SIGSEGV. Check that nobody has already installed
130 * its own handler. For example, the Java VM does this.
132 static void install_segvhandler()
136 stack.ss_sp = sigsegv_stack;
137 stack.ss_size = sizeof sigsegv_stack;
140 if (sigaltstack(&stack, &old_stack) == -1) {
141 XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
144 if (not(old_stack.ss_flags & SS_DISABLE)) {
145 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
146 old_stack.ss_size, (unsigned)old_stack.ss_flags);
147 sigaltstack(&old_stack, nullptr);
150 struct sigaction action;
151 struct sigaction old_action;
152 action.sa_sigaction = &segvhandler;
153 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
154 sigemptyset(&action.sa_mask);
156 if (sigaction(SIGSEGV, &action, &old_action) == -1) {
157 XBT_WARN("Failed to register signal handler for SIGSEGV: %s", strerror(errno));
160 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
161 XBT_DEBUG("A signal handler was already installed for SIGSEGV (%p). Restore it.",
162 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
163 sigaction(SIGSEGV, &old_action, nullptr);
169 /********************************* SIMIX **************************************/
170 double SIMIX_timer_next()
172 return simix_timers.empty() ? -1.0 : simix_timers.top().first;
175 static void kill_process(smx_actor_t process)
177 SIMIX_process_kill(process, nullptr);
180 static std::function<void()> maestro_code;
185 simgrid::xbt::signal<void()> onDeadlock;
187 XBT_PUBLIC(void) set_maestro(std::function<void()> code)
189 maestro_code = std::move(code);
195 void SIMIX_set_maestro(void (*code)(void*), void* data)
198 XBT_INFO("WARNING, SIMIX_set_maestro is believed to not work on windows. Please help us investigating this issue if you need that feature");
200 maestro_code = std::bind(code, data);
205 * \brief Initialize SIMIX internal data.
210 void SIMIX_global_init(int *argc, char **argv)
213 // The communication initialization is done ASAP.
214 // We need to communicate initialization of the different layers to the model-checker.
215 simgrid::mc::Client::initialize();
218 if (not simix_global) {
219 simix_global = std::unique_ptr<simgrid::simix::Global>(new simgrid::simix::Global());
221 simgrid::simix::ActorImpl proc;
222 simix_global->process_to_destroy = xbt_swag_new(xbt_swag_offset(proc, destroy_hookup));
223 simix_global->maestro_process = nullptr;
224 simix_global->create_process_function = &SIMIX_process_create;
225 simix_global->kill_process_function = &kill_process;
226 simix_global->cleanup_process_function = &SIMIX_process_cleanup;
227 simix_global->mutex = xbt_os_mutex_init();
229 surf_init(argc, argv); /* Initialize SURF structures */
230 SIMIX_context_mod_init();
232 // Either create a new context with maestro or create
233 // a context object with the current context mestro):
234 simgrid::simix::create_maestro(maestro_code);
236 /* Prepare to display some more info when dying on Ctrl-C pressing */
237 signal(SIGINT, inthandler);
240 install_segvhandler();
242 /* register a function to be called by SURF after the environment creation */
244 simgrid::s4u::onPlatformCreated.connect(SIMIX_post_create_environment);
245 simgrid::s4u::Host::onCreation.connect([](simgrid::s4u::Host& host) {
246 if (host.extension<simgrid::simix::Host>() == nullptr) // another callback to the same signal may have created it
247 host.extension_set<simgrid::simix::Host>(new simgrid::simix::Host());
250 simgrid::surf::storageCreatedCallbacks.connect([](simgrid::surf::StorageImpl* storage) {
251 sg_storage_t s = simgrid::s4u::Storage::byName(storage->getCname());
252 xbt_assert(s != nullptr, "Storage not found for name %s", storage->getCname());
256 if (xbt_cfg_get_boolean("clean-atexit"))
259 if (_sg_cfg_exit_asap)
266 * \brief Clean the SIMIX simulation
268 * This functions remove the memory used by SIMIX
273 return; // to avoid double cleaning by java and C
276 XBT_DEBUG("SIMIX_clean called. Simulation's over.");
277 if (not simix_global->process_to_run.empty() && SIMIX_get_clock() <= 0.0) {
279 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
280 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
281 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
285 if (SIMIX_process_count()>0){
286 if(smpi_process()->initialized()){
287 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
289 XBT_WARN("Process called exit when leaving - Skipping cleanups");
295 /* Kill all processes (but maestro) */
296 SIMIX_process_killall(simix_global->maestro_process, 1);
297 SIMIX_context_runall();
298 SIMIX_process_empty_trash();
300 /* Exit the SIMIX network module */
301 SIMIX_mailbox_exit();
303 while (not simix_timers.empty()) {
304 delete simix_timers.top().second;
307 /* Free the remaining data structures */
308 simix_global->process_to_run.clear();
309 simix_global->process_that_ran.clear();
310 xbt_swag_free(simix_global->process_to_destroy);
311 simix_global->process_list.clear();
312 simix_global->process_to_destroy = nullptr;
314 xbt_os_mutex_destroy(simix_global->mutex);
315 simix_global->mutex = nullptr;
317 xbt_dynar_free(&simix_global->actors_vector);
320 /* Let's free maestro now */
321 delete simix_global->maestro_process->context;
322 simix_global->maestro_process->context = nullptr;
323 delete simix_global->maestro_process;
324 simix_global->maestro_process = nullptr;
326 /* Finish context module and SURF */
327 SIMIX_context_mod_exit();
331 simix_global = nullptr;
337 * \brief A clock (in second).
339 * \return Return the clock.
341 double SIMIX_get_clock()
343 if(MC_is_active() || MC_record_replay_is_active()){
344 return MC_process_clock_get(SIMIX_process_self());
346 return surf_get_clock();
350 /** Wake up all processes waiting for a Surf action to finish */
351 static void SIMIX_wake_processes()
353 surf_action_t action;
355 for (auto const& model : *all_existing_models) {
356 XBT_DEBUG("Handling the processes whose action failed (if any)");
357 while ((action = surf_model_extract_failed_action_set(model))) {
358 XBT_DEBUG(" Handling Action %p",action);
359 SIMIX_simcall_exit(static_cast<simgrid::kernel::activity::ActivityImpl*>(action->getData()));
361 XBT_DEBUG("Handling the processes whose action terminated normally (if any)");
362 while ((action = surf_model_extract_done_action_set(model))) {
363 XBT_DEBUG(" Handling Action %p",action);
364 if (action->getData() == nullptr)
365 XBT_DEBUG("probably vcpu's action %p, skip", action);
367 SIMIX_simcall_exit(static_cast<simgrid::kernel::activity::ActivityImpl*>(action->getData()));
372 /** Handle any pending timer */
373 static bool SIMIX_execute_timers()
376 while (not simix_timers.empty() && SIMIX_get_clock() >= simix_timers.top().first) {
378 // FIXME: make the timers being real callbacks
379 // (i.e. provide dispatchers that read and expand the args)
380 smx_timer_t timer = simix_timers.top().second;
386 xbt_die("Exception thrown ouf of timer callback");
393 /** Execute all the tasks that are queued
395 * e.g. `.then()` callbacks of futures.
397 static bool SIMIX_execute_tasks()
399 xbt_assert(simix_global->tasksTemp.empty());
401 if (simix_global->tasks.empty())
406 // We don't want the callbacks to modify the vector we are iterating over:
407 swap(simix_global->tasks, simix_global->tasksTemp);
409 // Execute all the queued tasks:
410 for (auto& task : simix_global->tasksTemp)
413 simix_global->tasksTemp.clear();
414 } while (not simix_global->tasks.empty());
421 * \brief Run the main simulation loop.
425 if (not MC_record_path.empty()) {
426 simgrid::mc::replay(MC_record_path);
433 XBT_DEBUG("New Schedule Round; size(queue)=%zu", simix_global->process_to_run.size());
435 SIMIX_execute_tasks();
437 while (not simix_global->process_to_run.empty()) {
438 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", simix_global->process_to_run.size());
440 /* Run all processes that are ready to run, possibly in parallel */
441 SIMIX_process_runall();
443 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
445 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
447 /* Here, the order is ok because:
449 * Short proof: only maestro adds stuff to the process_to_run array, so the execution order of user contexts do not impact its order.
451 * Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
453 * - if there is no kill during the simulation, processes remain sorted according by their PID.
454 * rational: This can be proved inductively.
455 * Assume that process_to_run is sorted at a beginning of one round (it is at round 0: the deployment file is parsed linearly).
456 * Let's show that it is still so at the end of this round.
457 * - if a process is added when being created, that's from maestro. It can be either at startup
458 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
459 * in arbitrary order (inductive hypothesis), we are fine.
460 * - If a process is added because it's getting killed, its subsequent actions shouldn't matter
461 * - If a process gets added to process_to_run because one of their blocking action constituting the meat
462 * of a simcall terminates, we're still good. Proof:
463 * - You are added from SIMIX_simcall_answer() only. When this function is called depends on the resource
464 * kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an example.
465 * - For communications, this function is called from SIMIX_comm_finish().
466 * This function itself don't mess with the order since simcalls are handled in FIFO order.
467 * The function is called:
468 * - before the comm starts (invalid parameters, or resource already dead or whatever).
469 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
470 * - because the communication failed or were canceled after startup. In this case, it's called from the function
471 * we are in, by the chunk:
472 * set = model->states.failed_action_set;
473 * while ((synchro = xbt_swag_extract(set)))
474 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
475 * This order is also fixed because it depends of the order in which the surf actions were
476 * added to the system, and only maestro can add stuff this way, through simcalls.
477 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
478 * poped out of the swag does not depend on the user code's execution order.
479 * - because the communication terminated. In this case, synchros are served in the order given by
480 * set = model->states.done_action_set;
481 * while ((synchro = xbt_swag_extract(set)))
482 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
483 * and the argument is very similar to the previous one.
484 * So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user processes are executed.
485 * 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.
486 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
487 * - If there is some process killings, the order is changed by this decision that comes from user-land
488 * But this decision may not have been motivated by a situation that were different because the simulation is not reproducible.
489 * So, even the order change induced by the process killing is perfectly reproducible.
491 * So science works, bitches [http://xkcd.com/54/].
493 * We could sort the process_that_ran array completely so that we can describe the order in which simcalls are handled
494 * (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if unfriendly).
495 * That would thus be a pure waste of time.
498 for (smx_actor_t const& process : simix_global->process_that_ran) {
499 if (process->simcall.call != SIMCALL_NONE) {
500 SIMIX_simcall_handle(&process->simcall, 0);
504 SIMIX_execute_tasks();
506 SIMIX_wake_processes();
507 } while (SIMIX_execute_tasks());
509 /* If only daemon processes remain, cancel their actions, mark them to die and reschedule them */
510 if (simix_global->process_list.size() == simix_global->daemons.size())
511 for (auto const& dmon : simix_global->daemons) {
512 XBT_DEBUG("Kill %s", dmon->getCname());
513 SIMIX_process_kill(dmon, simix_global->maestro_process);
517 time = SIMIX_timer_next();
518 if (time > -1.0 || not simix_global->process_list.empty()) {
519 XBT_DEBUG("Calling surf_solve");
520 time = surf_solve(time);
521 XBT_DEBUG("Moving time ahead : %g", time);
524 /* Notify all the hosts that have failed */
525 /* FIXME: iterate through the list of failed host and mark each of them */
526 /* as failed. On each host, signal all the running processes with host_fail */
528 // Execute timers and tasks until there isn't anything to be done:
531 again = SIMIX_execute_timers();
532 if (SIMIX_execute_tasks())
534 SIMIX_wake_processes();
537 /* Autorestart all process */
538 for (auto const& host : host_that_restart) {
539 XBT_INFO("Restart processes on host %s", host->getCname());
540 SIMIX_host_autorestart(host);
542 host_that_restart.clear();
544 /* Clean processes to destroy */
545 SIMIX_process_empty_trash();
547 XBT_DEBUG("### time %f, #processes %zu, #to_run %zu", time, simix_global->process_list.size(),
548 simix_global->process_to_run.size());
550 if (simix_global->process_to_run.empty() && not simix_global->process_list.empty())
551 simgrid::simix::onDeadlock();
553 } while (time > -1.0 || not simix_global->process_to_run.empty());
555 if (not simix_global->process_list.empty()) {
559 XBT_CRITICAL("Oops ! Deadlock or code not perfectly clean.");
560 SIMIX_display_process_status();
563 simgrid::s4u::onSimulationEnd();
567 * \brief Set the date to execute a function
569 * Set the date to execute the function on the surf.
570 * \param date Date to execute function
571 * \param callback Function to be executed
572 * \param arg Parameters of the function
575 smx_timer_t SIMIX_timer_set(double date, void (*callback)(void*), void *arg)
577 smx_timer_t timer = new s_smx_timer_t(date, [callback, arg]() { callback(arg); });
578 simix_timers.emplace(date, timer);
582 smx_timer_t SIMIX_timer_set(double date, simgrid::xbt::Task<void()> callback)
584 smx_timer_t timer = new s_smx_timer_t(date, std::move(callback));
585 simix_timers.emplace(date, timer);
589 /** @brief cancels a timer that was added earlier */
590 void SIMIX_timer_remove(smx_timer_t timer) {
595 /** @brief Returns the date at which the timer will trigger (or 0 if nullptr timer) */
596 double SIMIX_timer_get_date(smx_timer_t timer) {
597 return timer ? timer->getDate() : 0;
601 * \brief Registers a function to create a process.
603 * This function registers a function to be called
604 * when a new process is created. The function has
605 * to call SIMIX_process_create().
606 * \param function create process function
608 void SIMIX_function_register_process_create(smx_creation_func_t function)
610 simix_global->create_process_function = function;
614 * \brief Registers a function to kill a process.
616 * This function registers a function to be called when a process is killed. The function has to call the
617 * SIMIX_process_kill().
619 * \param function Kill process function
621 void SIMIX_function_register_process_kill(void_pfn_smxprocess_t function)
623 simix_global->kill_process_function = function;
627 * \brief Registers a function to cleanup a process.
629 * This function registers a user function to be called when a process ends properly.
631 * \param function cleanup process function
633 void SIMIX_function_register_process_cleanup(void_pfn_smxprocess_t function)
635 simix_global->cleanup_process_function = function;
639 void SIMIX_display_process_status()
641 int nbprocess = simix_global->process_list.size();
643 XBT_INFO("%d processes are still running, waiting for something.", nbprocess);
644 /* List the process and their state */
645 XBT_INFO("Legend of the following listing: \"Process <pid> (<name>@<host>): <status>\"");
646 for (auto const& kv : simix_global->process_list) {
647 smx_actor_t process = kv.second;
649 if (process->waiting_synchro) {
651 const char* synchro_description = "unknown";
653 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro) != nullptr)
654 synchro_description = "execution";
656 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro) != nullptr)
657 synchro_description = "communication";
659 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro) != nullptr)
660 synchro_description = "sleeping";
662 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro) != nullptr)
663 synchro_description = "synchronization";
665 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro) != nullptr)
666 synchro_description = "I/O";
668 XBT_INFO("Process %lu (%s@%s): waiting for %s synchro %p (%s) in state %d to finish", process->pid,
669 process->getCname(), process->host->getCname(), synchro_description, process->waiting_synchro.get(),
670 process->waiting_synchro->name.c_str(), (int)process->waiting_synchro->state);
673 XBT_INFO("Process %lu (%s@%s)", process->pid, process->getCname(), process->host->getCname());
678 int SIMIX_is_maestro()
680 smx_actor_t self = SIMIX_process_self();
681 return simix_global == nullptr /*SimDag*/ || self == nullptr || self == simix_global->maestro_process;