Logo AND Algorithmique Numérique Distribuée

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