Logo AND Algorithmique Numérique Distribuée

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