Logo AND Algorithmique Numérique Distribuée

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