Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Activity refactoring
[simgrid.git] / src / kernel / EngineImpl.cpp
1 /* Copyright (c) 2016-2021. 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/profile/Profile.hpp"
16 #include "src/mc/mc_record.hpp"
17 #include "src/mc/mc_replay.hpp"
18 #include "src/smpi/include/smpi_actor.hpp"
19 #include "src/surf/network_interface.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 xbt_dynar_t get_dead_actors_addr()
54 {
55 #if SIMGRID_HAVE_MC
56   return EngineImpl::get_instance()->get_dead_actors_vector();
57 #else
58   xbt_die("This function is intended to be used when compiling with MC");
59 #endif
60 }
61
62 constexpr std::initializer_list<std::pair<const char*, context::ContextFactoryInitializer>> context_factories = {
63 #if HAVE_RAW_CONTEXTS
64     {"raw", &context::raw_factory},
65 #endif
66 #if HAVE_UCONTEXT_CONTEXTS
67     {"ucontext", &context::sysv_factory},
68 #endif
69 #if HAVE_BOOST_CONTEXTS
70     {"boost", &context::boost_factory},
71 #endif
72     {"thread", &context::thread_factory},
73 };
74
75 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
76
77 // Create the list of possible contexts:
78 static inline std::string contexts_list()
79 {
80   std::string res;
81   std::string sep = "";
82   for (auto const& factory : context_factories) {
83     res += sep + factory.first;
84     sep = ", ";
85   }
86   return res;
87 }
88
89 static config::Flag<std::string> context_factory_name("contexts/factory",
90                                                       (std::string("Possible values: ") + contexts_list()).c_str(),
91                                                       context_factories.begin()->first);
92
93 } // namespace kernel
94 } // namespace simgrid
95
96 XBT_ATTRIB_NORETURN static void inthandler(int)
97 {
98   if (simgrid::kernel::cfg_verbose_exit) {
99     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
100              "'debug/verbose-exit').");
101     simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
102   } else {
103     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
104   }
105   exit(1);
106 }
107
108 #ifndef _WIN32
109 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
110 {
111   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
112     fprintf(stderr,
113             "Access violation or Bus error detected.\n"
114             "This probably comes from a programming error in your code, or from a stack\n"
115             "overflow. If you are certain of your code, try increasing the stack size\n"
116             "   --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
117             "\n"
118             "If it does not help, this may have one of the following causes:\n"
119             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
120             "Failing hardware can sometimes generate such errors too.\n"
121             "\n"
122             "If you think you've found a bug in SimGrid, please report it along with a\n"
123             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
124             "of the fault captured with gdb or valgrind.\n",
125             simgrid::kernel::context::stack_size / 1024);
126   } else if (siginfo->si_signo == SIGSEGV) {
127     fprintf(stderr, "Segmentation fault.\n");
128 #if HAVE_SMPI
129     if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
130 #if HAVE_PRIVATIZATION
131       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
132 #else
133       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
134 #endif /* HAVE_PRIVATIZATION */
135     }
136 #endif /* HAVE_SMPI */
137   }
138   std::raise(signum);
139 }
140
141 /**
142  * Install signal handler for SIGSEGV.  Check that nobody has already installed
143  * its own handler.  For example, the Java VM does this.
144  */
145 static void install_segvhandler()
146 {
147   stack_t old_stack;
148
149   if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
150     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
151     return;
152   }
153   if (not(old_stack.ss_flags & SS_DISABLE)) {
154     XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
155               old_stack.ss_size, (unsigned)old_stack.ss_flags);
156     sigaltstack(&old_stack, nullptr);
157   }
158
159   struct sigaction action;
160   struct sigaction old_action;
161   action.sa_sigaction = &segvhandler;
162   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
163   sigemptyset(&action.sa_mask);
164
165   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
166   for (int sig : {SIGSEGV, SIGBUS}) {
167     if (sigaction(sig, &action, &old_action) == -1) {
168       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
169       continue;
170     }
171     if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
172       XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
173                 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
174       sigaction(sig, &old_action, nullptr);
175     }
176   }
177 }
178
179 #endif /* _WIN32 */
180
181 namespace simgrid {
182 namespace kernel {
183
184 EngineImpl::~EngineImpl()
185 {
186   /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
187    * reproducible.
188    */
189   while (not hosts_.empty())
190     hosts_.begin()->second->destroy();
191
192   /* Also delete the other data */
193   delete netzone_root_;
194   for (auto const& kv : netpoints_)
195     delete kv.second;
196
197   while (not links_.empty())
198     links_.begin()->second->destroy();
199
200   for (auto const& kv : mailboxes_)
201     delete kv.second;
202
203     /* Free the remaining data structures */
204 #if SIMGRID_HAVE_MC
205   xbt_dynar_free(&actors_vector_);
206   xbt_dynar_free(&dead_actors_vector_);
207 #endif
208   /* clear models before freeing handle, network models can use external callback defined in the handle */
209   models_prio_.clear();
210 }
211
212 void EngineImpl::initialize(int* argc, char** argv)
213 {
214   xbt_assert(EngineImpl::instance_ == nullptr,
215              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
216   EngineImpl::instance_ = this;
217 #if SIMGRID_HAVE_MC
218   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
219   // layers. But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to
220   // read them directly.
221   simgrid::mc::AppSide::initialize();
222 #endif
223
224   if (xbt_initialized == 0) {
225     xbt_init(argc, argv);
226
227     sg_config_init(argc, argv);
228   }
229
230   instance_->context_mod_init();
231
232   /* Prepare to display some more info when dying on Ctrl-C pressing */
233   std::signal(SIGINT, inthandler);
234
235 #ifndef _WIN32
236   install_segvhandler();
237 #endif
238
239   /* register a function to be called by SURF after the environment creation */
240   sg_platf_init();
241   s4u::Engine::on_platform_created.connect([this]() { this->presolve(); });
242
243   if (config::get_value<bool>("debug/clean-atexit"))
244     atexit(shutdown);
245 }
246
247 void EngineImpl::context_mod_init() const
248 {
249   xbt_assert(not instance_->has_context_factory());
250
251 #if HAVE_SMPI && defined(__NetBSD__)
252   smpi_init_options_internal(false);
253   std::string priv = config::get_value<std::string>("smpi/privatization");
254   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
255     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
256     context_factory_name = "raw";
257   }
258 #endif
259
260 #if HAVE_SMPI && defined(__FreeBSD__)
261   smpi_init_options_internal(false);
262   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
263     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
264     context_factory_name = "raw";
265   }
266 #endif
267
268   /* select the context factory to use to create the contexts */
269   if (context::factory_initializer != nullptr) { // Give Java a chance to hijack the factory mechanism
270     instance_->set_context_factory(context::factory_initializer());
271     return;
272   }
273   /* use the factory specified by --cfg=contexts/factory:value */
274   for (auto const& factory : context_factories)
275     if (context_factory_name == factory.first) {
276       instance_->set_context_factory(factory.second());
277       break;
278     }
279
280   if (not instance_->has_context_factory()) {
281     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
282 #if HAVE_RAW_CONTEXTS
283     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
284 #else
285     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
286 #endif
287 #if HAVE_UCONTEXT_CONTEXTS
288     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
289 #else
290     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
291 #endif
292 #if HAVE_BOOST_CONTEXTS
293     XBT_ERROR("  boost: this uses the boost libraries context implementation");
294 #else
295     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
296               "install the libboost-context-dev package?)");
297 #endif
298     XBT_ERROR("  thread: slow portability layer using pthreads as provided by gcc");
299     xbt_die("Please use a valid factory.");
300   }
301 }
302
303 void EngineImpl::shutdown()
304 {
305   if (EngineImpl::instance_ == nullptr)
306     return;
307   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
308 #if HAVE_SMPI
309   if (not instance_->actor_list_.empty()) {
310     if (smpi_process()->initialized()) {
311       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
312     } else {
313       XBT_WARN("Process called exit when leaving - Skipping cleanups");
314       return;
315     }
316   }
317 #endif
318
319   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
320     XBT_CRITICAL("   ");
321     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
322     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
323     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
324   }
325
326   /* Kill all actors (but maestro) */
327   instance_->maestro_->kill_all();
328   instance_->run_all_actors();
329   instance_->empty_trash();
330
331   /* Let's free maestro now */
332   delete instance_->maestro_;
333   instance_->maestro_ = nullptr;
334
335   /* Finish context module and SURF */
336   instance_->destroy_context_factory();
337
338   while (not timer::kernel_timers().empty()) {
339     delete timer::kernel_timers().top().second;
340     timer::kernel_timers().pop();
341   }
342
343   tmgr_finalize();
344   sg_platf_exit();
345
346   delete instance_;
347   instance_ = nullptr;
348 }
349
350 void EngineImpl::load_platform(const std::string& platf)
351 {
352   double start = xbt_os_time();
353   if (boost::algorithm::ends_with(platf, ".so") or boost::algorithm::ends_with(platf, ".dylib")) {
354 #ifdef _WIN32
355     xbt_die("loading platform through shared library isn't supported on windows");
356 #else
357     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
358     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
359     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
360     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
361     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
362     const char* dlsym_error = dlerror();
363     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
364     callable(*simgrid::s4u::Engine::get_instance());
365 #endif /* _WIN32 */
366   } else {
367     parse_platform_file(platf);
368   }
369
370   double end = xbt_os_time();
371   XBT_DEBUG("PARSE TIME: %g", (end - start));
372 }
373
374 void EngineImpl::load_deployment(const std::string& file) const
375 {
376   sg_platf_exit();
377   sg_platf_init();
378
379   surf_parse_open(file);
380   surf_parse();
381   surf_parse_close();
382 }
383
384 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
385 {
386   registered_functions[name] = code;
387 }
388 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
389 {
390   default_function = code;
391 }
392
393 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
394 {
395   auto model_name = model->get_name();
396   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
397              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
398
399   for (const auto dep : dependencies) {
400     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
401                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
402   }
403   models_.push_back(model.get());
404   models_prio_[model_name] = std::move(model);
405 }
406
407 void EngineImpl::add_split_duplex_link(const std::string& name, std::unique_ptr<resource::SplitDuplexLinkImpl> link)
408 {
409   split_duplex_links_[name] = std::move(link);
410 }
411
412 /** Wake up all actors waiting for a Surf action to finish */
413 void EngineImpl::wake_all_waiting_actors() const
414 {
415   for (auto const& model : models_) {
416     XBT_DEBUG("Handling the failed actions (if any)");
417     while (auto* action = model->extract_failed_action()) {
418       XBT_DEBUG("   Handling Action %p", action);
419       if (action->get_activity() != nullptr) {
420         // If nobody told the interface that the activity has failed, that's because no actor waits on it (maestro
421         // started it). SimDAG I see you!
422         if (action->get_activity()->get_actor() == maestro_)
423           action->get_activity()->get_iface()->complete(s4u::Activity::State::FAILED);
424
425         activity::ActivityImplPtr(action->get_activity())->post();
426       }
427     }
428     XBT_DEBUG("Handling the terminated actions (if any)");
429     while (auto* action = model->extract_done_action()) {
430       XBT_DEBUG("   Handling Action %p", action);
431       if (action->get_activity() == nullptr)
432         XBT_DEBUG("probably vcpu's action %p, skip", action);
433       else {
434         // If nobody told the interface that the activity is finished, that's because no actor waits on it (maestro
435         // started it). SimDAG I see you!
436         // TODO: do the same for other activity kinds once comms are cleaned up
437         auto* exec = dynamic_cast<activity::ExecImpl*>(action->get_activity());
438         if (exec != nullptr && exec->get_actor() == maestro_) {
439           exec->set_finish_time(action->get_finish_time());
440           exec->get_iface()->complete(s4u::Activity::State::FINISHED);
441         }
442         auto* io = dynamic_cast<activity::IoImpl*>(action->get_activity());
443         if (io != nullptr && io->get_actor() == maestro_)
444           io->get_iface()->complete(s4u::Activity::State::FINISHED);
445
446         activity::ActivityImplPtr(action->get_activity())->post();
447       }
448     }
449   }
450 }
451 /**
452  * @brief Executes the actors in actors_to_run.
453  *
454  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
455  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
456  * a call to this function.
457  */
458 void EngineImpl::run_all_actors()
459 {
460   instance_->get_context_factory()->run_all();
461
462   actors_to_run_.swap(actors_that_ran_);
463   actors_to_run_.clear();
464 }
465
466 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
467 {
468   auto item = actor_list_.find(pid);
469   if (item != actor_list_.end())
470     return item->second;
471
472   // Search the trash
473   for (auto& a : actors_to_destroy_)
474     if (a.get_pid() == pid)
475       return &a;
476   return nullptr; // Not found, even in the trash
477 }
478
479 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
480 bool EngineImpl::execute_tasks()
481 {
482   if (tasks.empty())
483     return false;
484
485   std::vector<xbt::Task<void()>> tasksTemp;
486   do {
487     // We don't want the callbacks to modify the vector we are iterating over:
488     tasks.swap(tasksTemp);
489
490     // Execute all the queued tasks:
491     for (auto& task : tasksTemp)
492       task();
493
494     tasksTemp.clear();
495   } while (not tasks.empty());
496
497   return true;
498 }
499
500 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
501 {
502   auto it = daemons_.find(actor);
503   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
504   daemons_.erase(it);
505 }
506
507 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
508 {
509   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
510   actors_to_run_.push_back(actor);
511 }
512
513 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
514 {
515   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
516     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
517   } else {
518     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
519     actors_to_run_.push_back(actor);
520   }
521 }
522 void EngineImpl::empty_trash()
523 {
524   while (not actors_to_destroy_.empty()) {
525     actor::ActorImpl* actor = &actors_to_destroy_.front();
526     actors_to_destroy_.pop_front();
527     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
528     intrusive_ptr_release(actor);
529   }
530 #if SIMGRID_HAVE_MC
531   xbt_dynar_reset(dead_actors_vector_);
532 #endif
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     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::RawImpl>(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 %d 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(), (int)actor->waiting_synchro_->state_);
565     } else {
566       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
567                SIMIX_simcall_name(actor->simcall_));
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   if (MC_record_replay_is_active()) {
698     mc::replay(MC_record_path());
699     empty_trash();
700     return;
701   }
702
703   double elapsed_time = -1;
704   std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
705
706   do {
707     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
708
709     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
710       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
711       cfg_breakpoint = -1.0;
712 #ifdef SIGTRAP
713       std::raise(SIGTRAP);
714 #else
715       std::raise(SIGABRT);
716 #endif
717     }
718
719     execute_tasks();
720
721     while (not actors_to_run_.empty()) {
722       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
723
724       /* Run all actors that are ready to run, possibly in parallel */
725       run_all_actors();
726
727       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
728
729       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
730
731       /* Here, the order is ok because:
732        *
733        *   Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
734        *   not impact its order.
735        *
736        *   Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
737        *
738        *   - if there is no kill during the simulation, actors remain sorted according by their PID.
739        *     Rationale: This can be proved inductively.
740        *        Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
741        *        is parsed linearly).
742        *        Let's show that it is still so at the end of this round.
743        *        - if an actor is added when being created, that's from maestro. It can be either at startup
744        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
745        *          in arbitrary order (inductive hypothesis), we are fine.
746        *        - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
747        *        - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
748        *          of a simcall terminates, we're still good. Proof:
749        *          - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
750        *            resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
751        *            as an example.
752        *          - For communications, this function is called from CommImpl::finish().
753        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
754        *            The function is called:
755        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
756        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
757        *            - because the communication failed or were canceled after startup. In this case, it's called from
758        *              the function we are in, by the chunk:
759        *                       set = model->states.failed_action_set;
760        *                       while ((synchro = extract(set)))
761        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
762        *              This order is also fixed because it depends of the order in which the surf actions were
763        *              added to the system, and only maestro can add stuff this way, through simcalls.
764        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
765        *              popped out of the set does not depend on the user code's execution order.
766        *            - because the communication terminated. In this case, synchros are served in the order given by
767        *                       set = model->states.done_action_set;
768        *                       while ((synchro = extract(set)))
769        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
770        *              and the argument is very similar to the previous one.
771        *            So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
772        *            actors are executed.
773        *          So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
774        *          user actors were executed previously.
775        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
776        *   - If there is some actor killings, the order is changed by this decision that comes from user-land
777        *     But this decision may not have been motivated by a situation that were different because the simulation is
778        *     not reproducible.
779        *     So, even the order change induced by the actor killing is perfectly reproducible.
780        *
781        *   So science works, bitches [http://xkcd.com/54/].
782        *
783        *   We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
784        *   handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
785        *   unfriendly).
786        *   That would thus be a pure waste of time.
787        */
788
789       for (auto const& actor : actors_that_ran_) {
790         if (actor->simcall_.call_ != simix::Simcall::NONE) {
791           actor->simcall_handle(0);
792         }
793       }
794
795       execute_tasks();
796       do {
797         wake_all_waiting_actors();
798       } while (execute_tasks());
799
800       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
801       if (actor_list_.size() == daemons_.size())
802         for (auto const& dmon : daemons_) {
803           XBT_DEBUG("Kill %s", dmon->get_cname());
804           maestro_->kill(dmon);
805         }
806     }
807
808     // Compute the max_date of the next solve.
809     // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
810     double next_time = timer::Timer::next();
811     if (next_time < 0 && max_date > -1) {
812       next_time = max_date;
813     } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
814       next_time = std::min(next_time, max_date);
815     }
816
817     XBT_DEBUG("Calling solve(%g) %g", next_time, NOW);
818     elapsed_time = solve(next_time);
819     XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", NOW, elapsed_time);
820
821     /* Notify all the hosts that have failed */
822     /* FIXME: iterate through the list of failed host and mark each of them */
823     /* as failed. On each host, signal all the running actors with host_fail */
824
825     // Execute timers and tasks until there isn't anything to be done:
826     bool again = false;
827     do {
828       again = timer::Timer::execute_all();
829       if (execute_tasks())
830         again = true;
831       wake_all_waiting_actors();
832     } while (again);
833
834     /* Clean actors to destroy */
835     empty_trash();
836
837     XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
838               actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
839
840     if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
841       if (actor_list_.size() <= daemons_.size()) {
842         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
843                      "once the simulation is over. Please fix your on_exit() functions.");
844       } else {
845         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
846       }
847       display_all_actor_status();
848       simgrid::s4u::Engine::on_deadlock();
849       for (auto const& kv : actor_list_) {
850         XBT_DEBUG("Kill %s", kv.second->get_cname());
851         maestro_->kill(kv.second);
852       }
853     }
854
855   } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
856            ((elapsed_time > -1.0 && not double_equals(max_date, NOW, 0.00001)) || has_actors_to_run()));
857
858   if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
859     THROW_IMPOSSIBLE;
860
861   simgrid::s4u::Engine::on_simulation_end();
862 }
863
864 double EngineImpl::get_clock()
865 {
866   return NOW;
867 }
868 } // namespace kernel
869 } // namespace simgrid
870
871 void SIMIX_run() // XBT_ATTRIB_DEPRECATED_v332
872 {
873   simgrid::kernel::EngineImpl::get_instance()->run(-1);
874 }