Logo AND Algorithmique Numérique Distribuée

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