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 RawContext.cpp
8 * Fast context switching inspired from SystemV ucontexts.
10 * In contrast to System V context, it does not touch the signal mask
11 * which avoids making a system call (at least on Linux).
19 #include "src/internal_config.h"
22 #include "xbt/parmap.h"
23 #include "xbt/dynar.h"
25 #include "smx_private.h"
26 #include "smx_private.hpp"
29 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
31 // ***** Class definitions
37 class RawContextFactory;
39 class RawContext : public Context {
41 void* stack_ = nullptr;
42 /** pointer to top the stack stack */
43 void* stack_top_ = nullptr;
45 friend class RawContextFactory;
46 RawContext(std::function<void()> code,
47 void_pfn_smxprocess_t cleanup_func,
48 smx_process_t process);
51 static void wrapper(void* arg);
53 void suspend() override;
56 void suspend_serial();
57 void suspend_parallel();
59 void resume_parallel();
62 class RawContextFactory : public ContextFactory {
66 RawContext* create_context(std::function<void()> code,
67 void_pfn_smxprocess_t, smx_process_t process) override;
68 void run_all() override;
70 void run_all_adaptative();
71 void run_all_serial();
72 void run_all_parallel();
75 ContextFactory* raw_factory()
77 XBT_VERB("Using raw contexts. Because the glibc is just not good enough for us.");
78 return new RawContextFactory();
84 // ***** Loads of static stuff
86 #if HAVE_THREAD_CONTEXTS
87 static xbt_parmap_t raw_parmap;
88 static simgrid::simix::RawContext** raw_workers_context; /* space to save the worker context in each thread */
89 static uintptr_t raw_threads_working; /* number of threads that have started their work */
90 static xbt_os_thread_key_t raw_worker_id_key; /* thread-specific storage for the thread id */
92 #ifdef ADAPTIVE_THRESHOLD
93 #define SCHED_ROUND_LIMIT 5
94 static xbt_os_timer_t round_time;
95 static double par_time,seq_time;
96 static double par_ratio,seq_ratio;
97 static int reached_seq_limit, reached_par_limit;
98 static unsigned int par_proc_that_ran = 0,seq_proc_that_ran = 0; /* Counters of processes that have run in SCHED_ROUND_LIMIT scheduling rounds */
99 static unsigned int seq_sched_round=0, par_sched_round=0; /* Amount of SR that ran serial/parallel*/
100 /*Varables used to calculate running variance and mean*/
101 static double prev_avg_par_proc=0,prev_avg_seq_proc=0;
102 static double delta=0;
103 static double s_par_proc=0,s_seq_proc=0; /*Standard deviation of number of processes computed in par/seq during the current simulation*/
104 static double avg_par_proc=0,sd_par_proc=0;
105 static double avg_seq_proc=0,sd_seq_proc=0;
106 static long long par_window=(long long)HUGE_VAL,seq_window=0;
108 static unsigned long raw_process_index = 0; /* index of the next process to run in the
109 * list of runnable processes */
110 static simgrid::simix::RawContext* raw_maestro_context;
112 static bool raw_context_parallel = false;
113 #ifdef ADAPTIVE_THRESHOLD
114 static bool raw_context_adaptative = false;
117 // ***** Raw context routines
119 typedef void (*rawctx_entry_point_t)(void *);
121 typedef void* raw_stack_t;
122 extern "C" raw_stack_t raw_makecontext(void* malloced_stack, int stack_size,
123 rawctx_entry_point_t entry_point, void* arg);
124 extern "C" void raw_swapcontext(raw_stack_t* old, raw_stack_t new_context);
128 #if defined(__APPLE__)
130 ".globl _raw_makecontext\n"
131 "_raw_makecontext:\n"
132 #elif defined(_WIN32)
134 ".globl raw_makecontext\n"
138 ".globl raw_makecontext\n"
139 ".type raw_makecontext,@function\n"
140 "raw_makecontext:\n"/* Calling convention sets the arguments in rdi, rsi, rdx and rcx, respectively */
142 " mov %rdi,%rax\n" /* stack */
143 " add %rsi,%rax\n" /* size */
144 " andq $-16, %rax\n" /* align stack */
145 " movq $0, -8(%rax)\n" /* @return for func */
146 " mov %rdx,-16(%rax)\n" /* func */
147 " mov %rcx,-24(%rax)\n" /* arg/rdi */
148 " movq $0, -32(%rax)\n" /* rsi */
149 " movq $0, -40(%rax)\n" /* rdx */
150 " movq $0, -48(%rax)\n" /* rcx */
151 " movq $0, -56(%rax)\n" /* r8 */
152 " movq $0, -64(%rax)\n" /* r9 */
153 " movq $0, -72(%rax)\n" /* rbp */
154 " movq $0, -80(%rax)\n" /* rbx */
155 " movq $0, -88(%rax)\n" /* r12 */
156 " movq $0, -96(%rax)\n" /* r13 */
157 " movq $0, -104(%rax)\n" /* r14 */
158 " movq $0, -112(%rax)\n" /* r15 */
164 #if defined(__APPLE__)
166 ".globl _raw_swapcontext\n"
167 "_raw_swapcontext:\n"
168 #elif defined(_WIN32)
170 ".globl raw_swapcontext\n"
174 ".globl raw_swapcontext\n"
175 ".type raw_swapcontext,@function\n"
176 "raw_swapcontext:\n" /* Calling convention sets the arguments in rdi and rsi, respectively */
190 " mov %rsp,(%rdi)\n" /* old */
191 " mov %rsi,%rsp\n" /* new */
208 #if defined(__APPLE__) || defined(_WIN32)
210 ".globl _raw_makecontext\n"
211 "_raw_makecontext:\n"
214 ".globl raw_makecontext\n"
215 ".type raw_makecontext,@function\n"
218 " movl 4(%esp),%eax\n" /* stack */
219 " addl 8(%esp),%eax\n" /* size */
220 " andl $-16, %eax\n" /* align stack */
221 " movl 12(%esp),%ecx\n" /* func */
222 " movl 16(%esp),%edx\n" /* arg */
223 " movl %edx, -4(%eax)\n"
224 " movl $0, -8(%eax)\n" /* @return for func */
225 " movl %ecx,-12(%eax)\n"
226 " movl $0, -16(%eax)\n" /* ebp */
227 " movl $0, -20(%eax)\n" /* ebx */
228 " movl $0, -24(%eax)\n" /* esi */
229 " movl $0, -28(%eax)\n" /* edi */
235 #if defined(__APPLE__) || defined(_WIN32)
237 ".globl _raw_swapcontext\n"
238 "_raw_swapcontext:\n"
241 ".globl raw_swapcontext\n"
242 ".type raw_swapcontext,@function\n"
245 " movl 4(%esp),%eax\n" /* old */
246 " movl 8(%esp),%edx\n" /* new */
251 " movl %esp,(%eax)\n"
262 /* If you implement raw contexts for other processors, don't forget to
263 update the definition of HAVE_RAW_CONTEXTS in tools/cmake/CompleteInFiles.cmake */
265 raw_stack_t raw_makecontext(void* malloced_stack, int stack_size,
266 rawctx_entry_point_t entry_point, void* arg) {
270 void raw_swapcontext(raw_stack_t* old, raw_stack_t new_context) {
276 // ***** Method definitions
281 RawContextFactory::RawContextFactory()
282 : ContextFactory("RawContextFactory")
284 #ifdef ADAPTIVE_THRESHOLD
285 raw_context_adaptative = (SIMIX_context_get_parallel_threshold() > 1);
287 raw_context_parallel = SIMIX_context_is_parallel();
288 if (raw_context_parallel) {
289 #if HAVE_THREAD_CONTEXTS
290 int nthreads = SIMIX_context_get_nthreads();
291 xbt_os_thread_key_create(&raw_worker_id_key);
293 raw_parmap = nullptr;
294 raw_workers_context = xbt_new(RawContext*, nthreads);
295 raw_maestro_context = nullptr;
297 // TODO, if(SIMIX_context_get_parallel_threshold() > 1) => choose dynamically
299 #ifdef ADAPTIVE_THRESHOLD
300 round_time = xbt_os_timer_new();
301 reached_seq_limit = 0;
302 reached_par_limit = 0;
306 RawContextFactory::~RawContextFactory()
308 #if HAVE_THREAD_CONTEXTS
310 xbt_parmap_destroy(raw_parmap);
311 xbt_free(raw_workers_context);
315 RawContext* RawContextFactory::create_context(std::function<void()> code,
316 void_pfn_smxprocess_t cleanup, smx_process_t process)
318 return this->new_context<RawContext>(std::move(code),
322 void RawContext::wrapper(void* arg)
324 RawContext* context = (RawContext*) arg;
329 RawContext::RawContext(std::function<void()> code,
330 void_pfn_smxprocess_t cleanup, smx_process_t process)
331 : Context(std::move(code), cleanup, process)
334 this->stack_ = SIMIX_context_stack_new();
335 this->stack_top_ = raw_makecontext(this->stack_,
336 smx_context_usable_stack_size,
340 if(process != nullptr && raw_maestro_context == nullptr)
341 raw_maestro_context = this;
344 &raw_maestro_context->stack_top_,
345 sizeof(raw_maestro_context->stack_top_));
349 RawContext::~RawContext()
351 SIMIX_context_stack_delete(this->stack_);
354 void RawContext::stop()
360 void RawContextFactory::run_all()
362 #ifdef ADAPTIVE_THRESHOLD
363 if (raw_context_adaptative)
364 run_all_adaptative();
367 if (raw_context_parallel)
373 void RawContextFactory::run_all_serial()
375 smx_process_t first_process =
376 xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
377 raw_process_index = 1;
378 static_cast<RawContext*>(first_process->context)->resume_serial();
381 void RawContextFactory::run_all_parallel()
383 #if HAVE_THREAD_CONTEXTS
384 raw_threads_working = 0;
385 if (raw_parmap == nullptr)
386 raw_parmap = xbt_parmap_new(
387 SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
388 xbt_parmap_apply(raw_parmap,
390 smx_process_t process = static_cast<smx_process_t>(arg);
391 RawContext* context = static_cast<RawContext*>(process->context);
392 context->resume_parallel();
394 simix_global->process_to_run);
396 xbt_die("You asked for a parallel execution, but you don't have any threads.");
400 void RawContext::suspend()
402 if (raw_context_parallel)
403 RawContext::suspend_parallel();
405 RawContext::suspend_serial();
408 void RawContext::suspend_serial()
410 /* determine the next context */
411 RawContext* next_context = nullptr;
413 i = raw_process_index++;
414 if (i < xbt_dynar_length(simix_global->process_to_run)) {
415 /* execute the next process */
416 XBT_DEBUG("Run next process");
417 next_context = (RawContext*) xbt_dynar_get_as(
418 simix_global->process_to_run, i, smx_process_t)->context;
421 /* all processes were run, return to maestro */
422 XBT_DEBUG("No more process to run");
423 next_context = (RawContext*) raw_maestro_context;
425 SIMIX_context_set_current(next_context);
426 raw_swapcontext(&this->stack_top_, next_context->stack_top_);
429 void RawContext::suspend_parallel()
431 #if HAVE_THREAD_CONTEXTS
432 /* determine the next context */
433 smx_process_t next_work = (smx_process_t) xbt_parmap_next(raw_parmap);
434 RawContext* next_context = nullptr;
436 if (next_work != NULL) {
437 /* there is a next process to resume */
438 XBT_DEBUG("Run next process");
439 next_context = (RawContext*) next_work->context;
442 /* all processes were run, go to the barrier */
443 XBT_DEBUG("No more processes to run");
444 uintptr_t worker_id = (uintptr_t)
445 xbt_os_thread_get_specific(raw_worker_id_key);
446 next_context = (RawContext*) raw_workers_context[worker_id];
447 XBT_DEBUG("Restoring worker stack %zu (working threads = %zu)",
448 worker_id, raw_threads_working);
451 SIMIX_context_set_current(next_context);
452 raw_swapcontext(&this->stack_top_, next_context->stack_top_);
456 void RawContext::resume()
458 if (raw_context_parallel)
464 void RawContext::resume_serial()
466 SIMIX_context_set_current(this);
467 raw_swapcontext(&raw_maestro_context->stack_top_, this->stack_top_);
470 void RawContext::resume_parallel()
472 #if HAVE_THREAD_CONTEXTS
473 uintptr_t worker_id = __sync_fetch_and_add(&raw_threads_working, 1);
474 xbt_os_thread_set_specific(raw_worker_id_key, (void*) worker_id);
475 RawContext* worker_context = (RawContext*) SIMIX_context_self();
476 raw_workers_context[worker_id] = worker_context;
477 XBT_DEBUG("Saving worker stack %zu", worker_id);
478 SIMIX_context_set_current(this);
479 raw_swapcontext(&worker_context->stack_top_, this->stack_top_);
481 xbt_die("Parallel execution disabled");
486 * \brief Resumes all processes ready to run.
488 #ifdef ADAPTIVE_THRESHOLD
489 void RawContectFactory::run_all_adaptative()
491 unsigned long nb_processes = xbt_dynar_length(simix_global->process_to_run);
492 unsigned long threshold = SIMIX_context_get_parallel_threshold();
493 reached_seq_limit = (seq_sched_round % SCHED_ROUND_LIMIT == 0);
494 reached_par_limit = (par_sched_round % SCHED_ROUND_LIMIT == 0);
496 if(reached_seq_limit && reached_par_limit){
497 par_ratio = (par_proc_that_ran != 0) ? (par_time / (double)par_proc_that_ran) : 0;
498 seq_ratio = (seq_proc_that_ran != 0) ? (seq_time / (double)seq_proc_that_ran) : 0;
499 if(seq_ratio > par_ratio){
500 if(nb_processes < avg_par_proc) {
501 threshold = (threshold>2) ? threshold - 1 : threshold ;
502 SIMIX_context_set_parallel_threshold(threshold);
505 if(nb_processes > avg_seq_proc){
506 SIMIX_context_set_parallel_threshold(threshold+1);
511 if (nb_processes >= SIMIX_context_get_parallel_threshold()) {
512 simix_global->context_factory->suspend = smx_ctx_raw_suspend_parallel;
513 if (nb_processes < par_window){
515 xbt_os_walltimer_start(round_time);
516 smx_ctx_raw_runall_parallel();
517 xbt_os_walltimer_stop(round_time);
518 par_time += xbt_os_timer_elapsed(round_time);
520 prev_avg_par_proc = avg_par_proc;
521 delta = nb_processes - avg_par_proc;
522 avg_par_proc = (par_sched_round==1) ? nb_processes : avg_par_proc + delta / (double) par_sched_round;
524 if(par_sched_round>=2){
525 s_par_proc = s_par_proc + (nb_processes - prev_avg_par_proc) * delta;
526 sd_par_proc = sqrt(s_par_proc / (par_sched_round-1));
527 par_window = (int) (avg_par_proc + sd_par_proc);
532 par_proc_that_ran += nb_processes;
534 smx_ctx_raw_runall_parallel();
537 simix_global->context_factory->suspend = smx_ctx_raw_suspend_serial;
538 if(nb_processes > seq_window){
540 xbt_os_walltimer_start(round_time);
541 smx_ctx_raw_runall_serial();
542 xbt_os_walltimer_stop(round_time);
543 seq_time += xbt_os_timer_elapsed(round_time);
545 prev_avg_seq_proc = avg_seq_proc;
546 delta = (nb_processes-avg_seq_proc);
547 avg_seq_proc = (seq_sched_round==1) ? nb_processes : avg_seq_proc + delta / (double) seq_sched_round;
549 if(seq_sched_round>=2){
550 s_seq_proc = s_seq_proc + (nb_processes - prev_avg_seq_proc)*delta;
551 sd_seq_proc = sqrt(s_seq_proc / (seq_sched_round-1));
552 seq_window = (int) (avg_seq_proc - sd_seq_proc);
557 seq_proc_that_ran += nb_processes;
559 smx_ctx_raw_runall_serial();
567 void RawContextFactory::run_all_adaptative()
569 unsigned long nb_processes = xbt_dynar_length(simix_global->process_to_run);
570 if (SIMIX_context_is_parallel()
571 && (unsigned long) SIMIX_context_get_parallel_threshold() < nb_processes) {
572 raw_context_parallel = true;
573 XBT_DEBUG("Runall // %lu", nb_processes);
574 this->run_all_parallel();
576 XBT_DEBUG("Runall serial %lu", nb_processes);
577 raw_context_parallel = false;
578 this->run_all_serial();