Logo AND Algorithmique Numérique Distribuée

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