Logo AND Algorithmique Numérique Distribuée

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