Logo AND Algorithmique Numérique Distribuée

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