Logo AND Algorithmique Numérique Distribuée

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