1 /* Copyright (c) 2009-2015. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 /* \file UContext.cpp Context switching with ucontexts from System V */
12 #include <ucontext.h> /* context relative declarations */
14 #include "xbt/parmap.h"
15 #include "src/simix/smx_private.h"
16 #include "src/simix/smx_private.hpp"
17 #include "src/internal_config.h"
20 /** Many integers are needed to store a pointer
22 * This is a bit paranoid about sizeof(smx_ctx_sysv_t) not being a multiple
23 * of sizeof(int), but it doesn't harm. */
24 #define CTX_ADDR_LEN \
25 (sizeof(void*) / sizeof(int) + \
26 !!(sizeof(void*) % sizeof(int)))
28 /** A better makecontext
30 * Makecontext expects integer arguments, we the context
31 * variable is decomposed into a serie of integers and
32 * each integer is passed as argument to makecontext. */
34 void simgrid_makecontext(ucontext_t* ucp, void (*func)(int first, ...), void* arg)
36 int ctx_addr[CTX_ADDR_LEN];
37 memcpy(ctx_addr, &arg, sizeof(void*));
38 switch (CTX_ADDR_LEN) {
40 makecontext(ucp, (void (*)())func, 1, ctx_addr[0]);
43 makecontext(ucp, (void (*)()) func, 2, ctx_addr[0], ctx_addr[1]);
46 xbt_die("Ucontexts are not supported on this arch yet (addr len = %zu/%zu = %zu)",
47 sizeof(void*), sizeof(int), CTX_ADDR_LEN);
51 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
57 class ParallelUContext;
58 class UContextFactory;
62 #ifdef HAVE_THREAD_CONTEXTS
63 static xbt_parmap_t sysv_parmap;
64 static simgrid::simix::ParallelUContext** sysv_workers_context; /* space to save the worker's context in each thread */
65 static uintptr_t sysv_threads_working; /* number of threads that have started their work */
66 static xbt_os_thread_key_t sysv_worker_id_key; /* thread-specific storage for the thread id */
68 static unsigned long sysv_process_index = 0; /* index of the next process to run in the
69 * list of runnable processes */
70 static simgrid::simix::UContext* sysv_maestro_context;
71 static bool sysv_parallel;
73 // The name of this function is currently hardcoded in the code (as string).
74 // Do not change it without fixing those references as well.
75 static void smx_ctx_sysv_wrapper(int first, ...);
80 class UContext : public Context {
82 ucontext_t uc_; /* the ucontext that executes the code */
83 char *stack_ = nullptr; /* the thread stack */
85 friend UContextFactory;
86 UContext(std::function<void()> code,
87 void_pfn_smxprocess_t cleanup_func, smx_process_t process);
91 class SerialUContext : public UContext {
93 SerialUContext(std::function<void()> code,
94 void_pfn_smxprocess_t cleanup_func, smx_process_t process)
95 : UContext(std::move(code), cleanup_func, process)
98 void suspend() override;
102 class ParallelUContext : public UContext {
104 ParallelUContext(std::function<void()> code,
105 void_pfn_smxprocess_t cleanup_func, smx_process_t process)
106 : UContext(std::move(code), cleanup_func, process)
108 void stop() override;
109 void suspend() override;
113 class UContextFactory : public ContextFactory {
116 friend SerialUContext;
117 friend ParallelUContext;
120 virtual ~UContextFactory();
121 virtual Context* create_context(std::function<void()> code,
122 void_pfn_smxprocess_t, smx_process_t process) override;
123 void run_all() override;
126 XBT_PRIVATE ContextFactory* sysv_factory()
128 XBT_VERB("Activating SYSV context factory");
129 return new UContextFactory();
132 UContextFactory::UContextFactory() : ContextFactory("UContextFactory")
134 if (SIMIX_context_is_parallel()) {
135 sysv_parallel = true;
136 #ifdef HAVE_THREAD_CONTEXTS /* To use parallel ucontexts a thread pool is needed */
137 int nthreads = SIMIX_context_get_nthreads();
138 sysv_parmap = nullptr;
139 sysv_workers_context = xbt_new(ParallelUContext*, nthreads);
140 sysv_maestro_context = nullptr;
141 xbt_os_thread_key_create(&sysv_worker_id_key);
143 THROWF(arg_error, 0, "No thread support for parallel context execution");
146 sysv_parallel = false;
150 UContextFactory::~UContextFactory()
152 #ifdef HAVE_THREAD_CONTEXTS
154 xbt_parmap_destroy(sysv_parmap);
155 xbt_free(sysv_workers_context);
159 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some stuff
160 * It is much easier to understand what happens if you see the working threads as bodies that swap their soul for the
161 * ones of the simulated processes that must run.
163 void UContextFactory::run_all()
166 #ifdef HAVE_THREAD_CONTEXTS
167 sysv_threads_working = 0;
168 // Parmap_apply ensures that every working thread get an index in the
169 // process_to_run array (through an atomic fetch_and_add),
170 // and runs the smx_ctx_sysv_resume_parallel function on that index
172 // We lazily create the parmap because the parmap creates context
173 // with simix_global->context_factory (which might not be initialized
174 // when bootstrapping):
175 if (sysv_parmap == nullptr)
176 sysv_parmap = xbt_parmap_new(
177 SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
179 xbt_parmap_apply(sysv_parmap,
181 smx_process_t process = (smx_process_t) arg;
182 ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
185 simix_global->process_to_run);
187 xbt_die("You asked for a parallel execution, but you don't have any threads.");
191 smx_process_t first_process =
192 xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
193 sysv_process_index = 1;
194 SerialUContext* context =
195 static_cast<SerialUContext*>(first_process->context);
200 Context* UContextFactory::create_context(std::function<void()> code,
201 void_pfn_smxprocess_t cleanup, smx_process_t process)
204 return new_context<ParallelUContext>(std::move(code), cleanup, process);
206 return new_context<SerialUContext>(std::move(code), cleanup, process);
209 UContext::UContext(std::function<void()> code,
210 void_pfn_smxprocess_t cleanup_func, smx_process_t process)
211 : Context(std::move(code), cleanup_func, process)
213 /* if the user provided a function for the process then use it,
214 otherwise it is the context for maestro */
216 this->stack_ = (char*) SIMIX_context_stack_new();
217 getcontext(&this->uc_);
218 this->uc_.uc_link = nullptr;
219 this->uc_.uc_stack.ss_sp = pth_skaddr_makecontext(
220 this->stack_, smx_context_usable_stack_size);
221 this->uc_.uc_stack.ss_size = pth_sksize_makecontext(
222 this->stack_, smx_context_usable_stack_size);
223 simgrid_makecontext(&this->uc_, smx_ctx_sysv_wrapper, this);
225 if (process != NULL && sysv_maestro_context == NULL)
226 sysv_maestro_context = this;
230 if (MC_is_active() && has_code()) {
231 MC_register_stack_area(this->stack_, process,
232 &(this->uc_), smx_context_usable_stack_size);
237 UContext::~UContext()
239 SIMIX_context_stack_delete(this->stack_);
245 static void smx_ctx_sysv_wrapper(int first, ...)
247 // Rebuild the Context* pointer from the integers:
248 int ctx_addr[CTX_ADDR_LEN];
249 simgrid::simix::UContext* context;
251 if (CTX_ADDR_LEN > 1) {
254 for (unsigned i = 1; i < CTX_ADDR_LEN; i++)
255 ctx_addr[i] = va_arg(ap, int);
258 memcpy(&context, ctx_addr, sizeof(simgrid::simix::UContext*));
267 void SerialUContext::stop()
273 void SerialUContext::suspend()
275 /* determine the next context */
276 SerialUContext* next_context = nullptr;
277 unsigned long int i = sysv_process_index++;
279 if (i < xbt_dynar_length(simix_global->process_to_run)) {
280 /* execute the next process */
281 XBT_DEBUG("Run next process");
282 next_context = (SerialUContext*) xbt_dynar_get_as(
283 simix_global->process_to_run,i, smx_process_t)->context;
286 /* all processes were run, return to maestro */
287 XBT_DEBUG("No more process to run");
288 next_context = (SerialUContext*) sysv_maestro_context;
290 SIMIX_context_set_current(next_context);
291 swapcontext(&this->uc_, &next_context->uc_);
296 void SerialUContext::resume()
298 SIMIX_context_set_current(this);
299 swapcontext(&((SerialUContext*)sysv_maestro_context)->uc_, &this->uc_);
302 void ParallelUContext::stop()
308 /** Run one particular simulated process on the current thread. */
309 void ParallelUContext::resume()
311 #ifdef HAVE_THREAD_CONTEXTS
312 // What is my containing body?
313 uintptr_t worker_id = __sync_fetch_and_add(&sysv_threads_working, 1);
314 // Store the number of my containing body in os-thread-specific area :
315 xbt_os_thread_set_specific(sysv_worker_id_key, (void*) worker_id);
316 // Get my current soul:
317 ParallelUContext* worker_context = (ParallelUContext*) SIMIX_context_self();
318 // Write down that this soul is hosted in that body (for now)
319 sysv_workers_context[worker_id] = worker_context;
320 // Retrieve the system-level info that fuels this soul:
321 ucontext_t* worker_stack = &((ParallelUContext*) worker_context)->uc_;
322 // Write in simix that I switched my soul
323 SIMIX_context_set_current(this);
324 // Actually do that using the relevant library call:
325 swapcontext(worker_stack, &this->uc_);
326 // No body runs that soul anymore at this point.
327 // Instead the current body took the soul of simulated process
328 // The simulated process wakes back after the call to
329 // "SIMIX_context_suspend(self->context);" within
330 // smx_process.c::SIMIX_process_yield()
332 // From now on, the simulated processes will change their
333 // soul with the next soul to execute (in suspend_parallel, below).
334 // When nobody is to be executed in this scheduling round,
335 // the last simulated process will take back the initial
336 // soul of the current working thread
342 * This function is called when a simulated process wants to yield back
343 * to the maestro in a blocking simcall. This naturally occurs within
344 * SIMIX_context_suspend(self->context), called from SIMIX_process_yield()
345 * Actually, it does not really yield back to maestro, but into the next
346 * process that must be executed. If no one is to be executed, then it
347 * yields to the initial soul that was in this working thread (that was
348 * saved in resume_parallel).
350 void ParallelUContext::suspend()
352 #ifdef HAVE_THREAD_CONTEXTS
353 /* determine the next context */
354 // Get the next soul to embody now:
355 smx_process_t next_work = (smx_process_t) xbt_parmap_next(sysv_parmap);
356 ParallelUContext* next_context = nullptr;
357 // Will contain the next soul to run, either simulated or initial minion's one
358 ucontext_t* next_stack;
360 if (next_work != NULL) {
361 // There is a next soul to embody (ie, a next process to resume)
362 XBT_DEBUG("Run next process");
363 next_context = (ParallelUContext*) next_work->context;
366 // All processes were run, go to the barrier
367 XBT_DEBUG("No more processes to run");
368 // Get back the identity of my body that was stored when starting
369 // the scheduling round
370 uintptr_t worker_id =
371 (uintptr_t) xbt_os_thread_get_specific(sysv_worker_id_key);
372 // Deduce the initial soul of that body
373 next_context = (ParallelUContext*) sysv_workers_context[worker_id];
374 // When given that soul, the body will wait for the next scheduling round
377 next_stack = &next_context->uc_;
379 SIMIX_context_set_current(next_context);
380 // Get that next soul:
381 swapcontext(&this->uc_, next_stack);