Logo AND Algorithmique Numérique Distribuée

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