Logo AND Algorithmique Numérique Distribuée

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