Logo AND Algorithmique Numérique Distribuée

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