Logo AND Algorithmique Numérique Distribuée

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