Logo AND Algorithmique Numérique Distribuée

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