1 /* Copyright (c) 2007-2020. 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/AppSide.hpp"
29 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix, "Logging specific to SIMIX (kernel)");
32 std::unique_ptr<simgrid::simix::Global> simix_global;
34 void (*SMPI_switch_data_segment)(simgrid::s4u::ActorPtr) = nullptr;
38 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit",
39 {"verbose-exit"}, // XBT_ATTRIB_DEPRECATED_v327(option alias)
40 "Display the actor status at exit",
43 } // namespace simgrid
45 XBT_ATTRIB_NORETURN static void inthandler(int)
47 if (simgrid::simix::cfg_verbose_exit) {
48 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
49 "'debug/verbose-exit').");
50 simix_global->display_all_actor_status();
53 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
59 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
61 if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
63 "Access violation or Bus error detected.\n"
64 "This probably comes from a programming error in your code, or from a stack\n"
65 "overflow. If you are certain of your code, try increasing the stack size\n"
66 " --cfg=contexts/stack-size=XXX (current size is %u KiB).\n"
68 "If it does not help, this may have one of the following causes:\n"
69 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
70 "Failing hardware can sometimes generate such errors too.\n"
72 "If you think you've found a bug in SimGrid, please report it along with a\n"
73 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
74 "of the fault captured with gdb or valgrind.\n",
75 smx_context_stack_size / 1024);
76 } else if (siginfo->si_signo == SIGSEGV) {
77 fprintf(stderr, "Segmentation fault.\n");
79 if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
80 #if HAVE_PRIVATIZATION
81 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
83 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
84 #endif /* HAVE_PRIVATIZATION */
86 #endif /* HAVE_SMPI */
91 std::array<unsigned char, SIGSTKSZ> sigsegv_stack; /* alternate stack for SIGSEGV handler */
94 * Install signal handler for SIGSEGV. Check that nobody has already installed
95 * its own handler. For example, the Java VM does this.
97 static void install_segvhandler()
101 if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -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 auto* 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 /** Wake up all actors waiting for a Surf action to finish */
201 void Global::wake_all_waiting_actors() const
203 for (auto const& model : all_existing_models) {
204 kernel::resource::Action* action;
206 XBT_DEBUG("Handling the failed actions (if any)");
207 while ((action = model->extract_failed_action())) {
208 XBT_DEBUG(" Handling Action %p", action);
209 if (action->get_activity() != nullptr)
210 kernel::activity::ActivityImplPtr(action->get_activity())->post();
212 XBT_DEBUG("Handling the terminated actions (if any)");
213 while ((action = model->extract_done_action())) {
214 XBT_DEBUG(" Handling Action %p", action);
215 if (action->get_activity() == nullptr)
216 XBT_DEBUG("probably vcpu's action %p, skip", action);
218 kernel::activity::ActivityImplPtr(action->get_activity())->post();
223 void Global::display_all_actor_status() const
225 XBT_INFO("%zu actors are still running, waiting for something.", process_list.size());
226 /* List the actors and their state */
227 XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
228 for (auto const& kv : process_list) {
229 kernel::actor::ActorImpl* actor = kv.second;
231 if (actor->waiting_synchro_) {
232 const char* synchro_description = "unknown";
234 if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
235 synchro_description = "execution";
237 if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
238 synchro_description = "communication";
240 if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
241 synchro_description = "sleeping";
243 if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
244 synchro_description = "synchronization";
246 if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
247 synchro_description = "I/O";
249 XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
250 actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
251 (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
252 actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
254 XBT_INFO("Actor %ld (%s@%s)", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname());
259 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
260 {"simix/breakpoint"}, // XBT_ATTRIB_DEPRECATED_v327(option alias)
261 "When non-negative, raise a SIGTRAP after given (simulated) time",
264 } // namespace simgrid
266 static simgrid::kernel::actor::ActorCode maestro_code;
267 void SIMIX_set_maestro(void (*code)(void*), void* data)
270 XBT_INFO("WARNING, SIMIX_set_maestro is believed to not work on windows. Please help us investigating this issue if you need that feature");
272 maestro_code = std::bind(code, data);
277 * @brief Initialize SIMIX internal data.
279 void SIMIX_global_init(int *argc, char **argv)
282 // The communication initialization is done ASAP.
283 // We need to communicate initialization of the different layers to the model-checker.
284 simgrid::mc::AppSide::initialize();
287 if (simix_global == nullptr) {
288 surf_init(argc, argv); /* Initialize SURF structures */
290 simix_global = std::make_unique<simgrid::simix::Global>();
291 simix_global->maestro_ = nullptr;
292 SIMIX_context_mod_init();
294 // Either create a new context with maestro or create
295 // a context object with the current context maestro):
296 simgrid::kernel::actor::create_maestro(maestro_code);
298 /* Prepare to display some more info when dying on Ctrl-C pressing */
299 std::signal(SIGINT, inthandler);
302 install_segvhandler();
304 /* register a function to be called by SURF after the environment creation */
306 simgrid::s4u::Engine::on_platform_created.connect(surf_presolve);
309 if (simgrid::config::get_value<bool>("debug/clean-atexit"))
316 * @brief Clean the SIMIX simulation
318 * This functions remove the memory used by SIMIX
323 return; // to avoid double cleaning by java and C
326 XBT_DEBUG("SIMIX_clean called. Simulation's over.");
327 if (not simix_global->actors_to_run.empty() && SIMIX_get_clock() <= 0.0) {
329 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
330 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
331 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
335 if (not simix_global->process_list.empty()) {
336 if(smpi_process()->initialized()){
337 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
339 XBT_WARN("Process called exit when leaving - Skipping cleanups");
345 /* Kill all processes (but maestro) */
346 simix_global->maestro_->kill_all();
347 simix_global->run_all_actors();
348 simix_global->empty_trash();
350 /* Exit the SIMIX network module */
351 SIMIX_mailbox_exit();
353 while (not simgrid::simix::simix_timers.empty()) {
354 delete simgrid::simix::simix_timers.top().second;
355 simgrid::simix::simix_timers.pop();
357 /* Free the remaining data structures */
358 simix_global->actors_to_run.clear();
359 simix_global->actors_that_ran.clear();
360 simix_global->actors_to_destroy.clear();
361 simix_global->process_list.clear();
364 xbt_dynar_free(&simix_global->actors_vector);
365 xbt_dynar_free(&simix_global->dead_actors_vector);
368 /* Let's free maestro now */
369 delete simix_global->maestro_;
370 simix_global->maestro_ = nullptr;
372 /* Finish context module and SURF */
373 SIMIX_context_mod_exit();
377 simix_global = nullptr;
382 * @brief A clock (in second).
384 * @return Return the clock.
386 double SIMIX_get_clock()
388 if(MC_is_active() || MC_record_replay_is_active()){
389 return MC_process_clock_get(SIMIX_process_self());
391 return surf_get_clock();
395 /** Handle any pending timer. Returns if something was actually run. */
396 static bool SIMIX_execute_timers()
399 while (not simgrid::simix::simix_timers.empty() && SIMIX_get_clock() >= simgrid::simix::simix_timers.top().first) {
401 // FIXME: make the timers being real callbacks (i.e. provide dispatchers that read and expand the args)
402 smx_timer_t timer = simgrid::simix::simix_timers.top().second;
403 simgrid::simix::simix_timers.pop();
412 * @brief Run the main simulation loop.
416 if (MC_record_replay_is_active()) {
417 simgrid::mc::replay(MC_record_path);
424 XBT_DEBUG("New Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
426 if (simgrid::simix::cfg_breakpoint >= 0.0 && surf_get_clock() >= simgrid::simix::cfg_breakpoint) {
427 XBT_DEBUG("Breakpoint reached (%g)", simgrid::simix::cfg_breakpoint.get());
428 simgrid::simix::cfg_breakpoint = -1.0;
436 simix_global->execute_tasks();
438 while (not simix_global->actors_to_run.empty()) {
439 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
441 /* Run all processes that are ready to run, possibly in parallel */
442 simix_global->run_all_actors();
444 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
446 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
448 /* Here, the order is ok because:
450 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
451 * not impact its order.
453 * Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
455 * - if there is no kill during the simulation, actors remain sorted according by their PID.
456 * Rationale: This can be proved inductively.
457 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
458 * is parsed linearly).
459 * Let's show that it is still so at the end of this round.
460 * - if an actor is added when being created, that's from maestro. It can be either at startup
461 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
462 * in arbitrary order (inductive hypothesis), we are fine.
463 * - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
464 * - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
465 * of a simcall terminates, we're still good. Proof:
466 * - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
467 * resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
469 * - For communications, this function is called from SIMIX_comm_finish().
470 * This function itself don't mess with the order since simcalls are handled in FIFO order.
471 * The function is called:
472 * - before the comm starts (invalid parameters, or resource already dead or whatever).
473 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
474 * - because the communication failed or were canceled after startup. In this case, it's called from
475 * the function we are in, by the chunk:
476 * set = model->states.failed_action_set;
477 * while ((synchro = extract(set)))
478 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
479 * This order is also fixed because it depends of the order in which the surf actions were
480 * added to the system, and only maestro can add stuff this way, through simcalls.
481 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
482 * popped out of the set does not depend on the user code's execution order.
483 * - because the communication terminated. In this case, synchros are served in the order given by
484 * set = model->states.done_action_set;
485 * while ((synchro = extract(set)))
486 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
487 * and the argument is very similar to the previous one.
488 * So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
489 * actors are executed.
490 * So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
491 * user actors were executed previously.
492 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
493 * - If there is some actor killings, the order is changed by this decision that comes from user-land
494 * But this decision may not have been motivated by a situation that were different because the simulation is
496 * So, even the order change induced by the actor killing is perfectly reproducible.
498 * So science works, bitches [http://xkcd.com/54/].
500 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
501 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
503 * That would thus be a pure waste of time.
506 for (auto const& actor : simix_global->actors_that_ran) {
507 if (actor->simcall_.call_ != simgrid::simix::Simcall::NONE) {
508 actor->simcall_handle(0);
512 simix_global->execute_tasks();
514 simix_global->wake_all_waiting_actors();
515 } while (simix_global->execute_tasks());
517 /* If only daemon processes remain, cancel their actions, mark them to die and reschedule them */
518 if (simix_global->process_list.size() == simix_global->daemons.size())
519 for (auto const& dmon : simix_global->daemons) {
520 XBT_DEBUG("Kill %s", dmon->get_cname());
521 simix_global->maestro_->kill(dmon);
525 time = simgrid::simix::Timer::next();
526 if (time > -1.0 || not simix_global->process_list.empty()) {
527 XBT_DEBUG("Calling surf_solve");
528 time = surf_solve(time);
529 XBT_DEBUG("Moving time ahead : %g", time);
532 /* Notify all the hosts that have failed */
533 /* FIXME: iterate through the list of failed host and mark each of them */
534 /* as failed. On each host, signal all the running processes with host_fail */
536 // Execute timers and tasks until there isn't anything to be done:
539 again = SIMIX_execute_timers();
540 if (simix_global->execute_tasks())
542 simix_global->wake_all_waiting_actors();
545 /* Clean actors to destroy */
546 simix_global->empty_trash();
548 XBT_DEBUG("### time %f, #processes %zu, #to_run %zu", time, simix_global->process_list.size(),
549 simix_global->actors_to_run.size());
551 if (time < 0. && simix_global->actors_to_run.empty() && not simix_global->process_list.empty()) {
552 if (simix_global->process_list.size() <= simix_global->daemons.size()) {
553 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
554 "once the simulation is over. Please fix your on_exit() functions.");
556 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
558 simix_global->display_all_actor_status();
559 simgrid::s4u::Engine::on_deadlock();
560 for (auto const& kv : simix_global->process_list) {
561 XBT_DEBUG("Kill %s", kv.second->get_cname());
562 simix_global->maestro_->kill(kv.second);
565 } while (time > -1.0 || not simix_global->actors_to_run.empty());
567 if (not simix_global->process_list.empty())
570 simgrid::s4u::Engine::on_simulation_end();
573 double SIMIX_timer_next() // XBT_ATTRIB_DEPRECATED_v329
575 return simgrid::simix::Timer::next();
578 smx_timer_t SIMIX_timer_set(double date, void (*callback)(void*), void* arg) // XBT_ATTRIB_DEPRECATED_v329
580 return simgrid::simix::Timer::set(date, std::bind(callback, arg));
583 /** @brief cancels a timer that was added earlier */
584 void SIMIX_timer_remove(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
589 /** @brief Returns the date at which the timer will trigger (or 0 if nullptr timer) */
590 double SIMIX_timer_get_date(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
592 return timer ? timer->get_date() : 0;
595 void SIMIX_display_process_status() // XBT_ATTRIB_DEPRECATED_v329
597 simix_global->display_all_actor_status();
600 int SIMIX_is_maestro()
602 if (simix_global == nullptr) // SimDag
604 const simgrid::kernel::actor::ActorImpl* self = SIMIX_process_self();
605 return self == nullptr || self == simix_global->maestro_;