Logo AND Algorithmique Numérique Distribuée

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