Logo AND Algorithmique Numérique Distribuée

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