Logo AND Algorithmique Numérique Distribuée

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