Logo AND Algorithmique Numérique Distribuée

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