Logo AND Algorithmique Numérique Distribuée

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