Logo AND Algorithmique Numérique Distribuée

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