Logo AND Algorithmique Numérique Distribuée

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