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