Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
2295dd34d2c1697e8fb2284ec4c57ed241735463
[simgrid.git] / src / simix / ActorImpl.cpp
1 /* Copyright (c) 2007-2017. 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 <exception>
7 #include <functional>
8 #include <map>
9 #include <string>
10 #include <utility>
11
12 #include <boost/range/algorithm.hpp>
13
14 #include "xbt/ex.hpp"
15 #include "xbt/functional.hpp"
16 #include "xbt/log.h"
17 #include "xbt/sysdep.h"
18 #include "xbt/utility.hpp"
19
20 #include "simgrid/s4u/Host.hpp"
21
22 #include "mc/mc.h"
23
24 #include "smx_private.hpp"
25 #include "src/kernel/activity/SleepImpl.hpp"
26 #include "src/kernel/activity/SynchroIo.hpp"
27 #include "src/kernel/activity/SynchroRaw.hpp"
28 #include "src/mc/mc_replay.hpp"
29 #include "src/mc/remote/Client.hpp"
30 #include "src/msg/msg_private.hpp"
31 #include "src/surf/cpu_interface.hpp"
32 #include "src/surf/surf_interface.hpp"
33
34 #ifdef HAVE_SMPI
35 #include "src/smpi/include/private.hpp"
36 #endif
37
38 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
39
40 unsigned long simix_process_maxpid = 0;
41
42 /**
43  * \brief Returns the current agent.
44  *
45  * This functions returns the currently running SIMIX process.
46  *
47  * \return The SIMIX process
48  */
49 smx_actor_t SIMIX_process_self()
50 {
51   smx_context_t self_context = SIMIX_context_self();
52
53   return (self_context != nullptr) ? self_context->process() : nullptr;
54 }
55
56 /**
57  * \brief Returns whether a process has pending asynchronous communications.
58  * \return true if there are asynchronous communications in this process
59  */
60 int SIMIX_process_has_pending_comms(smx_actor_t process) {
61
62   return process->comms.size() > 0;
63 }
64
65 /**
66  * \brief Moves a process to the list of processes to destroy.
67  */
68 void SIMIX_process_cleanup(smx_actor_t process)
69 {
70   XBT_DEBUG("Cleanup process %s (%p), waiting synchro %p", process->name.c_str(), process,
71             process->waiting_synchro.get());
72
73   process->finished = true;
74   SIMIX_process_on_exit_runall(process);
75
76   /* Unregister from the kill timer if any */
77   if (process->kill_timer != nullptr) {
78     SIMIX_timer_remove(process->kill_timer);
79     process->kill_timer = nullptr;
80   }
81
82   xbt_os_mutex_acquire(simix_global->mutex);
83
84   /* cancel non-blocking communications */
85   while (not process->comms.empty()) {
86     smx_activity_t synchro = process->comms.front();
87     process->comms.pop_front();
88     simgrid::kernel::activity::CommImplPtr comm =
89         boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
90
91     /* make sure no one will finish the comm after this process is destroyed,
92      * because src_proc or dst_proc would be an invalid pointer */
93
94     if (comm->src_proc == process) {
95       XBT_DEBUG("Found an unfinished send comm %p (detached = %d), state %d, src = %p, dst = %p", comm.get(),
96                 comm->detached, (int)comm->state, comm->src_proc, comm->dst_proc);
97       comm->src_proc = nullptr;
98
99     } else if (comm->dst_proc == process) {
100       XBT_DEBUG("Found an unfinished recv comm %p, state %d, src = %p, dst = %p", comm.get(), (int)comm->state,
101                 comm->src_proc, comm->dst_proc);
102       comm->dst_proc = nullptr;
103
104       if (comm->detached && comm->src_proc != nullptr) {
105         /* the comm will be freed right now, remove it from the sender */
106         comm->src_proc->comms.remove(comm);
107       }
108     } else {
109       xbt_die("Communication synchro %p is in my list but I'm not the sender nor the receiver", synchro.get());
110     }
111     comm->cancel();
112   }
113
114   XBT_DEBUG("%p should not be run anymore",process);
115   simix_global->process_list.erase(process->pid);
116   if (process->host && process->host_process_list_hook.is_linked())
117     simgrid::xbt::intrusive_erase(process->host->extension<simgrid::simix::Host>()->process_list, *process);
118   xbt_swag_insert(process, simix_global->process_to_destroy);
119   process->context->iwannadie = 0;
120
121   xbt_os_mutex_release(simix_global->mutex);
122 }
123
124 /**
125  * Garbage collection
126  *
127  * Should be called some time to time to free the memory allocated for processes that have finished (or killed).
128  */
129 void SIMIX_process_empty_trash()
130 {
131   smx_actor_t process = static_cast<smx_actor_t>(xbt_swag_extract(simix_global->process_to_destroy));
132
133   while (process) {
134     XBT_DEBUG("Getting rid of %p",process);
135     intrusive_ptr_release(process);
136     process = static_cast<smx_actor_t>(xbt_swag_extract(simix_global->process_to_destroy));
137   }
138 }
139
140 namespace simgrid {
141 namespace simix {
142
143 ActorImpl::~ActorImpl()
144 {
145   delete this->context;
146 }
147
148 static int dying_daemon(void* exit_status, void* data)
149 {
150   std::vector<ActorImpl*>* vect = &simix_global->daemons;
151
152   auto it = std::find(vect->begin(), vect->end(), static_cast<ActorImpl*>(data));
153   xbt_assert(it != vect->end(), "The dying daemon is not a daemon after all. Please report that bug.");
154
155   /* Don't move the whole content since we don't really care about the order */
156   std::swap(*it, vect->back());
157   vect->pop_back();
158
159   return 0;
160 }
161 /** This process will be terminated automatically when the last non-daemon process finishes */
162 void ActorImpl::daemonize()
163 {
164   if (not daemon) {
165     daemon = true;
166     simix_global->daemons.push_back(this);
167     SIMIX_process_on_exit(this, dying_daemon, this);
168   }
169 }
170
171 simgrid::s4u::Actor* ActorImpl::restart()
172 {
173   XBT_DEBUG("Restarting process %s on %s", getCname(), host->getCname());
174
175   // retrieve the arguments of the old process
176   // FIXME: Factorize this with SIMIX_host_add_auto_restart_process ?
177   simgrid::simix::ProcessArg arg;
178   arg.name         = name;
179   arg.code         = code;
180   arg.host         = host;
181   arg.kill_time    = SIMIX_timer_get_date(kill_timer);
182   arg.data         = userdata;
183   arg.properties   = nullptr;
184   arg.auto_restart = auto_restart;
185
186   // kill the old process
187   SIMIX_process_kill(this, (this == simix_global->maestro_process) ? this : SIMIX_process_self());
188
189   // start the new process
190   ActorImpl* actor = simix_global->create_process_function(arg.name.c_str(), std::move(arg.code), arg.data, arg.host,
191                                                            arg.properties.get(), nullptr);
192   if (arg.kill_time >= 0)
193     simcall_process_set_kill_time(actor, arg.kill_time);
194   if (arg.auto_restart)
195     actor->auto_restart = arg.auto_restart;
196
197   return actor->ciface();
198 }
199
200 smx_activity_t ActorImpl::suspend(ActorImpl* issuer)
201 {
202   if (suspended) {
203     XBT_DEBUG("Actor '%s' is already suspended", name.c_str());
204     return nullptr;
205   }
206
207   suspended = 1;
208
209   /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
210   if (this != issuer) {
211     if (waiting_synchro)
212       waiting_synchro->suspend();
213     /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
214
215     return nullptr;
216   } else {
217     return SIMIX_execution_start(this, "suspend", 0.0, 1.0, 0.0);
218   }
219 }
220
221 void ActorImpl::resume()
222 {
223   XBT_IN("process = %p", this);
224
225   if (context->iwannadie) {
226     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
227     return;
228   }
229
230   if (not suspended)
231     return;
232   suspended = 0;
233
234   /* resume the synchronization that was blocking the resumed actor. */
235   if (waiting_synchro)
236     waiting_synchro->resume();
237
238   XBT_OUT();
239 }
240
241 smx_activity_t ActorImpl::sleep(double duration)
242 {
243   if (host->isOff())
244     THROWF(host_error, 0, "Host %s failed, you cannot sleep there.", host->getCname());
245
246   simgrid::kernel::activity::SleepImpl* synchro = new simgrid::kernel::activity::SleepImpl();
247   synchro->host                                 = host;
248   synchro->surf_sleep                           = host->pimpl_cpu->sleep(duration);
249   synchro->surf_sleep->setData(synchro);
250   XBT_DEBUG("Create sleep synchronization %p", synchro);
251
252   return synchro;
253 }
254
255 void create_maestro(std::function<void()> code)
256 {
257   smx_actor_t maestro = nullptr;
258   /* Create maestro process and initialize it */
259   maestro = new simgrid::simix::ActorImpl();
260   maestro->pid = simix_process_maxpid++;
261   maestro->name = "";
262   maestro->userdata = nullptr;
263
264   if (not code) {
265     maestro->context = SIMIX_context_new(std::function<void()>(), nullptr, maestro);
266   } else {
267     if (not simix_global)
268       xbt_die("simix is not initialized, please call MSG_init first");
269     maestro->context = simix_global->context_factory->create_maestro(code, maestro);
270   }
271
272   maestro->simcall.issuer = maestro;
273   simix_global->maestro_process = maestro;
274 }
275
276 }
277 }
278
279 /** @brief Creates and runs the maestro process */
280 void SIMIX_maestro_create(void (*code)(void*), void* data)
281 {
282   simgrid::simix::create_maestro(std::bind(code, data));
283 }
284
285 /**
286  * \brief Internal function to create a process.
287  *
288  * This function actually creates the process.
289  * It may be called when a SIMCALL_PROCESS_CREATE simcall occurs,
290  * or directly for SIMIX internal purposes. The sure thing is that it's called from maestro context.
291  *
292  * \return the process created
293  */
294 smx_actor_t SIMIX_process_create(const char* name, std::function<void()> code, void* data, simgrid::s4u::Host* host,
295                                  std::map<std::string, std::string>* properties, smx_actor_t parent_process)
296 {
297
298   XBT_DEBUG("Start process %s on host '%s'", name, host->getCname());
299
300   if (host->isOff()) {
301     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, host->getCname());
302     return nullptr;
303   }
304
305   smx_actor_t process = new simgrid::simix::ActorImpl();
306
307   xbt_assert(code && host != nullptr, "Invalid parameters");
308   /* Process data */
309   process->pid            = simix_process_maxpid++;
310   process->name           = simgrid::xbt::string(name);
311   process->host           = host;
312   process->userdata       = data;
313   process->simcall.issuer = process;
314
315   if (parent_process != nullptr) {
316     process->ppid = parent_process->pid;
317 /* SMPI process have their own data segment and each other inherit from their father */
318 #if HAVE_SMPI
319     if (smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) {
320       if (parent_process->pid != 0) {
321         process->segment_index = parent_process->segment_index;
322       } else {
323         process->segment_index = process->pid - 1;
324       }
325     }
326 #endif
327   }
328
329   process->code         = code;
330
331   XBT_VERB("Create context %s", process->name.c_str());
332   process->context = SIMIX_context_new(std::move(code), simix_global->cleanup_process_function, process);
333
334   /* Add properties */
335   if (properties != nullptr)
336     for (auto const& kv : *properties)
337       process->setProperty(kv.first, kv.second);
338
339   /* Make sure that the process is initialized for simix, in case we are called from the Host::onCreation signal */
340   if (host->extension<simgrid::simix::Host>() == nullptr)
341     host->extension_set<simgrid::simix::Host>(new simgrid::simix::Host());
342
343   /* Add the process to its host process list */
344   host->extension<simgrid::simix::Host>()->process_list.push_back(*process);
345
346   XBT_DEBUG("Start context '%s'", process->name.c_str());
347
348   /* Now insert it in the global process list and in the process to run list */
349   simix_global->process_list[process->pid] = process;
350   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->getCname(), host->getCname());
351   simix_global->process_to_run.push_back(process);
352   intrusive_ptr_add_ref(process);
353
354   /* Tracing the process creation */
355   TRACE_msg_process_create(process->getName(), process->pid, process->host);
356
357   return process;
358 }
359
360 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
361                                  std::map<std::string, std::string>* properties, smx_actor_t parent_process)
362 {
363   // This is mostly a copy/paste from SIMIX_process_new(),
364   // it'd be nice to share some code between those two functions.
365
366   sg_host_t host = sg_host_by_name(hostname);
367   XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
368
369   if (host->isOff()) {
370     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, hostname);
371     return nullptr;
372   }
373
374   smx_actor_t process = new simgrid::simix::ActorImpl();
375   /* Process data */
376   process->pid = simix_process_maxpid++;
377   process->name = std::string(name);
378   process->host = host;
379   process->userdata       = data;
380   process->simcall.issuer = process;
381
382   if (parent_process != nullptr) {
383     process->ppid = parent_process->pid;
384     /* SMPI process have their own data segment and each other inherit from their father */
385 #if HAVE_SMPI
386     if (smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) {
387       if (parent_process->pid != 0) {
388         process->segment_index = parent_process->segment_index;
389       } else {
390         process->segment_index = process->pid - 1;
391       }
392     }
393 #endif
394   }
395
396   /* Process data for auto-restart */
397   process->code = nullptr;
398
399   XBT_VERB("Create context %s", process->name.c_str());
400   if (not simix_global)
401     xbt_die("simix is not initialized, please call MSG_init first");
402   process->context = simix_global->context_factory->attach(simix_global->cleanup_process_function, process);
403
404   /* Add properties */
405   if (properties != nullptr)
406     for (auto const& kv : *properties)
407       process->setProperty(kv.first, kv.second);
408
409   /* Add the process to it's host process list */
410   host->extension<simgrid::simix::Host>()->process_list.push_back(*process);
411
412   /* Now insert it in the global process list and in the process to run list */
413   simix_global->process_list[process->pid] = process;
414   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->getCname(), host->getCname());
415   simix_global->process_to_run.push_back(process);
416
417   /* Tracing the process creation */
418   TRACE_msg_process_create(process->getName(), process->pid, process->host);
419
420   auto context = dynamic_cast<simgrid::kernel::context::AttachContext*>(process->context);
421   if (not context)
422     xbt_die("Not a suitable context");
423
424   context->attach_start();
425   return process;
426 }
427
428 void SIMIX_process_detach()
429 {
430   auto context = dynamic_cast<simgrid::kernel::context::AttachContext*>(SIMIX_context_self());
431   if (not context)
432     xbt_die("Not a suitable context");
433
434   auto process = context->process();
435   simix_global->cleanup_process_function(process);
436   context->attach_stop();
437   delete process;
438 }
439
440 /**
441  * \brief Executes the processes from simix_global->process_to_run.
442  *
443  * The processes of simix_global->process_to_run are run (in parallel if
444  * possible).  On exit, simix_global->process_to_run is empty, and
445  * simix_global->process_that_ran contains the list of processes that just ran.
446  * The two lists are swapped so, be careful when using them before and after a
447  * call to this function.
448  */
449 void SIMIX_process_runall()
450 {
451   SIMIX_context_runall();
452
453   simix_global->process_to_run.swap(simix_global->process_that_ran);
454   simix_global->process_to_run.clear();
455 }
456
457 /**
458  * \brief Internal function to kill a SIMIX process.
459  *
460  * This function may be called when a SIMCALL_PROCESS_KILL simcall occurs,
461  * or directly for SIMIX internal purposes.
462  *
463  * \param process poor victim
464  * \param issuer the process which has sent the PROCESS_KILL. Important to not schedule twice the same process.
465  */
466 void SIMIX_process_kill(smx_actor_t process, smx_actor_t issuer) {
467
468   if (process->finished) {
469     XBT_DEBUG("Ignoring request to kill process %s@%s that is already dead", process->getCname(),
470               process->host->getCname());
471     return;
472   }
473
474   XBT_DEBUG("Killing process %s@%s", process->getCname(), process->host->getCname());
475
476   process->context->iwannadie = 1;
477   process->blocked = 0;
478   process->suspended = 0;
479   process->exception = nullptr;
480
481   /* destroy the blocking synchro if any */
482   if (process->waiting_synchro != nullptr) {
483
484     simgrid::kernel::activity::ExecImplPtr exec =
485         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
486     simgrid::kernel::activity::CommImplPtr comm =
487         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
488     simgrid::kernel::activity::SleepImplPtr sleep =
489         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
490     simgrid::kernel::activity::RawImplPtr raw =
491         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
492     simgrid::kernel::activity::IoImplPtr io =
493         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
494
495     if (exec != nullptr) {
496       /* Nothing to do */
497     } else if (comm != nullptr) {
498       process->comms.remove(process->waiting_synchro);
499       comm->cancel();
500       // Remove first occurrence of &process->simcall:
501       auto i = boost::range::find(process->waiting_synchro->simcalls, &process->simcall);
502       if (i != process->waiting_synchro->simcalls.end())
503         process->waiting_synchro->simcalls.remove(&process->simcall);
504     } else if (sleep != nullptr) {
505       SIMIX_process_sleep_destroy(process->waiting_synchro);
506
507     } else if (raw != nullptr) {
508       SIMIX_synchro_stop_waiting(process, &process->simcall);
509
510     } else if (io != nullptr) {
511       SIMIX_io_destroy(process->waiting_synchro);
512     } else {
513       xbt_die("Unknown type of activity");
514     }
515
516     process->waiting_synchro = nullptr;
517   }
518   if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
519           end(simix_global->process_to_run) &&
520       process != issuer) {
521     XBT_DEBUG("Inserting %s in the to_run list", process->name.c_str());
522     simix_global->process_to_run.push_back(process);
523   }
524 }
525
526 /** @brief Ask another process to raise the given exception
527  *
528  * @param process The process that should raise that exception
529  * @param cat category of exception
530  * @param value value associated to the exception
531  * @param msg string information associated to the exception
532  */
533 void SIMIX_process_throw(smx_actor_t process, xbt_errcat_t cat, int value, const char *msg) {
534   SMX_EXCEPTION(process, cat, value, msg);
535
536   if (process->suspended)
537     process->resume();
538
539   /* cancel the blocking synchro if any */
540   if (process->waiting_synchro) {
541
542     simgrid::kernel::activity::ExecImplPtr exec =
543         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
544     if (exec != nullptr && exec->surf_exec)
545       exec->surf_exec->cancel();
546
547     simgrid::kernel::activity::CommImplPtr comm =
548         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
549     if (comm != nullptr) {
550       process->comms.remove(comm);
551       comm->cancel();
552     }
553
554     simgrid::kernel::activity::SleepImplPtr sleep =
555         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
556     if (sleep != nullptr) {
557       SIMIX_process_sleep_destroy(process->waiting_synchro);
558       if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
559               end(simix_global->process_to_run) &&
560           process != SIMIX_process_self()) {
561         XBT_DEBUG("Inserting %s in the to_run list", process->name.c_str());
562         simix_global->process_to_run.push_back(process);
563       }
564     }
565
566     simgrid::kernel::activity::RawImplPtr raw =
567         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
568     if (raw != nullptr) {
569       SIMIX_synchro_stop_waiting(process, &process->simcall);
570     }
571
572     simgrid::kernel::activity::IoImplPtr io =
573         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
574     if (io != nullptr) {
575       SIMIX_io_destroy(process->waiting_synchro);
576     }
577   }
578   process->waiting_synchro = nullptr;
579
580 }
581
582 void simcall_HANDLER_process_killall(smx_simcall_t simcall, int reset_pid) {
583   SIMIX_process_killall(simcall->issuer, reset_pid);
584 }
585 /**
586  * \brief Kills all running processes.
587  * \param issuer this one will not be killed
588  */
589 void SIMIX_process_killall(smx_actor_t issuer, int reset_pid)
590 {
591   for (auto const& kv : simix_global->process_list)
592     if (kv.second != issuer)
593       SIMIX_process_kill(kv.second, issuer);
594
595   if (reset_pid > 0)
596     simix_process_maxpid = reset_pid;
597 }
598
599 void SIMIX_process_change_host(smx_actor_t process, sg_host_t dest)
600 {
601   xbt_assert((process != nullptr), "Invalid parameters");
602   simgrid::xbt::intrusive_erase(process->host->extension<simgrid::simix::Host>()->process_list, *process);
603   process->host = dest;
604   dest->extension<simgrid::simix::Host>()->process_list.push_back(*process);
605 }
606
607 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t process)
608 {
609   smx_activity_t sync_suspend = process->suspend(simcall->issuer);
610
611   if (process != simcall->issuer) {
612     SIMIX_simcall_answer(simcall);
613   } else {
614     sync_suspend->simcalls.push_back(simcall);
615     process->waiting_synchro = sync_suspend;
616     process->waiting_synchro->suspend();
617   }
618   /* If we are suspending ourselves, then just do not finish the simcall now */
619 }
620
621 int SIMIX_process_get_maxpid() {
622   return simix_process_maxpid;
623 }
624
625 int SIMIX_process_count()
626 {
627   return simix_global->process_list.size();
628 }
629
630 void* SIMIX_process_self_get_data()
631 {
632   smx_actor_t self = SIMIX_process_self();
633
634   if (not self) {
635     return nullptr;
636   }
637   return self->getUserData();
638 }
639
640 void SIMIX_process_self_set_data(void *data)
641 {
642   SIMIX_process_self()->setUserData(data);
643 }
644
645
646 /* needs to be public and without simcall because it is called
647    by exceptions and logging events */
648 const char* SIMIX_process_self_get_name() {
649
650   smx_actor_t process = SIMIX_process_self();
651   if (process == nullptr || process == simix_global->maestro_process)
652     return "maestro";
653
654   return process->name.c_str();
655 }
656
657 smx_actor_t SIMIX_process_get_by_name(const char* name)
658 {
659   for (auto const& kv : simix_global->process_list)
660     if (kv.second->name == name)
661       return kv.second;
662   return nullptr;
663 }
664
665 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
666 {
667   if (process->finished) {
668     // The joined process is already finished, just wake up the issuer process right away
669     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
670     SIMIX_simcall_answer(simcall);
671     return;
672   }
673   smx_activity_t sync = SIMIX_process_join(simcall->issuer, process, timeout);
674   sync->simcalls.push_back(simcall);
675   simcall->issuer->waiting_synchro = sync;
676 }
677
678 smx_activity_t SIMIX_process_join(smx_actor_t issuer, smx_actor_t process, double timeout)
679 {
680   smx_activity_t res = issuer->sleep(timeout);
681   intrusive_ptr_add_ref(res.get());
682   SIMIX_process_on_exit(process,
683                         [](void*, void* arg) {
684                           auto sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(arg);
685                           if (sleep->surf_sleep)
686                             sleep->surf_sleep->finish(simgrid::surf::Action::State::done);
687                           intrusive_ptr_release(sleep);
688                           return 0;
689                         },
690                         res.get());
691   return res;
692 }
693
694 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
695 {
696   if (MC_is_active() || MC_record_replay_is_active()) {
697     MC_process_clock_add(simcall->issuer, duration);
698     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
699     SIMIX_simcall_answer(simcall);
700     return;
701   }
702   smx_activity_t sync = simcall->issuer->sleep(duration);
703   sync->simcalls.push_back(simcall);
704   simcall->issuer->waiting_synchro = sync;
705 }
706
707 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
708 {
709   XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
710   simgrid::kernel::activity::SleepImplPtr sleep =
711       boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
712
713   if (sleep->surf_sleep) {
714     sleep->surf_sleep->unref();
715     sleep->surf_sleep = nullptr;
716   }
717 }
718
719 /**
720  * \brief Calling this function makes the process to yield.
721  *
722  * Only the current process can call this function, giving back the control to maestro.
723  *
724  * \param self the current process
725  */
726 void SIMIX_process_yield(smx_actor_t self)
727 {
728   XBT_DEBUG("Yield actor '%s'", self->getCname());
729
730   /* Go into sleep and return control to maestro */
731   self->context->suspend();
732
733   /* Ok, maestro returned control to us */
734   XBT_DEBUG("Control returned to me: '%s'", self->name.c_str());
735
736   if (self->new_host) {
737     SIMIX_process_change_host(self, self->new_host);
738     self->new_host = nullptr;
739   }
740
741   if (self->context->iwannadie){
742     XBT_DEBUG("I wanna die!");
743     self->finished = true;
744     /* execute the on_exit functions */
745     SIMIX_process_on_exit_runall(self);
746     /* Add the process to the list of process to restart, only if the host is down */
747     if (self->auto_restart && self->host->isOff()) {
748       SIMIX_host_add_auto_restart_process(self->host, self->getCname(), self->code, self->userdata,
749                                           SIMIX_timer_get_date(self->kill_timer), self->getProperties(),
750                                           self->auto_restart);
751     }
752     XBT_DEBUG("Process %s@%s is dead", self->getCname(), self->host->getCname());
753     self->context->stop();
754   }
755
756   if (self->suspended) {
757     XBT_DEBUG("Hey! I'm suspended.");
758     xbt_assert(self->exception != nullptr, "Gasp! This exception may be lost by subsequent calls.");
759     self->suspended = 0;
760     self->suspend(self);
761   }
762
763   if (self->exception != nullptr) {
764     XBT_DEBUG("Wait, maestro left me an exception");
765     std::exception_ptr exception = std::move(self->exception);
766     self->exception = nullptr;
767     std::rethrow_exception(std::move(exception));
768   }
769
770   if(SMPI_switch_data_segment && self->segment_index != -1){
771     SMPI_switch_data_segment(self->segment_index);
772   }
773 }
774
775 /* callback: termination */
776 void SIMIX_process_exception_terminate(xbt_ex_t * e)
777 {
778   xbt_ex_display(e);
779   xbt_abort();
780 }
781
782 /** @brief Returns the list of processes to run. */
783 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
784 {
785   return simix_global->process_to_run;
786 }
787
788 /** @brief Returns the process from PID. */
789 smx_actor_t SIMIX_process_from_PID(aid_t PID)
790 {
791   auto process = simix_global->process_list.find(PID);
792   return process == simix_global->process_list.end() ? nullptr : process->second;
793 }
794
795 void SIMIX_process_on_exit_runall(smx_actor_t process) {
796   smx_process_exit_status_t exit_status = (process->context->iwannadie) ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
797   while (not process->on_exit.empty()) {
798     s_smx_process_exit_fun_t exit_fun = process->on_exit.back();
799     process->on_exit.pop_back();
800     (exit_fun.fun)((void*)exit_status, exit_fun.arg);
801   }
802 }
803
804 void SIMIX_process_on_exit(smx_actor_t process, int_f_pvoid_pvoid_t fun, void *data) {
805   xbt_assert(process, "current process not found: are you in maestro context ?");
806
807   s_smx_process_exit_fun_t exit_fun = {fun, data};
808
809   process->on_exit.push_back(exit_fun);
810 }
811
812 /**
813  * \brief Sets the auto-restart status of the process.
814  * If set to 1, the process will be automatically restarted when its host comes back.
815  */
816 void SIMIX_process_auto_restart_set(smx_actor_t process, int auto_restart) {
817   process->auto_restart = auto_restart;
818 }
819
820 /** @brief Restart a process, starting it again from the beginning. */
821 /**
822  * \ingroup simix_process_management
823  * \brief Creates and runs a new SIMIX process.
824  *
825  * The structure and the corresponding thread are created and put in the list of ready processes.
826  *
827  * \param name a name for the process. It is for user-level information and can be nullptr.
828  * \param code the main function of the process
829  * \param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
830  * be nullptr.
831  * It can be retrieved with the function \ref simcall_process_get_data.
832  * \param host where the new agent is executed.
833  * \param kill_time time when the process is killed
834  * \param argc first argument passed to \a code
835  * \param argv second argument passed to \a code
836  * \param properties the properties of the process
837  * \param auto_restart either it is autorestarting or not.
838  */
839 extern "C" smx_actor_t simcall_process_create(const char* name, xbt_main_func_t code, void* data, sg_host_t host,
840                                               int argc, char** argv, std::map<std::string, std::string>* properties)
841 {
842   if (name == nullptr)
843     name = "";
844   auto wrapped_code = simgrid::xbt::wrapMain(code, argc, argv);
845   for (int i = 0; i != argc; ++i)
846     xbt_free(argv[i]);
847   xbt_free(argv);
848   smx_actor_t res = simcall_process_create(name, std::move(wrapped_code), data, host, properties);
849   return res;
850 }
851
852 smx_actor_t simcall_process_create(const char* name, std::function<void()> code, void* data, sg_host_t host,
853                                    std::map<std::string, std::string>* properties)
854 {
855   if (name == nullptr)
856     name = "";
857   smx_actor_t self = SIMIX_process_self();
858   return simgrid::simix::kernelImmediate([name, code, data, host, properties, self] {
859     return SIMIX_process_create(name, std::move(code), data, host, properties, self);
860   });
861 }