Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Got bored during a meeting: fix the copyright notice of several useless files (found...
[simgrid.git] / src / xbt / context.c
1 /*      $Id$     */
2
3 /* a fast and simple context switching library                              */
4
5 /* Copyright (c) 2004 Arnaud Legrand.                                       */
6 /* Copyright (c) 2004, 2005 Martin Quinson.                                 */
7 /* All rights reserved.                                                     */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 #include "portable.h"
13 #include "context_private.h"
14 #include "xbt/log.h"
15 #include "xbt/dynar.h"
16 #include "xbt/xbt_os_thread.h"
17 #include "xbt/ex_interface.h"
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ctx, xbt, "Context");
20
21 #define VOIRP(expr) DEBUG1("  {" #expr " = %p }", expr)
22
23 static xbt_context_t current_context = NULL;
24 static xbt_context_t init_context = NULL;
25 static xbt_swag_t context_to_destroy = NULL;
26 static xbt_swag_t context_living = NULL;
27
28 #ifdef CONTEXT_THREADS
29 static xbt_os_mutex_t creation_mutex;
30 static xbt_os_cond_t creation_cond;
31 static xbt_os_mutex_t master_mutex;
32 static xbt_os_cond_t master_cond;
33
34 static xbt_os_thread_t current_thread_id;
35
36 static int is_main_thread(void) {
37    return xbt_os_thread_self() == current_thread_id;
38 }
39
40 #endif
41
42
43 /********************/
44 /* Module init/exit */
45 /********************/
46 #ifndef CONTEXT_THREADS
47 /* callback: context fetching (used only with ucontext, os_thread deal with it
48                                for us otherwise) */
49 static ex_ctx_t *_context_ex_ctx(void)
50 {
51   return current_context->exception;
52 }
53
54 /* callback: termination */
55 static void _context_ex_terminate(xbt_ex_t * e)
56 {
57   xbt_ex_display(e);
58
59   abort();
60   /* FIXME: there should be a configuration variable to 
61      choose to kill everyone or only this one */
62 }
63 #endif
64
65 /** \name Functions 
66  *  \ingroup XBT_context
67  */
68 /* @{ */
69 /** Context module initialization
70  *
71  * \warning It has to be called before using any other function of this module.
72  */
73 void xbt_context_init(void)
74 {
75   if (!current_context) {
76     current_context = init_context = xbt_new0(s_xbt_context_t, 1);
77     DEBUG1("Init Context (%p)", init_context);
78     init_context->iwannadie = 0;        /* useless but makes valgrind happy */
79     context_to_destroy =
80       xbt_swag_new(xbt_swag_offset(*current_context, hookup));
81     context_living = xbt_swag_new(xbt_swag_offset(*current_context, hookup));
82     xbt_swag_insert(init_context, context_living);
83
84 #ifdef CONTEXT_THREADS
85     /* only used during the creation of the processes */
86     creation_mutex = xbt_os_mutex_init();
87     creation_cond = xbt_os_cond_init();
88
89     /* used to schedule/unschedule the processes */
90     master_mutex = xbt_os_mutex_init();
91     master_cond = xbt_os_cond_init();
92
93     current_thread_id = xbt_os_thread_self();
94
95 #else
96     init_context->exception = xbt_new(ex_ctx_t, 1);
97     XBT_CTX_INITIALIZE(init_context->exception);
98     __xbt_ex_ctx = _context_ex_ctx;
99     __xbt_ex_terminate = _context_ex_terminate;
100 #endif
101   }
102 }
103
104 /** 
105  * This function kill all existing context and free all the memory
106  * that has been allocated in this module.
107  */
108 void xbt_context_exit(void)
109 {
110   xbt_context_t context = NULL;
111
112   xbt_context_empty_trash();
113
114   while ((context = xbt_swag_extract(context_living))) {
115     if (context != init_context) {
116       xbt_context_kill(context);
117     }
118   }
119
120 #ifdef CONTEXT_THREADS
121   xbt_os_mutex_destroy(creation_mutex);
122   xbt_os_cond_destroy(creation_cond);
123   xbt_os_mutex_destroy(master_mutex);
124   xbt_os_cond_destroy(master_cond);
125 #else
126   free(init_context->exception);
127 #endif
128
129   free(init_context);
130   init_context = current_context = NULL;
131
132   xbt_context_empty_trash();
133   xbt_swag_free(context_to_destroy);
134   xbt_swag_free(context_living);
135
136 }
137
138 /*******************************/
139 /* Object creation/destruction */
140 /*******************************/
141 /** 
142  * \param code a main function
143  * \param startup_func a function to call when running the context for
144  *      the first time and just before the main function \a code
145  * \param startup_arg the argument passed to the previous function (\a startup_func)
146  * \param cleanup_func a function to call when running the context, just after 
147         the termination of the main function \a code
148  * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
149  * \param argc first argument of function \a code
150  * \param argv seconde argument of function \a code
151  */
152 xbt_context_t
153 xbt_context_new(const char *name,
154                 xbt_main_func_t code,
155                 void_f_pvoid_t startup_func,
156                 void *startup_arg,
157                 void_f_pvoid_t cleanup_func,
158                 void *cleanup_arg, int argc, char *argv[]
159   )
160 {
161   xbt_context_t res = NULL;
162
163   res = xbt_new0(s_xbt_context_t, 1);
164
165   res->code = code;
166   res->name = xbt_strdup(name);
167
168 #ifdef CONTEXT_THREADS
169   res->mutex = xbt_os_mutex_init();
170   res->cond = xbt_os_cond_init();
171 #else
172
173   xbt_assert2(getcontext(&(res->uc)) == 0,
174               "Error in context saving: %d (%s)", errno, strerror(errno));
175   res->uc.uc_link = NULL;
176   /*   res->uc.uc_link = &(current_context->uc); */
177   /* WARNING : when this context is over, the current_context (i.e. the 
178      father), is awaken... Theorically, the wrapper should prevent using 
179      this feature. */
180   res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack, STACK_SIZE);
181   res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack, STACK_SIZE);
182
183   res->exception = xbt_new(ex_ctx_t, 1);
184   XBT_CTX_INITIALIZE(res->exception);
185 #endif /* CONTEXT_THREADS or not */
186
187   res->iwannadie = 0;           /* useless but makes valgrind happy */
188
189   res->argc = argc;
190   res->argv = argv;
191   res->startup_func = startup_func;
192   res->startup_arg = startup_arg;
193   res->cleanup_func = cleanup_func;
194   res->cleanup_arg = cleanup_arg;
195
196   xbt_swag_insert(res, context_living);
197
198   return res;
199 }
200
201 /* Scenario for the end of a context:
202  * 
203  * CASE 1: death after end of function
204  *   __context_wrapper, called by os thread, calls xbt_context_stop after user code stops
205  *   xbt_context_stop calls user cleanup_func if any (in context settings),
206  *                    add current to trashbin
207  *                    yields back to maestro (destroy os thread on need)
208  *   From time to time, maestro calls xbt_context_empty_trash, 
209  *       which maps xbt_context_free on the content
210  *   xbt_context_free frees some more memory, 
211  *                    joins os thread
212  * 
213  * CASE 2: brutal death
214  *   xbt_context_kill (from any context)
215  *                    set context->wannadie to 1
216  *                    yields to the context
217  *   the context is awaken in the middle of __yield. 
218  *   At the end of it, it checks that wannadie == 1, and call xbt_context_stop
219  *   (same than first case afterward)
220  */
221
222 /* Argument must be stopped first -- runs in maestro context */
223 static void xbt_context_free(xbt_context_t context)
224 {
225   int i;
226
227   if (!context)
228     return;
229
230   DEBUG1("Freeing %p", context);
231   free(context->name);
232
233   DEBUG0("Freeing arguments");
234
235   for (i = 0; i < context->argc; i++)
236     if (context->argv[i])
237       free(context->argv[i]);
238
239   if (context->argv)
240     free(context->argv);
241
242 #ifdef CONTEXT_THREADS
243   DEBUG1("\t joining %p", (void *) context->thread);
244
245   xbt_os_thread_join(context->thread, NULL);
246
247   xbt_os_mutex_destroy(context->mutex);
248   xbt_os_cond_destroy(context->cond);
249
250   context->thread = NULL;
251   context->mutex = NULL;
252   context->cond = NULL;
253 #else
254   if (context->exception)
255     free(context->exception);
256 #endif
257
258   free(context);
259 }
260
261 /************************/
262 /* Start/stop a context */
263 /************************/
264 static void xbt_context_stop(int retvalue);
265 static void __xbt_context_yield(xbt_context_t context);
266
267 static void *__context_wrapper(void *c)
268 {
269   xbt_context_t context = current_context;
270
271 #ifdef CONTEXT_THREADS
272   context = (xbt_context_t) c;
273   context->thread = xbt_os_thread_self();
274
275   DEBUG3("**[ctx:%p;self:%p]** Lock creation_mutex %p ****", context,
276          (void *) xbt_os_thread_self(), creation_mutex);
277   xbt_os_mutex_lock(creation_mutex);
278   xbt_os_mutex_lock(context->mutex);
279
280   DEBUG4
281     ("**[ctx:%p;self:%p]** Releasing the creator (creation_cond %p,%p) ****",
282      context, (void *) xbt_os_thread_self(), creation_cond, creation_mutex);
283   xbt_os_cond_signal(creation_cond);
284   xbt_os_mutex_unlock(creation_mutex);
285
286   DEBUG4("**[ctx:%p;self:%p]** Going to Jail on lock %p and cond %p ****",
287          context, (void *) xbt_os_thread_self(), context->mutex,
288          context->cond);
289   xbt_os_cond_wait(context->cond, context->mutex);
290
291   DEBUG3("**[ctx:%p;self:%p]** Unlocking individual %p ****", context,
292          (void *) xbt_os_thread_self(), context->mutex);
293   xbt_os_mutex_unlock(context->mutex);
294
295 #endif
296
297   if (context->startup_func)
298     context->startup_func(context->startup_arg);
299
300   DEBUG0("Calling the main function");
301
302   xbt_context_stop((context->code) (context->argc, context->argv));
303   return NULL;
304 }
305
306 /** 
307  * \param context the context to start
308  * 
309  * Calling this function prepares \a context to be run. It will 
310    however run effectively only when calling #xbt_context_schedule
311  */
312 void xbt_context_start(xbt_context_t context)
313 {
314 #ifdef CONTEXT_THREADS
315   /* Launch the thread */
316
317   DEBUG3("**[ctx:%p;self:%p]** Locking creation_mutex %p ****", context,
318          xbt_os_thread_self(), creation_mutex);
319   xbt_os_mutex_lock(creation_mutex);
320
321   DEBUG2("**[ctx:%p;self:%p]** Thread create ****", context,
322          xbt_os_thread_self());
323   context->thread =
324     xbt_os_thread_create(context->name, __context_wrapper, context);
325   DEBUG3("**[ctx:%p;self:%p]** Thread created : %p ****", context,
326          xbt_os_thread_self(), context->thread);
327
328   DEBUG4
329     ("**[ctx:%p;self:%p]** Going to jail on creation_cond/mutex (%p,%p) ****",
330      context, xbt_os_thread_self(), creation_cond, creation_mutex);
331   xbt_os_cond_wait(creation_cond, creation_mutex);
332   DEBUG3("**[ctx:%p;self:%p]** Unlocking creation %p ****", context,
333          xbt_os_thread_self(), creation_mutex);
334   xbt_os_mutex_unlock(creation_mutex);
335 #else
336   makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1, context);
337 #endif
338 }
339
340 /* Stops current context: calls user's cleanup function, kills os thread, and yields back to maestro */
341 static void xbt_context_stop(int retvalue)
342 {
343   DEBUG1("--------- %p is exiting ---------", current_context);
344
345   if (current_context->cleanup_func) {
346     DEBUG0("Calling cleanup function");
347     current_context->cleanup_func(current_context->cleanup_arg);
348   }
349
350   DEBUG0("Putting context in the to_destroy set");
351   xbt_swag_remove(current_context, context_living);
352   xbt_swag_insert(current_context, context_to_destroy);
353
354   DEBUG0("Yielding");
355
356 #ifdef CONTEXT_THREADS
357   /* a java thread has called this function
358    * - update the current context
359    * - signal the condition of the main thread
360    * - wait on its condition
361    * - restore thr current contex
362    */
363
364   xbt_os_mutex_lock(master_mutex);
365   xbt_os_cond_signal(master_cond);
366   xbt_os_mutex_unlock(master_mutex);
367   xbt_os_thread_exit(NULL);     /* We should provide return value in case other wants it */
368
369
370 #else
371   __xbt_context_yield(current_context);
372 #endif
373   THROW_IMPOSSIBLE;
374 }
375
376
377
378 /** Garbage collection
379  *
380  * Should be called some time to time to free the memory allocated for contexts
381  * that have finished executing their main functions.
382  */
383 void xbt_context_empty_trash(void)
384 {
385   xbt_context_t context = NULL;
386
387   DEBUG1("Emptying trashbin (%d contexts to free)",
388          xbt_swag_size(context_to_destroy));
389
390   while ((context = xbt_swag_extract(context_to_destroy)))
391     xbt_context_free(context);
392 }
393
394 /*********************/
395 /* context switching */
396 /*********************/
397
398 static void __xbt_context_yield(xbt_context_t context)
399 {
400 #ifdef CONTEXT_THREADS
401   xbt_context_t self;
402 #endif
403
404   xbt_assert0(current_context, "You have to call context_init() first.");
405   xbt_assert0(context, "Invalid argument");
406
407   if (current_context == context) {
408     DEBUG1
409       ("--------- current_context (%p) is yielding back to maestro ---------",
410        context);
411   } else {
412     DEBUG2
413       ("--------- current_context (%p) is yielding to context(%p) ---------",
414        current_context, context);
415   }
416
417 #ifdef CONTEXT_THREADS
418
419   self = current_context;
420
421   if (is_main_thread()) {
422     /* the main thread has called this function
423      * - update the current context
424      * - signal the condition of the process to run
425      * - wait on its condition
426      * - restore thr current contex
427      */
428
429     xbt_os_mutex_lock(master_mutex);
430     xbt_os_mutex_lock(context->mutex);
431
432     /* update the current context */
433     current_context = context;
434     xbt_os_cond_signal(context->cond);
435     xbt_os_mutex_unlock(context->mutex);
436
437     xbt_os_cond_wait(master_cond, master_mutex);
438     xbt_os_mutex_unlock(master_mutex);
439     /* retore the current context */
440     current_context = self;
441
442   } else {
443     /* a java thread has called this function
444      * - update the current context
445      * - signal the condition of the main thread
446      * - wait on its condition
447      * - restore thr current contex
448      */
449
450     xbt_os_mutex_lock(master_mutex);
451     xbt_os_mutex_lock(context->mutex);
452     /* update the current context */
453     current_context = context;
454     xbt_os_cond_signal(master_cond);
455     xbt_os_mutex_unlock(master_mutex);
456     xbt_os_cond_wait(context->cond, context->mutex);
457     xbt_os_mutex_unlock(context->mutex);
458     /* retore the current context */
459     current_context = self;
460   }
461
462 #else /* use SUSv2 contexts */
463   VOIRP(current_context);
464   VOIRP(current_context->save);
465
466   VOIRP(context);
467   VOIRP(context->save);
468
469   int return_value = 0;
470
471   if (context->save == NULL) {
472     DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
473     DEBUG2("Saving current_context value (%p) to context(%p)->save",
474            current_context, context);
475     context->save = current_context;
476     DEBUG1("current_context becomes  context(%p) ", context);
477     current_context = context;
478     DEBUG1
479       ("Current position memorized (context->save). Jumping to context (%p)",
480        context);
481     return_value = swapcontext(&(context->save->uc), &(context->uc));
482     xbt_assert0((return_value == 0), "Context swapping failure");
483     DEBUG1("I am (%p). Coming back\n", context);
484   } else {
485     xbt_context_t old_context = context->save;
486
487     DEBUG1("[%p] **** Back ! ****", context);
488     DEBUG2("Setting current_context (%p) to context(%p)->save",
489            current_context, context);
490     current_context = context->save;
491     DEBUG1("Setting context(%p)->save to NULL", context);
492     context->save = NULL;
493     DEBUG2("Current position memorized (%p). Jumping to context (%p)",
494            context, old_context);
495     return_value = swapcontext(&(context->uc), &(old_context->uc));
496     xbt_assert0((return_value == 0), "Context swapping failure");
497     DEBUG1("I am (%p). Coming back\n", context);
498   }
499 #endif
500
501   if (current_context->iwannadie)
502     xbt_context_stop(1);
503 }
504
505
506
507
508
509 /** 
510  * Calling this function makes the current context yield. The context
511  * that scheduled it returns from xbt_context_schedule as if nothing
512  * had happened.
513  * 
514  * Only the processes can call this function, giving back the control
515  * to the maestro
516  */
517 void xbt_context_yield(void)
518 {
519   __xbt_context_yield(current_context);
520 }
521
522 /** 
523  * \param context the winner
524  *
525  * Calling this function blocks the current context and schedule \a context.  
526  * When \a context will call xbt_context_yield, it will return
527  * to this function as if nothing had happened.
528  * 
529  * Only the maestro can call this function to run a given process.
530  */
531 void xbt_context_schedule(xbt_context_t context)
532 {
533   DEBUG1("Scheduling %p", context);
534   xbt_assert0((current_context == init_context),
535               "You are not supposed to run this function here!");
536   __xbt_context_yield(context);
537 }
538
539
540 /** 
541  * \param context poor victim
542  *
543  * This function simply kills \a context... scarry isn't it ?
544  */
545 void xbt_context_kill(xbt_context_t context)
546 {
547   DEBUG1("Killing %p", context);
548
549   context->iwannadie = 1;
550
551   DEBUG1("Scheduling %p", context);
552   __xbt_context_yield(context);
553   DEBUG1("End of Scheduling %p", context);
554 }
555
556 /* Java cruft I'm gonna kill in the next cleanup round */
557 void xbt_context_set_jprocess(xbt_context_t context, void *jp)
558 {
559 }
560 void *xbt_context_get_jprocess(xbt_context_t context)
561 {
562   return NULL;
563 }
564 void xbt_context_set_jenv(xbt_context_t context, void *je)
565 {
566 }
567 void *xbt_context_get_jenv(xbt_context_t context)
568 {
569   return NULL;
570 }
571
572 /* @} */