Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Cleanup: shuffle the functions to get them in a somehow logical order
[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 static void xbt_context_free(xbt_context_t context) {
175   if (!context)
176     return;
177   DEBUG1("Freeing %p", context);
178   free(context->name);
179 #ifdef CONTEXT_THREADS
180   /*DEBUG1("\t joining %p",(void *)context->thread->t); */
181   DEBUG1("\t joining %p", (void *) context->thread);
182
183   xbt_os_thread_join(context->thread, NULL);
184
185   DEBUG1("\t mutex_destroy %p", (void *) context->mutex);
186   xbt_os_mutex_destroy(context->mutex);
187   DEBUG1("\t cond_destroy %p", (void *) context->cond);
188   xbt_os_cond_destroy(context->cond);
189
190   context->thread = NULL;
191   context->mutex = NULL;
192   context->cond = NULL;
193 #else
194   if (context->exception)
195     free(context->exception);
196 #endif
197    
198   free(context);
199   return;
200 }
201
202 /************************/
203 /* Start/stop a context */
204 /************************/
205 static void xbt_context_stop(xbt_context_t context, int value);
206
207 static void *__context_wrapper(void *c)
208 {
209   xbt_context_t context = current_context;
210
211 #ifdef CONTEXT_THREADS
212   context = (xbt_context_t) c;
213   context->thread = xbt_os_thread_self();
214
215   DEBUG3("**[ctx:%p;self:%p]** Lock creation_mutex %p ****", context,
216          (void *) xbt_os_thread_self(), creation_mutex);
217   xbt_os_mutex_lock(creation_mutex);
218   xbt_os_mutex_lock(context->mutex);
219
220   DEBUG4
221       ("**[ctx:%p;self:%p]** Releasing the creator (creation_cond %p,%p) ****",
222        context, (void *) xbt_os_thread_self(), creation_cond,
223        creation_mutex);
224   xbt_os_cond_signal(creation_cond);
225   xbt_os_mutex_unlock(creation_mutex);
226
227   DEBUG4("**[ctx:%p;self:%p]** Going to Jail on lock %p and cond %p ****",
228          context, (void *) xbt_os_thread_self(), context->mutex,
229          context->cond);
230   xbt_os_cond_wait(context->cond, context->mutex);
231
232   DEBUG3("**[ctx:%p;self:%p]** Unlocking individual %p ****",
233          context, (void *) xbt_os_thread_self(), context->mutex);
234   xbt_os_mutex_unlock(context->mutex);
235
236 #endif
237
238   if (context->startup_func)
239     context->startup_func(context->startup_arg);
240
241   DEBUG0("Calling the main function");
242
243   xbt_context_stop(context, (context->code) (context->argc, context->argv));
244   return NULL;
245 }
246 /** 
247  * \param context the context to start
248  * 
249  * Calling this function prepares \a context to be run. It will 
250    however run effectively only when calling #xbt_context_schedule
251  */
252 void xbt_context_start(xbt_context_t context)
253 {
254 #ifdef CONTEXT_THREADS
255   /* Launch the thread */
256    
257   DEBUG3("**[ctx:%p;self:%p]** Locking creation_mutex %p ****", context,
258          xbt_os_thread_self(), creation_mutex);
259   xbt_os_mutex_lock(creation_mutex);
260
261   DEBUG2("**[ctx:%p;self:%p]** Thread create ****", context,
262          xbt_os_thread_self());
263   context->thread = xbt_os_thread_create(context->name,__context_wrapper, context);
264   DEBUG3("**[ctx:%p;self:%p]** Thread created : %p ****", context,
265          xbt_os_thread_self(), context->thread);
266
267   DEBUG4
268       ("**[ctx:%p;self:%p]** Going to jail on creation_cond/mutex (%p,%p) ****",
269        context, xbt_os_thread_self(), creation_cond, creation_mutex);
270   xbt_os_cond_wait(creation_cond, creation_mutex);
271   DEBUG3("**[ctx:%p;self:%p]** Unlocking creation %p ****", context,
272          xbt_os_thread_self(), creation_mutex);
273   xbt_os_mutex_unlock(creation_mutex);
274 #else
275   makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1,
276               context);
277 #endif
278   return;
279 }
280
281 static void xbt_context_stop(xbt_context_t context, int value)
282 {
283   int i;
284
285   DEBUG1("--------- %p is exiting ---------", context);
286
287   DEBUG0("Calling cleanup functions");
288   if (context->cleanup_func) {
289     DEBUG0("Calling cleanup function");
290     context->cleanup_func(context->cleanup_arg);
291   }
292
293   DEBUG0("Freeing arguments");
294   for (i = 0; i < context->argc; i++)
295     if (context->argv[i])
296       free(context->argv[i]);
297
298   if (context->argv)
299     free(context->argv);
300
301   DEBUG0("Putting context in the to_destroy set");
302   xbt_swag_remove(context, context_living);
303   xbt_swag_insert(context, context_to_destroy);
304   DEBUG0("Context put in the to_destroy set");
305
306   DEBUG0("Yielding");
307
308 #ifdef CONTEXT_THREADS
309   DEBUG2("[%p] **** Locking %p ****", context, context->mutex);
310   xbt_os_mutex_lock(context->mutex);
311 /*      DEBUG1("[%p] **** Updating current_context ****"); */
312 /*      current_context = context; */
313   DEBUG1("[%p] **** Releasing the prisonner ****", context);
314   xbt_os_cond_signal(context->cond);
315   DEBUG2("[%p] **** Unlocking individual %p ****", context,
316          context->mutex);
317   xbt_os_mutex_unlock(context->mutex);
318   DEBUG1("[%p] **** Exiting ****", context);
319   xbt_os_thread_exit(NULL);     // We should provide return value in case other wants it
320 #else
321   __xbt_context_yield(context);
322 #endif
323   xbt_assert0(0, "You can't be here!");
324 }
325
326
327
328 /** Garbage collection
329  *
330  * Should be called some time to time to free the memory allocated for contexts
331  * that have finished executing their main functions.
332  */
333 void xbt_context_empty_trash(void)
334 {
335   xbt_context_t context = NULL;
336   DEBUG1("Emptying trashbin (%d contexts to free)",
337          xbt_swag_size(context_to_destroy));
338   while ((context = xbt_swag_extract(context_to_destroy)))
339     xbt_context_free(context);
340 }
341
342 /*********************/
343 /* context switching */
344 /*********************/
345
346 static void __xbt_context_yield(xbt_context_t context)
347 {
348   xbt_assert0(current_context, "You have to call context_init() first.");
349
350   DEBUG2
351       ("--------- current_context (%p) is yielding to context(%p) ---------",
352        current_context, context);
353
354 #ifdef CONTEXT_THREADS
355   if (context) {
356     xbt_context_t self = current_context;
357     DEBUG2("[%p] **** Locking ctx %p ****", self, context);
358     xbt_os_mutex_lock(context->mutex);
359     DEBUG1("[%p] **** Updating current_context ****", self);
360     current_context = context;
361     DEBUG1("[%p] **** Releasing the prisonner ****", self);
362     xbt_os_cond_signal(context->cond);
363     DEBUG3("[%p] **** Going to jail on individual %p/%p ****", self,
364            context->cond, context->mutex);
365     xbt_os_cond_wait(context->cond, context->mutex);
366     DEBUG2("[%p] **** Unlocking individual %p ****", self, context->mutex);
367     xbt_os_mutex_unlock(context->mutex);
368     DEBUG1("[%p] **** Updating current_context ****", self);
369     current_context = self;
370   }
371 #else                           /* use SUSv2 contexts */
372   VOIRP(current_context);
373   if (current_context)
374     VOIRP(current_context->save);
375
376   VOIRP(context);
377
378   if (context)
379     VOIRP(context->save);
380
381   if (context) {
382
383     int return_value = 0;
384
385     if (context->save == NULL) {
386
387       DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
388       DEBUG2("Saving current_context value (%p) to context(%p)->save",
389              current_context, context);
390       context->save = current_context;
391       DEBUG1("current_context becomes  context(%p) ", context);
392       current_context = context;
393       DEBUG1
394           ("Current position memorized (context->save). Jumping to context (%p)",
395            context);
396       return_value = swapcontext(&(context->save->uc), &(context->uc));
397       xbt_assert0((return_value == 0), "Context swapping failure");
398       DEBUG1("I am (%p). Coming back\n", context);
399     } else {
400       xbt_context_t old_context = context->save;
401       DEBUG1("[%p] **** Back ! ****", context);
402       DEBUG2("Setting current_context (%p) to context(%p)->save",
403              current_context, context);
404       current_context = context->save;
405       DEBUG1("Setting context(%p)->save to NULL", context);
406       context->save = NULL;
407       DEBUG2("Current position memorized (%p). Jumping to context (%p)",
408              context, old_context);
409       return_value = swapcontext(&(context->uc), &(old_context->uc));
410       xbt_assert0((return_value == 0), "Context swapping failure");
411       DEBUG1("I am (%p). Coming back\n", context);
412
413     }
414   }
415 #endif
416   if (current_context->iwannadie)
417     xbt_context_stop(current_context, 1);
418
419   return;
420 }
421
422
423
424
425
426 /** 
427  * Calling this function makes the current context yield. The context
428  * that scheduled it returns from xbt_context_schedule as if nothing
429  * had happened.
430  */
431 void xbt_context_yield(void)
432 {
433   __xbt_context_yield(current_context);
434 }
435
436 /** 
437  * \param context the winner
438  *
439  * Calling this function blocks the current context and schedule \a context.  
440  * When \a context will call xbt_context_yield, it will return
441  * to this function as if nothing had happened.
442  */
443 void xbt_context_schedule(xbt_context_t context)
444 {
445   DEBUG1("Scheduling %p", context);
446   xbt_assert0((current_context == init_context),
447               "You are not supposed to run this function here!");
448   __xbt_context_yield(context);
449 }
450
451
452 /** 
453  * \param context poor victim
454  *
455  * This function simply kills \a context... scarry isn't it ?
456  */
457 void xbt_context_kill(xbt_context_t context)
458 {
459   DEBUG1("Killing %p", context);
460
461   context->iwannadie = 1;
462   DEBUG1("Scheduling %p", context);
463   __xbt_context_yield(context);
464   DEBUG1("End of Scheduling %p", context);
465
466   return;
467 }
468
469 /* Java cruft I'm gonna kill in the next cleanup round */
470 void  xbt_context_set_jprocess(xbt_context_t context, void *jp){}
471 void* xbt_context_get_jprocess(xbt_context_t context){return NULL;}
472 void  xbt_context_set_jmutex(xbt_context_t context,void *jm){}
473 void* xbt_context_get_jmutex(xbt_context_t context){return NULL;}
474 void  xbt_context_set_jcond(xbt_context_t context,void *jc){}
475 void* xbt_context_get_jcond(xbt_context_t context){return NULL;}
476 void  xbt_context_set_jenv(xbt_context_t context,void* je){}
477 void* xbt_context_get_jenv(xbt_context_t context){return NULL;}
478
479 /* @} */