Logo AND Algorithmique Numérique Distribuée

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