Logo AND Algorithmique Numérique Distribuée

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