Logo AND Algorithmique Numérique Distribuée

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