Logo AND Algorithmique Numérique Distribuée

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