Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[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 "smx_private.hpp"
8 #include "src/kernel/activity/CommImpl.hpp"
9 #include "src/kernel/activity/ExecImpl.hpp"
10 #include "src/kernel/activity/IoImpl.hpp"
11 #include "src/kernel/activity/SleepImpl.hpp"
12 #include "src/kernel/activity/SynchroRaw.hpp"
13 #include "src/mc/mc_replay.hpp"
14 #include "src/mc/remote/Client.hpp"
15 #include "src/simix/smx_host_private.hpp"
16 #include "src/simix/smx_io_private.hpp"
17 #include "src/simix/smx_synchro_private.hpp"
18 #include "src/surf/HostImpl.hpp"
19 #include "src/surf/cpu_interface.hpp"
20 #include "xbt/ex.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("%p should not be run anymore",process);
105   simix_global->process_list.erase(process->pid_);
106   if (process->host_ && process->host_process_list_hook.is_linked())
107     simgrid::xbt::intrusive_erase(process->host_->pimpl_->process_list_, *process);
108   if (not process->smx_destroy_list_hook.is_linked()) {
109 #if SIMGRID_HAVE_MC
110     xbt_dynar_push_as(simix_global->dead_actors_vector, smx_actor_t, process);
111 #endif
112     simix_global->process_to_destroy.push_back(*process);
113   }
114   process->context_->iwannadie = false;
115
116   simix_global->mutex.unlock();
117 }
118
119 /**
120  * Garbage collection
121  *
122  * Should be called some time to time to free the memory allocated for processes that have finished (or killed).
123  */
124 void SIMIX_process_empty_trash()
125 {
126   while (not simix_global->process_to_destroy.empty()) {
127     smx_actor_t process = &simix_global->process_to_destroy.front();
128     simix_global->process_to_destroy.pop_front();
129     XBT_DEBUG("Getting rid of %p",process);
130     intrusive_ptr_release(process);
131   }
132 #if SIMGRID_HAVE_MC
133   xbt_dynar_reset(simix_global->dead_actors_vector);
134 #endif
135 }
136
137 namespace simgrid {
138
139 namespace kernel {
140 namespace actor {
141
142 ActorImpl::~ActorImpl()
143 {
144   delete this->context_;
145 }
146
147 static void dying_daemon(int /*exit_status*/, void* data)
148 {
149   std::vector<ActorImpl*>* vect = &simix_global->daemons;
150
151   auto it = std::find(vect->begin(), vect->end(), static_cast<ActorImpl*>(data));
152   xbt_assert(it != vect->end(), "The dying daemon is not a daemon after all. Please report that bug.");
153
154   /* Don't move the whole content since we don't really care about the order */
155   std::swap(*it, vect->back());
156   vect->pop_back();
157 }
158
159 /** This process will be terminated automatically when the last non-daemon process finishes */
160 void ActorImpl::daemonize()
161 {
162   if (not daemon_) {
163     daemon_ = true;
164     simix_global->daemons.push_back(this);
165     SIMIX_process_on_exit(this, dying_daemon, this);
166   }
167 }
168
169 simgrid::s4u::Actor* ActorImpl::restart()
170 {
171   XBT_DEBUG("Restarting process %s on %s", get_cname(), host_->get_cname());
172
173   // retrieve the arguments of the old process
174   simgrid::kernel::actor::ProcessArg arg = ProcessArg(host_, this);
175
176   // kill the old process
177   SIMIX_process_kill(this, (this == simix_global->maestro_process) ? this : SIMIX_process_self());
178
179   // start the new process
180   ActorImpl* actor = simix_global->create_process_function(arg.name.c_str(), std::move(arg.code), arg.data, arg.host,
181                                                            arg.properties.get(), nullptr);
182   simcall_process_set_kill_time(actor, arg.kill_time);
183   actor->set_auto_restart(arg.auto_restart);
184
185   return actor->ciface();
186 }
187
188 smx_activity_t ActorImpl::suspend(ActorImpl* issuer)
189 {
190   if (suspended_) {
191     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
192     return nullptr;
193   }
194
195   suspended_ = true;
196
197   /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
198   if (this != issuer) {
199     if (waiting_synchro)
200       waiting_synchro->suspend();
201     /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
202
203     return nullptr;
204   } else {
205     return SIMIX_execution_start("suspend", "", 0.0, 1.0, 0.0, this->host_);
206   }
207 }
208
209 void ActorImpl::resume()
210 {
211   XBT_IN("process = %p", this);
212
213   if (context_->iwannadie) {
214     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
215     return;
216   }
217
218   if (not suspended_)
219     return;
220   suspended_ = false;
221
222   /* resume the synchronization that was blocking the resumed actor. */
223   if (waiting_synchro)
224     waiting_synchro->resume();
225
226   XBT_OUT();
227 }
228
229 smx_activity_t ActorImpl::sleep(double duration)
230 {
231   if (host_->is_off())
232     THROWF(host_error, 0, "Host %s failed, you cannot sleep there.", host_->get_cname());
233
234   simgrid::kernel::activity::SleepImpl* synchro = new simgrid::kernel::activity::SleepImpl();
235   synchro->host                                 = host_;
236   synchro->surf_sleep                           = host_->pimpl_cpu->sleep(duration);
237   synchro->surf_sleep->set_data(synchro);
238   XBT_DEBUG("Create sleep synchronization %p", synchro);
239
240   return synchro;
241 }
242
243 void create_maestro(simgrid::simix::ActorCode code)
244 {
245   smx_actor_t maestro = nullptr;
246   /* Create maestro process and initialize it */
247   maestro           = new simgrid::kernel::actor::ActorImpl();
248   maestro->pid_     = simix_process_maxpid++;
249   maestro->name_    = "";
250   maestro->set_user_data(nullptr);
251
252   if (not code) {
253     maestro->context_ = SIMIX_context_new(simgrid::simix::ActorCode(), nullptr, maestro);
254   } else {
255     if (not simix_global)
256       xbt_die("simix is not initialized, please call MSG_init first");
257     maestro->context_ = simix_global->context_factory->create_maestro(code, maestro);
258   }
259
260   maestro->simcall.issuer = maestro;
261   simix_global->maestro_process = maestro;
262 }
263
264 } // namespace actor
265 }
266 }
267
268 /** @brief Creates and runs the maestro process */
269 void SIMIX_maestro_create(void (*code)(void*), void* data)
270 {
271   simgrid::kernel::actor::create_maestro(std::bind(code, data));
272 }
273
274 /**
275  * @brief Internal function to create a process.
276  *
277  * This function actually creates the process.
278  * It may be called when a SIMCALL_PROCESS_CREATE simcall occurs,
279  * or directly for SIMIX internal purposes. The sure thing is that it's called from maestro context.
280  *
281  * @return the process created
282  */
283 smx_actor_t SIMIX_process_create(std::string name, simgrid::simix::ActorCode code, void* data, simgrid::s4u::Host* host,
284                                  std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
285 {
286
287   XBT_DEBUG("Start process %s on host '%s'", name.c_str(), host->get_cname());
288
289   if (host->is_off()) {
290     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
291     return nullptr;
292   }
293
294   smx_actor_t process = new simgrid::kernel::actor::ActorImpl();
295
296   xbt_assert(code && host != nullptr, "Invalid parameters");
297   /* Process data */
298   process->pid_           = simix_process_maxpid++;
299   process->name_          = simgrid::xbt::string(name);
300   process->host_          = host;
301   process->set_user_data(data);
302   process->simcall.issuer = process;
303
304   if (parent_process != nullptr) {
305     process->ppid_ = parent_process->pid_;
306   }
307
308   process->code         = code;
309
310   XBT_VERB("Create context %s", process->get_cname());
311   process->context_ = SIMIX_context_new(std::move(code), simix_global->cleanup_process_function, process);
312
313   /* Add properties */
314   if (properties != nullptr)
315     for (auto const& kv : *properties)
316       process->set_property(kv.first, kv.second);
317
318   /* Add the process to its host's process list */
319   host->pimpl_->process_list_.push_back(*process);
320
321   XBT_DEBUG("Start context '%s'", process->get_cname());
322
323   /* Now insert it in the global process list and in the process to run list */
324   simix_global->process_list[process->pid_] = process;
325   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->get_cname(), host->get_cname());
326   simix_global->process_to_run.push_back(process);
327   intrusive_ptr_add_ref(process);
328
329   /* The onCreation() signal must be delayed until there, where the pid and everything is set */
330   simgrid::s4u::ActorPtr tmp = process->iface(); // Passing this directly to onCreation will lead to crashes
331   simgrid::s4u::Actor::on_creation(tmp);
332
333   return process;
334 }
335
336 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
337                                  std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
338 {
339   // This is mostly a copy/paste from SIMIX_process_new(),
340   // it'd be nice to share some code between those two functions.
341
342   sg_host_t host = sg_host_by_name(hostname);
343   XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
344
345   if (host->is_off()) {
346     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, hostname);
347     return nullptr;
348   }
349
350   smx_actor_t process = new simgrid::kernel::actor::ActorImpl();
351   /* Process data */
352   process->pid_  = simix_process_maxpid++;
353   process->name_ = std::string(name);
354   process->host_ = host;
355   process->set_user_data(data);
356   process->simcall.issuer = process;
357
358   if (parent_process != nullptr) {
359     process->ppid_ = parent_process->pid_;
360   }
361
362   /* Process data for auto-restart */
363   process->code = nullptr;
364
365   XBT_VERB("Create context %s", process->get_cname());
366   if (not simix_global)
367     xbt_die("simix is not initialized, please call MSG_init first");
368   process->context_ = simix_global->context_factory->attach(simix_global->cleanup_process_function, process);
369
370   /* Add properties */
371   if (properties != nullptr)
372     for (auto const& kv : *properties)
373       process->set_property(kv.first, kv.second);
374
375   /* Add the process to it's host process list */
376   host->pimpl_->process_list_.push_back(*process);
377
378   /* Now insert it in the global process list and in the process to run list */
379   simix_global->process_list[process->pid_] = process;
380   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->get_cname(), host->get_cname());
381   simix_global->process_to_run.push_back(process);
382   intrusive_ptr_add_ref(process);
383
384   auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(process->context_);
385   if (not context)
386     xbt_die("Not a suitable context");
387
388   context->attach_start();
389
390   /* The onCreation() signal must be delayed until there, where the pid and everything is set */
391   simgrid::s4u::ActorPtr tmp = process->iface(); // Passing this directly to onCreation will lead to crashes
392   simgrid::s4u::Actor::on_creation(tmp);
393
394   return process;
395 }
396
397 void SIMIX_process_detach()
398 {
399   auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(SIMIX_context_self());
400   if (not context)
401     xbt_die("Not a suitable context");
402
403   auto process = context->process();
404   simix_global->cleanup_process_function(process);
405   context->attach_stop();
406 }
407
408 /**
409  * @brief Executes the processes from simix_global->process_to_run.
410  *
411  * The processes of simix_global->process_to_run are run (in parallel if
412  * possible).  On exit, simix_global->process_to_run is empty, and
413  * simix_global->process_that_ran contains the list of processes that just ran.
414  * The two lists are swapped so, be careful when using them before and after a
415  * call to this function.
416  */
417 void SIMIX_process_runall()
418 {
419   SIMIX_context_runall();
420
421   simix_global->process_to_run.swap(simix_global->process_that_ran);
422   simix_global->process_to_run.clear();
423 }
424
425 /**
426  * @brief Internal function to kill a SIMIX process.
427  *
428  * This function may be called when a SIMCALL_PROCESS_KILL simcall occurs,
429  * or directly for SIMIX internal purposes.
430  *
431  * @param process poor victim
432  * @param issuer the process which has sent the PROCESS_KILL. Important to not schedule twice the same process.
433  */
434 void SIMIX_process_kill(smx_actor_t process, smx_actor_t issuer) {
435
436   if (process->finished_) {
437     XBT_DEBUG("Ignoring request to kill process %s@%s that is already dead", process->get_cname(),
438               process->host_->get_cname());
439     return;
440   }
441
442   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", issuer->get_cname(),
443             (issuer->host_ == nullptr ? "(null)" : issuer->host_->get_cname()), process->get_cname(),
444             process->host_->get_cname());
445
446   process->context_->iwannadie = true;
447   process->blocked_            = false;
448   process->suspended_          = false;
449   process->exception = nullptr;
450
451   /* destroy the blocking synchro if any */
452   if (process->waiting_synchro != nullptr) {
453     if (process->host_->is_off()) {
454       SMX_EXCEPTION(process, host_error, 0, "Host failed");
455     }
456     simgrid::kernel::activity::ExecImplPtr exec =
457         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
458     simgrid::kernel::activity::CommImplPtr comm =
459         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
460     simgrid::kernel::activity::SleepImplPtr sleep =
461         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
462     simgrid::kernel::activity::RawImplPtr raw =
463         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
464     simgrid::kernel::activity::IoImplPtr io =
465         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
466
467     if (exec != nullptr) {
468       if (exec->surf_action_) {
469         exec->surf_action_->cancel();
470         exec->surf_action_->unref();
471         exec->surf_action_ = nullptr;
472       }
473     } else if (comm != nullptr) {
474       process->comms.remove(process->waiting_synchro);
475       comm->cancel();
476       // Remove first occurrence of &process->simcall:
477       auto i = boost::range::find(process->waiting_synchro->simcalls_, &process->simcall);
478       if (i != process->waiting_synchro->simcalls_.end())
479         process->waiting_synchro->simcalls_.remove(&process->simcall);
480     } else if (sleep != nullptr) {
481       if (sleep->surf_sleep)
482         sleep->surf_sleep->cancel();
483       sleep->post();
484     } else if (raw != nullptr) {
485       SIMIX_synchro_stop_waiting(process, &process->simcall);
486
487     } else if (io != nullptr) {
488       delete io.get();
489     } else {
490       xbt_die("Unknown type of activity");
491     }
492
493     process->waiting_synchro = nullptr;
494   }
495   if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
496           end(simix_global->process_to_run) &&
497       process != issuer) {
498     XBT_DEBUG("Inserting %s in the to_run list", process->get_cname());
499     simix_global->process_to_run.push_back(process);
500   }
501 }
502
503 /** @brief Ask another process to raise the given exception
504  *
505  * @param process The process that should raise that exception
506  * @param cat category of exception
507  * @param value value associated to the exception
508  * @param msg string information associated to the exception
509  */
510 void SIMIX_process_throw(smx_actor_t process, xbt_errcat_t cat, int value, const char *msg) {
511   SMX_EXCEPTION(process, cat, value, msg);
512
513   if (process->suspended_)
514     process->resume();
515
516   /* cancel the blocking synchro if any */
517   if (process->waiting_synchro) {
518
519     simgrid::kernel::activity::ExecImplPtr exec =
520         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
521     if (exec != nullptr && exec->surf_action_)
522       exec->surf_action_->cancel();
523
524     simgrid::kernel::activity::CommImplPtr comm =
525         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
526     if (comm != nullptr) {
527       process->comms.remove(comm);
528       comm->cancel();
529     }
530
531     simgrid::kernel::activity::SleepImplPtr sleep =
532         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
533     if (sleep != nullptr) {
534       SIMIX_process_sleep_destroy(process->waiting_synchro);
535       if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
536               end(simix_global->process_to_run) &&
537           process != SIMIX_process_self()) {
538         XBT_DEBUG("Inserting %s in the to_run list", process->get_cname());
539         simix_global->process_to_run.push_back(process);
540       }
541     }
542
543     simgrid::kernel::activity::RawImplPtr raw =
544         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
545     if (raw != nullptr) {
546       SIMIX_synchro_stop_waiting(process, &process->simcall);
547     }
548
549     simgrid::kernel::activity::IoImplPtr io =
550         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
551     if (io != nullptr) {
552       delete io.get();
553     }
554   }
555   process->waiting_synchro = nullptr;
556
557 }
558
559 /**
560  * @brief Kills all running processes.
561  * @param issuer this one will not be killed
562  */
563 void SIMIX_process_killall(smx_actor_t issuer)
564 {
565   for (auto const& kv : simix_global->process_list)
566     if (kv.second != issuer)
567       SIMIX_process_kill(kv.second, issuer);
568 }
569
570 void SIMIX_process_change_host(smx_actor_t actor, sg_host_t dest)
571 {
572   xbt_assert((actor != nullptr), "Invalid parameters");
573   simgrid::xbt::intrusive_erase(actor->host_->pimpl_->process_list_, *actor);
574   actor->host_ = dest;
575   dest->pimpl_->process_list_.push_back(*actor);
576 }
577
578 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t process)
579 {
580   smx_activity_t sync_suspend = process->suspend(simcall->issuer);
581
582   if (process != simcall->issuer) {
583     SIMIX_simcall_answer(simcall);
584   } else {
585     sync_suspend->simcalls_.push_back(simcall);
586     process->waiting_synchro = sync_suspend;
587     process->waiting_synchro->suspend();
588   }
589   /* If we are suspending ourselves, then just do not finish the simcall now */
590 }
591
592 int SIMIX_process_get_maxpid() {
593   return simix_process_maxpid;
594 }
595
596 int SIMIX_process_count()
597 {
598   return simix_global->process_list.size();
599 }
600
601 void* SIMIX_process_self_get_data()
602 {
603   smx_actor_t self = SIMIX_process_self();
604
605   if (not self) {
606     return nullptr;
607   }
608   return self->get_user_data();
609 }
610
611 void SIMIX_process_self_set_data(void *data)
612 {
613   SIMIX_process_self()->set_user_data(data);
614 }
615
616
617 /* needs to be public and without simcall because it is called
618    by exceptions and logging events */
619 const char* SIMIX_process_self_get_name() {
620
621   smx_actor_t process = SIMIX_process_self();
622   if (process == nullptr || process == simix_global->maestro_process)
623     return "maestro";
624
625   return process->get_cname();
626 }
627
628 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
629 {
630   if (process->finished_) {
631     // The joined process is already finished, just wake up the issuer process right away
632     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
633     SIMIX_simcall_answer(simcall);
634     return;
635   }
636   smx_activity_t sync = SIMIX_process_join(simcall->issuer, process, timeout);
637   sync->simcalls_.push_back(simcall);
638   simcall->issuer->waiting_synchro = sync;
639 }
640
641 smx_activity_t SIMIX_process_join(smx_actor_t issuer, smx_actor_t process, double timeout)
642 {
643   smx_activity_t res = issuer->sleep(timeout);
644   intrusive_ptr_add_ref(res.get());
645   SIMIX_process_on_exit(process,
646                         [](int, void* arg) {
647                           auto sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(arg);
648                           if (sleep->surf_sleep)
649                             sleep->surf_sleep->finish(simgrid::kernel::resource::Action::State::FINISHED);
650                           intrusive_ptr_release(sleep);
651                         },
652                         res.get());
653   return res;
654 }
655
656 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
657 {
658   if (MC_is_active() || MC_record_replay_is_active()) {
659     MC_process_clock_add(simcall->issuer, duration);
660     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
661     SIMIX_simcall_answer(simcall);
662     return;
663   }
664   smx_activity_t sync = simcall->issuer->sleep(duration);
665   sync->simcalls_.push_back(simcall);
666   simcall->issuer->waiting_synchro = sync;
667 }
668
669 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
670 {
671   XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
672   simgrid::kernel::activity::SleepImplPtr sleep =
673       boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
674
675   if (sleep->surf_sleep) {
676     sleep->surf_sleep->unref();
677     sleep->surf_sleep = nullptr;
678   }
679 }
680
681 /**
682  * @brief Calling this function makes the process to yield.
683  *
684  * Only the current process can call this function, giving back the control to maestro.
685  *
686  * @param self the current process
687  */
688 void SIMIX_process_yield(smx_actor_t self)
689 {
690   XBT_DEBUG("Yield actor '%s'", self->get_cname());
691
692   /* Go into sleep and return control to maestro */
693   self->context_->suspend();
694
695   /* Ok, maestro returned control to us */
696   XBT_DEBUG("Control returned to me: '%s'", self->get_cname());
697
698   if (self->context_->iwannadie) {
699     XBT_DEBUG("I wanna die!");
700     self->finished_ = true;
701     /* execute the on_exit functions */
702     SIMIX_process_on_exit_runall(self);
703
704     if (self->auto_restart_ && self->host_->is_off() &&
705         watched_hosts.find(self->host_->get_cname()) == watched_hosts.end()) {
706       XBT_DEBUG("Push host %s to watched_hosts because it's off and %s needs to restart", self->host_->get_cname(),
707                 self->get_cname());
708       watched_hosts.insert(self->host_->get_cname());
709     }
710
711     XBT_DEBUG("Process %s@%s is dead", self->get_cname(), self->host_->get_cname());
712     self->context_->stop();
713   }
714
715   if (self->suspended_) {
716     XBT_DEBUG("Hey! I'm suspended.");
717     xbt_assert(self->exception != nullptr, "Gasp! This exception may be lost by subsequent calls.");
718     self->suspended_ = false;
719     self->suspend(self);
720   }
721
722   if (self->exception != nullptr) {
723     XBT_DEBUG("Wait, maestro left me an exception");
724     std::exception_ptr exception = std::move(self->exception);
725     self->exception = nullptr;
726     std::rethrow_exception(std::move(exception));
727   }
728
729   if (SMPI_switch_data_segment && not self->finished_) {
730     SMPI_switch_data_segment(self->iface());
731   }
732 }
733
734 /** @brief Returns the list of processes to run. */
735 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
736 {
737   return simix_global->process_to_run;
738 }
739
740 /** @brief Returns the process from PID. */
741 smx_actor_t SIMIX_process_from_PID(aid_t PID)
742 {
743   auto process = simix_global->process_list.find(PID);
744   return process == simix_global->process_list.end() ? nullptr : process->second;
745 }
746
747 void SIMIX_process_on_exit_runall(smx_actor_t process) {
748   simgrid::s4u::Actor::on_destruction(process->iface());
749   smx_process_exit_status_t exit_status = (process->context_->iwannadie) ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
750   while (not process->on_exit.empty()) {
751     s_smx_process_exit_fun_t exit_fun = process->on_exit.back();
752     process->on_exit.pop_back();
753     (exit_fun.fun)(exit_status, exit_fun.arg);
754   }
755 }
756
757 void SIMIX_process_on_exit(smx_actor_t process, int_f_pvoid_pvoid_t fun, void* data)
758 {
759   SIMIX_process_on_exit(process, [fun](int a, void* b) { fun((void*)(intptr_t)a, b); }, data);
760 }
761
762 void SIMIX_process_on_exit(smx_actor_t process, std::function<void(int, void*)> fun, void* data)
763 {
764   xbt_assert(process, "current process not found: are you in maestro context ?");
765
766   process->on_exit.emplace_back(s_smx_process_exit_fun_t{fun, data});
767 }
768
769 /** @brief Restart a process, starting it again from the beginning. */
770 /**
771  * @ingroup simix_process_management
772  * @brief Creates and runs a new SIMIX process.
773  *
774  * The structure and the corresponding thread are created and put in the list of ready processes.
775  *
776  * @param name a name for the process. It is for user-level information and can be nullptr.
777  * @param code the main function of the process
778  * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
779  * be nullptr.
780  * It can be retrieved with the method ActorImpl::getUserData().
781  * @param host where the new agent is executed.
782  * @param argc first argument passed to @a code
783  * @param argv second argument passed to @a code
784  * @param properties the properties of the process
785  */
786 smx_actor_t simcall_process_create(std::string name, xbt_main_func_t code, void* data, sg_host_t host, int argc,
787                                    char** argv, std::unordered_map<std::string, std::string>* properties)
788 {
789   auto wrapped_code = simgrid::xbt::wrap_main(code, argc, argv);
790   for (int i = 0; i != argc; ++i)
791     xbt_free(argv[i]);
792   xbt_free(argv);
793   smx_actor_t res = simcall_process_create(name, std::move(wrapped_code), data, host, properties);
794   return res;
795 }
796
797 smx_actor_t simcall_process_create(std::string name, simgrid::simix::ActorCode code, void* data, sg_host_t host,
798                                    std::unordered_map<std::string, std::string>* properties)
799 {
800   smx_actor_t self = SIMIX_process_self();
801   return simgrid::simix::simcall([name, code, data, host, properties, self] {
802     return SIMIX_process_create(name, std::move(code), data, host, properties, self);
803   });
804 }