Logo AND Algorithmique Numérique Distribuée

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