Logo AND Algorithmique Numérique Distribuée

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