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"
21 #include "xbt/xbt_modinter.h" /* whether initialization was already done */
23 #include <boost/algorithm/string/predicate.hpp>
29 #include "src/mc/remote/AppSide.hpp"
34 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
38 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
40 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
41 "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
42 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
44 xbt_dynar_t get_actors_addr()
47 return EngineImpl::get_instance()->get_actors_vector();
49 xbt_die("This function is intended to be used when compiling with MC");
53 xbt_dynar_t get_dead_actors_addr()
56 return EngineImpl::get_instance()->get_dead_actors_vector();
58 xbt_die("This function is intended to be used when compiling with MC");
62 constexpr std::initializer_list<std::pair<const char*, context::ContextFactoryInitializer>> context_factories = {
64 {"raw", &context::raw_factory},
66 #if HAVE_UCONTEXT_CONTEXTS
67 {"ucontext", &context::sysv_factory},
69 #if HAVE_BOOST_CONTEXTS
70 {"boost", &context::boost_factory},
72 {"thread", &context::thread_factory},
75 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
77 // Create the list of possible contexts:
78 static inline std::string contexts_list()
82 for (auto const& factory : context_factories) {
83 res += sep + factory.first;
89 static config::Flag<std::string> context_factory_name("contexts/factory",
90 (std::string("Possible values: ") + contexts_list()).c_str(),
91 context_factories.begin()->first);
94 } // namespace simgrid
96 XBT_ATTRIB_NORETURN static void inthandler(int)
98 if (simgrid::kernel::cfg_verbose_exit) {
99 XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
100 "'debug/verbose-exit').");
101 simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
103 XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
109 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
111 if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
113 "Access violation or Bus error detected.\n"
114 "This probably comes from a programming error in your code, or from a stack\n"
115 "overflow. If you are certain of your code, try increasing the stack size\n"
116 " --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
118 "If it does not help, this may have one of the following causes:\n"
119 "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
120 "Failing hardware can sometimes generate such errors too.\n"
122 "If you think you've found a bug in SimGrid, please report it along with a\n"
123 "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
124 "of the fault captured with gdb or valgrind.\n",
125 simgrid::kernel::context::stack_size / 1024);
126 } else if (siginfo->si_signo == SIGSEGV) {
127 fprintf(stderr, "Segmentation fault.\n");
129 if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
130 #if HAVE_PRIVATIZATION
131 fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
133 fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
134 #endif /* HAVE_PRIVATIZATION */
136 #endif /* HAVE_SMPI */
142 * Install signal handler for SIGSEGV. Check that nobody has already installed
143 * its own handler. For example, the Java VM does this.
145 static void install_segvhandler()
149 if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
150 XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
153 if (not(old_stack.ss_flags & SS_DISABLE)) {
154 XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
155 old_stack.ss_size, (unsigned)old_stack.ss_flags);
156 sigaltstack(&old_stack, nullptr);
159 struct sigaction action;
160 struct sigaction old_action;
161 action.sa_sigaction = &segvhandler;
162 action.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
163 sigemptyset(&action.sa_mask);
165 /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
166 for (int sig : {SIGSEGV, SIGBUS}) {
167 if (sigaction(sig, &action, &old_action) == -1) {
168 XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
171 if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
172 XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
173 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
174 sigaction(sig, &old_action, nullptr);
184 EngineImpl::~EngineImpl()
186 /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
189 while (not hosts_.empty())
190 hosts_.begin()->second->destroy();
192 /* Also delete the other data */
193 delete netzone_root_;
194 for (auto const& kv : netpoints_)
197 while (not links_.empty())
198 links_.begin()->second->destroy();
200 for (auto const& kv : mailboxes_)
203 /* Free the remaining data structures */
205 xbt_dynar_free(&actors_vector_);
206 xbt_dynar_free(&dead_actors_vector_);
208 /* clear models before freeing handle, network models can use external callback defined in the handle */
209 models_prio_.clear();
212 void EngineImpl::initialize(int* argc, char** argv)
214 xbt_assert(EngineImpl::instance_ == nullptr,
215 "It is currently forbidden to create more than one instance of kernel::EngineImpl");
216 EngineImpl::instance_ = this;
218 // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
219 // layers. But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to
220 // read them directly.
221 simgrid::mc::AppSide::initialize();
224 if (xbt_initialized == 0) {
225 xbt_init(argc, argv);
227 sg_config_init(argc, argv);
230 instance_->context_mod_init();
232 /* Prepare to display some more info when dying on Ctrl-C pressing */
233 std::signal(SIGINT, inthandler);
236 install_segvhandler();
239 /* register a function to be called by SURF after the environment creation */
241 s4u::Engine::on_platform_created_cb([this]() { this->presolve(); });
243 if (config::get_value<bool>("debug/clean-atexit"))
247 void EngineImpl::context_mod_init() const
249 xbt_assert(not instance_->has_context_factory());
251 #if HAVE_SMPI && defined(__NetBSD__)
252 smpi_init_options_internal(false);
253 std::string priv = config::get_value<std::string>("smpi/privatization");
254 if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
255 XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
256 context_factory_name = "raw";
260 #if HAVE_SMPI && defined(__FreeBSD__)
261 smpi_init_options_internal(false);
262 if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
263 XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
264 context_factory_name = "raw";
268 /* select the context factory to use to create the contexts */
269 if (context::factory_initializer != nullptr) { // Give Java a chance to hijack the factory mechanism
270 instance_->set_context_factory(context::factory_initializer());
273 /* use the factory specified by --cfg=contexts/factory:value */
274 for (auto const& factory : context_factories)
275 if (context_factory_name == factory.first) {
276 instance_->set_context_factory(factory.second());
280 if (not instance_->has_context_factory()) {
281 XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
282 #if HAVE_RAW_CONTEXTS
283 XBT_ERROR(" raw: high performance context factory implemented specifically for SimGrid");
285 XBT_ERROR(" (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
287 #if HAVE_UCONTEXT_CONTEXTS
288 XBT_ERROR(" ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
290 XBT_ERROR(" (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
292 #if HAVE_BOOST_CONTEXTS
293 XBT_ERROR(" boost: this uses the boost libraries context implementation");
295 XBT_ERROR(" (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
296 "install the libboost-context-dev package?)");
298 XBT_ERROR(" thread: slow portability layer using pthreads as provided by gcc");
299 xbt_die("Please use a valid factory.");
303 void EngineImpl::shutdown()
305 if (EngineImpl::instance_ == nullptr)
307 XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
309 if (not instance_->actor_list_.empty()) {
310 if (smpi_process()->initialized()) {
311 xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
313 XBT_WARN("Process called exit when leaving - Skipping cleanups");
319 if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
321 XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
322 XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
323 xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
326 /* Kill all actors (but maestro) */
327 instance_->maestro_->kill_all();
328 instance_->run_all_actors();
329 instance_->empty_trash();
331 /* Let's free maestro now */
332 delete instance_->maestro_;
333 instance_->maestro_ = nullptr;
335 /* Finish context module and SURF */
336 instance_->destroy_context_factory();
338 while (not timer::kernel_timers().empty()) {
339 delete timer::kernel_timers().top().second;
340 timer::kernel_timers().pop();
350 void EngineImpl::seal_platform() const
352 /* sealing resources before run: links */
353 for (auto const& kv : links_)
354 kv.second->get_iface()->seal();
355 /* seal netzone root, recursively seal children netzones, hosts and disks */
356 netzone_root_->seal();
359 void EngineImpl::load_platform(const std::string& platf)
361 double start = xbt_os_time();
362 if (boost::algorithm::ends_with(platf, ".so") or boost::algorithm::ends_with(platf, ".dylib")) {
364 xbt_die("loading platform through shared library isn't supported on windows");
366 void* handle = dlopen(platf.c_str(), RTLD_LAZY);
367 xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
368 platf_handle_ = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
369 using load_fct_t = void (*)(const simgrid::s4u::Engine&);
370 auto callable = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
371 const char* dlsym_error = dlerror();
372 xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
373 callable(*simgrid::s4u::Engine::get_instance());
376 parse_platform_file(platf);
379 double end = xbt_os_time();
380 XBT_DEBUG("PARSE TIME: %g", (end - start));
383 void EngineImpl::load_deployment(const std::string& file) const
388 surf_parse_open(file);
393 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
395 registered_functions[name] = code;
397 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
399 default_function = code;
402 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
404 auto model_name = model->get_name();
405 xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
406 "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
408 for (const auto dep : dependencies) {
409 xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
410 "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
412 models_.push_back(model.get());
413 models_prio_[model_name] = std::move(model);
416 void EngineImpl::add_split_duplex_link(const std::string& name, std::unique_ptr<resource::SplitDuplexLinkImpl> link)
418 split_duplex_links_[name] = std::move(link);
421 /** Wake up all actors waiting for a Surf action to finish */
422 void EngineImpl::wake_all_waiting_actors() const
424 for (auto const& model : models_) {
425 XBT_DEBUG("Handling the failed actions (if any)");
426 while (auto* action = model->extract_failed_action()) {
427 XBT_DEBUG(" Handling Action %p", action);
428 if (action->get_activity() != nullptr) {
429 // If nobody told the interface that the activity has failed, that's because no actor waits on it (maestro
430 // started it). SimDAG I see you!
431 if (action->get_activity()->get_actor() == maestro_)
432 action->get_activity()->get_iface()->complete(s4u::Activity::State::FAILED);
434 activity::ActivityImplPtr(action->get_activity())->post();
437 XBT_DEBUG("Handling the terminated actions (if any)");
438 while (auto* action = model->extract_done_action()) {
439 XBT_DEBUG(" Handling Action %p", action);
440 if (action->get_activity() == nullptr)
441 XBT_DEBUG("probably vcpu's action %p, skip", action);
443 // If nobody told the interface that the activity is finished, that's because no actor waits on it (maestro
444 // started it). SimDAG I see you!
445 action->get_activity()->set_finish_time(action->get_finish_time());
447 if (action->get_activity()->get_actor() == maestro_)
448 action->get_activity()->get_iface()->complete(s4u::Activity::State::FINISHED);
450 activity::ActivityImplPtr(action->get_activity())->post();
456 * @brief Executes the actors in actors_to_run.
458 * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
459 * contains the list of actors that just ran. The two lists are swapped so, be careful when using them before and after
460 * a call to this function.
462 void EngineImpl::run_all_actors()
464 instance_->get_context_factory()->run_all();
466 actors_to_run_.swap(actors_that_ran_);
467 actors_to_run_.clear();
470 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
472 auto item = actor_list_.find(pid);
473 if (item != actor_list_.end())
477 for (auto& a : actors_to_destroy_)
478 if (a.get_pid() == pid)
480 return nullptr; // Not found, even in the trash
483 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
484 bool EngineImpl::execute_tasks()
489 std::vector<xbt::Task<void()>> tasksTemp;
491 // We don't want the callbacks to modify the vector we are iterating over:
492 tasks.swap(tasksTemp);
494 // Execute all the queued tasks:
495 for (auto& task : tasksTemp)
499 } while (not tasks.empty());
504 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
506 auto it = daemons_.find(actor);
507 xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
511 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
513 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
514 actors_to_run_.push_back(actor);
517 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
519 if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
520 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
522 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
523 actors_to_run_.push_back(actor);
526 void EngineImpl::empty_trash()
528 while (not actors_to_destroy_.empty()) {
529 actor::ActorImpl* actor = &actors_to_destroy_.front();
530 actors_to_destroy_.pop_front();
531 XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
532 intrusive_ptr_release(actor);
535 xbt_dynar_reset(dead_actors_vector_);
539 void EngineImpl::display_all_actor_status() const
541 XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
542 /* List the actors and their state */
543 XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
544 for (auto const& kv : actor_list_) {
545 actor::ActorImpl* actor = kv.second;
547 if (actor->waiting_synchro_) {
548 const char* synchro_description = "unknown";
550 if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
551 synchro_description = "execution";
553 if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
554 synchro_description = "communication";
556 if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
557 synchro_description = "sleeping";
559 if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
560 synchro_description = "synchronization";
562 if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
563 synchro_description = "I/O";
565 XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
566 actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
567 (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
568 actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
570 XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
571 SIMIX_simcall_name(actor->simcall_));
576 void EngineImpl::presolve() const
578 XBT_DEBUG("Consume all trace events occurring before the starting time.");
579 double next_event_date;
580 while ((next_event_date = profile::future_evt_set.next_date()) != -1.0) {
581 if (next_event_date > NOW)
585 resource::Resource* resource = nullptr;
586 while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
588 resource->apply_event(event, value);
592 XBT_DEBUG("Set every models in the right state by updating them to 0.");
593 for (auto const& model : models_)
594 model->update_actions_state(NOW, 0.0);
597 double EngineImpl::solve(double max_date) const
599 double time_delta = -1.0; /* duration */
601 resource::Resource* resource = nullptr;
603 if (max_date != -1.0) {
604 xbt_assert(max_date >= NOW, "You asked to simulate up to %f, but that's in the past already", max_date);
606 time_delta = max_date - NOW;
609 XBT_DEBUG("Looking for next event in all models");
610 for (auto model : models_) {
611 if (not model->next_occurring_event_is_idempotent()) {
614 double next_event = model->next_occurring_event(NOW);
615 if ((time_delta < 0.0 || next_event < time_delta) && next_event >= 0.0) {
616 time_delta = next_event;
620 XBT_DEBUG("Min for resources (remember that NS3 don't update that value): %f", time_delta);
622 XBT_DEBUG("Looking for next trace event");
624 while (true) { // Handle next occurring events until none remains
625 double next_event_date = profile::future_evt_set.next_date();
626 XBT_DEBUG("Next TRACE event: %f", next_event_date);
628 for (auto model : models_) {
629 /* Skip all idempotent models, they were already treated above
630 * NS3 is the one to handled here */
631 if (model->next_occurring_event_is_idempotent())
634 if (next_event_date != -1.0) {
635 time_delta = std::min(next_event_date - NOW, time_delta);
637 time_delta = std::max(next_event_date - NOW, time_delta); // Get the positive component
640 XBT_DEBUG("Run the NS3 network at most %fs", time_delta);
641 // run until min or next flow
642 double model_next_action_end = model->next_occurring_event(time_delta);
644 XBT_DEBUG("Min for network : %f", model_next_action_end);
645 if (model_next_action_end >= 0.0)
646 time_delta = model_next_action_end;
649 if (next_event_date < 0.0 || (next_event_date > NOW + time_delta)) {
650 // next event may have already occurred or will after the next resource change, then bail out
651 XBT_DEBUG("no next usable TRACE event. Stop searching for it");
655 XBT_DEBUG("Updating models (min = %g, NOW = %g, next_event_date = %g)", time_delta, NOW, next_event_date);
657 while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
658 if (resource->is_used() || (watched_hosts().find(resource->get_cname()) != watched_hosts().end())) {
659 time_delta = next_event_date - NOW;
660 XBT_DEBUG("This event invalidates the next_occurring_event() computation of models. Next event set to %f",
663 // FIXME: I'm too lame to update NOW live, so I change it and restore it so that the real update with surf_min
665 double round_start = NOW;
666 NOW = next_event_date;
667 /* update state of the corresponding resource to the new value. Does not touch lmm.
668 It will be modified if needed when updating actions */
669 XBT_DEBUG("Calling update_resource_state for resource %s", resource->get_cname());
670 resource->apply_event(event, value);
675 /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are
676 * with availability = 0. This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a
677 * trace with periodicity > 0.
678 * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed
680 if (time_delta < 0) {
681 XBT_DEBUG("No next event at all. Bail out now.");
685 XBT_DEBUG("Duration set to %f", time_delta);
687 // Bump the time: jump into the future
688 NOW = NOW + time_delta;
690 // Inform the models of the date change
691 for (auto const& model : models_)
692 model->update_actions_state(NOW, time_delta);
694 s4u::Engine::on_time_advance(time_delta);
699 void EngineImpl::run(double max_date)
703 if (MC_record_replay_is_active()) {
704 mc::replay(MC_record_path());
709 double elapsed_time = -1;
710 const std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
713 XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
715 if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
716 XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
717 cfg_breakpoint = -1.0;
727 while (not actors_to_run_.empty()) {
728 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
730 /* Run all actors that are ready to run, possibly in parallel */
733 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
735 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
737 /* Here, the order is ok because:
739 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
740 * not impact its order.
742 * Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
744 * - if there is no kill during the simulation, actors remain sorted according by their PID.
745 * Rationale: This can be proved inductively.
746 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
747 * is parsed linearly).
748 * Let's show that it is still so at the end of this round.
749 * - if an actor is added when being created, that's from maestro. It can be either at startup
750 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
751 * in arbitrary order (inductive hypothesis), we are fine.
752 * - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
753 * - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
754 * of a simcall terminates, we're still good. Proof:
755 * - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
756 * resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
758 * - For communications, this function is called from CommImpl::finish().
759 * This function itself don't mess with the order since simcalls are handled in FIFO order.
760 * The function is called:
761 * - before the comm starts (invalid parameters, or resource already dead or whatever).
762 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
763 * - because the communication failed or were canceled after startup. In this case, it's called from
764 * the function we are in, by the chunk:
765 * set = model->states.failed_action_set;
766 * while ((synchro = extract(set)))
767 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
768 * This order is also fixed because it depends of the order in which the surf actions were
769 * added to the system, and only maestro can add stuff this way, through simcalls.
770 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
771 * popped out of the set does not depend on the user code's execution order.
772 * - because the communication terminated. In this case, synchros are served in the order given by
773 * set = model->states.done_action_set;
774 * while ((synchro = extract(set)))
775 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
776 * and the argument is very similar to the previous one.
777 * So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
778 * actors are executed.
779 * So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
780 * user actors were executed previously.
781 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
782 * - If there is some actor killings, the order is changed by this decision that comes from user-land
783 * But this decision may not have been motivated by a situation that were different because the simulation is
785 * So, even the order change induced by the actor killing is perfectly reproducible.
787 * So science works, bitches [http://xkcd.com/54/].
789 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
790 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
792 * That would thus be a pure waste of time.
795 for (auto const& actor : actors_that_ran_) {
796 if (actor->simcall_.call_ != simix::Simcall::NONE) {
797 actor->simcall_handle(0);
803 wake_all_waiting_actors();
804 } while (execute_tasks());
806 /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
807 if (actor_list_.size() == daemons_.size())
808 for (auto const& dmon : daemons_) {
809 XBT_DEBUG("Kill %s", dmon->get_cname());
810 maestro_->kill(dmon);
814 // Compute the max_date of the next solve.
815 // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
816 double next_time = timer::Timer::next();
817 if (next_time < 0 && max_date > -1) {
818 next_time = max_date;
819 } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
820 next_time = std::min(next_time, max_date);
823 XBT_DEBUG("Calling solve(%g) %g", next_time, NOW);
824 elapsed_time = solve(next_time);
825 XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", NOW, elapsed_time);
827 /* Notify all the hosts that have failed */
828 /* FIXME: iterate through the list of failed host and mark each of them */
829 /* as failed. On each host, signal all the running actors with host_fail */
831 // Execute timers and tasks until there isn't anything to be done:
834 again = timer::Timer::execute_all();
837 wake_all_waiting_actors();
840 /* Clean actors to destroy */
843 XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
844 actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
846 if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
847 if (actor_list_.size() <= daemons_.size()) {
848 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
849 "once the simulation is over. Please fix your on_exit() functions.");
851 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
853 display_all_actor_status();
854 simgrid::s4u::Engine::on_deadlock();
855 for (auto const& kv : actor_list_) {
856 XBT_DEBUG("Kill %s", kv.second->get_cname());
857 maestro_->kill(kv.second);
861 } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
862 ((elapsed_time > -1.0 && not double_equals(max_date, NOW, 0.00001)) || has_actors_to_run()));
864 if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
867 simgrid::s4u::Engine::on_simulation_end();
870 double EngineImpl::get_clock()
874 } // namespace kernel
875 } // namespace simgrid
877 void SIMIX_run() // XBT_ATTRIB_DEPRECATED_v332
879 simgrid::kernel::EngineImpl::get_instance()->run(-1);