Logo AND Algorithmique Numérique Distribuée

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