Logo AND Algorithmique Numérique Distribuée

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