Logo AND Algorithmique Numérique Distribuée

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