Logo AND Algorithmique Numérique Distribuée

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