Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6afc6430b812bdb566154c338a57daa9e32fa393
[simgrid.git] / src / simix / smx_global.cpp
1 /* Copyright (c) 2007-2021. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "mc/mc.h"
7 #include "simgrid/kernel/Timer.hpp"
8 #include "simgrid/s4u/Engine.hpp"
9 #include "simgrid/s4u/Host.hpp"
10 #include "src/smpi/include/smpi_actor.hpp"
11
12 #include "simgrid/sg_config.hpp"
13 #include "src/kernel/EngineImpl.hpp"
14 #include "src/kernel/activity/ExecImpl.hpp"
15 #include "src/kernel/activity/IoImpl.hpp"
16 #include "src/kernel/activity/MailboxImpl.hpp"
17 #include "src/kernel/activity/SleepImpl.hpp"
18 #include "src/kernel/activity/SynchroRaw.hpp"
19 #include "src/mc/mc_record.hpp"
20 #include "src/mc/mc_replay.hpp"
21 #include "src/simix/smx_private.hpp"
22 #include "src/surf/xml/platf.hpp"
23
24 #include "simgrid/kernel/resource/Model.hpp"
25
26 #if SIMGRID_HAVE_MC
27 #include "src/mc/remote/AppSide.hpp"
28 #endif
29
30 #include <memory>
31
32 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
33 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_kernel, simix, "Logging specific to SIMIX (kernel)");
34
35 std::unique_ptr<simgrid::simix::Global> simix_global;
36
37 void (*SMPI_switch_data_segment)(simgrid::s4u::ActorPtr) = nullptr;
38
39 namespace simgrid {
40 namespace simix {
41 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
42
43 xbt_dynar_t simix_global_get_actors_addr()
44 {
45 #if SIMGRID_HAVE_MC
46   return simix_global->actors_vector;
47 #else
48   xbt_die("This function is intended to be used when compiling with MC");
49 #endif
50 }
51 xbt_dynar_t simix_global_get_dead_actors_addr()
52 {
53 #if SIMGRID_HAVE_MC
54   return simix_global->dead_actors_vector;
55 #else
56   xbt_die("This function is intended to be used when compiling with MC");
57 #endif
58 }
59
60 } // namespace simix
61 } // namespace simgrid
62
63 XBT_ATTRIB_NORETURN static void inthandler(int)
64 {
65   if (simgrid::simix::cfg_verbose_exit) {
66     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
67              "'debug/verbose-exit').");
68     simix_global->display_all_actor_status();
69   } else {
70     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
71   }
72   exit(1);
73 }
74
75 #ifndef _WIN32
76 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
77 {
78   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
79     fprintf(stderr,
80             "Access violation or Bus error detected.\n"
81             "This probably comes from a programming error in your code, or from a stack\n"
82             "overflow. If you are certain of your code, try increasing the stack size\n"
83             "   --cfg=contexts/stack-size=XXX (current size is %u KiB).\n"
84             "\n"
85             "If it does not help, this may have one of the following causes:\n"
86             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
87             "Failing hardware can sometimes generate such errors too.\n"
88             "\n"
89             "If you think you've found a bug in SimGrid, please report it along with a\n"
90             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
91             "of the fault captured with gdb or valgrind.\n",
92             smx_context_stack_size / 1024);
93   } else if (siginfo->si_signo == SIGSEGV) {
94     fprintf(stderr, "Segmentation fault.\n");
95 #if HAVE_SMPI
96     if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
97 #if HAVE_PRIVATIZATION
98       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
99 #else
100       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
101 #endif /* HAVE_PRIVATIZATION */
102     }
103 #endif /* HAVE_SMPI */
104   }
105   std::raise(signum);
106 }
107
108 /**
109  * Install signal handler for SIGSEGV.  Check that nobody has already installed
110  * its own handler.  For example, the Java VM does this.
111  */
112 static void install_segvhandler()
113 {
114   stack_t old_stack;
115
116   if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
117     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
118     return;
119   }
120   if (not(old_stack.ss_flags & SS_DISABLE)) {
121     XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
122               old_stack.ss_size, (unsigned)old_stack.ss_flags);
123     sigaltstack(&old_stack, nullptr);
124   }
125
126   struct sigaction action;
127   struct sigaction old_action;
128   action.sa_sigaction = &segvhandler;
129   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
130   sigemptyset(&action.sa_mask);
131
132   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
133   for (int sig : {SIGSEGV, SIGBUS}) {
134     if (sigaction(sig, &action, &old_action) == -1) {
135       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
136       continue;
137     }
138     if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
139       XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
140                 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
141       sigaction(sig, &old_action, nullptr);
142     }
143   }
144 }
145
146 #endif /* _WIN32 */
147
148 /********************************* SIMIX **************************************/
149 namespace simgrid {
150 namespace simix {
151
152 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
153 bool Global::execute_tasks()
154 {
155   xbt_assert(tasksTemp.empty());
156
157   if (tasks.empty())
158     return false;
159
160   do {
161     // We don't want the callbacks to modify the vector we are iterating over:
162     tasks.swap(tasksTemp);
163
164     // Execute all the queued tasks:
165     for (auto& task : tasksTemp)
166       task();
167
168     tasksTemp.clear();
169   } while (not tasks.empty());
170
171   return true;
172 }
173
174 void Global::empty_trash()
175 {
176   while (not actors_to_destroy.empty()) {
177     kernel::actor::ActorImpl* actor = &actors_to_destroy.front();
178     actors_to_destroy.pop_front();
179     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
180     intrusive_ptr_release(actor);
181   }
182 #if SIMGRID_HAVE_MC
183   xbt_dynar_reset(dead_actors_vector);
184 #endif
185 }
186 /**
187  * @brief Executes the actors in actors_to_run.
188  *
189  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
190  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
191  * a call to this function.
192  */
193 void Global::run_all_actors()
194 {
195   simix_global->context_factory->run_all();
196
197   actors_to_run.swap(actors_that_ran);
198   actors_to_run.clear();
199 }
200
201 /** Wake up all actors waiting for a Surf action to finish */
202 void Global::wake_all_waiting_actors() const
203 {
204   for (auto const& model : simgrid::kernel::EngineImpl::get_instance()->get_all_models()) {
205     XBT_DEBUG("Handling the failed actions (if any)");
206     while (auto* action = model->extract_failed_action()) {
207       XBT_DEBUG("   Handling Action %p", action);
208       if (action->get_activity() != nullptr)
209         kernel::activity::ActivityImplPtr(action->get_activity())->post();
210     }
211     XBT_DEBUG("Handling the terminated actions (if any)");
212     while (auto* action = model->extract_done_action()) {
213       XBT_DEBUG("   Handling Action %p", action);
214       if (action->get_activity() == nullptr)
215         XBT_DEBUG("probably vcpu's action %p, skip", action);
216       else
217         kernel::activity::ActivityImplPtr(action->get_activity())->post();
218     }
219   }
220 }
221
222 void Global::display_all_actor_status() const
223 {
224   XBT_INFO("%zu actors are still running, waiting for something.", process_list.size());
225   /*  List the actors and their state */
226   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
227   for (auto const& kv : process_list) {
228     kernel::actor::ActorImpl* actor = kv.second;
229
230     if (actor->waiting_synchro_) {
231       const char* synchro_description = "unknown";
232
233       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
234         synchro_description = "execution";
235
236       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
237         synchro_description = "communication";
238
239       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
240         synchro_description = "sleeping";
241
242       if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
243         synchro_description = "synchronization";
244
245       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
246         synchro_description = "I/O";
247
248       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
249                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
250                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
251                actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
252     } else {
253       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
254                SIMIX_simcall_name(actor->simcall_));
255     }
256   }
257 }
258
259 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
260                                     "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
261 } // namespace simix
262 } // namespace simgrid
263
264 static simgrid::kernel::actor::ActorCode maestro_code;
265 void SIMIX_set_maestro(void (*code)(void*), void* data)
266 {
267 #ifdef _WIN32
268   XBT_INFO("WARNING, SIMIX_set_maestro is believed to not work on windows. Please help us investigating this issue if "
269            "you need that feature");
270 #endif
271   maestro_code = std::bind(code, data);
272 }
273
274 void SIMIX_global_init(int* argc, char** argv)
275 {
276   if (simix_global == nullptr) {
277     simix_global = std::make_unique<simgrid::simix::Global>();
278
279 #if SIMGRID_HAVE_MC
280     // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different layers.
281     // But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to read them directly.
282     simgrid::mc::AppSide::initialize();
283 #endif
284
285     surf_init(argc, argv); /* Initialize SURF structures */
286
287     simix_global->maestro_ = nullptr;
288     SIMIX_context_mod_init();
289
290     // Either create a new context with maestro or create
291     // a context object with the current context maestro):
292     simgrid::kernel::actor::create_maestro(maestro_code);
293
294     /* Prepare to display some more info when dying on Ctrl-C pressing */
295     std::signal(SIGINT, inthandler);
296
297 #ifndef _WIN32
298     install_segvhandler();
299 #endif
300     /* register a function to be called by SURF after the environment creation */
301     sg_platf_init();
302     simgrid::s4u::Engine::on_platform_created.connect(surf_presolve);
303   }
304
305   if (simgrid::config::get_value<bool>("debug/clean-atexit"))
306     atexit(SIMIX_clean);
307 }
308
309 /**
310  * @ingroup SIMIX_API
311  * @brief Clean the SIMIX simulation
312  *
313  * This functions remove the memory used by SIMIX
314  */
315 void SIMIX_clean()
316 {
317   static bool smx_cleaned = false;
318   if (smx_cleaned)
319     return; // to avoid double cleaning by java and C
320
321   smx_cleaned = true;
322   XBT_DEBUG("SIMIX_clean called. Simulation's over.");
323   if (not simix_global->actors_to_run.empty() && SIMIX_get_clock() <= 0.0) {
324     XBT_CRITICAL("   ");
325     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
326     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
327     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
328   }
329
330 #if HAVE_SMPI
331   if (not simix_global->process_list.empty()) {
332     if (smpi_process()->initialized()) {
333       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
334     } else {
335       XBT_WARN("Process called exit when leaving - Skipping cleanups");
336       return;
337     }
338   }
339 #endif
340
341   /* Kill all processes (but maestro) */
342   simix_global->maestro_->kill_all();
343   simix_global->run_all_actors();
344   simix_global->empty_trash();
345
346   /* Exit the SIMIX network module */
347   SIMIX_mailbox_exit();
348
349   while (not simgrid::kernel::timer::kernel_timers().empty()) {
350     delete simgrid::kernel::timer::kernel_timers().top().second;
351     simgrid::kernel::timer::kernel_timers().pop();
352   }
353   /* Free the remaining data structures */
354   simix_global->actors_to_run.clear();
355   simix_global->actors_that_ran.clear();
356   simix_global->actors_to_destroy.clear();
357   simix_global->process_list.clear();
358
359 #if SIMGRID_HAVE_MC
360   xbt_dynar_free(&simix_global->actors_vector);
361   xbt_dynar_free(&simix_global->dead_actors_vector);
362 #endif
363
364   /* Let's free maestro now */
365   delete simix_global->maestro_;
366   simix_global->maestro_ = nullptr;
367
368   /* Finish context module and SURF */
369   SIMIX_context_mod_exit();
370
371   surf_exit();
372
373   simix_global = nullptr;
374 }
375
376 /**
377  * @ingroup SIMIX_API
378  * @brief A clock (in second).
379  *
380  * @return Return the clock.
381  */
382 double SIMIX_get_clock()
383 {
384   if (MC_is_active() || MC_record_replay_is_active()) {
385     return MC_process_clock_get(SIMIX_process_self());
386   } else {
387     return surf_get_clock();
388   }
389 }
390
391 /**
392  * @ingroup SIMIX_API
393  * @brief Run the main simulation loop.
394  */
395 void SIMIX_run()
396 {
397   if (MC_record_replay_is_active()) {
398     simgrid::mc::replay(MC_record_path());
399     return;
400   }
401
402   double time = 0;
403
404   do {
405     XBT_DEBUG("New Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
406
407     if (simgrid::simix::cfg_breakpoint >= 0.0 && surf_get_clock() >= simgrid::simix::cfg_breakpoint) {
408       XBT_DEBUG("Breakpoint reached (%g)", simgrid::simix::cfg_breakpoint.get());
409       simgrid::simix::cfg_breakpoint = -1.0;
410 #ifdef SIGTRAP
411       std::raise(SIGTRAP);
412 #else
413       std::raise(SIGABRT);
414 #endif
415     }
416
417     simix_global->execute_tasks();
418
419     while (not simix_global->actors_to_run.empty()) {
420       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", simix_global->actors_to_run.size());
421
422       /* Run all processes that are ready to run, possibly in parallel */
423       simix_global->run_all_actors();
424
425       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
426
427       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
428
429       /* Here, the order is ok because:
430        *
431        *   Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
432        *   not impact its order.
433        *
434        *   Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
435        *
436        *   - if there is no kill during the simulation, actors remain sorted according by their PID.
437        *     Rationale: This can be proved inductively.
438        *        Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
439        *        is parsed linearly).
440        *        Let's show that it is still so at the end of this round.
441        *        - if an actor is added when being created, that's from maestro. It can be either at startup
442        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
443        *          in arbitrary order (inductive hypothesis), we are fine.
444        *        - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
445        *        - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
446        *          of a simcall terminates, we're still good. Proof:
447        *          - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
448        *            resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
449        *            as an example.
450        *          - For communications, this function is called from SIMIX_comm_finish().
451        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
452        *            The function is called:
453        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
454        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
455        *            - because the communication failed or were canceled after startup. In this case, it's called from
456        *              the function we are in, by the chunk:
457        *                       set = model->states.failed_action_set;
458        *                       while ((synchro = extract(set)))
459        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
460        *              This order is also fixed because it depends of the order in which the surf actions were
461        *              added to the system, and only maestro can add stuff this way, through simcalls.
462        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
463        *              popped out of the set does not depend on the user code's execution order.
464        *            - because the communication terminated. In this case, synchros are served in the order given by
465        *                       set = model->states.done_action_set;
466        *                       while ((synchro = extract(set)))
467        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
468        *              and the argument is very similar to the previous one.
469        *            So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
470        *            actors are executed.
471        *          So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
472        *          user actors were executed previously.
473        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
474        *   - If there is some actor killings, the order is changed by this decision that comes from user-land
475        *     But this decision may not have been motivated by a situation that were different because the simulation is
476        *     not reproducible.
477        *     So, even the order change induced by the actor killing is perfectly reproducible.
478        *
479        *   So science works, bitches [http://xkcd.com/54/].
480        *
481        *   We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
482        *   handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
483        *   unfriendly).
484        *   That would thus be a pure waste of time.
485        */
486
487       for (auto const& actor : simix_global->actors_that_ran) {
488         if (actor->simcall_.call_ != simgrid::simix::Simcall::NONE) {
489           actor->simcall_handle(0);
490         }
491       }
492
493       simix_global->execute_tasks();
494       do {
495         simix_global->wake_all_waiting_actors();
496       } while (simix_global->execute_tasks());
497
498       /* If only daemon processes remain, cancel their actions, mark them to die and reschedule them */
499       if (simix_global->process_list.size() == simix_global->daemons.size())
500         for (auto const& dmon : simix_global->daemons) {
501           XBT_DEBUG("Kill %s", dmon->get_cname());
502           simix_global->maestro_->kill(dmon);
503         }
504     }
505
506     time = simgrid::kernel::timer::Timer::next();
507     if (time > -1.0 || not simix_global->process_list.empty()) {
508       XBT_DEBUG("Calling surf_solve");
509       time = surf_solve(time);
510       XBT_DEBUG("Moving time ahead : %g", time);
511     }
512
513     /* Notify all the hosts that have failed */
514     /* FIXME: iterate through the list of failed host and mark each of them */
515     /* as failed. On each host, signal all the running processes with host_fail */
516
517     // Execute timers and tasks until there isn't anything to be done:
518     bool again = false;
519     do {
520       again = simgrid::kernel::timer::Timer::execute_all();
521       if (simix_global->execute_tasks())
522         again = true;
523       simix_global->wake_all_waiting_actors();
524     } while (again);
525
526     /* Clean actors to destroy */
527     simix_global->empty_trash();
528
529     XBT_DEBUG("### time %f, #processes %zu, #to_run %zu", time, simix_global->process_list.size(),
530               simix_global->actors_to_run.size());
531
532     if (time < 0. && simix_global->actors_to_run.empty() && not simix_global->process_list.empty()) {
533       if (simix_global->process_list.size() <= simix_global->daemons.size()) {
534         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
535                      "once the simulation is over. Please fix your on_exit() functions.");
536       } else {
537         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
538       }
539       simix_global->display_all_actor_status();
540       simgrid::s4u::Engine::on_deadlock();
541       for (auto const& kv : simix_global->process_list) {
542         XBT_DEBUG("Kill %s", kv.second->get_cname());
543         simix_global->maestro_->kill(kv.second);
544       }
545     }
546   } while (time > -1.0 || not simix_global->actors_to_run.empty());
547
548   if (not simix_global->process_list.empty())
549     THROW_IMPOSSIBLE;
550
551   simgrid::s4u::Engine::on_simulation_end();
552 }
553
554 double SIMIX_timer_next() // XBT_ATTRIB_DEPRECATED_v329
555 {
556   return simgrid::kernel::timer::Timer::next();
557 }
558
559 smx_timer_t SIMIX_timer_set(double date, void (*callback)(void*), void* arg) // XBT_ATTRIB_DEPRECATED_v329
560 {
561   return simgrid::kernel::timer::Timer::set(date, std::bind(callback, arg));
562 }
563
564 /** @brief cancels a timer that was added earlier */
565 void SIMIX_timer_remove(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
566 {
567   timer->remove();
568 }
569
570 /** @brief Returns the date at which the timer will trigger (or 0 if nullptr timer) */
571 double SIMIX_timer_get_date(smx_timer_t timer) // XBT_ATTRIB_DEPRECATED_v329
572 {
573   return timer ? timer->get_date() : 0.0;
574 }
575
576 void SIMIX_display_process_status() // XBT_ATTRIB_DEPRECATED_v329
577 {
578   simix_global->display_all_actor_status();
579 }
580
581 int SIMIX_is_maestro()
582 {
583   if (simix_global == nullptr) // SimDag
584     return true;
585   const simgrid::kernel::actor::ActorImpl* self = SIMIX_process_self();
586   return self == nullptr || self == simix_global->maestro_;
587 }