Logo AND Algorithmique Numérique Distribuée

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