Logo AND Algorithmique Numérique Distribuée

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