Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Further rename the identifiers of flexml to simgrid_parse_*
[simgrid.git] / src / kernel / EngineImpl.cpp
1 /* Copyright (c) 2016-2023. The SimGrid Team. All rights reserved.          */
2
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. */
5
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>
12
13 #include "mc/mc.h"
14 #include "src/kernel/EngineImpl.hpp"
15 #include "src/kernel/resource/StandardLinkImpl.hpp"
16 #include "src/kernel/resource/profile/Profile.hpp"
17 #include "src/mc/mc_record.hpp"
18 #include "src/mc/mc_replay.hpp"
19 #include "src/smpi/include/smpi_actor.hpp"
20 #include "src/surf/xml/platf.hpp"
21 #include "xbt/module.h"
22 #include "xbt/xbt_modinter.h" /* whether initialization was already done */
23
24 #include <boost/algorithm/string/predicate.hpp>
25 #include <dlfcn.h>
26
27 #if SIMGRID_HAVE_MC
28 #include "src/mc/remote/AppSide.hpp"
29 #endif
30
31 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
32
33 namespace simgrid::kernel {
34 double EngineImpl::now_           = 0.0;
35 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
36
37 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
38                                     "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
39 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
40
41 constexpr std::initializer_list<std::pair<const char*, context::ContextFactory* (*)()>> context_factories = {
42 #if HAVE_RAW_CONTEXTS
43     {"raw", &context::raw_factory},
44 #endif
45 #if HAVE_UCONTEXT_CONTEXTS
46     {"ucontext", &context::sysv_factory},
47 #endif
48 #if HAVE_BOOST_CONTEXTS
49     {"boost", &context::boost_factory},
50 #endif
51     {"thread", &context::thread_factory},
52 };
53
54 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
55
56 // Create the list of possible contexts:
57 static inline std::string contexts_list()
58 {
59   std::string res;
60   std::string sep = "";
61   for (auto const& [factory_name, _] : context_factories) {
62     res += sep + factory_name;
63     sep = ", ";
64   }
65   return res;
66 }
67
68 static config::Flag<std::string> context_factory_name("contexts/factory",
69                                                       ("Possible values: " + contexts_list()).c_str(),
70                                                       context_factories.begin()->first);
71
72 } // namespace simgrid::kernel
73
74 XBT_ATTRIB_NORETURN static void inthandler(int)
75 {
76   if (simgrid::kernel::cfg_verbose_exit) {
77     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
78              "'debug/verbose-exit').");
79     simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
80   } else {
81     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
82   }
83   exit(1);
84 }
85
86 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
87 {
88   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
89     fprintf(stderr,
90             "Access violation or Bus error detected.\n"
91             "This probably comes from a programming error in your code, or from a stack\n"
92             "overflow. If you are certain of your code, try increasing the stack size\n"
93             "   --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
94             "\n"
95             "If it does not help, this may have one of the following causes:\n"
96             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
97             "Failing hardware can sometimes generate such errors too.\n"
98             "\n"
99             "If you think you've found a bug in SimGrid, please report it along with a\n"
100             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
101             "of the fault captured with gdb or valgrind.\n",
102             simgrid::kernel::context::Context::stack_size / 1024);
103   } else if (siginfo->si_signo == SIGSEGV) {
104     fprintf(stderr, "Segmentation fault.\n");
105 #if HAVE_SMPI
106     if (SMPI_is_inited() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
107 #if HAVE_PRIVATIZATION
108       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
109 #else
110       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
111 #endif /* HAVE_PRIVATIZATION */
112     }
113 #endif /* HAVE_SMPI */
114   }
115   std::raise(signum);
116 }
117
118 static void install_signal_handlers()
119 {
120   /* Install signal handler for SIGINT */
121   std::signal(SIGINT, inthandler);
122
123   /* Install signal handler for SIGSEGV */
124   if (simgrid::kernel::context::Context::install_sigsegv_stack(true) == -1) {
125     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
126     return;
127   }
128
129   struct sigaction action;
130   action.sa_sigaction = &segvhandler;
131   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
132   sigemptyset(&action.sa_mask);
133
134   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
135   for (int sig : {SIGSEGV, SIGBUS}) {
136     if (sigaction(sig, &action, nullptr) == -1)
137       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
138   }
139 }
140
141 namespace simgrid::kernel {
142
143 EngineImpl::~EngineImpl()
144 {
145   /* Also delete the other data */
146   delete netzone_root_;
147   for (auto const& [_, netpoint] : netpoints_)
148     delete netpoint;
149
150   for (auto const& [_, mailbox] : mailboxes_)
151     delete mailbox;
152
153   /* Kill all actors (but maestro) */
154   maestro_->kill_all();
155   run_all_actors();
156   empty_trash();
157
158   delete maestro_;
159   delete context_factory_;
160
161   /* clear models before freeing handle, network models can use external callback defined in the handle */
162   models_prio_.clear();
163 }
164
165 void EngineImpl::initialize(int* argc, char** argv)
166 {
167   xbt_assert(EngineImpl::instance_ == nullptr,
168              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
169   EngineImpl::instance_ = this;
170 #if SIMGRID_HAVE_MC
171   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
172   // layers. But instance_ needs to be created, as we send the address of some of its fields to the MC that wants to
173   // read them directly.
174   simgrid::mc::AppSide::initialize();
175 #endif
176
177   if (xbt_initialized == 0) {
178     xbt_init(argc, argv);
179
180     sg_config_init(argc, argv);
181   }
182
183   instance_->context_mod_init();
184
185   install_signal_handlers();
186
187   /* register a function to be called by SURF after the environment creation */
188   s4u::Engine::on_platform_created_cb([this]() { this->presolve(); });
189
190   if (config::get_value<bool>("debug/clean-atexit"))
191     atexit(shutdown);
192 }
193
194 void EngineImpl::context_mod_init() const
195 {
196   xbt_assert(not instance_->has_context_factory());
197
198 #if HAVE_SMPI && defined(__NetBSD__)
199   smpi_init_options_internal(false);
200   std::string priv = config::get_value<std::string>("smpi/privatization");
201   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
202     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
203     context_factory_name = "raw";
204   }
205 #endif
206
207 #if HAVE_SMPI && defined(__FreeBSD__)
208   smpi_init_options_internal(false);
209   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
210     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
211     context_factory_name = "raw";
212   }
213 #endif
214
215   /* use the factory specified by --cfg=contexts/factory:value */
216   for (auto const& [factory_name, factory] : context_factories)
217     if (context_factory_name == factory_name) {
218       instance_->set_context_factory(factory());
219       break;
220     }
221
222   if (not instance_->has_context_factory()) {
223     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
224 #if HAVE_RAW_CONTEXTS
225     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
226 #else
227     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
228 #endif
229 #if HAVE_UCONTEXT_CONTEXTS
230     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
231 #else
232     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
233 #endif
234 #if HAVE_BOOST_CONTEXTS
235     XBT_ERROR("  boost: this uses the boost libraries context implementation");
236 #else
237     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
238               "install the libboost-context-dev package?)");
239 #endif
240     XBT_ERROR("  thread: slow portability layer using standard threads as provided by libstdc");
241     xbt_die("Please use a valid factory.");
242   }
243 }
244
245 void EngineImpl::shutdown()
246 {
247   if (EngineImpl::instance_ == nullptr)
248     return;
249   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
250 #if HAVE_SMPI
251   if (not instance_->actor_list_.empty()) {
252     if (smpi_process() && smpi_process()->initialized()) {
253       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
254     } else {
255       XBT_WARN("Process called exit when leaving - Skipping cleanups");
256       return;
257     }
258   }
259 #endif
260
261   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
262     XBT_CRITICAL("   ");
263     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
264     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
265     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
266   }
267
268   while (not timer::kernel_timers().empty()) {
269     delete timer::kernel_timers().top().second;
270     timer::kernel_timers().pop();
271   }
272
273   tmgr_finalize();
274   sg_platf_parser_finalize();
275
276   delete instance_;
277   instance_ = nullptr;
278 }
279
280 void EngineImpl::seal_platform() const
281 {
282   /* Seal only once */
283   static bool sealed = false;
284   if (sealed)
285     return;
286   sealed = true;
287
288   /* seal netzone root, recursively seal children netzones, hosts and disks */
289   netzone_root_->seal();
290 }
291
292 void EngineImpl::load_platform(const std::string& platf)
293 {
294   double start = xbt_os_time();
295   if (boost::algorithm::ends_with(platf, ".so") || boost::algorithm::ends_with(platf, ".dylib")) {
296     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
297     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
298     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
299     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
300     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
301     const char* dlsym_error = dlerror();
302     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
303     callable(*simgrid::s4u::Engine::get_instance());
304   } else {
305     parse_platform_file(platf);
306   }
307
308   double end = xbt_os_time();
309   XBT_DEBUG("PARSE TIME: %g", (end - start));
310 }
311
312 void EngineImpl::load_deployment(const std::string& file) const
313 {
314   sg_platf_parser_finalize();
315
316   simgrid_parse_open(file);
317   simgrid_parse();
318   simgrid_parse_close();
319 }
320
321 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
322 {
323   registered_functions[name] = code;
324 }
325 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
326 {
327   default_function = code;
328 }
329
330 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
331 {
332   auto model_name = model->get_name();
333   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
334              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
335
336   for (const auto* dep : dependencies) {
337     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
338                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
339   }
340   models_.push_back(model.get());
341   models_prio_[model_name] = std::move(model);
342 }
343
344 /** Wake up all actors waiting for a Surf action to finish */
345 void EngineImpl::handle_ended_actions() const
346 {
347   for (auto const& model : models_) {
348     XBT_DEBUG("Handling the failed actions (if any)");
349     while (auto* action = model->extract_failed_action()) {
350       XBT_DEBUG("   Handling Action %p", action);
351       if (action->get_activity() != nullptr) { // Skip vcpu actions
352         // Action failures are not automatically reported when the action is started by maestro (as in SimDAG)
353         if (action->get_activity()->get_actor() == maestro_)
354           action->get_activity()->get_iface()->complete(s4u::Activity::State::FAILED);
355
356         activity::ActivityImplPtr(action->get_activity())->post();
357       }
358     }
359     XBT_DEBUG("Handling the terminated actions (if any)");
360     while (auto* action = model->extract_done_action()) {
361       XBT_DEBUG("   Handling Action %p", action);
362       if (action->get_activity() != nullptr) {
363         // Action termination are not automatically reported when the action is started by maestro (as in SimDAG)
364         action->get_activity()->set_finish_time(action->get_finish_time());
365
366         if (action->get_activity()->get_actor() == maestro_)
367           action->get_activity()->get_iface()->complete(s4u::Activity::State::FINISHED);
368
369         activity::ActivityImplPtr(action->get_activity())->post();
370       }
371     }
372   }
373 }
374 /**
375  * @brief Executes the actors in actors_to_run.
376  *
377  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
378  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
379  * a call to this function.
380  */
381 void EngineImpl::run_all_actors()
382 {
383   instance_->get_context_factory()->run_all(actors_to_run_);
384
385   for (auto const& actor : actors_to_run_)
386     if (actor->to_be_freed())
387       actor->cleanup_from_kernel();
388
389   actors_to_run_.swap(actors_that_ran_);
390   actors_to_run_.clear();
391 }
392
393 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
394 {
395   auto item = actor_list_.find(pid);
396   return item == actor_list_.end() ? nullptr : item->second;
397 }
398
399 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
400 {
401   auto it = daemons_.find(actor);
402   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
403   daemons_.erase(it);
404 }
405
406 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
407 {
408   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
409   actors_to_run_.push_back(actor);
410 }
411
412 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
413 {
414   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
415     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
416   } else {
417     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
418     actors_to_run_.push_back(actor);
419   }
420 }
421 void EngineImpl::empty_trash()
422 {
423   while (not actors_to_destroy_.empty()) {
424     actor::ActorImpl* actor = &actors_to_destroy_.front();
425     actors_to_destroy_.pop_front();
426     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
427     intrusive_ptr_release(actor);
428   }
429 }
430
431 void EngineImpl::display_all_actor_status() const
432 {
433   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
434   /*  List the actors and their state */
435   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
436   for (auto const& [_, actor] : actor_list_) {
437     if (actor->waiting_synchro_) {
438       const char* synchro_description = "unknown";
439
440       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
441         synchro_description = "execution";
442
443       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
444         synchro_description = "communication";
445
446       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
447         synchro_description = "sleeping";
448
449       if (boost::dynamic_pointer_cast<kernel::activity::SynchroImpl>(actor->waiting_synchro_) != nullptr)
450         synchro_description = "synchronization";
451
452       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
453         synchro_description = "I/O";
454
455       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %s to finish %s", actor->get_pid(),
456                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
457                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
458                actor->waiting_synchro_->get_cname(), actor->waiting_synchro_->get_state_str(),
459                (actor->simcall_.observer_ != nullptr && not xbt_log_no_loc
460                     ? actor->simcall_.observer_->to_string().c_str()
461                     : ""));
462     } else {
463       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
464                (actor->simcall_.observer_ != nullptr ? actor->simcall_.observer_->to_string().c_str()
465                                                      : actor->simcall_.get_cname()));
466     }
467   }
468 }
469
470 void EngineImpl::presolve() const
471 {
472   XBT_DEBUG("Consume all trace events occurring before the starting time.");
473   double next_event_date;
474   while ((next_event_date = profile::future_evt_set.next_date()) != -1.0) {
475     if (next_event_date > now_)
476       break;
477
478     double value                 = -1.0;
479     resource::Resource* resource = nullptr;
480     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
481       if (value >= 0)
482         resource->apply_event(event, value);
483     }
484   }
485
486   XBT_DEBUG("Set every models in the right state by updating them to 0.");
487   for (auto const& model : models_)
488     model->update_actions_state(now_, 0.0);
489 }
490
491 double EngineImpl::solve(double max_date) const
492 {
493   double time_delta            = -1.0; /* duration */
494   double value                 = -1.0;
495   resource::Resource* resource = nullptr;
496
497   if (max_date != -1.0) {
498     xbt_assert(max_date >= now_, "You asked to simulate up to %f, but that's in the past already", max_date);
499
500     time_delta = max_date - now_;
501   }
502
503   XBT_DEBUG("Looking for next event in all models");
504   for (auto model : models_) {
505     if (not model->next_occurring_event_is_idempotent()) {
506       continue;
507     }
508     double next_event = model->next_occurring_event(now_);
509     if ((time_delta < 0.0 || next_event < time_delta) && next_event >= 0.0) {
510       time_delta = next_event;
511     }
512   }
513
514   XBT_DEBUG("Min for resources (remember that NS3 don't update that value): %f", time_delta);
515
516   XBT_DEBUG("Looking for next trace event");
517
518   while (true) { // Handle next occurring events until none remains
519     double next_event_date = profile::future_evt_set.next_date();
520     XBT_DEBUG("Next TRACE event: %f", next_event_date);
521
522     for (auto model : models_) {
523       /* Skip all idempotent models, they were already treated above
524        * NS3 is the one to handled here */
525       if (model->next_occurring_event_is_idempotent())
526         continue;
527
528       if (next_event_date != -1.0) {
529         time_delta = std::min(next_event_date - now_, time_delta);
530       } else {
531         time_delta = std::max(next_event_date - now_, time_delta); // Get the positive component
532       }
533
534       XBT_DEBUG("Run the NS3 network at most %fs", time_delta);
535       // run until min or next flow
536       double model_next_action_end = model->next_occurring_event(time_delta);
537
538       XBT_DEBUG("Min for network : %f", model_next_action_end);
539       if (model_next_action_end >= 0.0)
540         time_delta = model_next_action_end;
541     }
542
543     if (next_event_date < 0.0 || (next_event_date > now_ + time_delta)) {
544       // next event may have already occurred or will after the next resource change, then bail out
545       XBT_DEBUG("no next usable TRACE event. Stop searching for it");
546       break;
547     }
548
549     XBT_DEBUG("Updating models (min = %g, NOW = %g, next_event_date = %g)", time_delta, now_, next_event_date);
550
551     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
552       if(value<0)
553               continue;
554       if (resource->is_used() || (watched_hosts().find(resource->get_cname()) != watched_hosts().end())) {
555         time_delta = next_event_date - now_;
556         XBT_DEBUG("This event invalidates the next_occurring_event() computation of models. Next event set to %f",
557                   time_delta);
558       }
559       // FIXME: I'm too lame to update now_ live, so I change it and restore it so that the real update with surf_min
560       // will work
561       double round_start = now_;
562       now_               = next_event_date;
563       /* update state of the corresponding resource to the new value. Does not touch lmm.
564          It will be modified if needed when updating actions */
565       XBT_DEBUG("Calling update_resource_state for resource %s", resource->get_cname());
566       resource->apply_event(event, value);
567       now_ = round_start;
568     }
569   }
570
571   /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are
572    * with availability = 0. This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a
573    * trace with periodicity > 0.
574    * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed
575    */
576   if (time_delta < 0) {
577     XBT_DEBUG("No next event at all. Bail out now.");
578     return -1.0;
579   }
580
581   XBT_DEBUG("Duration set to %f", time_delta);
582
583   // Bump the time: jump into the future
584   now_ += time_delta;
585
586   // Inform the models of the date change
587   for (auto const& model : models_)
588     model->update_actions_state(now_, time_delta);
589
590   s4u::Engine::on_time_advance(time_delta);
591
592   return time_delta;
593 }
594
595 void EngineImpl::run(double max_date)
596 {
597   seal_platform();
598
599   if (MC_is_active()) {
600 #if SIMGRID_HAVE_MC
601     mc::AppSide::get()->main_loop();
602 #else
603     xbt_die("MC_is_active() is not supposed to return true in non-MC settings");
604 #endif
605     THROW_IMPOSSIBLE; // main_loop never returns
606   }
607
608   if (MC_record_replay_is_active()) {
609     mc::RecordTrace::replay(MC_record_path());
610     empty_trash();
611     return;
612   }
613
614   double elapsed_time = -1;
615   const std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
616
617   do {
618     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
619
620     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
621       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
622       cfg_breakpoint = -1.0; // Let the simulation continue without hiting the breakpoint again and again
623 #ifdef SIGTRAP
624       std::raise(SIGTRAP);
625 #else
626       std::raise(SIGABRT);
627 #endif
628     }
629
630     while (not actors_to_run_.empty()) {
631       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
632
633       /* Run all actors that are ready to run, possibly in parallel */
634       run_all_actors();
635
636       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round.
637        * The order must be fixed for the simulation to be reproducible (see RR-7653). It's OK here because only maestro
638        * changes the list. Killer actors are moved to the end to let victims finish their simcall before dying, but
639        * the order remains reproducible (even if arbitrarily). No need to sort the vector for sake of reproducibility.
640        */
641       for (auto const& actor : actors_that_ran_)
642         if (actor->simcall_.call_ != actor::Simcall::Type::NONE)
643           actor->simcall_handle(0);
644
645       handle_ended_actions();
646
647       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
648       if (actor_list_.size() == daemons_.size())
649         for (auto const& dmon : daemons_) {
650           XBT_DEBUG("Kill %s", dmon->get_cname());
651           maestro_->kill(dmon);
652         }
653     }
654
655     // Compute the max_date of the next solve.
656     // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
657     double next_time = timer::Timer::next();
658     if (next_time < 0 && max_date > -1) {
659       next_time = max_date;
660     } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
661       next_time = std::min(next_time, max_date);
662     }
663
664     XBT_DEBUG("Calling solve(%g) %g", next_time, now_);
665     elapsed_time = solve(next_time);
666     XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", now_, elapsed_time);
667
668     // Execute timers until there isn't anything to be done:
669     bool again = false;
670     do {
671       again = timer::Timer::execute_all();
672       handle_ended_actions();
673     } while (again);
674
675     /* Clean actors to destroy */
676     empty_trash();
677
678     XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
679               actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
680
681     if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
682       if (actor_list_.size() <= daemons_.size()) {
683         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
684                      "once the simulation is over. Please fix your on_exit() functions.");
685       } else {
686         XBT_CRITICAL("Oops! Deadlock detected, some activities are still around but will never complete. "
687                      "This usually happens when the user code is not perfectly clean.");
688       }
689       display_all_actor_status();
690       simgrid::s4u::Engine::on_deadlock();
691       for (auto const& [_, actor] : actor_list_) {
692         XBT_DEBUG("Kill %s", actor->get_cname());
693         maestro_->kill(actor);
694       }
695     }
696   } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
697            ((elapsed_time > -1.0 && not double_equals(max_date, now_, 0.00001)) || has_actors_to_run()));
698
699   if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
700     THROW_IMPOSSIBLE;
701
702   simgrid::s4u::Engine::on_simulation_end();
703 }
704
705 double EngineImpl::get_clock()
706 {
707   return now_;
708 }
709 } // namespace simgrid::kernel