Logo AND Algorithmique Numérique Distribuée

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