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;
35 bool _sg_do_verbose_exit = true;
36 static void inthandler(int)
38 if ( _sg_do_verbose_exit ) {
39 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option 'verbose-exit').");
40 SIMIX_display_process_status();
43 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'verbose-exit' is set to false.");
49 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
51 if (siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) {
52 fprintf(stderr, "Access violation detected.\n"
53 "This probably comes from a programming error in your code, or from a stack\n"
54 "overflow. If you are certain of your code, try increasing the stack size\n"
55 " --cfg=contexts/stack-size=XXX (current size is %u KiB).\n"
57 "If it does not help, this may have one of the following causes:\n"
58 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
59 "Failing hardware can sometimes generate such errors too.\n"
61 "If you think you've found a bug in SimGrid, please report it along with a\n"
62 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
63 "of the fault captured with gdb or valgrind.\n",
64 smx_context_stack_size / 1024);
65 } else if (siginfo->si_signo == SIGSEGV) {
66 fprintf(stderr, "Segmentation fault.\n");
68 if (smpi_enabled() && smpi_privatize_global_variables == SmpiPrivStrategies::NONE) {
69 #if HAVE_PRIVATIZATION
70 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
72 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
73 #endif /* HAVE_PRIVATIZATION */
75 #endif /* HAVE_SMPI */
80 unsigned char sigsegv_stack[SIGSTKSZ]; /* alternate stack for SIGSEGV handler */
83 * Install signal handler for SIGSEGV. Check that nobody has already installed
84 * its own handler. For example, the Java VM does this.
86 static void install_segvhandler()
90 stack.ss_sp = sigsegv_stack;
91 stack.ss_size = sizeof sigsegv_stack;
94 if (sigaltstack(&stack, &old_stack) == -1) {
95 XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
98 if (not(old_stack.ss_flags & SS_DISABLE)) {
99 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
100 old_stack.ss_size, (unsigned)old_stack.ss_flags);
101 sigaltstack(&old_stack, nullptr);
104 struct sigaction action;
105 struct sigaction old_action;
106 action.sa_sigaction = &segvhandler;
107 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
108 sigemptyset(&action.sa_mask);
110 if (sigaction(SIGSEGV, &action, &old_action) == -1) {
111 XBT_WARN("Failed to register signal handler for SIGSEGV: %s", strerror(errno));
114 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
115 XBT_DEBUG("A signal handler was already installed for SIGSEGV (%p). Restore it.",
116 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
117 sigaction(SIGSEGV, &old_action, nullptr);
123 /********************************* SIMIX **************************************/
127 Timer* Timer::set(double date, simgrid::xbt::Task<void()>&& callback)
129 Timer* timer = new Timer(date, std::move(callback));
130 timer->handle_ = simix_timers.emplace(std::make_pair(date, timer));
134 /** @brief cancels a timer that was added earlier */
137 simgrid::simix::simix_timers.erase(handle_);
141 void Global::empty_trash()
143 while (not actors_to_destroy.empty()) {
144 smx_actor_t actor = &actors_to_destroy.front();
145 actors_to_destroy.pop_front();
146 XBT_DEBUG("Getting rid of %p", actor);
147 intrusive_ptr_release(actor);
150 xbt_dynar_reset(simix_global->dead_actors_vector);
154 * @brief Executes the actors in simix_global->actors_to_run.
156 * The actors in simix_global->actors_to_run are run (in parallel if possible). On exit, simix_global->actors_to_run
157 * is empty, and simix_global->actors_that_ran contains the list of actors that just ran.
158 * The two lists are swapped so, be careful when using them before and after a call to this function.
160 void Global::run_all_actors()
162 SIMIX_context_runall();
164 simix_global->actors_to_run.swap(simix_global->actors_that_ran);
165 simix_global->actors_to_run.clear();
168 simgrid::config::Flag<double> breakpoint{"simix/breakpoint",
169 "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
173 static simgrid::simix::ActorCode maestro_code;
174 void SIMIX_set_maestro(void (*code)(void*), void* data)
177 XBT_INFO("WARNING, SIMIX_set_maestro is believed to not work on windows. Please help us investigating this issue if you need that feature");
179 maestro_code = std::bind(code, data);
184 * @brief Initialize SIMIX internal data.
186 void SIMIX_global_init(int *argc, char **argv)
189 // The communication initialization is done ASAP.
190 // We need to communicate initialization of the different layers to the model-checker.
191 simgrid::mc::Client::initialize();
194 if (simix_global == nullptr) {
195 surf_init(argc, argv); /* Initialize SURF structures */
197 simix_global.reset(new simgrid::simix::Global());
198 simix_global->maestro_process = nullptr;
199 SIMIX_context_mod_init();
201 // Either create a new context with maestro or create
202 // a context object with the current context mestro):
203 simgrid::kernel::actor::create_maestro(maestro_code);
205 /* Prepare to display some more info when dying on Ctrl-C pressing */
206 std::signal(SIGINT, inthandler);
209 install_segvhandler();
211 /* register a function to be called by SURF after the environment creation */
213 simgrid::s4u::on_platform_created.connect(surf_presolve);
215 simgrid::s4u::Storage::on_creation.connect([](simgrid::s4u::Storage const& storage) {
216 sg_storage_t s = simgrid::s4u::Storage::by_name(storage.get_name());
217 xbt_assert(s != nullptr, "Storage not found for name %s", storage.get_cname());
221 if (simgrid::config::get_value<bool>("clean-atexit"))
228 * @brief Clean the SIMIX simulation
230 * This functions remove the memory used by SIMIX
235 return; // to avoid double cleaning by java and C
238 XBT_DEBUG("SIMIX_clean called. Simulation's over.");
239 if (not simix_global->actors_to_run.empty() && SIMIX_get_clock() <= 0.0) {
241 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
242 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
243 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
247 if (SIMIX_process_count()>0){
248 if(smpi_process()->initialized()){
249 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
251 XBT_WARN("Process called exit when leaving - Skipping cleanups");
257 /* Kill all processes (but maestro) */
258 simix_global->maestro_process->kill_all();
259 SIMIX_context_runall();
260 simix_global->empty_trash();
262 /* Exit the SIMIX network module */
263 SIMIX_mailbox_exit();
265 while (not simgrid::simix::simix_timers.empty()) {
266 delete simgrid::simix::simix_timers.top().second;
267 simgrid::simix::simix_timers.pop();
269 /* Free the remaining data structures */
270 simix_global->actors_to_run.clear();
271 simix_global->actors_that_ran.clear();
272 simix_global->actors_to_destroy.clear();
273 simix_global->process_list.clear();
276 xbt_dynar_free(&simix_global->actors_vector);
277 xbt_dynar_free(&simix_global->dead_actors_vector);
280 /* Let's free maestro now */
281 delete simix_global->maestro_process;
282 simix_global->maestro_process = nullptr;
284 /* Finish context module and SURF */
285 SIMIX_context_mod_exit();
289 simix_global = nullptr;
294 * @brief A clock (in second).
296 * @return Return the clock.
298 double SIMIX_get_clock()
300 if(MC_is_active() || MC_record_replay_is_active()){
301 return MC_process_clock_get(SIMIX_process_self());
303 return surf_get_clock();
307 /** Wake up all processes waiting for a Surf action to finish */
308 static void SIMIX_wake_processes()
310 for (auto const& model : all_existing_models) {
311 simgrid::kernel::resource::Action* action;
313 XBT_DEBUG("Handling the processes whose action failed (if any)");
314 while ((action = model->extract_failed_action())) {
315 XBT_DEBUG(" Handling Action %p",action);
316 if (action->get_activity() != nullptr)
317 simgrid::kernel::activity::ActivityImplPtr(action->get_activity())->post();
319 XBT_DEBUG("Handling the processes whose action terminated normally (if any)");
320 while ((action = model->extract_done_action())) {
321 XBT_DEBUG(" Handling Action %p",action);
322 if (action->get_activity() == nullptr)
323 XBT_DEBUG("probably vcpu's action %p, skip", action);
325 simgrid::kernel::activity::ActivityImplPtr(action->get_activity())->post();
330 /** Handle any pending timer */
331 static bool SIMIX_execute_timers()
334 while (not simgrid::simix::simix_timers.empty() && SIMIX_get_clock() >= simgrid::simix::simix_timers.top().first) {
336 // FIXME: make the timers being real callbacks (i.e. provide dispatchers that read and expand the args)
337 smx_timer_t timer = simgrid::simix::simix_timers.top().second;
338 simgrid::simix::simix_timers.pop();
342 xbt_die("Exception thrown ouf of timer callback");
349 /** Execute all the tasks that are queued
351 * e.g. `.then()` callbacks of futures.
353 static bool SIMIX_execute_tasks()
355 xbt_assert(simix_global->tasksTemp.empty());
357 if (simix_global->tasks.empty())
361 // We don't want the callbacks to modify the vector we are iterating over:
362 simix_global->tasks.swap(simix_global->tasksTemp);
364 // Execute all the queued tasks:
365 for (auto& task : simix_global->tasksTemp)
368 simix_global->tasksTemp.clear();
369 } while (not simix_global->tasks.empty());
376 * @brief Run the main simulation loop.
380 if (not MC_record_path.empty()) {
381 simgrid::mc::replay(MC_record_path);
388 XBT_DEBUG("New Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
390 if (simgrid::simix::breakpoint >= 0.0 && surf_get_clock() >= simgrid::simix::breakpoint) {
391 XBT_DEBUG("Breakpoint reached (%g)", simgrid::simix::breakpoint.get());
392 simgrid::simix::breakpoint = -1.0;
400 SIMIX_execute_tasks();
402 while (not simix_global->actors_to_run.empty()) {
403 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
405 /* Run all processes that are ready to run, possibly in parallel */
406 simix_global->run_all_actors();
408 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
410 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
412 /* Here, the order is ok because:
414 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
415 * not impact its order.
417 * Long proof: processes remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
419 * - if there is no kill during the simulation, processes remain sorted according by their PID.
420 * Rationale: This can be proved inductively.
421 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
422 * is parsed linearly).
423 * Let's show that it is still so at the end of this round.
424 * - if a process is added when being created, that's from maestro. It can be either at startup
425 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
426 * in arbitrary order (inductive hypothesis), we are fine.
427 * - If a process is added because it's getting killed, its subsequent actions shouldn't matter
428 * - If a process gets added to actors_to_run because one of their blocking action constituting the meat
429 * of a simcall terminates, we're still good. Proof:
430 * - You are added from SIMIX_simcall_answer() only. When this function is called depends on the resource
431 * kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications as an
433 * - For communications, this function is called from SIMIX_comm_finish().
434 * This function itself don't mess with the order since simcalls are handled in FIFO order.
435 * The function is called:
436 * - before the comm starts (invalid parameters, or resource already dead or whatever).
437 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
438 * - because the communication failed or were canceled after startup. In this case, it's called from
439 * the function we are in, by the chunk:
440 * set = model->states.failed_action_set;
441 * while ((synchro = extract(set)))
442 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
443 * This order is also fixed because it depends of the order in which the surf actions were
444 * added to the system, and only maestro can add stuff this way, through simcalls.
445 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
446 * poped out of the set does not depend on the user code's execution order.
447 * - because the communication terminated. In this case, synchros are served in the order given by
448 * set = model->states.done_action_set;
449 * while ((synchro = extract(set)))
450 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
451 * and the argument is very similar to the previous one.
452 * So, in any case, the orders of calls to SIMIX_comm_finish() do not depend on the order in which user
453 * processes are executed.
454 * So, in any cases, the orders of processes within actors_to_run do not depend on the order in which
455 * user processes were executed previously.
456 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
457 * - If there is some process killings, the order is changed by this decision that comes from user-land
458 * But this decision may not have been motivated by a situation that were different because the simulation is
460 * So, even the order change induced by the process killing is perfectly reproducible.
462 * So science works, bitches [http://xkcd.com/54/].
464 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
465 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
467 * That would thus be a pure waste of time.
470 for (smx_actor_t const& process : simix_global->actors_that_ran) {
471 if (process->simcall.call != SIMCALL_NONE) {
472 SIMIX_simcall_handle(&process->simcall, 0);
476 SIMIX_execute_tasks();
478 SIMIX_wake_processes();
479 } while (SIMIX_execute_tasks());
481 /* If only daemon processes remain, cancel their actions, mark them to die and reschedule them */
482 if (simix_global->process_list.size() == simix_global->daemons.size())
483 for (auto const& dmon : simix_global->daemons) {
484 XBT_DEBUG("Kill %s", dmon->get_cname());
485 simix_global->maestro_process->kill(dmon);
489 time = simgrid::simix::Timer::next();
490 if (time > -1.0 || not simix_global->process_list.empty()) {
491 XBT_DEBUG("Calling surf_solve");
492 time = surf_solve(time);
493 XBT_DEBUG("Moving time ahead : %g", time);
496 /* Notify all the hosts that have failed */
497 /* FIXME: iterate through the list of failed host and mark each of them */
498 /* as failed. On each host, signal all the running processes with host_fail */
500 // Execute timers and tasks until there isn't anything to be done:
503 again = SIMIX_execute_timers();
504 if (SIMIX_execute_tasks())
506 SIMIX_wake_processes();
509 /* Clean actors to destroy */
510 simix_global->empty_trash();
512 XBT_DEBUG("### time %f, #processes %zu, #to_run %zu", time, simix_global->process_list.size(),
513 simix_global->actors_to_run.size());
515 } while (time > -1.0 || not simix_global->actors_to_run.empty());
517 if (not simix_global->process_list.empty()) {
519 if (simix_global->process_list.size() <= simix_global->daemons.size()) {
520 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
521 "once the simulation is over. Please fix your on_exit() functions.");
523 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
525 SIMIX_display_process_status();
526 simgrid::s4u::on_deadlock();
529 simgrid::s4u::on_simulation_end();
532 double SIMIX_timer_next()
534 return simgrid::simix::Timer::next();
537 smx_timer_t SIMIX_timer_set(double date, void (*callback)(void*), void *arg)
539 return simgrid::simix::Timer::set(date, std::bind(callback, arg));
542 smx_timer_t SIMIX_timer_set(double date, simgrid::xbt::Task<void()>&& callback) // deprecated
544 return simgrid::simix::Timer::set(date, std::move(callback));
547 /** @brief cancels a timer that was added earlier */
548 void SIMIX_timer_remove(smx_timer_t timer) {
552 /** @brief Returns the date at which the timer will trigger (or 0 if nullptr timer) */
553 double SIMIX_timer_get_date(smx_timer_t timer) {
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 smx_actor_t process = kv.second;
567 if (process->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 process->waiting_synchro)
576 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro) != nullptr)
577 synchro_description = "execution";
579 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro) != nullptr)
580 synchro_description = "communication";
582 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro) != nullptr)
583 synchro_description = "sleeping";
585 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro) != nullptr)
586 synchro_description = "synchronization";
588 if (boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro) != nullptr)
589 synchro_description = "I/O";
591 XBT_INFO("Process %ld (%s@%s): waiting for %s synchro %p (%s) in state %d to finish", process->get_pid(),
592 process->get_cname(), process->get_host()->get_cname(), synchro_description,
593 process->waiting_synchro.get(), name, (int)process->waiting_synchro->state_);
596 XBT_INFO("Process %ld (%s@%s)", process->get_pid(), process->get_cname(), process->get_host()->get_cname());
601 int SIMIX_is_maestro()
603 smx_actor_t self = SIMIX_process_self();
604 return simix_global == nullptr /*SimDag*/ || self == nullptr || self == simix_global->maestro_process;