Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
SR experiment now working
[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 #include "smx_private.h"
9 #include "xbt/parmap.h"
10 #include "xbt/dynar.h"
11 #include "mc/mc.h"
12
13 typedef char * raw_stack_t;
14 typedef void (*rawctx_entry_point_t)(void *);
15
16 typedef struct s_smx_ctx_raw {
17   s_smx_ctx_base_t super;         /* Fields of super implementation */
18   char *malloced_stack;           /* malloced area containing the stack */
19   raw_stack_t stack_top;          /* pointer to stack top (within previous area) */
20 #ifdef TIME_BENCH_PER_SR
21   unsigned int thread;            /* Just for measuring purposes */
22 #endif
23 } s_smx_ctx_raw_t, *smx_ctx_raw_t;
24
25 #ifdef CONTEXT_THREADS
26 static xbt_parmap_t raw_parmap;
27 static smx_ctx_raw_t* raw_workers_context;    /* space to save the worker context in each thread */
28 static unsigned long raw_threads_working;     /* number of threads that have started their work */
29 static xbt_os_thread_key_t raw_worker_id_key; /* thread-specific storage for the thread id */
30 #endif
31
32 static unsigned long raw_process_index = 0;   /* index of the next process to run in the
33                                                * list of runnable processes */
34 static smx_ctx_raw_t raw_maestro_context;
35
36 extern raw_stack_t raw_makecontext(char* malloced_stack, int stack_size,
37                                    rawctx_entry_point_t entry_point, void* arg);
38 extern void raw_swapcontext(raw_stack_t* old, raw_stack_t new);
39
40 #if PROCESSOR_x86_64
41 __asm__ (
42 #if defined(APPLE)
43    ".text\n"
44    ".globl _raw_makecontext\n"
45    "_raw_makecontext:\n"
46 #elif defined(_WIN32)
47    ".text\n"
48    ".globl raw_makecontext\n"
49    "raw_makecontext:\n"
50 #else
51    ".text\n"
52    ".globl raw_makecontext\n"
53    ".type raw_makecontext,@function\n"
54    "raw_makecontext:\n"/* Calling convention sets the arguments in rdi, rsi, rdx and rcx, respectively */
55 #endif
56    "   mov %rdi,%rax\n"      /* stack */
57    "   add %rsi,%rax\n"      /* size  */
58    "   andq $-16, %rax\n"    /* align stack */
59    "   movq $0,   -8(%rax)\n" /* @return for func */
60    "   mov %rdx,-16(%rax)\n" /* func */
61    "   mov %rcx,-24(%rax)\n" /* arg/rdi */
62    "   movq $0,  -32(%rax)\n" /* rsi */
63    "   movq $0,  -40(%rax)\n" /* rdx */
64    "   movq $0,  -48(%rax)\n" /* rcx */
65    "   movq $0,  -56(%rax)\n" /* r8  */
66    "   movq $0,  -64(%rax)\n" /* r9  */
67    "   movq $0,  -72(%rax)\n" /* rbp */
68    "   movq $0,  -80(%rax)\n" /* rbx */
69    "   movq $0,  -88(%rax)\n" /* r12 */
70    "   movq $0,  -96(%rax)\n" /* r13 */
71    "   movq $0, -104(%rax)\n" /* r14 */
72    "   movq $0, -112(%rax)\n" /* r15 */
73    "   sub $112,%rax\n"
74    "   ret\n"
75 );
76
77 __asm__ (
78 #if defined(APPLE)
79    ".text\n"
80    ".globl _raw_swapcontext\n"
81    "_raw_swapcontext:\n"
82 #elif defined(_WIN32)
83    ".text\n"
84    ".globl raw_swapcontext\n"
85    "raw_swapcontext:\n"
86 #else
87    ".text\n"
88    ".globl raw_swapcontext\n"
89    ".type raw_swapcontext,@function\n"
90    "raw_swapcontext:\n" /* Calling convention sets the arguments in rdi and rsi, respectively */
91 #endif
92    "   push %rdi\n"
93    "   push %rsi\n"
94    "   push %rdx\n"
95    "   push %rcx\n"
96    "   push %r8\n"
97    "   push %r9\n"
98    "   push %rbp\n"
99    "   push %rbx\n"
100    "   push %r12\n"
101    "   push %r13\n"
102    "   push %r14\n"
103    "   push %r15\n"
104    "   mov %rsp,(%rdi)\n" /* old */
105    "   mov %rsi,%rsp\n" /* new */
106    "   pop %r15\n"
107    "   pop %r14\n"
108    "   pop %r13\n"
109    "   pop %r12\n"
110    "   pop %rbx\n"
111    "   pop %rbp\n"
112    "   pop %r9\n"
113    "   pop %r8\n"
114    "   pop %rcx\n"
115    "   pop %rdx\n"
116    "   pop %rsi\n"
117    "   pop %rdi\n"
118    "   ret\n"
119 );
120 #elif PROCESSOR_i686
121 __asm__ (
122 #if defined(APPLE) || defined(_WIN32)
123    ".text\n"
124    ".globl _raw_makecontext\n"
125    "_raw_makecontext:\n"
126 #else
127    ".text\n"
128    ".globl raw_makecontext\n"
129    ".type raw_makecontext,@function\n"
130    "raw_makecontext:\n"
131 #endif
132    "   movl 4(%esp),%eax\n"   /* stack */
133    "   addl 8(%esp),%eax\n"   /* size  */
134    "   andl $-16, %eax\n"     /* align stack */
135    "   movl 12(%esp),%ecx\n"  /* func  */
136    "   movl 16(%esp),%edx\n"  /* arg   */
137    "   movl %edx, -4(%eax)\n"
138    "   movl $0,   -8(%eax)\n" /* @return for func */
139    "   movl %ecx,-12(%eax)\n"
140    "   movl $0,  -16(%eax)\n" /* ebp */
141    "   movl $0,  -20(%eax)\n" /* ebx */
142    "   movl $0,  -24(%eax)\n" /* esi */
143    "   movl $0,  -28(%eax)\n" /* edi */
144    "   subl $28,%eax\n"
145    "   retl\n"
146 );
147
148 __asm__ (
149 #if defined(APPLE) || defined(_WIN32)
150    ".text\n"
151    ".globl _raw_swapcontext\n"
152    "_raw_swapcontext:\n"
153 #else
154    ".text\n"
155    ".globl raw_swapcontext\n"
156    ".type raw_swapcontext,@function\n"
157    "raw_swapcontext:\n"
158 #endif
159    "   movl 4(%esp),%eax\n" /* old */
160    "   movl 8(%esp),%edx\n" /* new */
161    "   pushl %ebp\n"
162    "   pushl %ebx\n"
163    "   pushl %esi\n"
164    "   pushl %edi\n"
165    "   movl %esp,(%eax)\n"
166    "   movl %edx,%esp\n"
167    "   popl %edi\n"
168    "   popl %esi\n"
169    "   popl %ebx\n"
170    "   popl %ebp\n"
171    "   retl\n"
172 );
173 #else
174
175
176 /* If you implement raw contexts for other processors, don't forget to
177    update the definition of HAVE_RAWCTX in buildtools/Cmake/CompleteInFiles.cmake */
178
179 raw_stack_t raw_makecontext(char* malloced_stack, int stack_size,
180                             rawctx_entry_point_t entry_point, void* arg) {
181    THROW_UNIMPLEMENTED;
182 }
183
184 void raw_swapcontext(raw_stack_t* old, raw_stack_t new) {
185    THROW_UNIMPLEMENTED;
186 }
187
188 #endif
189
190 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
191
192 #ifdef TIME_BENCH_PER_SR
193 #include "xbt/xbt_os_time.h"
194 #define NUM_THREADS 4
195 static xbt_os_timer_t timer;
196 static double time_thread_sr[NUM_THREADS];
197 static double time_thread_ssr[NUM_THREADS];
198 static double time_wasted_sr = 0;
199 static double time_wasted_ssr = 0;
200 static unsigned int sr_count = 0;
201 static unsigned int ssr_count = 0;
202 static char new_sr = 0;
203 #endif
204
205 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context);
206 static int smx_ctx_raw_factory_finalize(smx_context_factory_t *factory);
207 static smx_context_t smx_ctx_raw_create_context(xbt_main_func_t code, int argc,
208     char **argv, void_pfn_smxprocess_t cleanup_func, smx_process_t process);
209 static void smx_ctx_raw_free(smx_context_t context);
210 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context);
211 static void smx_ctx_raw_stop(smx_context_t context);
212 static void smx_ctx_raw_suspend_serial(smx_context_t context);
213 static void smx_ctx_raw_resume_serial(smx_process_t first_process);
214 #ifdef TIME_BENCH_PER_SR
215 static void smx_ctx_raw_runall_serial(xbt_dynar_t processes);
216 void smx_ctx_raw_new_sr(void);
217 #else
218 static void smx_ctx_raw_runall_serial(void);
219 #endif
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_VERB("Total wasted time in %u SR: %f", sr_count, time_wasted_sr);
280   XBT_VERB("Total wasted time in %u SSR: %f", 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 process SIMIX process
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                            smx_process_t process)
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           process);
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 = SIMIX_context_stack_new();
320        context->stack_top =
321            raw_makecontext(context->malloced_stack,
322                            smx_context_usable_stack_size,
323                            (void_f_pvoid_t)smx_ctx_raw_wrapper, context);
324
325      } else {
326        if(process != NULL && raw_maestro_context==NULL)
327          raw_maestro_context = context;
328
329        if(MC_is_active())
330          MC_ignore_heap(&(raw_maestro_context->stack_top), sizeof(raw_maestro_context->stack_top));
331
332      }
333
334      return (smx_context_t) context;
335 }
336
337 /**
338  * \brief Destroys a raw context.
339  * \param context a raw context
340  */
341 static void smx_ctx_raw_free(smx_context_t context)
342 {
343   if (context) {
344     SIMIX_context_stack_delete(((smx_ctx_raw_t) context)->malloced_stack);
345   }
346   smx_ctx_base_free(context);
347 }
348
349 /**
350  * \brief Wrapper for the main function of a context.
351  * \param context a raw context
352  */
353 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context)
354 {
355   (context->super.code) (context->super.argc, context->super.argv);
356
357   smx_ctx_raw_stop((smx_context_t) context);
358 }
359
360 /**
361  * \brief Stops a raw context.
362  *
363  * This function is called when the main function of the context if finished.
364  *
365  * \param context the current context
366  */
367 static void smx_ctx_raw_stop(smx_context_t context)
368 {
369   smx_ctx_base_stop(context);
370   simix_global->context_factory->suspend(context);
371 }
372
373 /**
374  * \brief Suspends a running context and resumes another one or returns to
375  * maestro.
376  * \param context the current context
377  */
378 static void smx_ctx_raw_suspend_serial(smx_context_t context)
379 {
380   /* determine the next context */
381   smx_context_t next_context;
382   unsigned long int i; 
383 #ifdef TIME_BENCH_PER_SR
384   i = ++raw_process_index;
385 #else
386   i = raw_process_index++;
387 #endif
388   if (i < xbt_dynar_length(simix_global->process_to_run)) {
389     /* execute the next process */
390     XBT_DEBUG("Run next process");
391     next_context = xbt_dynar_get_as(
392         simix_global->process_to_run, i, smx_process_t)->context;
393   }
394   else {
395     /* all processes were run, return to maestro */
396     XBT_DEBUG("No more process to run");
397     next_context = (smx_context_t) raw_maestro_context;
398   }
399   SIMIX_context_set_current(next_context);
400   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top,
401       ((smx_ctx_raw_t) next_context)->stack_top);
402 }
403
404 /**
405  * \brief Resumes sequentially all processes ready to run.
406  * \param first_process the first process to resume
407  */
408 static void smx_ctx_raw_resume_serial(smx_process_t first_process)
409 {
410   smx_ctx_raw_t context = (smx_ctx_raw_t) first_process->context;
411   SIMIX_context_set_current((smx_context_t) context);
412   raw_swapcontext(&raw_maestro_context->stack_top,
413       ((smx_ctx_raw_t) context)->stack_top);
414 }
415
416 #ifdef TIME_BENCH_PER_SR
417 static void smx_ctx_raw_runall_serial(xbt_dynar_t processes)
418 {
419   smx_process_t process;
420   unsigned int cursor;
421   double elapsed = 0;
422   double tmax = 0;
423   unsigned long num_proc = xbt_dynar_length(simix_global->process_to_run);
424   unsigned int t=0;
425   unsigned int data_size = (num_proc / NUM_THREADS) + ((num_proc % NUM_THREADS) ? 1 : 0);
426
427   ssr_count++;
428   time_thread_ssr[0] = 0;
429   xbt_dynar_foreach(processes, cursor, process){ 
430         XBT_VERB("Schedule item %u of %lu",cursor,num_proc);
431         if(cursor >= t * data_size + data_size){
432           if(time_thread_ssr[t] > tmax)
433             tmax = time_thread_ssr[t];
434           t++;
435           time_thread_ssr[t] = 0;
436         }
437
438         if(new_sr){
439           ((smx_ctx_raw_t)process->context)->thread = t;
440           time_thread_sr[t] = 0;
441         }
442
443         xbt_os_cputimer_start(timer);
444         smx_ctx_raw_resume_serial(process);
445         xbt_os_cputimer_stop(timer);
446         elapsed = xbt_os_timer_elapsed(timer);
447         time_thread_ssr[t] += elapsed;
448         time_thread_sr[((smx_ctx_raw_t)process->context)->thread] += elapsed;
449   }
450
451   if(new_sr)
452     new_sr = FALSE;
453
454   if(time_thread_ssr[t] > tmax)
455     tmax = time_thread_ssr[t];
456
457   for(cursor=0; cursor <= t; cursor++){
458     XBT_VERB("Time SSR thread %u = %f (max %f)", cursor, time_thread_ssr[cursor], tmax);
459     time_wasted_ssr += tmax - time_thread_ssr[cursor];
460   }
461 }
462
463 void smx_ctx_raw_new_sr(void)
464 {
465   int i;
466   double tmax = 0;
467   new_sr = TRUE;
468   sr_count++;
469   for(i=0; i < NUM_THREADS; i++){
470     if(time_thread_sr[i] > tmax)
471       tmax = time_thread_sr[i];
472   }
473
474   for(i=0; i < NUM_THREADS; i++){
475     XBT_VERB("Time SR thread %u = %f (max %f)", i, time_thread_sr[i], tmax);
476     time_wasted_sr += tmax - time_thread_sr[i];
477   }
478
479   XBT_VERB("Total time SR %u = %f, %d", sr_count, tmax, xbt_dynar_length(simix_global->process_that_ran));
480   XBT_VERB("New scheduling round");
481 }
482 #else
483 /**
484  * \brief Resumes sequentially all processes ready to run.
485  */
486 static void smx_ctx_raw_runall_serial(void)
487 {
488   smx_process_t first_process =
489       xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
490   raw_process_index = 1;
491
492   /* execute the first process */
493   smx_ctx_raw_resume_serial(first_process);
494 }
495 #endif
496
497 /**
498  * \brief Suspends a running context and resumes another one or returns to
499  * the main function of the current worker thread.
500  * \param context the context of the current worker thread
501  */
502 static void smx_ctx_raw_suspend_parallel(smx_context_t context)
503 {
504 #ifdef CONTEXT_THREADS
505   /* determine the next context */
506   smx_process_t next_work = xbt_parmap_next(raw_parmap);
507   smx_context_t next_context;
508   raw_stack_t next_stack;
509
510   if (next_work != NULL) {
511     /* there is a next process to resume */
512     XBT_DEBUG("Run next process");
513     next_context = next_work->context;
514     next_stack = ((smx_ctx_raw_t) next_context)->stack_top;
515   }
516   else {
517     /* all processes were run, go to the barrier */
518     XBT_DEBUG("No more processes to run");
519
520     unsigned long worker_id =
521         (unsigned long) xbt_os_thread_get_specific(raw_worker_id_key);
522
523     next_context = (smx_context_t)raw_workers_context[worker_id];
524     XBT_DEBUG("Restoring worker stack %lu (working threads = %lu)",
525         worker_id, raw_threads_working);
526     next_stack = ((smx_ctx_raw_t)next_context)->stack_top;
527   }
528
529   SIMIX_context_set_current(next_context);
530   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top, next_stack);
531 #endif
532 }
533
534 /**
535  * \brief Resumes sequentially in the current worker thread the processes ready
536  * to run.
537  * \param first_process the first process to resume
538  */
539 static void smx_ctx_raw_resume_parallel(smx_process_t first_process)
540 {
541 #ifdef CONTEXT_THREADS
542   unsigned long worker_id = __sync_fetch_and_add(&raw_threads_working, 1);
543   xbt_os_thread_set_specific(raw_worker_id_key, (void*) worker_id);
544   smx_ctx_raw_t worker_context = (smx_ctx_raw_t)SIMIX_context_self();
545   raw_workers_context[worker_id] = worker_context;
546   XBT_DEBUG("Saving worker stack %lu", worker_id);
547   raw_stack_t* worker_stack = &(worker_context)->stack_top;
548
549
550   smx_context_t context = first_process->context;
551   SIMIX_context_set_current(context);
552   raw_swapcontext(worker_stack, ((smx_ctx_raw_t) context)->stack_top);
553 #endif
554 }
555
556 /**
557  * \brief Resumes in parallel all processes ready to run.
558  */
559 static void smx_ctx_raw_runall_parallel(void)
560 {
561 #ifdef CONTEXT_THREADS
562   raw_threads_working = 0;
563   xbt_parmap_apply(raw_parmap, (void_f_pvoid_t) smx_ctx_raw_resume_parallel,
564       simix_global->process_to_run);
565 #else
566   xbt_die("You asked for a parallel execution, but you don't have any threads.");
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   #ifdef TIME_BENCH_PER_SR
584     smx_ctx_raw_runall_serial(simix_global->process_to_run);
585   #else
586     smx_ctx_raw_runall_serial();
587   #endif
588   }
589 }