Logo AND Algorithmique Numérique Distribuée

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