Logo AND Algorithmique Numérique Distribuée

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