Logo AND Algorithmique Numérique Distribuée

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