Logo AND Algorithmique Numérique Distribuée

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