Logo AND Algorithmique Numérique Distribuée

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