Logo AND Algorithmique Numérique Distribuée

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