Logo AND Algorithmique Numérique Distribuée

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