3 /* a fast and simple context switching library */
5 /* Copyright (c) 2004 Arnaud Legrand. */
6 /* Copyright (c) 2004, 2005 Martin Quinson. */
7 /* All rights reserved. */
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. */
13 #include "context_private.h"
15 #include "xbt/dynar.h"
16 #include "xbt/xbt_os_thread.h"
17 #include "xbt/ex_interface.h"
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ctx, xbt, "Context");
21 #define VOIRP(expr) DEBUG1(" {" #expr " = %p }", expr)
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;
33 /********************/
34 /* Module init/exit */
35 /********************/
36 #ifndef CONTEXT_THREADS
37 /* callback: context fetching (used only with ucontext, os_thread deal with it
39 static ex_ctx_t *_context_ex_ctx(void) {
40 return current_context->exception;
43 /* callback: termination */
44 static void _context_ex_terminate(xbt_ex_t * e) {
48 /* FIXME: there should be a configuration variable to
49 choose to kill everyone or only this one */
54 * \ingroup XBT_context
57 /** Context module initialization
59 * \warning It has to be called before using any other function of this module.
61 void xbt_context_init(void)
63 if (!current_context) {
64 current_context = init_context = xbt_new0(s_xbt_context_t, 1);
65 DEBUG1("Init Context (%p)", init_context);
67 init_context->iwannadie = 0; /* useless but makes valgrind happy */
69 xbt_swag_new(xbt_swag_offset(*current_context, hookup));
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();
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;
86 * This function kill all existing context and free all the memory
87 * that has been allocated in this module.
89 void xbt_context_exit(void)
91 xbt_context_t context = NULL;
93 xbt_context_empty_trash();
94 while ((context = xbt_swag_extract(context_living))) {
95 if (context != init_context) {
96 xbt_context_kill(context);
99 #ifdef CONTEXT_THREADS
100 xbt_os_mutex_destroy(creation_mutex);
101 xbt_os_cond_destroy(creation_cond);
103 free(init_context->exception);
106 init_context = current_context = NULL;
108 xbt_context_empty_trash();
109 xbt_swag_free(context_to_destroy);
110 xbt_swag_free(context_living);
114 /*******************************/
115 /* Object creation/destruction */
116 /*******************************/
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
128 xbt_context_t xbt_context_new(const char *name,xbt_main_func_t code,
129 void_f_pvoid_t startup_func,
131 void_f_pvoid_t cleanup_func,
132 void *cleanup_arg, int argc, char *argv[])
134 xbt_context_t res = NULL;
136 res = xbt_new0(s_xbt_context_t, 1);
139 res->name = xbt_strdup(name);
140 #ifdef CONTEXT_THREADS
141 res->mutex = xbt_os_mutex_init();
142 res->cond = xbt_os_cond_init();
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
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);
156 res->exception = xbt_new(ex_ctx_t, 1);
157 XBT_CTX_INITIALIZE(res->exception);
158 #endif /* CONTEXT_THREADS or not */
160 res->iwannadie = 0; /* useless but makes valgrind happy */
164 res->startup_func = startup_func;
165 res->startup_arg = startup_arg;
166 res->cleanup_func = cleanup_func;
167 res->cleanup_arg = cleanup_arg;
169 xbt_swag_insert(res, context_living);
174 /* Scenario for the end of a context:
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,
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)
195 /* Argument must be stopped first -- runs in maestro context */
196 static void xbt_context_free(xbt_context_t context) {
201 DEBUG1("Freeing %p", context);
204 DEBUG0("Freeing arguments");
205 for (i = 0; i < context->argc; i++)
206 if (context->argv[i])
207 free(context->argv[i]);
211 #ifdef CONTEXT_THREADS
212 DEBUG1("\t joining %p", (void *) context->thread);
214 xbt_os_thread_join(context->thread, NULL);
216 xbt_os_mutex_destroy(context->mutex);
217 xbt_os_cond_destroy(context->cond);
219 context->thread = NULL;
220 context->mutex = NULL;
221 context->cond = NULL;
223 if (context->exception)
224 free(context->exception);
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);
237 static void *__context_wrapper(void *c)
239 xbt_context_t context = current_context;
241 #ifdef CONTEXT_THREADS
242 context = (xbt_context_t) c;
243 context->thread = xbt_os_thread_self();
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);
251 ("**[ctx:%p;self:%p]** Releasing the creator (creation_cond %p,%p) ****",
252 context, (void *) xbt_os_thread_self(), creation_cond,
254 xbt_os_cond_signal(creation_cond);
255 xbt_os_mutex_unlock(creation_mutex);
257 DEBUG4("**[ctx:%p;self:%p]** Going to Jail on lock %p and cond %p ****",
258 context, (void *) xbt_os_thread_self(), context->mutex,
260 xbt_os_cond_wait(context->cond, context->mutex);
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);
268 if (context->startup_func)
269 context->startup_func(context->startup_arg);
271 DEBUG0("Calling the main function");
273 xbt_context_stop((context->code) (context->argc, context->argv));
277 * \param context the context to start
279 * Calling this function prepares \a context to be run. It will
280 however run effectively only when calling #xbt_context_schedule
282 void xbt_context_start(xbt_context_t context)
284 #ifdef CONTEXT_THREADS
285 /* Launch the thread */
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);
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);
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);
305 makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1,
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);
315 if (current_context->cleanup_func) {
316 DEBUG0("Calling cleanup function");
317 current_context->cleanup_func(current_context->cleanup_arg);
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);
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
337 __xbt_context_yield(current_context);
344 /** Garbage collection
346 * Should be called some time to time to free the memory allocated for contexts
347 * that have finished executing their main functions.
349 void xbt_context_empty_trash(void)
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);
358 /*********************/
359 /* context switching */
360 /*********************/
362 static void __xbt_context_yield(xbt_context_t context)
364 #ifdef CONTEXT_THREADS
367 xbt_assert0(current_context, "You have to call context_init() first.");
368 xbt_assert0(context,"Invalid argument");
370 if (current_context == context) {
371 DEBUG1("--------- current_context (%p) is yielding back to maestro ---------",
374 DEBUG2("--------- current_context (%p) is yielding to context(%p) ---------",
375 current_context, context);
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;
394 #else /* use SUSv2 contexts */
395 VOIRP(current_context);
396 VOIRP(current_context->save);
399 VOIRP(context->save);
401 int return_value = 0;
403 if (context->save == NULL) {
404 DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
405 DEBUG2("Saving current_context value (%p) to context(%p)->save",
406 current_context, context);
407 context->save = current_context;
408 DEBUG1("current_context becomes context(%p) ", context);
409 current_context = context;
411 ("Current position memorized (context->save). Jumping to context (%p)",
413 return_value = swapcontext(&(context->save->uc), &(context->uc));
414 xbt_assert0((return_value == 0), "Context swapping failure");
415 DEBUG1("I am (%p). Coming back\n", context);
417 xbt_context_t old_context = context->save;
418 DEBUG1("[%p] **** Back ! ****", context);
419 DEBUG2("Setting current_context (%p) to context(%p)->save",
420 current_context, context);
421 current_context = context->save;
422 DEBUG1("Setting context(%p)->save to NULL", context);
423 context->save = NULL;
424 DEBUG2("Current position memorized (%p). Jumping to context (%p)",
425 context, old_context);
426 return_value = swapcontext(&(context->uc), &(old_context->uc));
427 xbt_assert0((return_value == 0), "Context swapping failure");
428 DEBUG1("I am (%p). Coming back\n", context);
431 if (current_context->iwannadie)
442 * Calling this function makes the current context yield. The context
443 * that scheduled it returns from xbt_context_schedule as if nothing
446 * Only the processes can call this function, giving back the control
449 void xbt_context_yield(void)
451 __xbt_context_yield(current_context);
455 * \param context the winner
457 * Calling this function blocks the current context and schedule \a context.
458 * When \a context will call xbt_context_yield, it will return
459 * to this function as if nothing had happened.
461 * Only the maestro can call this function to run a given process.
463 void xbt_context_schedule(xbt_context_t context)
465 DEBUG1("Scheduling %p", context);
466 xbt_assert0((current_context == init_context),
467 "You are not supposed to run this function here!");
468 __xbt_context_yield(context);
473 * \param context poor victim
475 * This function simply kills \a context... scarry isn't it ?
477 void xbt_context_kill(xbt_context_t context)
479 DEBUG1("Killing %p", context);
481 context->iwannadie = 1;
482 DEBUG1("Scheduling %p", context);
483 __xbt_context_yield(context);
484 DEBUG1("End of Scheduling %p", context);
489 /* Java cruft I'm gonna kill in the next cleanup round */
490 void xbt_context_set_jprocess(xbt_context_t context, void *jp){}
491 void* xbt_context_get_jprocess(xbt_context_t context){return NULL;}
492 void xbt_context_set_jenv(xbt_context_t context,void* je){}
493 void* xbt_context_get_jenv(xbt_context_t context){return NULL;}