Logo AND Algorithmique Numérique Distribuée

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