Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
please emptty
[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 <string>
9 #include <utility>
10
11 #include <boost/range/algorithm.hpp>
12
13 #include "xbt/dict.h"
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.h"
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.h"
28 #include "src/mc/remote/Client.hpp"
29 #include "src/msg/msg_private.h"
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
79   xbt_os_mutex_acquire(simix_global->mutex);
80
81   /* cancel non-blocking communications */
82   smx_activity_t synchro = process->comms.front();
83   while (not process->comms.empty()) {
84     simgrid::kernel::activity::CommImplPtr comm =
85         boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
86
87     /* make sure no one will finish the comm after this process is destroyed,
88      * because src_proc or dst_proc would be an invalid pointer */
89
90     if (comm->src_proc == process) {
91       XBT_DEBUG("Found an unfinished send comm %p (detached = %d), state %d, src = %p, dst = %p", comm.get(),
92                 comm->detached, (int)comm->state, comm->src_proc, comm->dst_proc);
93       comm->src_proc = nullptr;
94
95     } else if (comm->dst_proc == process) {
96       XBT_DEBUG("Found an unfinished recv comm %p, state %d, src = %p, dst = %p", comm.get(), (int)comm->state,
97                 comm->src_proc, comm->dst_proc);
98       comm->dst_proc = nullptr;
99
100       if (comm->detached && comm->src_proc != nullptr) {
101         /* the comm will be freed right now, remove it from the sender */
102         comm->src_proc->comms.remove(comm);
103       }
104     } else {
105       xbt_die("Communication synchro %p is in my list but I'm not the sender nor the receiver", synchro.get());
106     }
107     process->comms.pop_front();
108     synchro = process->comms.front();
109     comm->cancel();
110   }
111
112   XBT_DEBUG("%p should not be run anymore",process);
113   simix_global->process_list.erase(process->pid);
114   if (process->host)
115     xbt_swag_remove(process, process->host->extension<simgrid::simix::Host>()->process_list);
116   xbt_swag_insert(process, simix_global->process_to_destroy);
117   process->context->iwannadie = 0;
118
119   xbt_os_mutex_release(simix_global->mutex);
120 }
121
122 /**
123  * Garbage collection
124  *
125  * Should be called some time to time to free the memory allocated for processes that have finished (or killed).
126  */
127 void SIMIX_process_empty_trash()
128 {
129   smx_actor_t process = static_cast<smx_actor_t>(xbt_swag_extract(simix_global->process_to_destroy));
130
131   while (process) {
132     XBT_DEBUG("Getting rid of %p",process);
133     intrusive_ptr_release(process);
134     process = static_cast<smx_actor_t>(xbt_swag_extract(simix_global->process_to_destroy));
135   }
136 }
137
138 namespace simgrid {
139 namespace simix {
140
141 ActorImpl::~ActorImpl()
142 {
143   delete this->context;
144   xbt_dict_free(&this->properties);
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", cname(), 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, 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                                  xbt_dict_t 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   process->properties = properties;
335
336   /* Make sure that the process is initialized for simix, in case we are called from the Host::onCreation signal */
337   if (host->extension<simgrid::simix::Host>() == nullptr)
338     host->extension_set<simgrid::simix::Host>(new simgrid::simix::Host());
339
340   /* Add the process to its host process list */
341   xbt_swag_insert(process, host->extension<simgrid::simix::Host>()->process_list);
342
343   XBT_DEBUG("Start context '%s'", process->name.c_str());
344
345   /* Now insert it in the global process list and in the process to run list */
346   simix_global->process_list[process->pid] = process;
347   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->cname(), host->getCname());
348   xbt_dynar_push_as(simix_global->process_to_run, smx_actor_t, process);
349   intrusive_ptr_add_ref(process);
350
351   /* Tracing the process creation */
352   TRACE_msg_process_create(process->cname(), process->pid, process->host);
353
354   return process;
355 }
356
357 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname, xbt_dict_t properties,
358                                  smx_actor_t parent_process)
359 {
360   // This is mostly a copy/paste from SIMIX_process_new(),
361   // it'd be nice to share some code between those two functions.
362
363   sg_host_t host = sg_host_by_name(hostname);
364   XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
365
366   if (host->isOff()) {
367     XBT_WARN("Cannot launch process '%s' on failed host '%s'",
368       name, hostname);
369     return nullptr;
370   }
371
372   smx_actor_t process = new simgrid::simix::ActorImpl();
373   /* Process data */
374   process->pid = simix_process_maxpid++;
375   process->name = std::string(name);
376   process->host = host;
377   process->userdata       = data;
378   process->simcall.issuer = process;
379
380   if (parent_process != nullptr) {
381     process->ppid = parent_process->pid;
382     /* SMPI process have their own data segment and each other inherit from their father */
383 #if HAVE_SMPI
384     if (smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) {
385       if (parent_process->pid != 0) {
386         process->segment_index = parent_process->segment_index;
387       } else {
388         process->segment_index = process->pid - 1;
389       }
390     }
391 #endif
392   }
393
394   /* Process data for auto-restart */
395   process->code = nullptr;
396
397   XBT_VERB("Create context %s", process->name.c_str());
398   if (not simix_global)
399     xbt_die("simix is not initialized, please call MSG_init first");
400   process->context = simix_global->context_factory->attach(simix_global->cleanup_process_function, process);
401
402   /* Add properties */
403   process->properties = properties;
404
405   /* Add the process to it's host process list */
406   xbt_swag_insert(process, host->extension<simgrid::simix::Host>()->process_list);
407
408   /* Now insert it in the global process list and in the process to run list */
409   simix_global->process_list[process->pid] = process;
410   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->cname(), host->getCname());
411   xbt_dynar_push_as(simix_global->process_to_run, smx_actor_t, process);
412
413   /* Tracing the process creation */
414   TRACE_msg_process_create(process->cname(), process->pid, process->host);
415
416   auto context = dynamic_cast<simgrid::kernel::context::AttachContext*>(process->context);
417   if (not context)
418     xbt_die("Not a suitable context");
419
420   context->attach_start();
421   return process;
422 }
423
424 void SIMIX_process_detach()
425 {
426   auto context = dynamic_cast<simgrid::kernel::context::AttachContext*>(SIMIX_context_self());
427   if (not context)
428     xbt_die("Not a suitable context");
429
430   simix_global->cleanup_process_function(context->process());
431
432   // Let maestro ignore we are still alive:
433   // xbt_swag_remove(context->process(), simix_global->process_list);
434
435   // TODO, Remove from proces list:
436   //   xbt_swag_remove(process, sg_host_simix(host)->process_list);
437
438   context->attach_stop();
439   // delete context;
440 }
441
442 /**
443  * \brief Executes the processes from simix_global->process_to_run.
444  *
445  * The processes of simix_global->process_to_run are run (in parallel if
446  * possible).  On exit, simix_global->process_to_run is empty, and
447  * simix_global->process_that_ran contains the list of processes that just ran.
448  * The two lists are swapped so, be careful when using them before and after a
449  * call to this function.
450  */
451 void SIMIX_process_runall()
452 {
453   SIMIX_context_runall();
454
455   xbt_dynar_t tmp = simix_global->process_that_ran;
456   simix_global->process_that_ran = simix_global->process_to_run;
457   simix_global->process_to_run = tmp;
458   xbt_dynar_reset(simix_global->process_to_run);
459 }
460
461 void simcall_HANDLER_process_kill(smx_simcall_t simcall, smx_actor_t process) {
462   SIMIX_process_kill(process, simcall->issuer);
463 }
464 /**
465  * \brief Internal function to kill a SIMIX process.
466  *
467  * This function may be called when a SIMCALL_PROCESS_KILL simcall occurs,
468  * or directly for SIMIX internal purposes.
469  *
470  * \param process poor victim
471  * \param issuer the process which has sent the PROCESS_KILL. Important to not schedule twice the same process.
472  */
473 void SIMIX_process_kill(smx_actor_t process, smx_actor_t issuer) {
474
475   XBT_DEBUG("Killing process %s@%s", process->cname(), process->host->getCname());
476
477   process->context->iwannadie = 1;
478   process->blocked = 0;
479   process->suspended = 0;
480   process->exception = nullptr;
481
482   /* destroy the blocking synchro if any */
483   if (process->waiting_synchro != nullptr) {
484
485     simgrid::kernel::activity::ExecImplPtr exec =
486         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
487     simgrid::kernel::activity::CommImplPtr comm =
488         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
489     simgrid::kernel::activity::SleepImplPtr sleep =
490         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
491     simgrid::kernel::activity::RawImplPtr raw =
492         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
493     simgrid::kernel::activity::IoImplPtr io =
494         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
495
496     if (exec != nullptr) {
497       /* Nothing to do */
498     } else if (comm != nullptr) {
499       process->comms.remove(process->waiting_synchro);
500       comm->cancel();
501       // Remove first occurrence of &process->simcall:
502       auto i = boost::range::find(process->waiting_synchro->simcalls, &process->simcall);
503       if (i != process->waiting_synchro->simcalls.end())
504         process->waiting_synchro->simcalls.remove(&process->simcall);
505     } else if (sleep != nullptr) {
506       SIMIX_process_sleep_destroy(process->waiting_synchro);
507
508     } else if (raw != nullptr) {
509       SIMIX_synchro_stop_waiting(process, &process->simcall);
510
511     } else if (io != nullptr) {
512       SIMIX_io_destroy(process->waiting_synchro);
513     } else {
514       xbt_die("Unknown type of activity");
515     }
516
517     /*
518     switch (process->waiting_synchro->type) {
519     case SIMIX_SYNC_JOIN:
520       SIMIX_process_sleep_destroy(process->waiting_synchro);
521       break;
522     } */
523
524     process->waiting_synchro = nullptr;
525   }
526   if (not xbt_dynar_member(simix_global->process_to_run, &(process)) && process != issuer) {
527     XBT_DEBUG("Inserting %s in the to_run list", process->name.c_str());
528     xbt_dynar_push_as(simix_global->process_to_run, smx_actor_t, process);
529   }
530 }
531
532 /** @brief Ask another process to raise the given exception
533  *
534  * @param process The process that should raise that exception
535  * @param cat category of exception
536  * @param value value associated to the exception
537  * @param msg string information associated to the exception
538  */
539 void SIMIX_process_throw(smx_actor_t process, xbt_errcat_t cat, int value, const char *msg) {
540   SMX_EXCEPTION(process, cat, value, msg);
541
542   if (process->suspended)
543     process->resume();
544
545   /* cancel the blocking synchro if any */
546   if (process->waiting_synchro) {
547
548     simgrid::kernel::activity::ExecImplPtr exec =
549         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
550     if (exec != nullptr) {
551       SIMIX_execution_cancel(process->waiting_synchro);
552     }
553
554     simgrid::kernel::activity::CommImplPtr comm =
555         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
556     if (comm != nullptr) {
557       process->comms.remove(comm);
558       comm->cancel();
559     }
560
561     simgrid::kernel::activity::SleepImplPtr sleep =
562         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
563     if (sleep != nullptr) {
564       SIMIX_process_sleep_destroy(process->waiting_synchro);
565       if (not xbt_dynar_member(simix_global->process_to_run, &(process)) && process != SIMIX_process_self()) {
566         XBT_DEBUG("Inserting %s in the to_run list", process->name.c_str());
567         xbt_dynar_push_as(simix_global->process_to_run, smx_actor_t, process);
568       }
569     }
570
571     simgrid::kernel::activity::RawImplPtr raw =
572         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
573     if (raw != nullptr) {
574       SIMIX_synchro_stop_waiting(process, &process->simcall);
575     }
576
577     simgrid::kernel::activity::IoImplPtr io =
578         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
579     if (io != nullptr) {
580       SIMIX_io_destroy(process->waiting_synchro);
581     }
582   }
583   process->waiting_synchro = nullptr;
584
585 }
586
587 void simcall_HANDLER_process_killall(smx_simcall_t simcall, int reset_pid) {
588   SIMIX_process_killall(simcall->issuer, reset_pid);
589 }
590 /**
591  * \brief Kills all running processes.
592  * \param issuer this one will not be killed
593  */
594 void SIMIX_process_killall(smx_actor_t issuer, int reset_pid)
595 {
596   for (auto kv : simix_global->process_list)
597     if (kv.second != issuer)
598       SIMIX_process_kill(kv.second, issuer);
599
600   if (reset_pid > 0)
601     simix_process_maxpid = reset_pid;
602
603   SIMIX_context_runall();
604
605   SIMIX_process_empty_trash();
606 }
607
608 void SIMIX_process_change_host(smx_actor_t process, sg_host_t dest)
609 {
610   xbt_assert((process != nullptr), "Invalid parameters");
611   xbt_swag_remove(process, process->host->extension<simgrid::simix::Host>()->process_list);
612   process->host = dest;
613   xbt_swag_insert(process, dest->extension<simgrid::simix::Host>()->process_list);
614 }
615
616 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t process)
617 {
618   smx_activity_t sync_suspend = process->suspend(simcall->issuer);
619
620   if (process != simcall->issuer) {
621     SIMIX_simcall_answer(simcall);
622   } else {
623     sync_suspend->simcalls.push_back(simcall);
624     process->waiting_synchro = sync_suspend;
625     process->waiting_synchro->suspend();
626   }
627   /* If we are suspending ourselves, then just do not finish the simcall now */
628 }
629
630 int SIMIX_process_get_maxpid() {
631   return simix_process_maxpid;
632 }
633
634 int SIMIX_process_count()
635 {
636   return simix_global->process_list.size();
637 }
638
639 void* SIMIX_process_self_get_data()
640 {
641   smx_actor_t self = SIMIX_process_self();
642
643   if (not self) {
644     return nullptr;
645   }
646   return self->getUserData();
647 }
648
649 void SIMIX_process_self_set_data(void *data)
650 {
651   SIMIX_process_self()->setUserData(data);
652 }
653
654
655 /* needs to be public and without simcall because it is called
656    by exceptions and logging events */
657 const char* SIMIX_process_self_get_name() {
658
659   smx_actor_t process = SIMIX_process_self();
660   if (process == nullptr || process == simix_global->maestro_process)
661     return "maestro";
662
663   return process->name.c_str();
664 }
665
666 smx_actor_t SIMIX_process_get_by_name(const char* name)
667 {
668   for (auto kv : simix_global->process_list)
669     if (kv.second->name == name)
670       return kv.second;
671   return nullptr;
672 }
673
674 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
675 {
676   if (process->finished) {
677     // The joined process is already finished, just wake up the issuer process right away
678     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
679     SIMIX_simcall_answer(simcall);
680     return;
681   }
682   smx_activity_t sync = SIMIX_process_join(simcall->issuer, process, timeout);
683   sync->simcalls.push_back(simcall);
684   simcall->issuer->waiting_synchro = sync;
685 }
686
687 static int SIMIX_process_join_finish(smx_process_exit_status_t status, void* synchro)
688 {
689   simgrid::kernel::activity::SleepImpl* sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(synchro);
690
691   if (sleep->surf_sleep) {
692     sleep->surf_sleep->cancel();
693
694     while (not sleep->simcalls.empty()) {
695       smx_simcall_t simcall = sleep->simcalls.front();
696       sleep->simcalls.pop_front();
697       simcall_process_sleep__set__result(simcall, SIMIX_DONE);
698       simcall->issuer->waiting_synchro = nullptr;
699       if (simcall->issuer->suspended) {
700         XBT_DEBUG("Wait! This process is suspended and can't wake up now.");
701         simcall->issuer->suspended = 0;
702         simcall_HANDLER_process_suspend(simcall, simcall->issuer);
703       } else {
704         SIMIX_simcall_answer(simcall);
705       }
706     }
707     sleep->surf_sleep->unref();
708     sleep->surf_sleep = nullptr;
709   }
710   // intrusive_ptr_release(process); // FIXME: We are leaking here. See comment in SIMIX_process_join()
711   return 0;
712 }
713
714 smx_activity_t SIMIX_process_join(smx_actor_t issuer, smx_actor_t process, double timeout)
715 {
716   smx_activity_t res = issuer->sleep(timeout);
717   intrusive_ptr_add_ref(res.get());
718   /* We are leaking the process here, but if we don't take the ref, we get a "use after free".
719    * The correct solution would be to derivate the type SynchroSleep into a SynchroProcessJoin,
720    * but the code is not clean enough for now for this.
721    * The C API should first be properly replaced with the C++ one, which is a fair amount of work.
722    */
723   intrusive_ptr_add_ref(process);
724   SIMIX_process_on_exit(process, (int_f_pvoid_pvoid_t)SIMIX_process_join_finish, &*res);
725   return res;
726 }
727
728 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
729 {
730   if (MC_is_active() || MC_record_replay_is_active()) {
731     MC_process_clock_add(simcall->issuer, duration);
732     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
733     SIMIX_simcall_answer(simcall);
734     return;
735   }
736   smx_activity_t sync = simcall->issuer->sleep(duration);
737   sync->simcalls.push_back(simcall);
738   simcall->issuer->waiting_synchro = sync;
739 }
740
741 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
742 {
743   XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
744   simgrid::kernel::activity::SleepImplPtr sleep =
745       boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
746
747   if (sleep->surf_sleep) {
748     sleep->surf_sleep->unref();
749     sleep->surf_sleep = nullptr;
750   }
751 }
752
753 /**
754  * \brief Calling this function makes the process to yield.
755  *
756  * Only the current process can call this function, giving back the control to maestro.
757  *
758  * \param self the current process
759  */
760 void SIMIX_process_yield(smx_actor_t self)
761 {
762   XBT_DEBUG("Yield actor '%s'", self->cname());
763
764   /* Go into sleep and return control to maestro */
765   self->context->suspend();
766
767   /* Ok, maestro returned control to us */
768   XBT_DEBUG("Control returned to me: '%s'", self->name.c_str());
769
770   if (self->new_host) {
771     SIMIX_process_change_host(self, self->new_host);
772     self->new_host = nullptr;
773   }
774
775   if (self->context->iwannadie){
776     XBT_DEBUG("I wanna die!");
777     self->finished = true;
778     /* execute the on_exit functions */
779     SIMIX_process_on_exit_runall(self);
780     /* Add the process to the list of process to restart, only if the host is down */
781     if (self->auto_restart && self->host->isOff()) {
782       SIMIX_host_add_auto_restart_process(self->host, self->cname(), self->code, self->userdata,
783                                           SIMIX_timer_get_date(self->kill_timer), self->properties, self->auto_restart);
784     }
785     XBT_DEBUG("Process %s@%s is dead", self->cname(), self->host->getCname());
786     self->context->stop();
787   }
788
789   if (self->suspended) {
790     XBT_DEBUG("Hey! I'm suspended.");
791     xbt_assert(self->exception != nullptr, "Gasp! This exception may be lost by subsequent calls.");
792     self->suspended = 0;
793     self->suspend(self);
794   }
795
796   if (self->exception != nullptr) {
797     XBT_DEBUG("Wait, maestro left me an exception");
798     std::exception_ptr exception = std::move(self->exception);
799     self->exception = nullptr;
800     std::rethrow_exception(std::move(exception));
801   }
802
803   if(SMPI_switch_data_segment && self->segment_index != -1){
804     SMPI_switch_data_segment(self->segment_index);
805   }
806 }
807
808 /* callback: termination */
809 void SIMIX_process_exception_terminate(xbt_ex_t * e)
810 {
811   xbt_ex_display(e);
812   xbt_abort();
813 }
814
815 /** @brief Returns the list of processes to run. */
816 xbt_dynar_t SIMIX_process_get_runnable()
817 {
818   return simix_global->process_to_run;
819 }
820
821 /** @brief Returns the process from PID. */
822 smx_actor_t SIMIX_process_from_PID(aid_t PID)
823 {
824   try {
825     return simix_global->process_list.at(PID);
826   } catch (std::out_of_range& unfound) {
827     return nullptr;
828   }
829 }
830
831 /** @brief returns a dynar containing all currently existing processes */
832 xbt_dynar_t SIMIX_processes_as_dynar() {
833   xbt_dynar_t res = xbt_dynar_new(sizeof(smx_actor_t),nullptr);
834   for (auto kv : simix_global->process_list) {
835     smx_actor_t proc = kv.second;
836     xbt_dynar_push(res,&proc);
837   }
838   return res;
839 }
840
841 void SIMIX_process_on_exit_runall(smx_actor_t process) {
842   smx_process_exit_status_t exit_status = (process->context->iwannadie) ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
843   while (not process->on_exit.empty()) {
844     s_smx_process_exit_fun_t exit_fun = process->on_exit.back();
845     (exit_fun.fun)((void*)exit_status, exit_fun.arg);
846     process->on_exit.pop_back();
847   }
848 }
849
850 void SIMIX_process_on_exit(smx_actor_t process, int_f_pvoid_pvoid_t fun, void *data) {
851   xbt_assert(process, "current process not found: are you in maestro context ?");
852
853   s_smx_process_exit_fun_t exit_fun = {fun, data};
854
855   process->on_exit.push_back(exit_fun);
856 }
857
858 /**
859  * \brief Sets the auto-restart status of the process.
860  * If set to 1, the process will be automatically restarted when its host comes back.
861  */
862 void SIMIX_process_auto_restart_set(smx_actor_t process, int auto_restart) {
863   process->auto_restart = auto_restart;
864 }
865
866 /** @brief Restart a process, starting it again from the beginning. */
867 /**
868  * \ingroup simix_process_management
869  * \brief Creates and runs a new SIMIX process.
870  *
871  * The structure and the corresponding thread are created and put in the list of ready processes.
872  *
873  * \param name a name for the process. It is for user-level information and can be nullptr.
874  * \param code the main function of the process
875  * \param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
876  * be nullptr.
877  * It can be retrieved with the function \ref simcall_process_get_data.
878  * \param host where the new agent is executed.
879  * \param kill_time time when the process is killed
880  * \param argc first argument passed to \a code
881  * \param argv second argument passed to \a code
882  * \param properties the properties of the process
883  * \param auto_restart either it is autorestarting or not.
884  */
885 extern "C"
886 smx_actor_t simcall_process_create(const char* name, xbt_main_func_t code, void* data, sg_host_t host, int argc,
887                                    char** argv, xbt_dict_t properties)
888 {
889   if (name == nullptr)
890     name = "";
891   auto wrapped_code = simgrid::xbt::wrapMain(code, argc, argv);
892   for (int i = 0; i != argc; ++i)
893     xbt_free(argv[i]);
894   xbt_free(argv);
895   smx_actor_t res = simcall_process_create(name, std::move(wrapped_code), data, host, properties);
896   return res;
897 }
898
899 smx_actor_t simcall_process_create(const char* name, std::function<void()> code, void* data, sg_host_t host,
900                                    xbt_dict_t properties)
901 {
902   if (name == nullptr)
903     name = "";
904   smx_actor_t self = SIMIX_process_self();
905   return simgrid::simix::kernelImmediate([name, code, data, host, properties, self] {
906     return SIMIX_process_create(name, std::move(code), data, host, properties, self);
907   });
908 }