Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Misc code simplifications guided by Sonar smells.
[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/module.h"
22 #include "xbt/xbt_modinter.h" /* whether initialization was already done */
23
24 #include <boost/algorithm/string/predicate.hpp>
25 #ifndef _WIN32
26 #include <dlfcn.h>
27 #endif /* _WIN32 */
28
29 #if SIMGRID_HAVE_MC
30 #include "src/mc/remote/AppSide.hpp"
31 #endif
32
33 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
34
35 namespace simgrid {
36 namespace kernel {
37 double EngineImpl::now_           = 0.0;
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::ContextFactory* (*)()>> 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_name, _] : context_factories) {
65     res += sep + factory_name;
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   /* Also delete the other data */
169   delete netzone_root_;
170   for (auto const& [_, netpoint] : netpoints_)
171     delete netpoint;
172
173   for (auto const& [_, mailbox] : mailboxes_)
174     delete mailbox;
175
176   /* Kill all actors (but maestro) */
177   maestro_->kill_all();
178   run_all_actors();
179   empty_trash();
180
181   delete maestro_;
182   delete context_factory_;
183
184   /* Free the remaining data structures */
185 #if SIMGRID_HAVE_MC
186   xbt_dynar_free(&actors_vector_);
187 #endif
188   /* clear models before freeing handle, network models can use external callback defined in the handle */
189   models_prio_.clear();
190 }
191
192 void EngineImpl::initialize(int* argc, char** argv)
193 {
194   xbt_assert(EngineImpl::instance_ == nullptr,
195              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
196   EngineImpl::instance_ = this;
197 #if SIMGRID_HAVE_MC
198   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
199   // layers. But instance_ needs to be created, as we send the address of some of its fields to the MC that wants to
200   // read them directly.
201   simgrid::mc::AppSide::initialize(actors_vector_);
202 #endif
203
204   if (xbt_initialized == 0) {
205     xbt_init(argc, argv);
206
207     sg_config_init(argc, argv);
208   }
209
210   instance_->context_mod_init();
211
212   /* Prepare to display some more info when dying on Ctrl-C pressing */
213   std::signal(SIGINT, inthandler);
214
215 #ifndef _WIN32
216   install_segvhandler();
217 #endif
218
219   /* register a function to be called by SURF after the environment creation */
220   sg_platf_init();
221   s4u::Engine::on_platform_created_cb([this]() { this->presolve(); });
222
223   if (config::get_value<bool>("debug/clean-atexit"))
224     atexit(shutdown);
225 }
226
227 void EngineImpl::context_mod_init() const
228 {
229   xbt_assert(not instance_->has_context_factory());
230
231 #if HAVE_SMPI && defined(__NetBSD__)
232   smpi_init_options_internal(false);
233   std::string priv = config::get_value<std::string>("smpi/privatization");
234   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
235     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
236     context_factory_name = "raw";
237   }
238 #endif
239
240 #if HAVE_SMPI && defined(__FreeBSD__)
241   smpi_init_options_internal(false);
242   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
243     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
244     context_factory_name = "raw";
245   }
246 #endif
247
248   /* select the context factory to use to create the contexts */
249   if (context::ContextFactory::initializer) { // Give Java a chance to hijack the factory mechanism
250     instance_->set_context_factory(context::ContextFactory::initializer());
251     return;
252   }
253   /* use the factory specified by --cfg=contexts/factory:value */
254   for (auto const& [factory_name, factory] : context_factories)
255     if (context_factory_name == factory_name) {
256       instance_->set_context_factory(factory());
257       break;
258     }
259
260   if (not instance_->has_context_factory()) {
261     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
262 #if HAVE_RAW_CONTEXTS
263     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
264 #else
265     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
266 #endif
267 #if HAVE_UCONTEXT_CONTEXTS
268     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
269 #else
270     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
271 #endif
272 #if HAVE_BOOST_CONTEXTS
273     XBT_ERROR("  boost: this uses the boost libraries context implementation");
274 #else
275     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
276               "install the libboost-context-dev package?)");
277 #endif
278     XBT_ERROR("  thread: slow portability layer using pthreads as provided by gcc");
279     xbt_die("Please use a valid factory.");
280   }
281 }
282
283 void EngineImpl::shutdown()
284 {
285   if (EngineImpl::instance_ == nullptr)
286     return;
287   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
288 #if HAVE_SMPI
289   if (not instance_->actor_list_.empty()) {
290     if (smpi_process()->initialized()) {
291       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
292     } else {
293       XBT_WARN("Process called exit when leaving - Skipping cleanups");
294       return;
295     }
296   }
297 #endif
298
299   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
300     XBT_CRITICAL("   ");
301     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
302     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
303     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
304   }
305
306   while (not timer::kernel_timers().empty()) {
307     delete timer::kernel_timers().top().second;
308     timer::kernel_timers().pop();
309   }
310
311   tmgr_finalize();
312   sg_platf_exit();
313
314   delete instance_;
315   instance_ = nullptr;
316 }
317
318 void EngineImpl::seal_platform() const
319 {
320   /* Seal only once */
321   static bool sealed = false;
322   if (sealed)
323     return;
324   sealed = true;
325
326   /* seal netzone root, recursively seal children netzones, hosts and disks */
327   netzone_root_->seal();
328 }
329
330 void EngineImpl::load_platform(const std::string& platf)
331 {
332   double start = xbt_os_time();
333   if (boost::algorithm::ends_with(platf, ".so") || boost::algorithm::ends_with(platf, ".dylib")) {
334 #ifdef _WIN32
335     xbt_die("loading platform through shared library isn't supported on windows");
336 #else
337     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
338     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
339     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
340     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
341     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
342     const char* dlsym_error = dlerror();
343     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
344     callable(*simgrid::s4u::Engine::get_instance());
345 #endif /* _WIN32 */
346   } else {
347     parse_platform_file(platf);
348   }
349
350   double end = xbt_os_time();
351   XBT_DEBUG("PARSE TIME: %g", (end - start));
352 }
353
354 void EngineImpl::load_deployment(const std::string& file) const
355 {
356   sg_platf_exit();
357   sg_platf_init();
358
359   surf_parse_open(file);
360   surf_parse();
361   surf_parse_close();
362 }
363
364 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
365 {
366   registered_functions[name] = code;
367 }
368 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
369 {
370   default_function = code;
371 }
372
373 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
374 {
375   auto model_name = model->get_name();
376   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
377              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
378
379   for (const auto dep : dependencies) {
380     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
381                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
382   }
383   models_.push_back(model.get());
384   models_prio_[model_name] = std::move(model);
385 }
386
387 /** Wake up all actors waiting for a Surf action to finish */
388 void EngineImpl::handle_ended_actions() const
389 {
390   for (auto const& model : models_) {
391     XBT_DEBUG("Handling the failed actions (if any)");
392     while (auto* action = model->extract_failed_action()) {
393       XBT_DEBUG("   Handling Action %p", action);
394       if (action->get_activity() != nullptr) { // Skip vcpu actions
395         // Action failures are not automatically reported when the action is started by maestro (as in SimDAG)
396         if (action->get_activity()->get_actor() == maestro_)
397           action->get_activity()->get_iface()->complete(s4u::Activity::State::FAILED);
398
399         activity::ActivityImplPtr(action->get_activity())->post();
400       }
401     }
402     XBT_DEBUG("Handling the terminated actions (if any)");
403     while (auto* action = model->extract_done_action()) {
404       XBT_DEBUG("   Handling Action %p", action);
405       if (action->get_activity() != nullptr) {
406         // Action termination are not automatically reported when the action is started by maestro (as in SimDAG)
407         action->get_activity()->set_finish_time(action->get_finish_time());
408
409         if (action->get_activity()->get_actor() == maestro_)
410           action->get_activity()->get_iface()->complete(s4u::Activity::State::FINISHED);
411
412         activity::ActivityImplPtr(action->get_activity())->post();
413       }
414     }
415   }
416 }
417 /**
418  * @brief Executes the actors in actors_to_run.
419  *
420  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
421  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
422  * a call to this function.
423  */
424 void EngineImpl::run_all_actors()
425 {
426   instance_->get_context_factory()->run_all(actors_to_run_);
427
428   for (auto const& actor : actors_to_run_)
429     if (actor->to_be_freed())
430       actor->cleanup_from_kernel();
431
432   actors_to_run_.swap(actors_that_ran_);
433   actors_to_run_.clear();
434 }
435
436 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
437 {
438   auto item = actor_list_.find(pid);
439   return item == actor_list_.end() ? nullptr : item->second;
440 }
441
442 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
443 {
444   auto it = daemons_.find(actor);
445   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
446   daemons_.erase(it);
447 }
448
449 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
450 {
451   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
452   actors_to_run_.push_back(actor);
453 }
454
455 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
456 {
457   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
458     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
459   } else {
460     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
461     actors_to_run_.push_back(actor);
462   }
463 }
464 void EngineImpl::empty_trash()
465 {
466   while (not actors_to_destroy_.empty()) {
467     actor::ActorImpl* actor = &actors_to_destroy_.front();
468     actors_to_destroy_.pop_front();
469     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
470     intrusive_ptr_release(actor);
471   }
472 }
473
474 void EngineImpl::display_all_actor_status() const
475 {
476   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
477   /*  List the actors and their state */
478   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
479   for (auto const& [_, actor] : actor_list_) {
480     if (actor->waiting_synchro_) {
481       const char* synchro_description = "unknown";
482
483       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
484         synchro_description = "execution";
485
486       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
487         synchro_description = "communication";
488
489       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
490         synchro_description = "sleeping";
491
492       if (boost::dynamic_pointer_cast<kernel::activity::SynchroImpl>(actor->waiting_synchro_) != nullptr)
493         synchro_description = "synchronization";
494
495       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
496         synchro_description = "I/O";
497
498       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %s to finish", actor->get_pid(),
499                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
500                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
501                actor->waiting_synchro_->get_cname(), actor->waiting_synchro_->get_state_str());
502     } else {
503       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
504                actor->simcall_.get_cname());
505     }
506   }
507 }
508
509 void EngineImpl::presolve() const
510 {
511   XBT_DEBUG("Consume all trace events occurring before the starting time.");
512   double next_event_date;
513   while ((next_event_date = profile::future_evt_set.next_date()) != -1.0) {
514     if (next_event_date > now_)
515       break;
516
517     double value                 = -1.0;
518     resource::Resource* resource = nullptr;
519     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
520       if (value >= 0)
521         resource->apply_event(event, value);
522     }
523   }
524
525   XBT_DEBUG("Set every models in the right state by updating them to 0.");
526   for (auto const& model : models_)
527     model->update_actions_state(now_, 0.0);
528 }
529
530 double EngineImpl::solve(double max_date) const
531 {
532   double time_delta            = -1.0; /* duration */
533   double value                 = -1.0;
534   resource::Resource* resource = nullptr;
535
536   if (max_date != -1.0) {
537     xbt_assert(max_date >= now_, "You asked to simulate up to %f, but that's in the past already", max_date);
538
539     time_delta = max_date - now_;
540   }
541
542   XBT_DEBUG("Looking for next event in all models");
543   for (auto model : models_) {
544     if (not model->next_occurring_event_is_idempotent()) {
545       continue;
546     }
547     double next_event = model->next_occurring_event(now_);
548     if ((time_delta < 0.0 || next_event < time_delta) && next_event >= 0.0) {
549       time_delta = next_event;
550     }
551   }
552
553   XBT_DEBUG("Min for resources (remember that NS3 don't update that value): %f", time_delta);
554
555   XBT_DEBUG("Looking for next trace event");
556
557   while (true) { // Handle next occurring events until none remains
558     double next_event_date = profile::future_evt_set.next_date();
559     XBT_DEBUG("Next TRACE event: %f", next_event_date);
560
561     for (auto model : models_) {
562       /* Skip all idempotent models, they were already treated above
563        * NS3 is the one to handled here */
564       if (model->next_occurring_event_is_idempotent())
565         continue;
566
567       if (next_event_date != -1.0) {
568         time_delta = std::min(next_event_date - now_, time_delta);
569       } else {
570         time_delta = std::max(next_event_date - now_, time_delta); // Get the positive component
571       }
572
573       XBT_DEBUG("Run the NS3 network at most %fs", time_delta);
574       // run until min or next flow
575       double model_next_action_end = model->next_occurring_event(time_delta);
576
577       XBT_DEBUG("Min for network : %f", model_next_action_end);
578       if (model_next_action_end >= 0.0)
579         time_delta = model_next_action_end;
580     }
581
582     if (next_event_date < 0.0 || (next_event_date > now_ + time_delta)) {
583       // next event may have already occurred or will after the next resource change, then bail out
584       XBT_DEBUG("no next usable TRACE event. Stop searching for it");
585       break;
586     }
587
588     XBT_DEBUG("Updating models (min = %g, NOW = %g, next_event_date = %g)", time_delta, now_, next_event_date);
589
590     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
591       if (resource->is_used() || (watched_hosts().find(resource->get_cname()) != watched_hosts().end())) {
592         time_delta = next_event_date - now_;
593         XBT_DEBUG("This event invalidates the next_occurring_event() computation of models. Next event set to %f",
594                   time_delta);
595       }
596       // FIXME: I'm too lame to update now_ live, so I change it and restore it so that the real update with surf_min
597       // will work
598       double round_start = now_;
599       now_               = next_event_date;
600       /* update state of the corresponding resource to the new value. Does not touch lmm.
601          It will be modified if needed when updating actions */
602       XBT_DEBUG("Calling update_resource_state for resource %s", resource->get_cname());
603       resource->apply_event(event, value);
604       now_ = round_start;
605     }
606   }
607
608   /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are
609    * with availability = 0. This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a
610    * trace with periodicity > 0.
611    * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed
612    */
613   if (time_delta < 0) {
614     XBT_DEBUG("No next event at all. Bail out now.");
615     return -1.0;
616   }
617
618   XBT_DEBUG("Duration set to %f", time_delta);
619
620   // Bump the time: jump into the future
621   now_ += time_delta;
622
623   // Inform the models of the date change
624   for (auto const& model : models_)
625     model->update_actions_state(now_, time_delta);
626
627   s4u::Engine::on_time_advance(time_delta);
628
629   return time_delta;
630 }
631
632 void EngineImpl::run(double max_date)
633 {
634   seal_platform();
635
636   if (MC_is_active()) {
637 #if SIMGRID_HAVE_MC
638     mc::AppSide::get()->main_loop();
639 #else
640     xbt_die("MC_is_active() is not supposed to return true in non-MC settings");
641 #endif
642     THROW_IMPOSSIBLE; // main_loop never returns
643   }
644
645   if (MC_record_replay_is_active()) {
646     mc::RecordTrace::replay(MC_record_path());
647     empty_trash();
648     return;
649   }
650
651   double elapsed_time = -1;
652   const std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
653
654   do {
655     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
656
657     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
658       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
659       cfg_breakpoint = -1.0; // Let the simulation continue without hiting the breakpoint again and again
660 #ifdef SIGTRAP
661       std::raise(SIGTRAP);
662 #else
663       std::raise(SIGABRT);
664 #endif
665     }
666
667     while (not actors_to_run_.empty()) {
668       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
669
670       /* Run all actors that are ready to run, possibly in parallel */
671       run_all_actors();
672
673       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round.
674        * The order must be fixed for the simulation to be reproducible (see RR-7653). It's OK here because only maestro
675        * changes the list. Killer actors are moved to the end to let victims finish their simcall before dying, but
676        * the order remains reproducible (even if arbitrarily). No need to sort the vector for sake of reproducibility.
677        */
678       for (auto const& actor : actors_that_ran_)
679         if (actor->simcall_.call_ != actor::Simcall::Type::NONE)
680           actor->simcall_handle(0);
681
682       handle_ended_actions();
683
684       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
685       if (actor_list_.size() == daemons_.size())
686         for (auto const& dmon : daemons_) {
687           XBT_DEBUG("Kill %s", dmon->get_cname());
688           maestro_->kill(dmon);
689         }
690     }
691
692     // Compute the max_date of the next solve.
693     // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
694     double next_time = timer::Timer::next();
695     if (next_time < 0 && max_date > -1) {
696       next_time = max_date;
697     } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
698       next_time = std::min(next_time, max_date);
699     }
700
701     XBT_DEBUG("Calling solve(%g) %g", next_time, now_);
702     elapsed_time = solve(next_time);
703     XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", now_, elapsed_time);
704
705     // Execute timers until there isn't anything to be done:
706     bool again = false;
707     do {
708       again = timer::Timer::execute_all();
709       handle_ended_actions();
710     } while (again);
711
712     /* Clean actors to destroy */
713     empty_trash();
714
715     XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
716               actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
717
718     if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
719       if (actor_list_.size() <= daemons_.size()) {
720         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
721                      "once the simulation is over. Please fix your on_exit() functions.");
722       } else {
723         XBT_CRITICAL("Oops! Deadlock detected, some activities are still around but will never complete. "
724                      "This usually happens when the user code is not perfectly clean.");
725       }
726       display_all_actor_status();
727       simgrid::s4u::Engine::on_deadlock();
728       for (auto const& [_, actor] : actor_list_) {
729         XBT_DEBUG("Kill %s", actor->get_cname());
730         maestro_->kill(actor);
731       }
732     }
733   } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
734            ((elapsed_time > -1.0 && not double_equals(max_date, now_, 0.00001)) || has_actors_to_run()));
735
736   if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
737     THROW_IMPOSSIBLE;
738
739   simgrid::s4u::Engine::on_simulation_end();
740 }
741
742 double EngineImpl::get_clock()
743 {
744   return now_;
745 }
746 } // namespace kernel
747 } // namespace simgrid