Logo AND Algorithmique Numérique Distribuée

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