Logo AND Algorithmique Numérique Distribuée

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