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