Logo AND Algorithmique Numérique Distribuée

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