Logo AND Algorithmique Numérique Distribuée

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