Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[s4u] Allocate Mailbox on the heap and return MailboxPtr
[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/simix/SynchroSleep.hpp"
30 #include "src/simix/SynchroRaw.hpp"
31 #include "src/simix/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(void)
64 {
65   smx_context_t self_context = SIMIX_context_self();
66
67   return self_context ? 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;
98   while ((synchro = (smx_synchro_t) xbt_fifo_pop(process->comms))) {
99     simgrid::simix::Comm *comm = static_cast<simgrid::simix::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   }
132
133   XBT_DEBUG("%p should not be run anymore",process);
134   xbt_swag_remove(process, simix_global->process_list);
135   if (process->host)
136     xbt_swag_remove(process, sg_host_simix(process->host)->process_list);
137   xbt_swag_insert(process, simix_global->process_to_destroy);
138   process->context->iwannadie = 0;
139
140   xbt_os_mutex_release(simix_global->mutex);
141 }
142
143 /**
144  * Garbage collection
145  *
146  * Should be called some time to time to free the memory allocated for processes
147  * that have finished (or killed).
148  */
149 void SIMIX_process_empty_trash(void)
150 {
151   smx_process_t process = nullptr;
152
153   while ((process = (smx_process_t) xbt_swag_extract(simix_global->process_to_destroy))) {
154     XBT_DEBUG("Getting rid of %p",process);
155     intrusive_ptr_release(process);
156   }
157 }
158
159 namespace simgrid {
160 namespace simix {
161
162 Process::~Process()
163 {
164   delete this->context;
165   if (this->properties)
166     xbt_dict_free(&this->properties);
167   if (this->comms != nullptr)
168     xbt_fifo_free(this->comms);
169   if (this->on_exit)
170     xbt_dynar_free(&this->on_exit);
171 }
172
173 void create_maestro(std::function<void()> code)
174 {
175   smx_process_t maestro = nullptr;
176   /* Create maestro process and intilialize it */
177   maestro = new simgrid::simix::Process();
178   maestro->pid = simix_process_maxpid++;
179   maestro->ppid = -1;
180   maestro->name = "";
181   maestro->data = nullptr;
182
183   if (!code) {
184     maestro->context = SIMIX_context_new(std::function<void()>(), nullptr, maestro);
185   } else {
186     if (!simix_global)
187       xbt_die("simix is not initialized, please call MSG_init first");
188     maestro->context =
189       simix_global->context_factory->create_maestro(code, maestro);
190   }
191
192   maestro->simcall.issuer = maestro;
193   simix_global->maestro_process = maestro;
194 }
195
196 }
197 }
198
199 /**
200  * \brief Creates and runs the maestro process
201  */
202 void SIMIX_maestro_create(void (*code)(void*), void* data)
203 {
204   simgrid::simix::create_maestro(std::bind(code, data));
205 }
206
207 /**
208  * \brief Stops a process.
209  *
210  * Stops the process, execute all the registered on_exit functions,
211  * register it to the list of the process to restart if needed
212  * and stops its context.
213  */
214 void SIMIX_process_stop(smx_process_t arg) {
215   arg->finished = true;
216   /* execute the on_exit functions */
217   SIMIX_process_on_exit_runall(arg);
218   /* Add the process to the list of process to restart, only if the host is down */
219   if (arg->auto_restart && arg->host->isOff()) {
220     SIMIX_host_add_auto_restart_process(arg->host, arg->name.c_str(),
221                                         arg->code, arg->data,
222                                         sg_host_get_name(arg->host),
223                                         SIMIX_timer_get_date(arg->kill_timer),
224                                         arg->properties,
225                                         arg->auto_restart);
226   }
227   XBT_DEBUG("Process %s (%s) is dead",
228     arg->name.c_str(), sg_host_get_name(arg->host));
229   arg->context->stop();
230 }
231
232 /**
233  * \brief Internal function to create a process.
234  *
235  * This function actually creates the process.
236  * It may be called when a SIMCALL_PROCESS_CREATE simcall occurs,
237  * or directly for SIMIX internal purposes. The sure thing is that it's called from maestro context.
238  *
239  * \return the process created
240  */
241 smx_process_t SIMIX_process_create(
242                           const char *name,
243                           std::function<void()> code,
244                           void *data,
245                           const char *hostname,
246                           double kill_time,
247                           xbt_dict_t properties,
248                           int auto_restart,
249                           smx_process_t parent_process)
250 {
251   smx_process_t process = nullptr;
252   sg_host_t host = sg_host_by_name(hostname);
253
254   XBT_DEBUG("Start process %s on host '%s'", name, hostname);
255
256   if (host->isOff()) {
257     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name,
258           hostname);
259     return nullptr;
260   }
261   else {
262     process = new simgrid::simix::Process();
263
264     xbt_assert(code && host != nullptr, "Invalid parameters");
265     /* Process data */
266     process->pid = simix_process_maxpid++;
267     process->name = simgrid::xbt::string(name);
268     process->host = host;
269     process->data = data;
270     process->comms = xbt_fifo_new();
271     process->simcall.issuer = process;
272     /* Initiliaze data segment to default value */
273     SIMIX_segment_index_set(process, -1);
274
275      if (parent_process != nullptr) {
276        process->ppid = SIMIX_process_get_PID(parent_process);
277        /* SMPI process have their own data segment and
278           each other inherit from their father */
279 #if HAVE_SMPI
280        if(smpi_privatize_global_variables){
281          if( parent_process->pid != 0){
282            SIMIX_segment_index_set(process, parent_process->segment_index);
283          } else {
284            SIMIX_segment_index_set(process, process->pid - 1);
285          }
286        }
287 #endif
288      } else {
289        process->ppid = -1;
290      }
291
292     /* Process data for auto-restart */
293     process->auto_restart = auto_restart;
294     process->code = code;
295
296     XBT_VERB("Create context %s", process->name.c_str());
297     process->context = SIMIX_context_new(
298       std::move(code),
299       simix_global->cleanup_process_function, process);
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, [=]() {
319         simix_global->kill_process_function(process);
320       });
321     }
322
323     /* Tracing the process creation */
324     TRACE_msg_process_create(process->name.c_str(), process->pid, process->host);
325   }
326   return process;
327 }
328
329 smx_process_t SIMIX_process_attach(
330   const char* name,
331   void *data,
332   const char* hostname,
333   xbt_dict_t properties,
334   smx_process_t parent_process)
335 {
336   // This is mostly a copy/paste from SIMIX_process_new(),
337   // it'd be nice to share some code between those two functions.
338
339   sg_host_t host = sg_host_by_name(hostname);
340   XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
341
342   if (host->isOff()) {
343     XBT_WARN("Cannot launch process '%s' on failed host '%s'",
344       name, hostname);
345     return nullptr;
346   }
347
348   smx_process_t process = new simgrid::simix::Process();
349   /* Process data */
350   process->pid = simix_process_maxpid++;
351   process->name = std::string(name);
352   process->host = host;
353   process->data = data;
354   process->comms = xbt_fifo_new();
355   process->simcall.issuer = process;
356   process->ppid = -1;
357   /* Initiliaze data segment to default value */
358   SIMIX_segment_index_set(process, -1);
359   if (parent_process != nullptr) {
360     process->ppid = SIMIX_process_get_PID(parent_process);
361    /* SMPI process have their own data segment and
362       each other inherit from their father */
363   #if HAVE_SMPI
364     if(smpi_privatize_global_variables){
365       if(parent_process->pid != 0){
366         SIMIX_segment_index_set(process, parent_process->segment_index);
367       } else {
368         SIMIX_segment_index_set(process, process->pid - 1);
369       }
370     }
371   #endif
372   }
373
374   /* Process data for auto-restart */
375   process->auto_restart = false;
376   process->code = nullptr;
377
378   XBT_VERB("Create context %s", process->name.c_str());
379   if (!simix_global)
380     xbt_die("simix is not initialized, please call MSG_init first");
381   process->context = simix_global->context_factory->attach(
382     simix_global->cleanup_process_function, process);
383
384   /* Add properties */
385   process->properties = properties;
386
387   /* Add the process to it's host process list */
388   xbt_swag_insert(process, sg_host_simix(host)->process_list);
389
390   /* Now insert it in the global process list and in the process to run list */
391   xbt_swag_insert(process, simix_global->process_list);
392   XBT_DEBUG("Inserting %s(%s) in the to_run list",
393     process->name.c_str(), sg_host_get_name(host));
394   xbt_dynar_push_as(simix_global->process_to_run, smx_process_t, process);
395
396   /* Tracing the process creation */
397   TRACE_msg_process_create(process->name.c_str(), process->pid, process->host);
398
399   auto context = dynamic_cast<simgrid::simix::AttachContext*>(process->context);
400   if (!context)
401     xbt_die("Not a suitable context");
402
403   context->attach_start();
404   return process;
405 }
406
407 void SIMIX_process_detach(void)
408 {
409   auto context = dynamic_cast<simgrid::simix::AttachContext*>(SIMIX_context_self());
410   if (!context)
411     xbt_die("Not a suitable context");
412
413   simix_global->cleanup_process_function(context->process());
414
415   // Let maestro ignore we are still alive:
416   // xbt_swag_remove(context->process(), simix_global->process_list);
417
418   // TODDO, Remove from proces list:
419   //   xbt_swag_remove(process, sg_host_simix(host)->process_list);
420
421   context->attach_stop();
422   // delete context;
423 }
424
425 /**
426  * \brief Executes the processes from simix_global->process_to_run.
427  *
428  * The processes of simix_global->process_to_run are run (in parallel if
429  * possible).  On exit, simix_global->process_to_run is empty, and
430  * simix_global->process_that_ran contains the list of processes that just ran.
431  * The two lists are swapped so, be careful when using them before and after a
432  * call to this function.
433  */
434 void SIMIX_process_runall(void)
435 {
436   SIMIX_context_runall();
437
438   xbt_dynar_t tmp = simix_global->process_that_ran;
439   simix_global->process_that_ran = simix_global->process_to_run;
440   simix_global->process_to_run = tmp;
441   xbt_dynar_reset(simix_global->process_to_run);
442 }
443
444 void simcall_HANDLER_process_kill(smx_simcall_t simcall, smx_process_t process) {
445   SIMIX_process_kill(process, simcall->issuer);
446 }
447 /**
448  * \brief Internal function to kill a SIMIX process.
449  *
450  * This function may be called when a SIMCALL_PROCESS_KILL simcall occurs,
451  * or directly for SIMIX internal purposes.
452  *
453  * \param process poor victim
454  * \param issuer the process which has sent the PROCESS_KILL. Important to not schedule twice the same process.
455  */
456 void SIMIX_process_kill(smx_process_t process, smx_process_t issuer) {
457
458   XBT_DEBUG("Killing process %s on %s",
459     process->name.c_str(), sg_host_get_name(process->host));
460
461   process->context->iwannadie = 1;
462   process->blocked = 0;
463   process->suspended = 0;
464   process->exception = nullptr;
465
466   /* destroy the blocking synchro if any */
467   if (process->waiting_synchro) {
468
469     simgrid::simix::Exec *exec = dynamic_cast<simgrid::simix::Exec*>(process->waiting_synchro);
470     simgrid::simix::Comm *comm = dynamic_cast<simgrid::simix::Comm*>(process->waiting_synchro);
471     simgrid::simix::Sleep *sleep = dynamic_cast<simgrid::simix::Sleep*>(process->waiting_synchro);
472     simgrid::simix::Raw *raw = dynamic_cast<simgrid::simix::Raw*>(process->waiting_synchro);
473     simgrid::simix::Io *io = dynamic_cast<simgrid::simix::Io*>(process->waiting_synchro);
474
475     if (exec != nullptr) {
476       exec->unref();
477
478     } else if (comm != nullptr) {
479       xbt_fifo_remove(process->comms, process->waiting_synchro);
480       comm->cancel();
481
482       // Remove first occurence of &process->simcall:
483       auto i = boost::range::find(
484         process->waiting_synchro->simcalls,
485         &process->simcall);
486       if (i != process->waiting_synchro->simcalls.end())
487         process->waiting_synchro->simcalls.remove(&process->simcall);
488
489       comm->unref();
490
491     } else if (sleep != nullptr) {
492       SIMIX_process_sleep_destroy(process->waiting_synchro);
493
494     } else if (raw != nullptr) {
495       SIMIX_synchro_stop_waiting(process, &process->simcall);
496       delete process->waiting_synchro;
497
498     } else if (io != nullptr) {
499       SIMIX_io_destroy(process->waiting_synchro);
500     }
501
502     /*
503     switch (process->waiting_synchro->type) {
504     case SIMIX_SYNC_JOIN:
505       SIMIX_process_sleep_destroy(process->waiting_synchro);
506       break;
507     } */
508
509     process->waiting_synchro = nullptr;
510   }
511   if(!xbt_dynar_member(simix_global->process_to_run, &(process)) && process != issuer) {
512     XBT_DEBUG("Inserting %s in the to_run list", process->name.c_str());
513     xbt_dynar_push_as(simix_global->process_to_run, smx_process_t, process);
514   }
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::simix::Exec *exec = dynamic_cast<simgrid::simix::Exec*>(process->waiting_synchro);
534     if (exec != nullptr) {
535       SIMIX_execution_cancel(process->waiting_synchro);
536     }
537
538     simgrid::simix::Comm *comm = dynamic_cast<simgrid::simix::Comm*>(process->waiting_synchro);
539     if (comm != nullptr) {
540       xbt_fifo_remove(process->comms, comm);
541       comm->cancel();
542     }
543
544     simgrid::simix::Sleep *sleep = dynamic_cast<simgrid::simix::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::simix::Raw *raw = dynamic_cast<simgrid::simix::Raw*>(process->waiting_synchro);
554     if (raw != nullptr) {
555       SIMIX_synchro_stop_waiting(process, &process->simcall);
556     }
557
558     simgrid::simix::Io *io = dynamic_cast<simgrid::simix::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,
597              sg_host_t dest)
598 {
599   xbt_assert((process != nullptr), "Invalid parameters");
600   xbt_swag_remove(process, sg_host_simix(process->host)->process_list);
601   process->host = dest;
602   xbt_swag_insert(process, sg_host_simix(dest)->process_list);
603 }
604
605
606 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_process_t process)
607 {
608   smx_synchro_t sync_suspend = SIMIX_process_suspend(process, simcall->issuer);
609
610   if (process != simcall->issuer) {
611     SIMIX_simcall_answer(simcall);
612   } else {
613     sync_suspend->simcalls.push_back(simcall);
614     process->waiting_synchro = sync_suspend;
615     process->waiting_synchro->suspend();
616   }
617   /* If we are suspending ourselves, then just do not finish the simcall now */
618 }
619
620 smx_synchro_t SIMIX_process_suspend(smx_process_t process, smx_process_t issuer)
621 {
622   if (process->suspended) {
623     XBT_DEBUG("Process '%s' is already suspended", process->name.c_str());
624     return nullptr;
625   }
626
627   process->suspended = 1;
628
629   /* If we are suspending another process that is waiting on a sync, suspend its synchronization. */
630   if (process != issuer) {
631
632     if (process->waiting_synchro)
633       process->waiting_synchro->suspend();
634     /* If the other process is not waiting, its suspension is delayed to when the process is rescheduled. */
635
636     return nullptr;
637   } else {
638     /* FIXME: computation size is zero. Is it okay that bound is zero ? */
639     return SIMIX_execution_start(process, "suspend", 0.0, 1.0, 0.0, 0);
640   }
641 }
642
643 void simcall_HANDLER_process_resume(smx_simcall_t simcall, smx_process_t process){
644   SIMIX_process_resume(process, simcall->issuer);
645 }
646
647 void SIMIX_process_resume(smx_process_t process, smx_process_t issuer)
648 {
649   XBT_IN("process = %p, issuer = %p", process, issuer);
650
651   if(process->context->iwannadie) {
652     XBT_VERB("Ignoring request to suspend a process that is currently dying.");
653     return;
654   }
655
656   if(!process->suspended) return;
657   process->suspended = 0;
658
659   /* If we are resuming another process, resume the synchronization it was waiting for
660      if any. Otherwise add it to the list of process to run in the next round. */
661   if (process != issuer) {
662
663     if (process->waiting_synchro) {
664       process->waiting_synchro->resume();
665     }
666   } else XBT_WARN("Strange. Process %p is trying to resume himself.", issuer);
667
668   XBT_OUT();
669 }
670
671 int SIMIX_process_get_maxpid(void) {
672   return simix_process_maxpid;
673 }
674
675 int SIMIX_process_count(void)
676 {
677   return xbt_swag_size(simix_global->process_list);
678 }
679
680 int SIMIX_process_get_PID(smx_process_t self){
681   if (self == nullptr)
682     return 0;
683   else
684     return self->pid;
685 }
686
687 int SIMIX_process_get_PPID(smx_process_t self){
688   if (self == nullptr)
689     return 0;
690   else
691     return self->ppid;
692 }
693
694 void* SIMIX_process_self_get_data()
695 {
696   smx_process_t self = SIMIX_process_self();
697
698   if (!self) {
699     return nullptr;
700   }
701   return SIMIX_process_get_data(self);
702 }
703
704 void SIMIX_process_self_set_data(void *data)
705 {
706   smx_process_t self = SIMIX_process_self();
707
708   SIMIX_process_set_data(self, data);
709 }
710
711 void* SIMIX_process_get_data(smx_process_t process)
712 {
713   return process->data;
714 }
715
716 void SIMIX_process_set_data(smx_process_t process, void *data)
717 {
718   process->data = data;
719 }
720
721 sg_host_t SIMIX_process_get_host(smx_process_t process)
722 {
723   return process->host;
724 }
725
726 /* needs to be public and without simcall because it is called
727    by exceptions and logging events */
728 const char* SIMIX_process_self_get_name(void) {
729
730   smx_process_t process = SIMIX_process_self();
731   if (process == nullptr || process == simix_global->maestro_process)
732     return "maestro";
733
734   return SIMIX_process_get_name(process);
735 }
736
737 const char* SIMIX_process_get_name(smx_process_t process)
738 {
739   return process->name.c_str();
740 }
741
742 smx_process_t SIMIX_process_get_by_name(const char* name)
743 {
744   smx_process_t proc;
745   xbt_swag_foreach(proc, simix_global->process_list) {
746     if (proc->name == name)
747       return proc;
748   }
749   return nullptr;
750 }
751
752 int SIMIX_process_is_suspended(smx_process_t process)
753 {
754   return process->suspended;
755 }
756
757 xbt_dict_t SIMIX_process_get_properties(smx_process_t process)
758 {
759   return process->properties;
760 }
761
762 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_process_t process, double timeout)
763 {
764   if (process->finished) {
765     // The joined process is already finished, just wake up the issuer process right away
766     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
767     SIMIX_simcall_answer(simcall);
768     return;
769   }
770   smx_synchro_t sync = SIMIX_process_join(simcall->issuer, process, timeout);
771   sync->simcalls.push_back(simcall);
772   simcall->issuer->waiting_synchro = sync;
773 }
774
775 static int SIMIX_process_join_finish(smx_process_exit_status_t status, smx_synchro_t synchro){
776   simgrid::simix::Sleep *sleep = static_cast<simgrid::simix::Sleep*>(synchro);
777
778   if (sleep->surf_sleep) {
779     sleep->surf_sleep->cancel();
780
781     while (!sleep->simcalls.empty()) {
782       smx_simcall_t simcall = sleep->simcalls.front();
783       sleep->simcalls.pop_front();
784       simcall_process_sleep__set__result(simcall, SIMIX_DONE);
785       simcall->issuer->waiting_synchro = nullptr;
786       if (simcall->issuer->suspended) {
787         XBT_DEBUG("Wait! This process is suspended and can't wake up now.");
788         simcall->issuer->suspended = 0;
789         simcall_HANDLER_process_suspend(simcall, simcall->issuer);
790       } else {
791         SIMIX_simcall_answer(simcall);
792       }
793     }
794     sleep->surf_sleep->unref();
795     sleep->surf_sleep = nullptr;
796   }
797   sleep->unref();
798   return 0;
799 }
800
801 smx_synchro_t SIMIX_process_join(smx_process_t issuer, smx_process_t process, double timeout)
802 {
803   smx_synchro_t res = SIMIX_process_sleep(issuer, timeout);
804   static_cast<simgrid::simix::Synchro*>(res)->ref();
805   SIMIX_process_on_exit(process, (int_f_pvoid_pvoid_t)SIMIX_process_join_finish, res);
806   return res;
807 }
808
809 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
810 {
811   if (MC_is_active() || MC_record_replay_is_active()) {
812     MC_process_clock_add(simcall->issuer, duration);
813     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
814     SIMIX_simcall_answer(simcall);
815     return;
816   }
817   smx_synchro_t sync = SIMIX_process_sleep(simcall->issuer, duration);
818   sync->simcalls.push_back(simcall);
819   simcall->issuer->waiting_synchro = sync;
820 }
821
822 smx_synchro_t SIMIX_process_sleep(smx_process_t process, double duration)
823 {
824   sg_host_t host = process->host;
825
826   /* check if the host is active */
827   if (host->isOff())
828     THROWF(host_error, 0, "Host %s failed, you cannot call this function", sg_host_get_name(host));
829
830   simgrid::simix::Sleep *synchro = new simgrid::simix::Sleep();
831   synchro->host = host;
832   synchro->surf_sleep = surf_host_sleep(host, duration);
833   synchro->surf_sleep->setData(synchro);
834   XBT_DEBUG("Create sleep synchronization %p", synchro);
835
836   return synchro;
837 }
838
839 void SIMIX_process_sleep_destroy(smx_synchro_t synchro)
840 {
841   XBT_DEBUG("Destroy synchro %p", synchro);
842   simgrid::simix::Sleep *sleep = static_cast<simgrid::simix::Sleep*>(synchro);
843
844   if (sleep->surf_sleep) {
845     sleep->surf_sleep->unref();
846     sleep->surf_sleep = nullptr;
847     sleep->unref();
848   }
849 }
850
851 /**
852  * \brief Calling this function makes the process to yield.
853  *
854  * Only the current process can call this function, giving back the control to
855  * maestro.
856  *
857  * \param self the current process
858  */
859 void SIMIX_process_yield(smx_process_t self)
860 {
861   XBT_DEBUG("Yield process '%s'", self->name.c_str());
862
863   /* Go into sleep and return control to maestro */
864   self->context->suspend();
865
866   /* Ok, maestro returned control to us */
867   XBT_DEBUG("Control returned to me: '%s'", self->name.c_str());
868
869   if (self->new_host) {
870     SIMIX_process_change_host(self, self->new_host);
871     self->new_host = nullptr;
872   }
873
874   if (self->context->iwannadie){
875     XBT_DEBUG("I wanna die!");
876     SIMIX_process_stop(self);
877   }
878
879   if (self->suspended) {
880     XBT_DEBUG("Hey! I'm suspended.");
881     xbt_assert(self->exception != nullptr, "Gasp! This exception may be lost by subsequent calls.");
882     self->suspended = 0;
883     SIMIX_process_suspend(self, self);
884   }
885
886   if (self->exception != nullptr) {
887     XBT_DEBUG("Wait, maestro left me an exception");
888     std::exception_ptr exception = std::move(self->exception);
889     self->exception = nullptr;
890     std::rethrow_exception(std::move(exception));
891   }
892
893   if(SMPI_switch_data_segment && self->segment_index != -1){
894     SMPI_switch_data_segment(self->segment_index);
895   }
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 nullptr;
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),nullptr);
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), nullptr);
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 = nullptr;
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 /**
1017  * \ingroup simix_process_management
1018  * \brief Creates and runs a new SIMIX process.
1019  *
1020  * The structure and the corresponding thread are created and put in the list of ready processes.
1021  *
1022  * \param name a name for the process. It is for user-level information and can be nullptr.
1023  * \param code the main function of the process
1024  * \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.
1025  * It can be retrieved with the function \ref simcall_process_get_data.
1026  * \param hostname name of the host where the new agent is executed.
1027  * \param kill_time time when the process is killed
1028  * \param argc first argument passed to \a code
1029  * \param argv second argument passed to \a code
1030  * \param properties the properties of the process
1031  * \param auto_restart either it is autorestarting or not.
1032  */
1033 smx_process_t simcall_process_create(const char *name,
1034                               xbt_main_func_t code,
1035                               void *data,
1036                               const char *hostname,
1037                               double kill_time,
1038                               int argc, char **argv,
1039                               xbt_dict_t properties,
1040                               int auto_restart)
1041 {
1042   if (name == nullptr)
1043     name = "";
1044   auto wrapped_code = simgrid::xbt::wrapMain(code, argc, argv);
1045   for (int i = 0; i != argc; ++i)
1046     xbt_free(argv[i]);
1047   xbt_free(argv);
1048   smx_process_t res = simcall_process_create(name,
1049     std::move(wrapped_code),
1050     data, hostname, kill_time, properties, auto_restart);
1051   return res;
1052 }
1053
1054 smx_process_t simcall_process_create(
1055   const char *name, std::function<void()> code, void *data,
1056   const char *hostname, double kill_time,
1057   xbt_dict_t properties, int auto_restart)
1058 {
1059   if (name == nullptr)
1060     name = "";
1061   smx_process_t self = SIMIX_process_self();
1062   return simgrid::simix::kernelImmediate([&] {
1063     return SIMIX_process_create(name,
1064           std::move(code), data, hostname,
1065           kill_time, properties, auto_restart,
1066           self);
1067   });
1068 }