Logo AND Algorithmique Numérique Distribuée

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