1 /* Copyright (c) 2007-2019. 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. */
7 #include "simgrid/s4u/Engine.hpp"
8 #include "simgrid/s4u/Host.hpp"
9 #include "src/smpi/include/smpi_actor.hpp"
11 #include "simgrid/sg_config.hpp"
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/kernel/activity/IoImpl.hpp"
14 #include "src/kernel/activity/MailboxImpl.hpp"
15 #include "src/kernel/activity/SleepImpl.hpp"
16 #include "src/kernel/activity/SynchroRaw.hpp"
17 #include "src/mc/mc_record.hpp"
18 #include "src/mc/mc_replay.hpp"
19 #include "src/simix/smx_private.hpp"
20 #include "src/surf/StorageImpl.hpp"
21 #include "src/surf/xml/platf.hpp"
24 #include "src/mc/remote/Client.hpp"
28 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix, "Logging specific to SIMIX (kernel)");
31 std::unique_ptr<simgrid::simix::Global> simix_global;
33 void (*SMPI_switch_data_segment)(simgrid::s4u::ActorPtr) = nullptr;
37 config::Flag<double> cfg_verbose_exit{"debug/verbose-exit", {"verbose-exit"}, "Display the actor status at exit", true};
39 } // namespace simgrid
41 XBT_ATTRIB_NORETURN static void inthandler(int)
43 if (simgrid::simix::cfg_verbose_exit) {
44 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
45 "'debug/verbose-exit').");
46 SIMIX_display_process_status();
49 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
55 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
57 if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
59 "Access violation or Bus error detected.\n"
60 "This probably comes from a programming error in your code, or from a stack\n"
61 "overflow. If you are certain of your code, try increasing the stack size\n"
62 " --cfg=contexts/stack-size=XXX (current size is %u KiB).\n"
64 "If it does not help, this may have one of the following causes:\n"
65 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
66 "Failing hardware can sometimes generate such errors too.\n"
68 "If you think you've found a bug in SimGrid, please report it along with a\n"
69 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
70 "of the fault captured with gdb or valgrind.\n",
71 smx_context_stack_size / 1024);
72 } else if (siginfo->si_signo == SIGSEGV) {
73 fprintf(stderr, "Segmentation fault.\n");
75 if (smpi_enabled() && smpi_privatize_global_variables == SmpiPrivStrategies::NONE) {
76 #if HAVE_PRIVATIZATION
77 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
79 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
80 #endif /* HAVE_PRIVATIZATION */
82 #endif /* HAVE_SMPI */
87 unsigned char sigsegv_stack[SIGSTKSZ]; /* alternate stack for SIGSEGV handler */
90 * Install signal handler for SIGSEGV. Check that nobody has already installed
91 * its own handler. For example, the Java VM does this.
93 static void install_segvhandler()
97 stack.ss_sp = sigsegv_stack;
98 stack.ss_size = sizeof sigsegv_stack;
101 if (sigaltstack(&stack, &old_stack) == -1) {
102 XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
105 if (not(old_stack.ss_flags & SS_DISABLE)) {
106 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
107 old_stack.ss_size, (unsigned)old_stack.ss_flags);
108 sigaltstack(&old_stack, nullptr);
111 struct sigaction action;
112 struct sigaction old_action;
113 action.sa_sigaction = &segvhandler;
114 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
115 sigemptyset(&action.sa_mask);
117 /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
118 for (int sig : {SIGSEGV, SIGBUS}) {
119 if (sigaction(sig, &action, &old_action) == -1) {
120 XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
123 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
124 XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
125 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
126 sigaction(sig, &old_action, nullptr);
133 /********************************* SIMIX **************************************/
137 Timer* Timer::set(double date, xbt::Task<void()>&& callback)
139 Timer* timer = new Timer(date, std::move(callback));
140 timer->handle_ = simix_timers.emplace(std::make_pair(date, timer));
144 /** @brief cancels a timer that was added earlier */
147 simix_timers.erase(handle_);
151 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
152 bool Global::execute_tasks()
154 xbt_assert(tasksTemp.empty());
160 // We don't want the callbacks to modify the vector we are iterating over:
161 tasks.swap(tasksTemp);
163 // Execute all the queued tasks:
164 for (auto& task : tasksTemp)
168 } while (not tasks.empty());
173 void Global::empty_trash()
175 while (not actors_to_destroy.empty()) {
176 kernel::actor::ActorImpl* actor = &actors_to_destroy.front();
177 actors_to_destroy.pop_front();
178 XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
179 intrusive_ptr_release(actor);
182 xbt_dynar_reset(dead_actors_vector);
186 * @brief Executes the actors in actors_to_run.
188 * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
189 * contains the list of actors that just ran. The two lists are swapped so, be careful when using them before and after
190 * a call to this function.
192 void Global::run_all_actors()
194 simix_global->context_factory->run_all();
196 actors_to_run.swap(actors_that_ran);
197 actors_to_run.clear();
200 config::Flag<double> cfg_breakpoint{
201 "debug/breakpoint", {"simix/breakpoint"}, "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
203 } // namespace simgrid
205 static simgrid::simix::ActorCode maestro_code;
206 void SIMIX_set_maestro(void (*code)(void*), void* data)
209 XBT_INFO("WARNING, SIMIX_set_maestro is believed to not work on windows. Please help us investigating this issue if you need that feature");
211 maestro_code = std::bind(code, data);
216 * @brief Initialize SIMIX internal data.
218 void SIMIX_global_init(int *argc, char **argv)
221 // The communication initialization is done ASAP.
222 // We need to communicate initialization of the different layers to the model-checker.
223 simgrid::mc::Client::initialize();
226 if (simix_global == nullptr) {
227 surf_init(argc, argv); /* Initialize SURF structures */
229 simix_global.reset(new simgrid::simix::Global());
230 simix_global->maestro_process = nullptr;
231 SIMIX_context_mod_init();
233 // Either create a new context with maestro or create
234 // a context object with the current context maestro):
235 simgrid::kernel::actor::create_maestro(maestro_code);
237 /* Prepare to display some more info when dying on Ctrl-C pressing */
238 std::signal(SIGINT, inthandler);
241 install_segvhandler();
243 /* register a function to be called by SURF after the environment creation */
245 simgrid::s4u::Engine::on_platform_created.connect(surf_presolve);
247 simgrid::s4u::Storage::on_creation.connect([](simgrid::s4u::Storage const& storage) {
248 sg_storage_t s = simgrid::s4u::Storage::by_name(storage.get_name());
249 xbt_assert(s != nullptr, "Storage not found for name %s", storage.get_cname());
253 if (simgrid::config::get_value<bool>("debug/clean-atexit"))
260 * @brief Clean the SIMIX simulation
262 * This functions remove the memory used by SIMIX
267 return; // to avoid double cleaning by java and C
270 XBT_DEBUG("SIMIX_clean called. Simulation's over.");
271 if (not simix_global->actors_to_run.empty() && SIMIX_get_clock() <= 0.0) {
273 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
274 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
275 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
279 if (simix_global->process_list.size() > 0) {
280 if(smpi_process()->initialized()){
281 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
283 XBT_WARN("Process called exit when leaving - Skipping cleanups");
289 /* Kill all processes (but maestro) */
290 simix_global->maestro_process->kill_all();
291 simix_global->run_all_actors();
292 simix_global->empty_trash();
294 /* Exit the SIMIX network module */
295 SIMIX_mailbox_exit();
297 while (not simgrid::simix::simix_timers.empty()) {
298 delete simgrid::simix::simix_timers.top().second;
299 simgrid::simix::simix_timers.pop();
301 /* Free the remaining data structures */
302 simix_global->actors_to_run.clear();
303 simix_global->actors_that_ran.clear();
304 simix_global->actors_to_destroy.clear();
305 simix_global->process_list.clear();
308 xbt_dynar_free(&simix_global->actors_vector);
309 xbt_dynar_free(&simix_global->dead_actors_vector);
312 /* Let's free maestro now */
313 delete simix_global->maestro_process;
314 simix_global->maestro_process = nullptr;
316 /* Finish context module and SURF */
317 SIMIX_context_mod_exit();
321 simix_global = nullptr;
326 * @brief A clock (in second).
328 * @return Return the clock.
330 double SIMIX_get_clock()
332 if(MC_is_active() || MC_record_replay_is_active()){
333 return MC_process_clock_get(SIMIX_process_self());
335 return surf_get_clock();
339 /** Wake up all processes waiting for a Surf action to finish */
340 static void SIMIX_wake_processes()
342 for (auto const& model : all_existing_models) {
343 simgrid::kernel::resource::Action* action;
345 XBT_DEBUG("Handling the failed actions (if any)");
346 while ((action = model->extract_failed_action())) {
347 XBT_DEBUG(" Handling Action %p",action);
348 if (action->get_activity() != nullptr)
349 simgrid::kernel::activity::ActivityImplPtr(action->get_activity())->post();
351 XBT_DEBUG("Handling the terminated actions (if any)");
352 while ((action = model->extract_done_action())) {
353 XBT_DEBUG(" Handling Action %p",action);
354 if (action->get_activity() == nullptr)
355 XBT_DEBUG("probably vcpu's action %p, skip", action);
357 simgrid::kernel::activity::ActivityImplPtr(action->get_activity())->post();
362 /** Handle any pending timer. Returns if something was actually run. */
363 static bool SIMIX_execute_timers()
366 while (not simgrid::simix::simix_timers.empty() && SIMIX_get_clock() >= simgrid::simix::simix_timers.top().first) {
368 // FIXME: make the timers being real callbacks (i.e. provide dispatchers that read and expand the args)
369 smx_timer_t timer = simgrid::simix::simix_timers.top().second;
370 simgrid::simix::simix_timers.pop();
379 * @brief Run the main simulation loop.
383 if (MC_record_replay_is_active()) {
384 simgrid::mc::replay(MC_record_path);
391 XBT_DEBUG("New Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
393 if (simgrid::simix::cfg_breakpoint >= 0.0 && surf_get_clock() >= simgrid::simix::cfg_breakpoint) {
394 XBT_DEBUG("Breakpoint reached (%g)", simgrid::simix::cfg_breakpoint.get());
395 simgrid::simix::cfg_breakpoint = -1.0;
403 simix_global->execute_tasks();
405 while (not simix_global->actors_to_run.empty()) {
406 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
408 /* Run all processes that are ready to run, possibly in parallel */
409 simix_global->run_all_actors();
411 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
413 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
415 /* Here, the order is ok because:
417 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
418 * not impact its order.
420 * Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
422 * - if there is no kill during the simulation, processes remain sorted according by their PID.
423 * Rationale: This can be proved inductively.
424 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
425 * is parsed linearly).
426 * Let's show that it is still so at the end of this round.
427 * - if a process is added when being created, that's from maestro. It can be either at startup
428 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
429 * in arbitrary order (inductive hypothesis), we are fine.
430 * - If a process is added because it's getting killed, its subsequent actions shouldn't matter
431 * - If a process gets added to actors_to_run because one of their blocking action constituting the meat
432 * of a simcall terminates, we're still good. Proof:
433 * - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the resource
434 * kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an
436 * - For communications, this function is called from SIMIX_comm_finish().
437 * This function itself don't mess with the order since simcalls are handled in FIFO order.
438 * The function is called:
439 * - before the comm starts (invalid parameters, or resource already dead or whatever).
440 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
441 * - because the communication failed or were canceled after startup. In this case, it's called from
442 * the function we are in, by the chunk:
443 * set = model->states.failed_action_set;
444 * while ((synchro = extract(set)))
445 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
446 * This order is also fixed because it depends of the order in which the surf actions were
447 * added to the system, and only maestro can add stuff this way, through simcalls.
448 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
449 * poped out of the set does not depend on the user code's execution order.
450 * - because the communication terminated. In this case, synchros are served in the order given by
451 * set = model->states.done_action_set;
452 * while ((synchro = extract(set)))
453 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
454 * and the argument is very similar to the previous one.
455 * So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user
456 * processes are executed.
457 * So, in any cases, the orders of processes within actors_to_run do not depend on the order in which
458 * user processes were executed previously.
459 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
460 * - If there is some process killings, the order is changed by this decision that comes from user-land
461 * But this decision may not have been motivated by a situation that were different because the simulation is
463 * So, even the order change induced by the process killing is perfectly reproducible.
465 * So science works, bitches [http://xkcd.com/54/].
467 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
468 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
470 * That would thus be a pure waste of time.
473 for (auto const& actor : simix_global->actors_that_ran) {
474 if (actor->simcall.call_ != SIMCALL_NONE) {
475 actor->simcall_handle(0);
479 simix_global->execute_tasks();
481 SIMIX_wake_processes();
482 } while (simix_global->execute_tasks());
484 /* If only daemon processes remain, cancel their actions, mark them to die and reschedule them */
485 if (simix_global->process_list.size() == simix_global->daemons.size())
486 for (auto const& dmon : simix_global->daemons) {
487 XBT_DEBUG("Kill %s", dmon->get_cname());
488 simix_global->maestro_process->kill(dmon);
492 time = simgrid::simix::Timer::next();
493 if (time > -1.0 || not simix_global->process_list.empty()) {
494 XBT_DEBUG("Calling surf_solve");
495 time = surf_solve(time);
496 XBT_DEBUG("Moving time ahead : %g", time);
499 /* Notify all the hosts that have failed */
500 /* FIXME: iterate through the list of failed host and mark each of them */
501 /* as failed. On each host, signal all the running processes with host_fail */
503 // Execute timers and tasks until there isn't anything to be done:
506 again = SIMIX_execute_timers();
507 if (simix_global->execute_tasks())
509 SIMIX_wake_processes();
512 /* Clean actors to destroy */
513 simix_global->empty_trash();
515 XBT_DEBUG("### time %f, #processes %zu, #to_run %zu", time, simix_global->process_list.size(),
516 simix_global->actors_to_run.size());
518 } while (time > -1.0 || not simix_global->actors_to_run.empty());
520 if (not simix_global->process_list.empty()) {
522 if (simix_global->process_list.size() <= simix_global->daemons.size()) {
523 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
524 "once the simulation is over. Please fix your on_exit() functions.");
526 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
528 SIMIX_display_process_status();
529 simgrid::s4u::Engine::on_deadlock();
532 simgrid::s4u::Engine::on_simulation_end();
535 double SIMIX_timer_next() // XBT_ATTRIB_DEPRECATED_v329
537 return simgrid::simix::Timer::next();
540 smx_timer_t SIMIX_timer_set(double date, void (*callback)(void*), void* arg) // XBT_ATTRIB_DEPRECATED_v329
542 return simgrid::simix::Timer::set(date, std::bind(callback, arg));
545 /** @brief cancels a timer that was added earlier */
546 void SIMIX_timer_remove(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
551 /** @brief Returns the date at which the timer will trigger (or 0 if nullptr timer) */
552 double SIMIX_timer_get_date(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
554 return timer ? timer->get_date() : 0;
557 void SIMIX_display_process_status()
559 int nbprocess = simix_global->process_list.size();
561 XBT_INFO("%d processes are still running, waiting for something.", nbprocess);
562 /* List the process and their state */
563 XBT_INFO("Legend of the following listing: \"Process <pid> (<name>@<host>): <status>\"");
564 for (auto const& kv : simix_global->process_list) {
565 simgrid::kernel::actor::ActorImpl* actor = kv.second;
567 if (actor->waiting_synchro) {
569 const char* synchro_description = "unknown";
570 // we don't care about the Activity type to get its name, use RawImpl
572 boost::static_pointer_cast<simgrid::kernel::activity::ActivityImpl_T<simgrid::kernel::activity::RawImpl>>(
573 actor->waiting_synchro)
576 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(actor->waiting_synchro) != nullptr)
577 synchro_description = "execution";
579 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(actor->waiting_synchro) != nullptr)
580 synchro_description = "communication";
582 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(actor->waiting_synchro) != nullptr)
583 synchro_description = "sleeping";
585 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(actor->waiting_synchro) != nullptr)
586 synchro_description = "synchronization";
588 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(actor->waiting_synchro) != nullptr)
589 synchro_description = "I/O";
591 XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %p (%s) in state %d to finish", actor->get_pid(),
592 actor->get_cname(), actor->get_host()->get_cname(), synchro_description, actor->waiting_synchro.get(),
593 name, (int)actor->waiting_synchro->state_);
596 XBT_INFO("Actor %ld (%s@%s)", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname());
601 int SIMIX_is_maestro()
603 if (simix_global == nullptr) // SimDag
605 simgrid::kernel::actor::ActorImpl* self = SIMIX_process_self();
606 return self == nullptr || self == simix_global->maestro_process;