Logo AND Algorithmique Numérique Distribuée

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