Logo AND Algorithmique Numérique Distribuée

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