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 */
11 #include "xbt/parmap.h"
12 #include "smx_private.h"
13 #include "smx_private.hpp"
14 #include "src/internal_config.h"
15 #include "src/context_sysv_config.h" /* loads context system definitions */
19 # include <xbt/win32_ucontext.h> /* context relative declarations */
21 # include <ucontext.h> /* context relative declarations */
24 /** Many integers are needed to store a pointer
26 * This is a bit paranoid about sizeof(smx_ctx_sysv_t) not being a multiple
27 * of sizeof(int), but it doesn't harm. */
28 #define CTX_ADDR_LEN \
29 (sizeof(void*) / sizeof(int) + \
30 !!(sizeof(void*) % sizeof(int)))
32 /** A better makecontext
34 * Makecontext expects integer arguments, we the context
35 * variable is decomposed into a serie of integers and
36 * each integer is passed as argument to makecontext. */
38 void simgrid_makecontext(ucontext* ucp, void (*func)(int first, ...), void* arg)
40 int ctx_addr[CTX_ADDR_LEN];
41 memcpy(ctx_addr, &arg, sizeof(void*));
42 switch (CTX_ADDR_LEN) {
44 makecontext(ucp, (void (*)())func, 1, ctx_addr[0]);
47 makecontext(ucp, (void (*)()) func, 2, ctx_addr[0], ctx_addr[1]);
50 xbt_die("Ucontexts are not supported on this arch yet (addr len = %zu/%zu = %zu)",
51 sizeof(void*), sizeof(int), CTX_ADDR_LEN);
55 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
61 class ParallelUContext;
62 class UContextFactory;
66 #ifdef CONTEXT_THREADS
67 static xbt_parmap_t sysv_parmap;
68 static simgrid::simix::ParallelUContext** sysv_workers_context; /* space to save the worker's context in each thread */
69 static unsigned long sysv_threads_working; /* number of threads that have started their work */
70 static xbt_os_thread_key_t sysv_worker_id_key; /* thread-specific storage for the thread id */
72 static unsigned long sysv_process_index = 0; /* index of the next process to run in the
73 * list of runnable processes */
74 static simgrid::simix::UContext* sysv_maestro_context;
75 static bool sysv_parallel;
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(xbt_main_func_t code,
87 int argc, char **argv,
88 void_pfn_smxprocess_t cleanup_func,
89 smx_process_t process);
92 static void wrapper(int first, ...);
95 class SerialUContext : public UContext {
97 SerialUContext(xbt_main_func_t code,
98 int argc, char **argv,
99 void_pfn_smxprocess_t cleanup_func,
100 smx_process_t process)
101 : UContext(code, argc, argv, cleanup_func, process)
103 void stop() override;
104 void suspend() override;
108 class ParallelUContext : public UContext {
110 ParallelUContext(xbt_main_func_t code,
111 int argc, char **argv,
112 void_pfn_smxprocess_t cleanup_func,
113 smx_process_t process)
114 : UContext(code, argc, argv, cleanup_func, process)
116 void stop() override;
117 void suspend() override;
121 class UContextFactory : public ContextFactory {
124 friend SerialUContext;
125 friend ParallelUContext;
128 virtual ~UContextFactory();
129 virtual Context* create_context(
130 xbt_main_func_t, int, char **, void_pfn_smxprocess_t,
131 smx_process_t process
133 void run_all() override;
136 XBT_PRIVATE ContextFactory* sysv_factory()
138 XBT_VERB("Activating SYSV context factory");
139 return new UContextFactory();
142 UContextFactory::UContextFactory() : ContextFactory("UContextFactory")
144 if (SIMIX_context_is_parallel()) {
145 sysv_parallel = true;
146 #ifdef CONTEXT_THREADS /* To use parallel ucontexts a thread pool is needed */
147 int nthreads = SIMIX_context_get_nthreads();
148 sysv_parmap = nullptr;
149 sysv_workers_context = xbt_new(ParallelUContext*, nthreads);
150 sysv_maestro_context = nullptr;
151 xbt_os_thread_key_create(&sysv_worker_id_key);
153 THROWF(arg_error, 0, "No thread support for parallel context execution");
156 sysv_parallel = false;
160 UContextFactory::~UContextFactory()
162 #ifdef CONTEXT_THREADS
164 xbt_parmap_destroy(sysv_parmap);
165 xbt_free(sysv_workers_context);
169 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some stuff
170 * It is much easier to understand what happens if you see the working threads as bodies that swap their soul for the
171 * ones of the simulated processes that must run.
173 void UContextFactory::run_all()
176 #ifdef CONTEXT_THREADS
177 sysv_threads_working = 0;
178 // Parmap_apply ensures that every working thread get an index in the
179 // process_to_run array (through an atomic fetch_and_add),
180 // and runs the smx_ctx_sysv_resume_parallel function on that index
182 // We lazily create the parmap because the parmap creates context
183 // with simix_global->context_factory (which might not be initialized
184 // when bootstrapping):
185 if (sysv_parmap == nullptr)
186 sysv_parmap = xbt_parmap_new(
187 SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
189 xbt_parmap_apply(sysv_parmap,
191 smx_process_t process = (smx_process_t) arg;
192 ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
195 simix_global->process_to_run);
197 xbt_die("You asked for a parallel execution, but you don't have any threads.");
201 smx_process_t first_process =
202 xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
203 sysv_process_index = 1;
204 SerialUContext* context =
205 static_cast<SerialUContext*>(first_process->context);
210 Context* UContextFactory::create_context(
211 xbt_main_func_t code, int argc, char ** argv,
212 void_pfn_smxprocess_t cleanup,
213 smx_process_t process
217 return new_context<ParallelUContext>(code, argc, argv, cleanup, process);
219 return new_context<SerialUContext>(code, argc, argv, cleanup, process);
222 UContext::UContext(xbt_main_func_t code,
223 int argc, char **argv,
224 void_pfn_smxprocess_t cleanup_func,
225 smx_process_t process)
226 : Context(code, argc, argv, cleanup_func, process)
228 /* if the user provided a function for the process then use it,
229 otherwise it is the context for maestro */
231 this->stack_ = (char*) SIMIX_context_stack_new();
232 getcontext(&this->uc_);
233 this->uc_.uc_link = nullptr;
234 this->uc_.uc_stack.ss_sp = pth_skaddr_makecontext(
235 this->stack_, smx_context_usable_stack_size);
236 this->uc_.uc_stack.ss_size = pth_sksize_makecontext(
237 this->stack_, smx_context_usable_stack_size);
238 simgrid_makecontext(&this->uc_, UContext::wrapper, this);
240 if (process != NULL && sysv_maestro_context == NULL)
241 sysv_maestro_context = this;
245 if (MC_is_active() && code) {
246 MC_register_stack_area(this->stack_, context->process,
247 &(this->uc_), smx_context_usable_stack_size);
252 UContext::~UContext()
254 SIMIX_context_stack_delete(this->stack_);
257 void UContext::wrapper(int first, ...)
259 // Rebuild the Context* pointer from the integers:
260 int ctx_addr[CTX_ADDR_LEN];
263 if (CTX_ADDR_LEN > 1) {
266 for (unsigned i = 1; i < CTX_ADDR_LEN; i++)
267 ctx_addr[i] = va_arg(ap, int);
270 memcpy(&context, ctx_addr, sizeof(UContext*));
276 void SerialUContext::stop()
282 void SerialUContext::suspend()
284 /* determine the next context */
285 SerialUContext* next_context = nullptr;
286 unsigned long int i = sysv_process_index++;
288 if (i < xbt_dynar_length(simix_global->process_to_run)) {
289 /* execute the next process */
290 XBT_DEBUG("Run next process");
291 next_context = (SerialUContext*) xbt_dynar_get_as(
292 simix_global->process_to_run,i, smx_process_t)->context;
295 /* all processes were run, return to maestro */
296 XBT_DEBUG("No more process to run");
297 next_context = (SerialUContext*) sysv_maestro_context;
299 SIMIX_context_set_current(next_context);
300 swapcontext(&this->uc_, &next_context->uc_);
305 void SerialUContext::resume()
307 SIMIX_context_set_current(this);
308 swapcontext(&((SerialUContext*)sysv_maestro_context)->uc_, &this->uc_);
311 void ParallelUContext::stop()
317 /** Run one particular simulated process on the current thread. */
318 void ParallelUContext::resume()
320 #ifdef CONTEXT_THREADS
321 // What is my containing body?
322 unsigned long worker_id = __sync_fetch_and_add(&sysv_threads_working, 1);
323 // Store the number of my containing body in os-thread-specific area :
324 xbt_os_thread_set_specific(sysv_worker_id_key, (void*) worker_id);
325 // Get my current soul:
326 ParallelUContext* worker_context = (ParallelUContext*) SIMIX_context_self();
327 // Write down that this soul is hosted in that body (for now)
328 sysv_workers_context[worker_id] = worker_context;
329 // Retrieve the system-level info that fuels this soul:
330 ucontext_t* worker_stack = &((ParallelUContext*) worker_context)->uc_;
331 // Write in simix that I switched my soul
332 SIMIX_context_set_current(this);
333 // Actually do that using the relevant library call:
334 swapcontext(worker_stack, &this->uc_);
335 // No body runs that soul anymore at this point.
336 // Instead the current body took the soul of simulated process
337 // The simulated process wakes back after the call to
338 // "SIMIX_context_suspend(self->context);" within
339 // smx_process.c::SIMIX_process_yield()
341 // From now on, the simulated processes will change their
342 // soul with the next soul to execute (in suspend_parallel, below).
343 // When nobody is to be executed in this scheduling round,
344 // the last simulated process will take back the initial
345 // soul of the current working thread
351 * This function is called when a simulated process wants to yield back
352 * to the maestro in a blocking simcall. This naturally occurs within
353 * SIMIX_context_suspend(self->context), called from SIMIX_process_yield()
354 * Actually, it does not really yield back to maestro, but into the next
355 * process that must be executed. If no one is to be executed, then it
356 * yields to the initial soul that was in this working thread (that was
357 * saved in resume_parallel).
359 void ParallelUContext::suspend()
361 #ifdef CONTEXT_THREADS
362 /* determine the next context */
363 // Get the next soul to embody now:
364 smx_process_t next_work = (smx_process_t) xbt_parmap_next(sysv_parmap);
365 ParallelUContext* next_context = nullptr;
366 // Will contain the next soul to run, either simulated or initial minion's one
367 ucontext_t* next_stack;
369 if (next_work != NULL) {
370 // There is a next soul to embody (ie, a next process to resume)
371 XBT_DEBUG("Run next process");
372 next_context = (ParallelUContext*) next_work->context;
375 // All processes were run, go to the barrier
376 XBT_DEBUG("No more processes to run");
377 // Get back the identity of my body that was stored when starting
378 // the scheduling round
379 unsigned long worker_id =
380 (unsigned long) xbt_os_thread_get_specific(sysv_worker_id_key);
381 // Deduce the initial soul of that body
382 next_context = (ParallelUContext*) sysv_workers_context[worker_id];
383 // When given that soul, the body will wait for the next scheduling round
386 next_stack = &next_context->uc_;
388 SIMIX_context_set_current(next_context);
389 // Get that next soul:
390 swapcontext(&this->uc_, next_stack);