Logo AND Algorithmique Numérique Distribuée

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