Logo AND Algorithmique Numérique Distribuée

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