Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
bd78c9cff9c825360151253c85da32994e4e860d
[simgrid.git] / src / simix / smx_context_raw.c
1 /* context_raw - fast context switching inspired from System V ucontextes   */
2
3 /* Copyright (c) 2009-2013. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "smx_private.h"
10 #include "xbt/parmap.h"
11 #include "mc/mc.h"
12
13 #ifdef HAVE_VALGRIND_VALGRIND_H
14 #  include <valgrind/valgrind.h>
15 #endif                          /* HAVE_VALGRIND_VALGRIND_H */
16
17 typedef char * raw_stack_t;
18 typedef void (*rawctx_entry_point_t)(void *);
19
20 typedef struct s_smx_ctx_raw {
21   s_smx_ctx_base_t super;         /* Fields of super implementation */
22   char *malloced_stack;           /* malloced area containing the stack */
23   raw_stack_t stack_top;          /* pointer to stack top (within previous area) */
24 #ifdef HAVE_VALGRIND_VALGRIND_H
25   unsigned int valgrind_stack_id; /* the valgrind stack id */
26 #endif
27 #ifdef TIME_BENCH_PER_SR
28   unsigned int thread;            /* Just for measuring purposes */
29 #endif
30 } s_smx_ctx_raw_t, *smx_ctx_raw_t;
31
32 #ifdef CONTEXT_THREADS
33 static xbt_parmap_t raw_parmap;
34 static smx_ctx_raw_t* raw_workers_context;    /* space to save the worker context in each thread */
35 static unsigned long raw_threads_working;     /* number of threads that have started their work */
36 static xbt_os_thread_key_t raw_worker_id_key; /* thread-specific storage for the thread id */
37 #endif
38
39 static unsigned long raw_process_index = 0;   /* index of the next process to run in the
40                                                * list of runnable processes */
41 static smx_ctx_raw_t raw_maestro_context;
42
43 extern raw_stack_t raw_makecontext(char* malloced_stack, int stack_size,
44                                    rawctx_entry_point_t entry_point, void* arg);
45 extern void raw_swapcontext(raw_stack_t* old, raw_stack_t new);
46
47 #ifdef PROCESSOR_x86_64
48 __asm__ (
49 #if defined(APPLE)
50    ".text\n"
51    ".globl _raw_makecontext\n"
52    "_raw_makecontext:\n"
53 #elif defined(_WIN32)
54    ".text\n"
55    ".globl raw_makecontext\n"
56    "raw_makecontext:\n"
57 #else
58    ".text\n"
59    ".globl raw_makecontext\n"
60    ".type raw_makecontext,@function\n"
61    "raw_makecontext:\n"/* Calling convention sets the arguments in rdi, rsi, rdx and rcx, respectively */
62 #endif
63    "   mov %rdi,%rax\n"      /* stack */
64    "   add %rsi,%rax\n"      /* size  */
65    "   movq $0,   -8(%rax)\n" /* @return for func */
66    "   mov %rdx,-16(%rax)\n" /* func */
67    "   mov %rcx,-24(%rax)\n" /* arg/rdi */
68    "   movq $0,  -32(%rax)\n" /* rsi */
69    "   movq $0,  -40(%rax)\n" /* rdx */
70    "   movq $0,  -48(%rax)\n" /* rcx */
71    "   movq $0,  -56(%rax)\n" /* r8  */
72    "   movq $0,  -64(%rax)\n" /* r9  */
73    "   movq $0,  -72(%rax)\n" /* rbp */
74    "   movq $0,  -80(%rax)\n" /* rbx */
75    "   movq $0,  -88(%rax)\n" /* r12 */
76    "   movq $0,  -96(%rax)\n" /* r13 */
77    "   movq $0, -104(%rax)\n" /* r14 */
78    "   movq $0, -112(%rax)\n" /* r15 */
79    "   sub $112,%rax\n"
80    "   ret\n"
81 );
82
83 __asm__ (
84 #if defined(APPLE)
85    ".text\n"
86    ".globl _raw_swapcontext\n"
87    "_raw_swapcontext:\n"
88 #elif defined(_WIN32)
89    ".text\n"
90    ".globl raw_swapcontext\n"
91    "raw_swapcontext:\n"
92 #else
93    ".text\n"
94    ".globl raw_swapcontext\n"
95    ".type raw_swapcontext,@function\n"
96    "raw_swapcontext:\n" /* Calling convention sets the arguments in rdi and rsi, respectively */
97 #endif
98    "   push %rdi\n"
99    "   push %rsi\n"
100    "   push %rdx\n"
101    "   push %rcx\n"
102    "   push %r8\n"
103    "   push %r9\n"
104    "   push %rbp\n"
105    "   push %rbx\n"
106    "   push %r12\n"
107    "   push %r13\n"
108    "   push %r14\n"
109    "   push %r15\n"
110    "   mov %rsp,(%rdi)\n" /* old */
111    "   mov %rsi,%rsp\n" /* new */
112    "   pop %r15\n"
113    "   pop %r14\n"
114    "   pop %r13\n"
115    "   pop %r12\n"
116    "   pop %rbx\n"
117    "   pop %rbp\n"
118    "   pop %r9\n"
119    "   pop %r8\n"
120    "   pop %rcx\n"
121    "   pop %rdx\n"
122    "   pop %rsi\n"
123    "   pop %rdi\n"
124    "   ret\n"
125 );
126 #elif PROCESSOR_i686
127 __asm__ (
128 #if defined(APPLE) || defined(_WIN32)
129    ".text\n"
130    ".globl _raw_makecontext\n"
131    "_raw_makecontext:\n"
132 #else
133    ".text\n"
134    ".globl raw_makecontext\n"
135    ".type raw_makecontext,@function\n"
136    "raw_makecontext:\n"
137 #endif
138    "   movl 4(%esp),%eax\n"   /* stack */
139    "   addl 8(%esp),%eax\n"   /* size  */
140    "   movl 12(%esp),%ecx\n"  /* func  */
141    "   movl 16(%esp),%edx\n"  /* arg   */
142    "   movl %edx, -4(%eax)\n"
143    "   movl $0,   -8(%eax)\n" /* @return for func */
144    "   movl %ecx,-12(%eax)\n"
145    "   movl $0,  -16(%eax)\n" /* ebp */
146    "   movl $0,  -20(%eax)\n" /* ebx */
147    "   movl $0,  -24(%eax)\n" /* esi */
148    "   movl $0,  -28(%eax)\n" /* edi */
149    "   subl $28,%eax\n"
150    "   retl\n"
151 );
152
153 __asm__ (
154 #if defined(APPLE) || defined(_WIN32)
155    ".text\n"
156    ".globl _raw_swapcontext\n"
157    "_raw_swapcontext:\n"
158 #else
159    ".text\n"
160    ".globl raw_swapcontext\n"
161    ".type raw_swapcontext,@function\n"
162    "raw_swapcontext:\n"
163 #endif
164    "   movl 4(%esp),%eax\n" /* old */
165    "   movl 8(%esp),%edx\n" /* new */
166    "   pushl %ebp\n"
167    "   pushl %ebx\n"
168    "   pushl %esi\n"
169    "   pushl %edi\n"
170    "   movl %esp,(%eax)\n"
171    "   movl %edx,%esp\n"
172    "   popl %edi\n"
173    "   popl %esi\n"
174    "   popl %ebx\n"
175    "   popl %ebp\n"
176    "   retl\n"
177 );
178 #else
179
180
181 /* If you implement raw contexts for other processors, don't forget to
182    update the definition of HAVE_RAWCTX in buildtools/Cmake/CompleteInFiles.cmake */
183
184 raw_stack_t raw_makecontext(char* malloced_stack, int stack_size,
185                             rawctx_entry_point_t entry_point, void* arg) {
186    THROW_UNIMPLEMENTED;
187 }
188
189 void raw_swapcontext(raw_stack_t* old, raw_stack_t new) {
190    THROW_UNIMPLEMENTED;
191 }
192
193 #endif
194
195 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
196
197 #ifdef TIME_BENCH_PER_SR
198 #include "xbt/xbt_os_time.h"
199 #define NUM_THREADS 4
200 static xbt_os_timer_t timer;
201 static double time_thread_sr[NUM_THREADS];
202 static double time_thread_ssr[NUM_THREADS];
203 static double time_wasted_sr = 0;
204 static double time_wasted_ssr = 0;
205 static unsigned int sr_count = 0;
206 static unsigned int ssr_count = 0;
207 static char new_sr = 0;
208 #endif
209
210 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context);
211 static int smx_ctx_raw_factory_finalize(smx_context_factory_t *factory);
212 static smx_context_t smx_ctx_raw_create_context(xbt_main_func_t code, int argc,
213     char **argv, void_pfn_smxprocess_t cleanup_func, void *data);
214 static void smx_ctx_raw_free(smx_context_t context);
215 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context);
216 static void smx_ctx_raw_stop(smx_context_t context);
217 static void smx_ctx_raw_suspend_serial(smx_context_t context);
218 static void smx_ctx_raw_resume_serial(smx_process_t first_process);
219 static void smx_ctx_raw_runall_serial(void);
220 static void smx_ctx_raw_suspend_parallel(smx_context_t context);
221 static void smx_ctx_raw_resume_parallel(smx_process_t first_process);
222 static void smx_ctx_raw_runall_parallel(void);
223 static void smx_ctx_raw_runall(void);
224
225 /**
226  * \brief Initializes the raw context factory.
227  * \param factory where to initialize the factory
228  */
229 void SIMIX_ctx_raw_factory_init(smx_context_factory_t *factory)
230 {
231
232   XBT_VERB("Using raw contexts. Because the glibc is just not good enough for us.");
233   smx_ctx_base_factory_init(factory);
234
235   (*factory)->finalize  = smx_ctx_raw_factory_finalize;
236   (*factory)->create_context = smx_ctx_raw_create_context;
237   /* Do not overload that method (*factory)->finalize */
238   (*factory)->free = smx_ctx_raw_free;
239   (*factory)->stop = smx_ctx_raw_stop;
240   (*factory)->name = "smx_raw_context_factory";
241
242   if (SIMIX_context_is_parallel()) {
243 #ifdef CONTEXT_THREADS
244     int nthreads = SIMIX_context_get_nthreads();
245     xbt_os_thread_key_create(&raw_worker_id_key);
246     raw_parmap = xbt_parmap_new(nthreads, SIMIX_context_get_parallel_mode());
247     raw_workers_context = xbt_new(smx_ctx_raw_t, nthreads);
248     raw_maestro_context=NULL;
249
250 #endif
251     if (SIMIX_context_get_parallel_threshold() > 1) {
252       /* choose dynamically */
253       (*factory)->runall = smx_ctx_raw_runall;
254       (*factory)->suspend = NULL;
255     }
256     else {
257       /* always parallel */
258       (*factory)->runall = smx_ctx_raw_runall_parallel;
259       (*factory)->suspend = smx_ctx_raw_suspend_parallel;
260     }
261   }
262   else {
263     /* always serial */
264     (*factory)->runall = smx_ctx_raw_runall_serial;
265     (*factory)->suspend = smx_ctx_raw_suspend_serial;
266   }
267 #ifdef TIME_BENCH_PER_SR
268   timer = xbt_os_timer_new();
269 #endif
270 }
271
272 /**
273  * \brief Finalizes the raw context factory.
274  * \param factory the raw context factory
275  */
276 static int smx_ctx_raw_factory_finalize(smx_context_factory_t *factory)
277 {
278 #ifdef TIME_BENCH_PER_SR
279   XBT_CRITICAL("Total wasted time in %u SR: %lf", sr_count, time_wasted_sr);
280   XBT_CRITICAL("Total wasted time in %u SSR: %lf", ssr_count, time_wasted_ssr);
281 #endif
282
283 #ifdef CONTEXT_THREADS
284   if (raw_parmap)
285     xbt_parmap_destroy(raw_parmap);
286   xbt_free(raw_workers_context);
287 #endif
288   return smx_ctx_base_factory_finalize(factory);
289 }
290
291 /**
292  * \brief Creates a new raw context.
293  * \param code main function of this context or NULL to create the maestro
294  * context
295  * \param argc argument number
296  * \param argv arguments to pass to the main function
297  * \param cleanup_func a function to call to free the user data when the
298  * context finished
299  * \param data user data
300  */
301 static smx_context_t
302 smx_ctx_raw_create_context(xbt_main_func_t code, int argc, char **argv,
303     void_pfn_smxprocess_t cleanup_func,
304     void *data)
305 {
306
307   smx_ctx_raw_t context =
308       (smx_ctx_raw_t) smx_ctx_base_factory_create_context_sized(
309           sizeof(s_smx_ctx_raw_t),
310           code,
311           argc,
312           argv,
313           cleanup_func,
314           data);
315
316   /* if the user provided a function for the process then use it,
317      otherwise it is the context for maestro */
318      if (code) {
319        context->malloced_stack = xbt_malloc0(smx_context_stack_size);
320        context->stack_top =
321            raw_makecontext(context->malloced_stack, smx_context_stack_size,
322                (void_f_pvoid_t) smx_ctx_raw_wrapper, context);
323
324 #ifdef HAVE_VALGRIND_VALGRIND_H
325        context->valgrind_stack_id =
326            VALGRIND_STACK_REGISTER(context->malloced_stack,
327                context->malloced_stack + smx_context_stack_size);
328 #endif                          /* HAVE_VALGRIND_VALGRIND_H */
329
330      } else {
331        if(data != NULL && raw_maestro_context==NULL)
332          raw_maestro_context = context;
333
334        if(MC_is_active())
335          MC_ignore_heap(&(raw_maestro_context->stack_top), sizeof(raw_maestro_context->stack_top));
336
337      }
338
339      return (smx_context_t) context;
340 }
341
342 /**
343  * \brief Destroys a raw context.
344  * \param context a raw context
345  */
346 static void smx_ctx_raw_free(smx_context_t context)
347 {
348   if (context) {
349
350 #ifdef HAVE_VALGRIND_VALGRIND_H
351     VALGRIND_STACK_DEREGISTER(((smx_ctx_raw_t)
352         context)->valgrind_stack_id);
353 #endif                          /* HAVE_VALGRIND_VALGRIND_H */
354
355     free(((smx_ctx_raw_t) context)->malloced_stack);
356   }
357   smx_ctx_base_free(context);
358 }
359
360 /**
361  * \brief Wrapper for the main function of a context.
362  * \param context a raw context
363  */
364 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context)
365 {
366   (context->super.code) (context->super.argc, context->super.argv);
367
368   smx_ctx_raw_stop((smx_context_t) context);
369 }
370
371 /**
372  * \brief Stops a raw context.
373  *
374  * This function is called when the main function of the context if finished.
375  *
376  * \param context the current context
377  */
378 static void smx_ctx_raw_stop(smx_context_t context)
379 {
380   smx_ctx_base_stop(context);
381   simix_global->context_factory->suspend(context);
382 }
383
384 /**
385  * \brief Suspends a running context and resumes another one or returns to
386  * maestro.
387  * \param context the current context
388  */
389 static void smx_ctx_raw_suspend_serial(smx_context_t context)
390 {
391   /* determine the next context */
392   smx_context_t next_context;
393   unsigned long int i = raw_process_index++;
394
395   if (i < xbt_dynar_length(simix_global->process_to_run)) {
396     /* execute the next process */
397     XBT_DEBUG("Run next process");
398     next_context = xbt_dynar_get_as(
399         simix_global->process_to_run, i, smx_process_t)->context;
400   }
401   else {
402     /* all processes were run, return to maestro */
403     XBT_DEBUG("No more process to run");
404     next_context = (smx_context_t) raw_maestro_context;
405   }
406   SIMIX_context_set_current(next_context);
407   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top,
408       ((smx_ctx_raw_t) next_context)->stack_top);
409 }
410
411 /**
412  * \brief Resumes sequentially all processes ready to run.
413  * \param first_process the first process to resume
414  */
415 static void smx_ctx_raw_resume_serial(smx_process_t first_process)
416 {
417   smx_ctx_raw_t context = (smx_ctx_raw_t) first_process->context;
418   SIMIX_context_set_current((smx_context_t) context);
419   raw_swapcontext(&raw_maestro_context->stack_top,
420       ((smx_ctx_raw_t) context)->stack_top);
421 }
422
423 #ifdef TIME_BENCH_PER_SR
424 static void smx_ctx_raw_runall_serial(xbt_dynar_t processes)
425 {
426   smx_process_t process;
427   unsigned int cursor;
428
429   double elapsed = 0;
430   double tmax = 0;
431   unsigned long num_proc = xbt_dynar_length(processes);
432   unsigned int t=0;
433   unsigned int data_size = (num_proc / NUM_THREADS) + ((num_proc % NUM_THREADS) ? 1 : 0);
434
435   ssr_count++;
436   time_thread_ssr[0] = 0;
437   xbt_dynar_foreach(processes, cursor, process) {
438     XBT_DEBUG("Schedule item %u of %lu",cursor,xbt_dynar_length(processes));
439     if(cursor >= t * data_size + data_size){
440       if(time_thread_ssr[t] > tmax)
441         tmax = time_thread_ssr[t];
442       t++;
443       time_thread_ssr[t] = 0;
444     }
445
446     if(new_sr){
447       ((smx_ctx_raw_t)process->context)->thread = t;
448       time_thread_sr[t] = 0;
449     }
450
451     xbt_os_cputimer_start(timer);
452     smx_ctx_raw_resume(process);
453     xbt_os_cputimer_stop(timer);
454     elapsed = xbt_os_timer_elapsed(timer);
455     time_thread_ssr[t] += elapsed;
456     time_thread_sr[((smx_ctx_raw_t)process->context)->thread] += elapsed;
457   }
458
459   if(new_sr)
460     new_sr = FALSE;
461
462   if(time_thread_ssr[t] > tmax)
463     tmax = time_thread_ssr[t];
464
465   for(cursor=0; cursor <= t; cursor++){
466     XBT_VERB("Time SSR thread %u = %lf (max %lf)", cursor, time_thread_ssr[cursor], tmax);
467     time_wasted_ssr += tmax - time_thread_ssr[cursor];
468   }
469 }
470
471 void smx_ctx_raw_new_sr(void);
472 void smx_ctx_raw_new_sr(void)
473 {
474   int i;
475   double tmax = 0;
476   new_sr = TRUE;
477   sr_count++;
478   for(i=0; i < NUM_THREADS; i++){
479     if(time_thread_sr[i] > tmax)
480       tmax = time_thread_sr[i];
481   }
482
483   for(i=0; i < NUM_THREADS; i++){
484     XBT_VERB("Time SR thread %u = %lf (max %lf)", i, time_thread_sr[i], tmax);
485     time_wasted_sr += tmax - time_thread_sr[i];
486   }
487
488   XBT_VERB("New scheduling round");
489 }
490 #else
491
492 /**
493  * \brief Resumes sequentially all processes ready to run.
494  */
495 static void smx_ctx_raw_runall_serial(void)
496 {
497   smx_process_t first_process =
498       xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
499   raw_process_index = 1;
500
501   /* execute the first process */
502   smx_ctx_raw_resume_serial(first_process);
503 }
504 #endif
505
506 /**
507  * \brief Suspends a running context and resumes another one or returns to
508  * the main function of the current worker thread.
509  * \param context the context of the current worker thread
510  */
511 static void smx_ctx_raw_suspend_parallel(smx_context_t context)
512 {
513 #ifdef CONTEXT_THREADS
514   /* determine the next context */
515   smx_process_t next_work = xbt_parmap_next(raw_parmap);
516   smx_context_t next_context;
517   raw_stack_t next_stack;
518
519   if (next_work != NULL) {
520     /* there is a next process to resume */
521     XBT_DEBUG("Run next process");
522     next_context = next_work->context;
523     next_stack = ((smx_ctx_raw_t) next_context)->stack_top;
524   }
525   else {
526     /* all processes were run, go to the barrier */
527     XBT_DEBUG("No more processes to run");
528
529     unsigned long worker_id =
530         (unsigned long) xbt_os_thread_get_specific(raw_worker_id_key);
531
532     next_context = (smx_context_t)raw_workers_context[worker_id];
533     XBT_DEBUG("Restoring worker stack %lu (working threads = %lu)",
534         worker_id, raw_threads_working);
535     next_stack = ((smx_ctx_raw_t)next_context)->stack_top;
536   }
537
538   SIMIX_context_set_current(next_context);
539   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top, next_stack);
540 #endif
541 }
542
543 /**
544  * \brief Resumes sequentially in the current worker thread the processes ready
545  * to run.
546  * \param first_process the first process to resume
547  */
548 static void smx_ctx_raw_resume_parallel(smx_process_t first_process)
549 {
550 #ifdef CONTEXT_THREADS
551   unsigned long worker_id = __sync_fetch_and_add(&raw_threads_working, 1);
552   xbt_os_thread_set_specific(raw_worker_id_key, (void*) worker_id);
553   smx_ctx_raw_t worker_context = (smx_ctx_raw_t)SIMIX_context_self();
554   raw_workers_context[worker_id] = worker_context;
555   XBT_DEBUG("Saving worker stack %lu", worker_id);
556   raw_stack_t* worker_stack = &(worker_context)->stack_top;
557
558
559   smx_context_t context = first_process->context;
560   SIMIX_context_set_current(context);
561   raw_swapcontext(worker_stack, ((smx_ctx_raw_t) context)->stack_top);
562 #endif
563 }
564
565 /**
566  * \brief Resumes in parallel all processes ready to run.
567  */
568 static void smx_ctx_raw_runall_parallel(void)
569 {
570 #ifdef CONTEXT_THREADS
571   raw_threads_working = 0;
572   xbt_parmap_apply(raw_parmap, (void_f_pvoid_t) smx_ctx_raw_resume_parallel,
573       simix_global->process_to_run);
574 #else
575   xbt_die("You asked for a parallel execution, but you don't have any threads.")
576 #endif
577 }
578
579 /**
580  * \brief Resumes all processes ready to run.
581  */
582 static void smx_ctx_raw_runall(void)
583 {
584   unsigned long nb_processes = xbt_dynar_length(simix_global->process_to_run);
585   if (nb_processes >= SIMIX_context_get_parallel_threshold()) {
586     XBT_DEBUG("Runall // %lu", nb_processes);
587     simix_global->context_factory->suspend = smx_ctx_raw_suspend_parallel;
588     smx_ctx_raw_runall_parallel();
589   } else {
590     XBT_DEBUG("Runall serial %lu", nb_processes);
591     simix_global->context_factory->suspend = smx_ctx_raw_suspend_serial;
592     smx_ctx_raw_runall_serial();
593   }
594 }