Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Starting simix mecanism for io.
[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 static 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 contexts 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, SIMIX_context_get_parallel_mode());
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   if (context) {
331
332 #ifdef HAVE_VALGRIND_VALGRIND_H
333     VALGRIND_STACK_DEREGISTER(((smx_ctx_raw_t)
334         context)->valgrind_stack_id);
335 #endif                          /* HAVE_VALGRIND_VALGRIND_H */
336
337     free(((smx_ctx_raw_t) context)->malloced_stack);
338   }
339   smx_ctx_base_free(context);
340 }
341
342 /**
343  * \brief Wrapper for the main function of a context.
344  * \param context a raw context
345  */
346 static void smx_ctx_raw_wrapper(smx_ctx_raw_t context)
347 {
348   (context->super.code) (context->super.argc, context->super.argv);
349
350   smx_ctx_raw_stop((smx_context_t) context);
351 }
352
353 /**
354  * \brief Stops a raw context.
355  *
356  * This function is called when the main function of the context if finished.
357  *
358  * \param context the current context
359  */
360 static void smx_ctx_raw_stop(smx_context_t context)
361 {
362   smx_ctx_base_stop(context);
363   simix_global->context_factory->suspend(context);
364 }
365
366 /**
367  * \brief Suspends a running context and resumes another one or returns to
368  * maestro.
369  * \param context the current context
370  */
371 static void smx_ctx_raw_suspend_serial(smx_context_t context)
372 {
373   /* determine the next context */
374   smx_context_t next_context;
375   unsigned long int i = raw_process_index++;
376
377   if (i < xbt_dynar_length(simix_global->process_to_run)) {
378     /* execute the next process */
379     XBT_DEBUG("Run next process");
380     next_context = xbt_dynar_get_as(
381         simix_global->process_to_run, i, smx_process_t)->context;
382   }
383   else {
384     /* all processes were run, return to maestro */
385     XBT_DEBUG("No more process to run");
386     next_context = (smx_context_t) raw_maestro_context;
387   }
388   SIMIX_context_set_current(next_context);
389   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top,
390       ((smx_ctx_raw_t) next_context)->stack_top);
391 }
392
393 /**
394  * \brief Resumes sequentially all processes ready to run.
395  * \param first_process the first process to resume
396  */
397 static void smx_ctx_raw_resume_serial(smx_process_t first_process)
398 {
399   smx_ctx_raw_t context = (smx_ctx_raw_t) first_process->context;
400   SIMIX_context_set_current((smx_context_t) context);
401   raw_swapcontext(&raw_maestro_context->stack_top,
402       ((smx_ctx_raw_t) context)->stack_top);
403 }
404
405 #ifdef TIME_BENCH
406 static void smx_ctx_raw_runall_serial(xbt_dynar_t processes)
407 {
408   smx_process_t process;
409   unsigned int cursor;
410
411   double elapsed = 0;
412   double tmax = 0;
413   unsigned long num_proc = xbt_dynar_length(processes);
414   unsigned int t=0;
415   unsigned int data_size = (num_proc / NUM_THREADS) + ((num_proc % NUM_THREADS) ? 1 : 0);
416
417   ssr_count++;
418   time_thread_ssr[0] = 0;
419   xbt_dynar_foreach(processes, cursor, process) {
420     XBT_DEBUG("Schedule item %u of %lu",cursor,xbt_dynar_length(processes));
421     if(cursor >= t * data_size + data_size){
422       if(time_thread_ssr[t] > tmax)
423         tmax = time_thread_ssr[t];
424       t++;
425       time_thread_ssr[t] = 0;
426     }
427
428     if(new_sr){
429       ((smx_ctx_raw_t)process->context)->thread = t;
430       time_thread_sr[t] = 0;
431     }
432
433     xbt_os_timer_start(timer);
434     smx_ctx_raw_resume(process);
435     xbt_os_timer_stop(timer);
436     elapsed = xbt_os_timer_elapsed(timer);
437     time_thread_ssr[t] += elapsed;
438     time_thread_sr[((smx_ctx_raw_t)process->context)->thread] += elapsed;
439   }
440
441   if(new_sr)
442     new_sr = FALSE;
443
444   if(time_thread_ssr[t] > tmax)
445     tmax = time_thread_ssr[t];
446
447   for(cursor=0; cursor <= t; cursor++){
448     XBT_VERB("Time SSR thread %u = %lf (max %lf)", cursor, time_thread_ssr[cursor], tmax);
449     time_wasted_ssr += tmax - time_thread_ssr[cursor];
450   }
451 }
452
453 void smx_ctx_raw_new_sr(void);
454 void smx_ctx_raw_new_sr(void)
455 {
456   int i;
457   double tmax = 0;
458   new_sr = TRUE;
459   sr_count++;
460   for(i=0; i < NUM_THREADS; i++){
461     if(time_thread_sr[i] > tmax)
462       tmax = time_thread_sr[i];
463   }
464
465   for(i=0; i < NUM_THREADS; i++){
466     XBT_VERB("Time SR thread %u = %lf (max %lf)", i, time_thread_sr[i], tmax);
467     time_wasted_sr += tmax - time_thread_sr[i];
468   }
469
470   XBT_VERB("New scheduling round");
471 }
472 #else
473
474 /**
475  * \brief Resumes sequentially all processes ready to run.
476  */
477 static void smx_ctx_raw_runall_serial(void)
478 {
479   if (!xbt_dynar_is_empty(simix_global->process_to_run)) {
480     smx_process_t first_process =
481         xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
482     raw_process_index = 1;
483
484     /* execute the first process */
485     smx_ctx_raw_resume_serial(first_process);
486   }
487 }
488 #endif
489
490 /**
491  * \brief Stops a raw context.
492  *
493  * This function is called when the main function of the context if finished.
494  *
495  * \param context the context of the current worker thread
496  */
497 static void smx_ctx_raw_stop_parallel(smx_context_t context)
498 {
499   smx_ctx_base_stop(context);
500   smx_ctx_raw_suspend_parallel(context);
501 }
502
503 /**
504  * \brief Suspends a running context and resumes another one or returns to
505  * the main function of the current worker thread.
506  * \param context the context of the current worker thread
507  */
508 static void smx_ctx_raw_suspend_parallel(smx_context_t context)
509 {
510 #ifdef CONTEXT_THREADS
511   /* determine the next context */
512   smx_process_t next_work = xbt_parmap_next(raw_parmap);
513   smx_context_t next_context;
514   raw_stack_t next_stack;
515
516   if (next_work != NULL) {
517     /* there is a next process to resume */
518     XBT_DEBUG("Run next process");
519     next_context = next_work->context;
520     next_stack = ((smx_ctx_raw_t) next_context)->stack_top;
521   }
522   else {
523     /* all processes were run, go to the barrier */
524     XBT_DEBUG("No more processes to run");
525     next_context = (smx_context_t) raw_maestro_context;
526     unsigned long worker_id =
527         (unsigned long) xbt_os_thread_get_specific(raw_worker_id_key);
528     XBT_DEBUG("Restoring worker stack %lu (working threads = %lu)",
529         worker_id, raw_threads_working);
530     next_stack = raw_workers_stacks[worker_id];
531   }
532
533   SIMIX_context_set_current(next_context);
534   raw_swapcontext(&((smx_ctx_raw_t) context)->stack_top, next_stack);
535 #endif
536 }
537
538 /**
539  * \brief Resumes sequentially in the current worker thread the processes ready
540  * to run.
541  * \param first_process the first process to resume
542  */
543 static void smx_ctx_raw_resume_parallel(smx_process_t first_process)
544 {
545 #ifdef CONTEXT_THREADS
546   unsigned long worker_id = __sync_fetch_and_add(&raw_threads_working, 1);
547   xbt_os_thread_set_specific(raw_worker_id_key, (void*) worker_id);
548   XBT_DEBUG("Saving worker stack %lu", worker_id);
549   raw_stack_t* worker_stack = &raw_workers_stacks[worker_id];
550
551   smx_context_t context = first_process->context;
552   SIMIX_context_set_current(context);
553   raw_swapcontext(worker_stack, ((smx_ctx_raw_t) context)->stack_top);
554 #endif
555 }
556
557 /**
558  * \brief Resumes in parallel all processes ready to run.
559  */
560 static void smx_ctx_raw_runall_parallel(void)
561 {
562 #ifdef CONTEXT_THREADS
563   raw_threads_working = 0;
564   xbt_parmap_apply(raw_parmap, (void_f_pvoid_t) smx_ctx_raw_resume_parallel,
565       simix_global->process_to_run);
566 #endif
567 }
568
569 /**
570  * \brief Resumes all processes ready to run.
571  */
572 static void smx_ctx_raw_runall(void)
573 {
574   unsigned long nb_processes = xbt_dynar_length(simix_global->process_to_run);
575   if (nb_processes >= SIMIX_context_get_parallel_threshold()) {
576     XBT_DEBUG("Runall // %lu", nb_processes);
577     simix_global->context_factory->suspend = smx_ctx_raw_suspend_parallel;
578     smx_ctx_raw_runall_parallel();
579   } else {
580     XBT_DEBUG("Runall serial %lu", nb_processes);
581     simix_global->context_factory->suspend = smx_ctx_raw_suspend_serial;
582     smx_ctx_raw_runall_serial();
583   }
584 }