Logo AND Algorithmique Numérique Distribuée

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