Logo AND Algorithmique Numérique Distribuée

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