1 /* Copyright (c) 2016-2021. 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. */
6 #include <simgrid/Exception.hpp>
7 #include <simgrid/kernel/Timer.hpp>
8 #include <simgrid/kernel/routing/NetPoint.hpp>
9 #include <simgrid/kernel/routing/NetZoneImpl.hpp>
10 #include <simgrid/s4u/Host.hpp>
11 #include <simgrid/sg_config.hpp>
14 #include "src/kernel/EngineImpl.hpp"
15 #include "src/kernel/resource/profile/Profile.hpp"
16 #include "src/mc/mc_record.hpp"
17 #include "src/mc/mc_replay.hpp"
18 #include "src/smpi/include/smpi_actor.hpp"
19 #include "src/surf/network_interface.hpp"
20 #include "src/surf/xml/platf.hpp" // FIXME: KILLME. There must be a better way than mimicking XML here
21 #include "surf/surf.hpp" //surf_presolve() and surf_solve()
22 #include "xbt/xbt_modinter.h" /* whether initialization was already done */
24 #include <boost/algorithm/string/predicate.hpp>
30 #include "src/mc/remote/AppSide.hpp"
33 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
36 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
38 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
39 "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
40 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
42 xbt_dynar_t get_actors_addr()
45 return EngineImpl::get_instance()->get_actors_vector();
47 xbt_die("This function is intended to be used when compiling with MC");
51 xbt_dynar_t get_dead_actors_addr()
54 return EngineImpl::get_instance()->get_dead_actors_vector();
56 xbt_die("This function is intended to be used when compiling with MC");
61 } // namespace simgrid
63 XBT_ATTRIB_NORETURN static void inthandler(int)
65 if (simgrid::kernel::cfg_verbose_exit) {
66 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
67 "'debug/verbose-exit').");
68 simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
70 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
76 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
78 if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
80 "Access violation or Bus error detected.\n"
81 "This probably comes from a programming error in your code, or from a stack\n"
82 "overflow. If you are certain of your code, try increasing the stack size\n"
83 " --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
85 "If it does not help, this may have one of the following causes:\n"
86 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
87 "Failing hardware can sometimes generate such errors too.\n"
89 "If you think you've found a bug in SimGrid, please report it along with a\n"
90 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
91 "of the fault captured with gdb or valgrind.\n",
92 smx_context_stack_size / 1024);
93 } else if (siginfo->si_signo == SIGSEGV) {
94 fprintf(stderr, "Segmentation fault.\n");
96 if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
97 #if HAVE_PRIVATIZATION
98 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
100 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
101 #endif /* HAVE_PRIVATIZATION */
103 #endif /* HAVE_SMPI */
109 * Install signal handler for SIGSEGV. Check that nobody has already installed
110 * its own handler. For example, the Java VM does this.
112 static void install_segvhandler()
116 if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
117 XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
120 if (not(old_stack.ss_flags & SS_DISABLE)) {
121 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
122 old_stack.ss_size, (unsigned)old_stack.ss_flags);
123 sigaltstack(&old_stack, nullptr);
126 struct sigaction action;
127 struct sigaction old_action;
128 action.sa_sigaction = &segvhandler;
129 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
130 sigemptyset(&action.sa_mask);
132 /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
133 for (int sig : {SIGSEGV, SIGBUS}) {
134 if (sigaction(sig, &action, &old_action) == -1) {
135 XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
138 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
139 XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
140 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
141 sigaction(sig, &old_action, nullptr);
151 EngineImpl::~EngineImpl()
153 /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
156 while (not hosts_.empty())
157 hosts_.begin()->second->destroy();
159 /* Also delete the other data */
160 delete netzone_root_;
161 for (auto const& kv : netpoints_)
164 while (not links_.empty())
165 links_.begin()->second->destroy();
167 for (auto const& kv : mailboxes_)
170 /* Free the remaining data structures */
172 xbt_dynar_free(&actors_vector_);
173 xbt_dynar_free(&dead_actors_vector_);
175 /* clear models before freeing handle, network models can use external callback defined in the handle */
176 models_prio_.clear();
179 void EngineImpl::initialize(int* argc, char** argv)
181 xbt_assert(EngineImpl::instance_ == nullptr,
182 "It is currently forbidden to create more than one instance of kernel::EngineImpl");
183 EngineImpl::instance_ = this;
185 // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
186 // layers. But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to
187 // read them directly.
188 simgrid::mc::AppSide::initialize();
191 if (xbt_initialized == 0) {
192 xbt_init(argc, argv);
194 sg_config_init(argc, argv);
197 instance_->context_mod_init();
199 /* Prepare to display some more info when dying on Ctrl-C pressing */
200 std::signal(SIGINT, inthandler);
203 install_segvhandler();
206 /* register a function to be called by SURF after the environment creation */
208 s4u::Engine::on_platform_created.connect(surf_presolve);
210 if (config::get_value<bool>("debug/clean-atexit"))
214 void EngineImpl::shutdown()
216 if (EngineImpl::instance_ == nullptr)
218 XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
220 if (not instance_->actor_list_.empty()) {
221 if (smpi_process()->initialized()) {
222 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
224 XBT_WARN("Process called exit when leaving - Skipping cleanups");
230 if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
232 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
233 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
234 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
237 /* Kill all actors (but maestro) */
238 instance_->maestro_->kill_all();
239 instance_->run_all_actors();
240 instance_->empty_trash();
242 /* Let's free maestro now */
243 instance_->destroy_maestro();
245 /* Finish context module and SURF */
246 instance_->destroy_context_factory();
248 while (not timer::kernel_timers().empty()) {
249 delete timer::kernel_timers().top().second;
250 timer::kernel_timers().pop();
260 void EngineImpl::load_platform(const std::string& platf)
262 double start = xbt_os_time();
263 if (boost::algorithm::ends_with(platf, ".so") or boost::algorithm::ends_with(platf, ".dylib")) {
265 xbt_die("loading platform through shared library isn't supported on windows");
267 void* handle = dlopen(platf.c_str(), RTLD_LAZY);
268 xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
269 platf_handle_ = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
270 using load_fct_t = void (*)(const simgrid::s4u::Engine&);
271 auto callable = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
272 const char* dlsym_error = dlerror();
273 xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
274 callable(*simgrid::s4u::Engine::get_instance());
277 parse_platform_file(platf);
280 double end = xbt_os_time();
281 XBT_DEBUG("PARSE TIME: %g", (end - start));
284 void EngineImpl::load_deployment(const std::string& file) const
289 surf_parse_open(file);
294 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
296 registered_functions[name] = code;
298 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
300 default_function = code;
303 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
305 auto model_name = model->get_name();
306 xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
307 "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
309 for (const auto dep : dependencies) {
310 xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
311 "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
313 models_.push_back(model.get());
314 models_prio_[model_name] = std::move(model);
317 void EngineImpl::add_split_duplex_link(const std::string& name, std::unique_ptr<resource::SplitDuplexLinkImpl> link)
319 split_duplex_links_[name] = std::move(link);
322 /** Wake up all actors waiting for a Surf action to finish */
323 void EngineImpl::wake_all_waiting_actors() const
325 for (auto const& model : models_) {
326 XBT_DEBUG("Handling the failed actions (if any)");
327 while (auto* action = model->extract_failed_action()) {
328 XBT_DEBUG(" Handling Action %p", action);
329 if (action->get_activity() != nullptr)
330 activity::ActivityImplPtr(action->get_activity())->post();
332 XBT_DEBUG("Handling the terminated actions (if any)");
333 while (auto* action = model->extract_done_action()) {
334 XBT_DEBUG(" Handling Action %p", action);
335 if (action->get_activity() == nullptr)
336 XBT_DEBUG("probably vcpu's action %p, skip", action);
338 activity::ActivityImplPtr(action->get_activity())->post();
343 * @brief Executes the actors in actors_to_run.
345 * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
346 * contains the list of actors that just ran. The two lists are swapped so, be careful when using them before and after
347 * a call to this function.
349 void EngineImpl::run_all_actors()
351 instance_->get_context_factory()->run_all();
353 actors_to_run_.swap(actors_that_ran_);
354 actors_to_run_.clear();
357 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
359 auto item = actor_list_.find(pid);
360 if (item != actor_list_.end())
364 for (auto& a : actors_to_destroy_)
365 if (a.get_pid() == pid)
367 return nullptr; // Not found, even in the trash
370 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
371 bool EngineImpl::execute_tasks()
376 std::vector<xbt::Task<void()>> tasksTemp;
378 // We don't want the callbacks to modify the vector we are iterating over:
379 tasks.swap(tasksTemp);
381 // Execute all the queued tasks:
382 for (auto& task : tasksTemp)
386 } while (not tasks.empty());
391 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
393 auto it = daemons_.find(actor);
394 xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
398 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
400 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
401 actors_to_run_.push_back(actor);
404 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
406 if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
407 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
409 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
410 actors_to_run_.push_back(actor);
413 void EngineImpl::empty_trash()
415 while (not actors_to_destroy_.empty()) {
416 actor::ActorImpl* actor = &actors_to_destroy_.front();
417 actors_to_destroy_.pop_front();
418 XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
419 intrusive_ptr_release(actor);
422 xbt_dynar_reset(dead_actors_vector_);
426 void EngineImpl::display_all_actor_status() const
428 XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
429 /* List the actors and their state */
430 XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
431 for (auto const& kv : actor_list_) {
432 actor::ActorImpl* actor = kv.second;
434 if (actor->waiting_synchro_) {
435 const char* synchro_description = "unknown";
437 if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
438 synchro_description = "execution";
440 if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
441 synchro_description = "communication";
443 if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
444 synchro_description = "sleeping";
446 if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
447 synchro_description = "synchronization";
449 if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
450 synchro_description = "I/O";
452 XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
453 actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
454 (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
455 actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
457 XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
458 SIMIX_simcall_name(actor->simcall_));
463 void EngineImpl::run()
465 if (MC_record_replay_is_active()) {
466 mc::replay(MC_record_path());
474 XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
476 if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
477 XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
478 cfg_breakpoint = -1.0;
488 while (not actors_to_run_.empty()) {
489 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
491 /* Run all actors that are ready to run, possibly in parallel */
494 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
496 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
498 /* Here, the order is ok because:
500 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
501 * not impact its order.
503 * Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
505 * - if there is no kill during the simulation, actors remain sorted according by their PID.
506 * Rationale: This can be proved inductively.
507 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
508 * is parsed linearly).
509 * Let's show that it is still so at the end of this round.
510 * - if an actor is added when being created, that's from maestro. It can be either at startup
511 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
512 * in arbitrary order (inductive hypothesis), we are fine.
513 * - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
514 * - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
515 * of a simcall terminates, we're still good. Proof:
516 * - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
517 * resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
519 * - For communications, this function is called from SIMIX_comm_finish().
520 * This function itself don't mess with the order since simcalls are handled in FIFO order.
521 * The function is called:
522 * - before the comm starts (invalid parameters, or resource already dead or whatever).
523 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
524 * - because the communication failed or were canceled after startup. In this case, it's called from
525 * the function we are in, by the chunk:
526 * set = model->states.failed_action_set;
527 * while ((synchro = extract(set)))
528 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
529 * This order is also fixed because it depends of the order in which the surf actions were
530 * added to the system, and only maestro can add stuff this way, through simcalls.
531 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
532 * popped out of the set does not depend on the user code's execution order.
533 * - because the communication terminated. In this case, synchros are served in the order given by
534 * set = model->states.done_action_set;
535 * while ((synchro = extract(set)))
536 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
537 * and the argument is very similar to the previous one.
538 * So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
539 * actors are executed.
540 * So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
541 * user actors were executed previously.
542 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
543 * - If there is some actor killings, the order is changed by this decision that comes from user-land
544 * But this decision may not have been motivated by a situation that were different because the simulation is
546 * So, even the order change induced by the actor killing is perfectly reproducible.
548 * So science works, bitches [http://xkcd.com/54/].
550 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
551 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
553 * That would thus be a pure waste of time.
556 for (auto const& actor : actors_that_ran_) {
557 if (actor->simcall_.call_ != simix::Simcall::NONE) {
558 actor->simcall_handle(0);
564 wake_all_waiting_actors();
565 } while (execute_tasks());
567 /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
568 if (actor_list_.size() == daemons_.size())
569 for (auto const& dmon : daemons_) {
570 XBT_DEBUG("Kill %s", dmon->get_cname());
571 maestro_->kill(dmon);
575 time = timer::Timer::next();
576 if (time > -1.0 || not actor_list_.empty()) {
577 XBT_DEBUG("Calling surf_solve");
578 time = surf_solve(time);
579 XBT_DEBUG("Moving time ahead : %g", time);
582 /* Notify all the hosts that have failed */
583 /* FIXME: iterate through the list of failed host and mark each of them */
584 /* as failed. On each host, signal all the running actors with host_fail */
586 // Execute timers and tasks until there isn't anything to be done:
589 again = timer::Timer::execute_all();
592 wake_all_waiting_actors();
595 /* Clean actors to destroy */
598 XBT_DEBUG("### time %f, #actors %zu, #to_run %zu", time, actor_list_.size(), actors_to_run_.size());
600 if (time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
601 if (actor_list_.size() <= daemons_.size()) {
602 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
603 "once the simulation is over. Please fix your on_exit() functions.");
605 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
607 display_all_actor_status();
608 simgrid::s4u::Engine::on_deadlock();
609 for (auto const& kv : actor_list_) {
610 XBT_DEBUG("Kill %s", kv.second->get_cname());
611 maestro_->kill(kv.second);
614 } while (time > -1.0 || has_actors_to_run());
616 if (not actor_list_.empty())
619 simgrid::s4u::Engine::on_simulation_end();
621 } // namespace kernel
622 } // namespace simgrid
624 void SIMIX_run() // XBT_ATTRIB_DEPRECATED_v332
626 simgrid::kernel::EngineImpl::get_instance()->run();