1 /* Copyright (c) 2009-2017. The SimGrid Team. All rights reserved. */
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. */
6 /* \file UContext.cpp Context switching with ucontexts from System V */
8 #include <ucontext.h> /* context relative declarations */
11 #include "src/mc/mc_ignore.h"
12 #include "src/simix/ActorImpl.hpp"
13 #include "src/simix/smx_private.hpp"
14 #include "xbt/parmap.hpp"
16 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
23 class ParallelUContext;
24 class UContextFactory;
27 /** Many integers are needed to store a pointer
29 * Support up to two ints. */
30 constexpr int CTX_ADDR_LEN = 2;
32 static_assert(sizeof(simgrid::kernel::context::UContext*) <= CTX_ADDR_LEN * sizeof(int),
33 "Ucontexts are not supported on this arch yet");
35 /** A better makecontext
37 * Makecontext expects integer arguments, we the context
38 * variable is decomposed into a serie of integers and
39 * each integer is passed as argument to makecontext. */
40 static void simgrid_makecontext(ucontext_t* ucp, void (*func)(int, int), simgrid::kernel::context::UContext* arg)
42 int ctx_addr[CTX_ADDR_LEN]{};
43 memcpy(ctx_addr, &arg, sizeof arg);
44 makecontext(ucp, (void (*)())func, 2, ctx_addr[0], ctx_addr[1]);
47 #if HAVE_THREAD_CONTEXTS
48 static simgrid::xbt::Parmap<smx_actor_t>* sysv_parmap;
49 static simgrid::kernel::context::UContext** sysv_workers_context; /* space to save the worker's context
51 static uintptr_t sysv_threads_working; /* number of threads that have started their work */
52 static xbt_os_thread_key_t sysv_worker_id_key; /* thread-specific storage for the thread id */
54 static unsigned long sysv_process_index = 0; /* index of the next process to run in the
55 * list of runnable processes */
56 static simgrid::kernel::context::UContext* sysv_maestro_context;
57 static bool sysv_parallel;
59 // The name of this function is currently hardcoded in the code (as string).
60 // Do not change it without fixing those references as well.
61 static void smx_ctx_sysv_wrapper(int, int);
67 class UContext : public Context {
69 ucontext_t uc_; /* the ucontext that executes the code */
70 char *stack_ = nullptr; /* the thread stack */
72 friend UContextFactory;
73 UContext(std::function<void()> code,
74 void_pfn_smxprocess_t cleanup_func, smx_actor_t process);
77 static void swap(UContext* from, UContext* to) { swapcontext(&from->uc_, &to->uc_); }
80 class SerialUContext : public UContext {
82 SerialUContext(std::function<void()> code,
83 void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
84 : UContext(std::move(code), cleanup_func, process)
86 void suspend() override;
90 class ParallelUContext : public UContext {
92 ParallelUContext(std::function<void()> code,
93 void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
94 : UContext(std::move(code), cleanup_func, process)
96 void suspend() override;
100 class UContextFactory : public ContextFactory {
103 friend SerialUContext;
104 friend ParallelUContext;
107 ~UContextFactory() override;
108 Context* create_context(std::function<void()> code,
109 void_pfn_smxprocess_t cleanup, smx_actor_t process) override;
110 void run_all() override;
113 XBT_PRIVATE ContextFactory* sysv_factory()
115 XBT_VERB("Activating SYSV context factory");
116 return new UContextFactory();
119 UContextFactory::UContextFactory() : ContextFactory("UContextFactory")
121 if (SIMIX_context_is_parallel()) {
122 sysv_parallel = true;
123 #if HAVE_THREAD_CONTEXTS /* To use parallel ucontexts a thread pool is needed */
124 int nthreads = SIMIX_context_get_nthreads();
125 sysv_parmap = nullptr;
126 sysv_workers_context = new UContext*[nthreads];
127 sysv_maestro_context = nullptr;
128 xbt_os_thread_key_create(&sysv_worker_id_key);
130 THROWF(arg_error, 0, "No thread support for parallel context execution");
133 sysv_parallel = false;
137 UContextFactory::~UContextFactory()
139 #if HAVE_THREAD_CONTEXTS
141 delete[] sysv_workers_context;
145 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some stuff
146 * It is much easier to understand what happens if you see the working threads as bodies that swap their soul for the
147 * ones of the simulated processes that must run.
149 void UContextFactory::run_all()
152 #if HAVE_THREAD_CONTEXTS
153 sysv_threads_working = 0;
154 // Parmap_apply ensures that every working thread get an index in the
155 // process_to_run array (through an atomic fetch_and_add),
156 // and runs the smx_ctx_sysv_resume_parallel function on that index
158 // We lazily create the parmap because the parmap creates context
159 // with simix_global->context_factory (which might not be initialized
160 // when bootstrapping):
161 if (sysv_parmap == nullptr)
163 new simgrid::xbt::Parmap<smx_actor_t>(SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
166 [](smx_actor_t process) {
167 ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
170 simix_global->process_to_run);
172 xbt_die("You asked for a parallel execution, but you don't have any threads.");
176 if (simix_global->process_to_run.empty())
179 smx_actor_t first_process = simix_global->process_to_run.front();
180 sysv_process_index = 1;
181 SerialUContext* context = static_cast<SerialUContext*>(first_process->context);
186 Context* UContextFactory::create_context(std::function<void()> code,
187 void_pfn_smxprocess_t cleanup, smx_actor_t process)
190 return new_context<ParallelUContext>(std::move(code), cleanup, process);
192 return new_context<SerialUContext>(std::move(code), cleanup, process);
195 UContext::UContext(std::function<void()> code,
196 void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
197 : Context(std::move(code), cleanup_func, process)
199 /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
201 this->stack_ = (char*) SIMIX_context_stack_new();
202 getcontext(&this->uc_);
203 this->uc_.uc_link = nullptr;
204 this->uc_.uc_stack.ss_sp = sg_makecontext_stack_addr(this->stack_);
205 this->uc_.uc_stack.ss_size = sg_makecontext_stack_size(smx_context_usable_stack_size);
206 simgrid_makecontext(&this->uc_, smx_ctx_sysv_wrapper, this);
208 if (process != nullptr && sysv_maestro_context == nullptr)
209 sysv_maestro_context = this;
213 if (MC_is_active() && has_code()) {
214 MC_register_stack_area(this->stack_, process,
215 &(this->uc_), smx_context_usable_stack_size);
220 UContext::~UContext()
222 SIMIX_context_stack_delete(this->stack_);
225 void UContext::stop()
230 }}} // namespace simgrid::kernel::context
232 static void smx_ctx_sysv_wrapper(int i1, int i2)
234 // Rebuild the Context* pointer from the integers:
235 int ctx_addr[CTX_ADDR_LEN] = {i1, i2};
236 simgrid::kernel::context::UContext* context;
237 memcpy(&context, ctx_addr, sizeof context);
241 context->Context::stop();
242 } catch (simgrid::kernel::context::Context::StopRequest const&) {
243 XBT_DEBUG("Caught a StopRequest");
252 void SerialUContext::suspend()
254 /* determine the next context */
255 UContext* next_context = nullptr;
256 unsigned long int i = sysv_process_index;
257 sysv_process_index++;
259 if (i < simix_global->process_to_run.size()) {
260 /* execute the next process */
261 XBT_DEBUG("Run next process");
262 next_context = static_cast<UContext*>(simix_global->process_to_run[i]->context);
264 /* all processes were run, return to maestro */
265 XBT_DEBUG("No more process to run");
266 next_context = sysv_maestro_context;
268 SIMIX_context_set_current(next_context);
269 UContext::swap(this, next_context);
274 void SerialUContext::resume()
276 SIMIX_context_set_current(this);
277 UContext::swap(sysv_maestro_context, this);
280 /** Run one particular simulated process on the current thread. */
281 void ParallelUContext::resume()
283 #if HAVE_THREAD_CONTEXTS
284 // What is my containing body?
285 uintptr_t worker_id = __sync_fetch_and_add(&sysv_threads_working, 1);
286 // Store the number of my containing body in os-thread-specific area :
287 xbt_os_thread_set_specific(sysv_worker_id_key, (void*) worker_id);
288 // Get my current soul:
289 UContext* worker_context = static_cast<UContext*>(SIMIX_context_self());
290 // Write down that this soul is hosted in that body (for now)
291 sysv_workers_context[worker_id] = worker_context;
292 // Write in simix that I switched my soul
293 SIMIX_context_set_current(this);
294 // Actually do that using the relevant library call:
295 UContext::swap(worker_context, this);
296 // No body runs that soul anymore at this point.
297 // Instead the current body took the soul of simulated process
298 // The simulated process wakes back after the call to
299 // "SIMIX_context_suspend(self->context);" within
300 // smx_process.c::SIMIX_process_yield()
302 // From now on, the simulated processes will change their
303 // soul with the next soul to execute (in suspend_parallel, below).
304 // When nobody is to be executed in this scheduling round,
305 // the last simulated process will take back the initial
306 // soul of the current working thread
312 * This function is called when a simulated process wants to yield back
313 * to the maestro in a blocking simcall. This naturally occurs within
314 * SIMIX_context_suspend(self->context), called from SIMIX_process_yield()
315 * Actually, it does not really yield back to maestro, but into the next
316 * process that must be executed. If no one is to be executed, then it
317 * yields to the initial soul that was in this working thread (that was
318 * saved in resume_parallel).
320 void ParallelUContext::suspend()
322 #if HAVE_THREAD_CONTEXTS
323 /* determine the next context */
324 // Get the next soul to embody now:
325 boost::optional<smx_actor_t> next_work = sysv_parmap->next();
326 UContext* next_context;
328 // There is a next soul to embody (ie, a next process to resume)
329 XBT_DEBUG("Run next process");
330 next_context = static_cast<UContext*>(next_work.get()->context);
332 // All processes were run, go to the barrier
333 XBT_DEBUG("No more processes to run");
334 // Get back the identity of my body that was stored when starting
335 // the scheduling round
336 uintptr_t worker_id =
337 (uintptr_t) xbt_os_thread_get_specific(sysv_worker_id_key);
338 // Deduce the initial soul of that body
339 next_context = sysv_workers_context[worker_id];
340 // When given that soul, the body will wait for the next scheduling round
343 SIMIX_context_set_current(next_context);
344 // Get the next soul to run, either simulated or initial minion's one:
345 UContext::swap(this, next_context);
349 }}} // namespace simgrid::kernel::context