Logo AND Algorithmique Numérique Distribuée

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