Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Answer to Martin's feedback
[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/xbt_modinter.h" /* whether initialization was already done */
22
23 #include <boost/algorithm/string/predicate.hpp>
24 #ifndef _WIN32
25 #include <dlfcn.h>
26 #endif /* _WIN32 */
27
28 #if SIMGRID_HAVE_MC
29 #include "src/mc/remote/AppSide.hpp"
30 #endif
31
32 double NOW = 0;
33
34 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
35
36 namespace simgrid {
37 namespace kernel {
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 xbt_dynar_t get_actors_addr()
45 {
46 #if SIMGRID_HAVE_MC
47   return EngineImpl::get_instance()->get_actors_vector();
48 #else
49   xbt_die("This function is intended to be used when compiling with MC");
50 #endif
51 }
52
53 constexpr std::initializer_list<std::pair<const char*, context::ContextFactoryInitializer>> context_factories = {
54 #if HAVE_RAW_CONTEXTS
55     {"raw", &context::raw_factory},
56 #endif
57 #if HAVE_UCONTEXT_CONTEXTS
58     {"ucontext", &context::sysv_factory},
59 #endif
60 #if HAVE_BOOST_CONTEXTS
61     {"boost", &context::boost_factory},
62 #endif
63     {"thread", &context::thread_factory},
64 };
65
66 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
67
68 // Create the list of possible contexts:
69 static inline std::string contexts_list()
70 {
71   std::string res;
72   std::string sep = "";
73   for (auto const& factory : context_factories) {
74     res += sep + factory.first;
75     sep = ", ";
76   }
77   return res;
78 }
79
80 static config::Flag<std::string> context_factory_name("contexts/factory",
81                                                       (std::string("Possible values: ") + contexts_list()).c_str(),
82                                                       context_factories.begin()->first);
83
84 } // namespace kernel
85 } // namespace simgrid
86
87 XBT_ATTRIB_NORETURN static void inthandler(int)
88 {
89   if (simgrid::kernel::cfg_verbose_exit) {
90     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
91              "'debug/verbose-exit').");
92     simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
93   } else {
94     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
95   }
96   exit(1);
97 }
98
99 #ifndef _WIN32
100 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
101 {
102   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
103     fprintf(stderr,
104             "Access violation or Bus error detected.\n"
105             "This probably comes from a programming error in your code, or from a stack\n"
106             "overflow. If you are certain of your code, try increasing the stack size\n"
107             "   --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
108             "\n"
109             "If it does not help, this may have one of the following causes:\n"
110             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
111             "Failing hardware can sometimes generate such errors too.\n"
112             "\n"
113             "If you think you've found a bug in SimGrid, please report it along with a\n"
114             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
115             "of the fault captured with gdb or valgrind.\n",
116             simgrid::kernel::context::stack_size / 1024);
117   } else if (siginfo->si_signo == SIGSEGV) {
118     fprintf(stderr, "Segmentation fault.\n");
119 #if HAVE_SMPI
120     if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
121 #if HAVE_PRIVATIZATION
122       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
123 #else
124       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
125 #endif /* HAVE_PRIVATIZATION */
126     }
127 #endif /* HAVE_SMPI */
128   }
129   std::raise(signum);
130 }
131
132 /**
133  * Install signal handler for SIGSEGV.  Check that nobody has already installed
134  * its own handler.  For example, the Java VM does this.
135  */
136 static void install_segvhandler()
137 {
138   stack_t old_stack;
139
140   if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
141     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
142     return;
143   }
144   if (not(old_stack.ss_flags & SS_DISABLE)) {
145     XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
146               old_stack.ss_size, (unsigned)old_stack.ss_flags);
147     sigaltstack(&old_stack, nullptr);
148   }
149
150   struct sigaction action;
151   struct sigaction old_action;
152   action.sa_sigaction = &segvhandler;
153   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
154   sigemptyset(&action.sa_mask);
155
156   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
157   for (int sig : {SIGSEGV, SIGBUS}) {
158     if (sigaction(sig, &action, &old_action) == -1) {
159       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
160       continue;
161     }
162     if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
163       XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
164                 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
165       sigaction(sig, &old_action, nullptr);
166     }
167   }
168 }
169
170 #endif /* _WIN32 */
171
172 namespace simgrid {
173 namespace kernel {
174
175 EngineImpl::~EngineImpl()
176 {
177   /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
178    * reproducible.
179    */
180   while (not hosts_.empty())
181     hosts_.begin()->second->destroy();
182
183   /* Also delete the other data */
184   delete netzone_root_;
185   for (auto const& kv : netpoints_)
186     delete kv.second;
187
188   while (not links_.empty())
189     links_.begin()->second->destroy();
190
191   for (auto const& kv : mailboxes_)
192     delete kv.second;
193
194     /* Free the remaining data structures */
195 #if SIMGRID_HAVE_MC
196   xbt_dynar_free(&actors_vector_);
197 #endif
198   /* clear models before freeing handle, network models can use external callback defined in the handle */
199   models_prio_.clear();
200 }
201
202 void EngineImpl::initialize(int* argc, char** argv)
203 {
204   xbt_assert(EngineImpl::instance_ == nullptr,
205              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
206   EngineImpl::instance_ = this;
207 #if SIMGRID_HAVE_MC
208   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
209   // layers. But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to
210   // read them directly.
211   simgrid::mc::AppSide::initialize();
212 #endif
213
214   if (xbt_initialized == 0) {
215     xbt_init(argc, argv);
216
217     sg_config_init(argc, argv);
218   }
219
220   instance_->context_mod_init();
221
222   /* Prepare to display some more info when dying on Ctrl-C pressing */
223   std::signal(SIGINT, inthandler);
224
225 #ifndef _WIN32
226   install_segvhandler();
227 #endif
228
229   /* register a function to be called by SURF after the environment creation */
230   sg_platf_init();
231   s4u::Engine::on_platform_created_cb([this]() { this->presolve(); });
232
233   if (config::get_value<bool>("debug/clean-atexit"))
234     atexit(shutdown);
235 }
236
237 void EngineImpl::context_mod_init() const
238 {
239   xbt_assert(not instance_->has_context_factory());
240
241 #if HAVE_SMPI && defined(__NetBSD__)
242   smpi_init_options_internal(false);
243   std::string priv = config::get_value<std::string>("smpi/privatization");
244   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
245     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
246     context_factory_name = "raw";
247   }
248 #endif
249
250 #if HAVE_SMPI && defined(__FreeBSD__)
251   smpi_init_options_internal(false);
252   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
253     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
254     context_factory_name = "raw";
255   }
256 #endif
257
258   /* select the context factory to use to create the contexts */
259   if (context::factory_initializer != nullptr) { // Give Java a chance to hijack the factory mechanism
260     instance_->set_context_factory(context::factory_initializer());
261     return;
262   }
263   /* use the factory specified by --cfg=contexts/factory:value */
264   for (auto const& factory : context_factories)
265     if (context_factory_name == factory.first) {
266       instance_->set_context_factory(factory.second());
267       break;
268     }
269
270   if (not instance_->has_context_factory()) {
271     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
272 #if HAVE_RAW_CONTEXTS
273     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
274 #else
275     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
276 #endif
277 #if HAVE_UCONTEXT_CONTEXTS
278     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
279 #else
280     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
281 #endif
282 #if HAVE_BOOST_CONTEXTS
283     XBT_ERROR("  boost: this uses the boost libraries context implementation");
284 #else
285     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
286               "install the libboost-context-dev package?)");
287 #endif
288     XBT_ERROR("  thread: slow portability layer using pthreads as provided by gcc");
289     xbt_die("Please use a valid factory.");
290   }
291 }
292
293 void EngineImpl::shutdown()
294 {
295   if (EngineImpl::instance_ == nullptr)
296     return;
297   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
298 #if HAVE_SMPI
299   if (not instance_->actor_list_.empty()) {
300     if (smpi_process()->initialized()) {
301       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
302     } else {
303       XBT_WARN("Process called exit when leaving - Skipping cleanups");
304       return;
305     }
306   }
307 #endif
308
309   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
310     XBT_CRITICAL("   ");
311     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
312     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
313     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
314   }
315
316   /* Kill all actors (but maestro) */
317   instance_->maestro_->kill_all();
318   instance_->run_all_actors();
319   instance_->empty_trash();
320
321   /* Let's free maestro now */
322   delete instance_->maestro_;
323   instance_->maestro_ = nullptr;
324
325   /* Finish context module and SURF */
326   instance_->destroy_context_factory();
327
328   while (not timer::kernel_timers().empty()) {
329     delete timer::kernel_timers().top().second;
330     timer::kernel_timers().pop();
331   }
332
333   tmgr_finalize();
334   sg_platf_exit();
335
336   delete instance_;
337   instance_ = nullptr;
338 }
339
340 void EngineImpl::seal_platform() const
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   actors_to_run_.swap(actors_that_ran_);
457   actors_to_run_.clear();
458 }
459
460 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
461 {
462   auto item = actor_list_.find(pid);
463   if (item != actor_list_.end())
464     return item->second;
465
466   // Search the trash
467   for (auto& a : actors_to_destroy_)
468     if (a.get_pid() == pid)
469       return &a;
470   return nullptr; // Not found, even in the trash
471 }
472
473 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
474 bool EngineImpl::execute_tasks()
475 {
476   if (tasks.empty())
477     return false;
478
479   std::vector<xbt::Task<void()>> tasksTemp;
480   do {
481     // We don't want the callbacks to modify the vector we are iterating over:
482     tasks.swap(tasksTemp);
483
484     // Execute all the queued tasks:
485     for (auto& task : tasksTemp)
486       task();
487
488     tasksTemp.clear();
489   } while (not tasks.empty());
490
491   return true;
492 }
493
494 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
495 {
496   auto it = daemons_.find(actor);
497   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
498   daemons_.erase(it);
499 }
500
501 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
502 {
503   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
504   actors_to_run_.push_back(actor);
505 }
506
507 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
508 {
509   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
510     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
511   } else {
512     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
513     actors_to_run_.push_back(actor);
514   }
515 }
516 void EngineImpl::empty_trash()
517 {
518   while (not actors_to_destroy_.empty()) {
519     actor::ActorImpl* actor = &actors_to_destroy_.front();
520     actors_to_destroy_.pop_front();
521     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
522     intrusive_ptr_release(actor);
523   }
524 }
525
526 void EngineImpl::display_all_actor_status() const
527 {
528   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
529   /*  List the actors and their state */
530   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
531   for (auto const& kv : actor_list_) {
532     const actor::ActorImpl* actor = kv.second;
533
534     if (actor->waiting_synchro_) {
535       const char* synchro_description = "unknown";
536
537       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
538         synchro_description = "execution";
539
540       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
541         synchro_description = "communication";
542
543       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
544         synchro_description = "sleeping";
545
546       if (boost::dynamic_pointer_cast<kernel::activity::SynchroImpl>(actor->waiting_synchro_) != nullptr)
547         synchro_description = "synchronization";
548
549       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
550         synchro_description = "I/O";
551
552       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %s to finish", actor->get_pid(),
553                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
554                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
555                actor->waiting_synchro_->get_cname(), actor->waiting_synchro_->get_state_str());
556     } else {
557       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
558                SIMIX_simcall_name(actor->simcall_));
559     }
560   }
561 }
562
563 void EngineImpl::presolve() const
564 {
565   XBT_DEBUG("Consume all trace events occurring before the starting time.");
566   double next_event_date;
567   while ((next_event_date = profile::future_evt_set.next_date()) != -1.0) {
568     if (next_event_date > NOW)
569       break;
570
571     double value                 = -1.0;
572     resource::Resource* resource = nullptr;
573     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
574       if (value >= 0)
575         resource->apply_event(event, value);
576     }
577   }
578
579   XBT_DEBUG("Set every models in the right state by updating them to 0.");
580   for (auto const& model : models_)
581     model->update_actions_state(NOW, 0.0);
582 }
583
584 double EngineImpl::solve(double max_date) const
585 {
586   double time_delta            = -1.0; /* duration */
587   double value                 = -1.0;
588   resource::Resource* resource = nullptr;
589
590   if (max_date != -1.0) {
591     xbt_assert(max_date >= NOW, "You asked to simulate up to %f, but that's in the past already", max_date);
592
593     time_delta = max_date - NOW;
594   }
595
596   XBT_DEBUG("Looking for next event in all models");
597   for (auto model : models_) {
598     if (not model->next_occurring_event_is_idempotent()) {
599       continue;
600     }
601     double next_event = model->next_occurring_event(NOW);
602     if ((time_delta < 0.0 || next_event < time_delta) && next_event >= 0.0) {
603       time_delta = next_event;
604     }
605   }
606
607   XBT_DEBUG("Min for resources (remember that NS3 don't update that value): %f", time_delta);
608
609   XBT_DEBUG("Looking for next trace event");
610
611   while (true) { // Handle next occurring events until none remains
612     double next_event_date = profile::future_evt_set.next_date();
613     XBT_DEBUG("Next TRACE event: %f", next_event_date);
614
615     for (auto model : models_) {
616       /* Skip all idempotent models, they were already treated above
617        * NS3 is the one to handled here */
618       if (model->next_occurring_event_is_idempotent())
619         continue;
620
621       if (next_event_date != -1.0) {
622         time_delta = std::min(next_event_date - NOW, time_delta);
623       } else {
624         time_delta = std::max(next_event_date - NOW, time_delta); // Get the positive component
625       }
626
627       XBT_DEBUG("Run the NS3 network at most %fs", time_delta);
628       // run until min or next flow
629       double model_next_action_end = model->next_occurring_event(time_delta);
630
631       XBT_DEBUG("Min for network : %f", model_next_action_end);
632       if (model_next_action_end >= 0.0)
633         time_delta = model_next_action_end;
634     }
635
636     if (next_event_date < 0.0 || (next_event_date > NOW + time_delta)) {
637       // next event may have already occurred or will after the next resource change, then bail out
638       XBT_DEBUG("no next usable TRACE event. Stop searching for it");
639       break;
640     }
641
642     XBT_DEBUG("Updating models (min = %g, NOW = %g, next_event_date = %g)", time_delta, NOW, next_event_date);
643
644     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
645       if (resource->is_used() || (watched_hosts().find(resource->get_cname()) != watched_hosts().end())) {
646         time_delta = next_event_date - NOW;
647         XBT_DEBUG("This event invalidates the next_occurring_event() computation of models. Next event set to %f",
648                   time_delta);
649       }
650       // FIXME: I'm too lame to update NOW live, so I change it and restore it so that the real update with surf_min
651       // will work
652       double round_start = NOW;
653       NOW                = next_event_date;
654       /* update state of the corresponding resource to the new value. Does not touch lmm.
655          It will be modified if needed when updating actions */
656       XBT_DEBUG("Calling update_resource_state for resource %s", resource->get_cname());
657       resource->apply_event(event, value);
658       NOW = round_start;
659     }
660   }
661
662   /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are
663    * with availability = 0. This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a
664    * trace with periodicity > 0.
665    * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed
666    */
667   if (time_delta < 0) {
668     XBT_DEBUG("No next event at all. Bail out now.");
669     return -1.0;
670   }
671
672   XBT_DEBUG("Duration set to %f", time_delta);
673
674   // Bump the time: jump into the future
675   NOW = NOW + time_delta;
676
677   // Inform the models of the date change
678   for (auto const& model : models_)
679     model->update_actions_state(NOW, time_delta);
680
681   s4u::Engine::on_time_advance(time_delta);
682
683   return time_delta;
684 }
685
686 void EngineImpl::run(double max_date)
687 {
688   seal_platform();
689
690   if (MC_record_replay_is_active()) {
691     mc::RecordTrace::replay(MC_record_path());
692     empty_trash();
693     return;
694   }
695
696   double elapsed_time = -1;
697   const std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
698
699   do {
700     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
701
702     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
703       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
704       cfg_breakpoint = -1.0;
705 #ifdef SIGTRAP
706       std::raise(SIGTRAP);
707 #else
708       std::raise(SIGABRT);
709 #endif
710     }
711
712     execute_tasks();
713
714     while (not actors_to_run_.empty()) {
715       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
716
717       /* Run all actors that are ready to run, possibly in parallel */
718       run_all_actors();
719
720       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
721
722       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
723
724       /* Here, the order is ok because:
725        *
726        *   Only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do not impact its order.
727        * 
728        *   In addition, actors remain sorted through an arbitrary but fixed order in all cases:
729        *
730        *   - If there is no killing during the simulation, actors remain sorted according by their PID.
731        *   - Killer actors are moved to the end of the scheduling round (to let victims finish their simcall before dying), but 
732        *      (1) this decision of killing is reproducible because the simulation was reproducible until then
733        *      (2) this reordering introduces no reproducibility hazard in the subsequent simulation. 
734        *          Even the order change induced by the actor killing is perfectly reproducible.
735        * 
736        *   So the array order is implicit and somewhat complex, but fixed and reproducible (science works, http://xkcd.com/54/).
737        *
738        *   We could manually sort the actors_that_ran array so that simcalls are handled in an easy to predict order 
739        *  (e.g. "according to the PID of issuer"), but it's not mandatory for the simulation soundness and reproducibility, 
740        *   and would thus be a pure waste of time.
741        */
742
743       for (auto const& actor : actors_that_ran_) {
744         if (actor->simcall_.call_ != simix::Simcall::NONE) {
745           actor->simcall_handle(0);
746         }
747       }
748
749       execute_tasks();
750       do {
751         wake_all_waiting_actors();
752       } while (execute_tasks());
753
754       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
755       if (actor_list_.size() == daemons_.size())
756         for (auto const& dmon : daemons_) {
757           XBT_DEBUG("Kill %s", dmon->get_cname());
758           maestro_->kill(dmon);
759         }
760     }
761
762     // Compute the max_date of the next solve.
763     // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
764     double next_time = timer::Timer::next();
765     if (next_time < 0 && max_date > -1) {
766       next_time = max_date;
767     } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
768       next_time = std::min(next_time, max_date);
769     }
770
771     XBT_DEBUG("Calling solve(%g) %g", next_time, NOW);
772     elapsed_time = solve(next_time);
773     XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", NOW, elapsed_time);
774
775     /* Notify all the hosts that have failed */
776     /* FIXME: iterate through the list of failed host and mark each of them */
777     /* as failed. On each host, signal all the running actors with host_fail */
778
779     // Execute timers and tasks until there isn't anything to be done:
780     bool again = false;
781     do {
782       again = timer::Timer::execute_all();
783       if (execute_tasks())
784         again = true;
785       wake_all_waiting_actors();
786     } while (again);
787
788     /* Clean actors to destroy */
789     empty_trash();
790
791     XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
792               actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
793
794     if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
795       if (actor_list_.size() <= daemons_.size()) {
796         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
797                      "once the simulation is over. Please fix your on_exit() functions.");
798       } else {
799         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
800       }
801       display_all_actor_status();
802       simgrid::s4u::Engine::on_deadlock();
803       for (auto const& kv : actor_list_) {
804         XBT_DEBUG("Kill %s", kv.second->get_cname());
805         maestro_->kill(kv.second);
806       }
807     }
808   } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
809            ((elapsed_time > -1.0 && not double_equals(max_date, NOW, 0.00001)) || has_actors_to_run()));
810
811   if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
812     THROW_IMPOSSIBLE;
813
814   simgrid::s4u::Engine::on_simulation_end();
815 }
816
817 double EngineImpl::get_clock()
818 {
819   return NOW;
820 }
821 } // namespace kernel
822 } // namespace simgrid
823
824 void SIMIX_run() // XBT_ATTRIB_DEPRECATED_v332
825 {
826   simgrid::kernel::EngineImpl::get_instance()->run(-1);
827 }