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;
28 #ifdef CONTEXT_THREADS
29 static xbt_os_mutex_t creation_mutex;
30 static xbt_os_cond_t creation_cond;
31 static xbt_os_mutex_t master_mutex;
32 static xbt_os_cond_t master_cond;
34 static xbt_os_thread_t current_thread_id;
36 static int is_main_thread(void) {
37 return xbt_os_thread_self() == current_thread_id;
43 /********************/
44 /* Module init/exit */
45 /********************/
46 #ifndef CONTEXT_THREADS
47 /* callback: context fetching (used only with ucontext, os_thread deal with it
49 static ex_ctx_t *_context_ex_ctx(void)
51 return current_context->exception;
54 /* callback: termination */
55 static void _context_ex_terminate(xbt_ex_t * e)
60 /* FIXME: there should be a configuration variable to
61 choose to kill everyone or only this one */
66 * \ingroup XBT_context
69 /** Context module initialization
71 * \warning It has to be called before using any other function of this module.
73 void xbt_context_init(void)
75 if (!current_context) {
76 current_context = init_context = xbt_new0(s_xbt_context_t, 1);
77 DEBUG1("Init Context (%p)", init_context);
78 init_context->iwannadie = 0; /* useless but makes valgrind happy */
80 xbt_swag_new(xbt_swag_offset(*current_context, hookup));
81 context_living = xbt_swag_new(xbt_swag_offset(*current_context, hookup));
82 xbt_swag_insert(init_context, context_living);
84 #ifdef CONTEXT_THREADS
85 /* only used during the creation of the processes */
86 creation_mutex = xbt_os_mutex_init();
87 creation_cond = xbt_os_cond_init();
89 /* used to schedule/unschedule the processes */
90 master_mutex = xbt_os_mutex_init();
91 master_cond = xbt_os_cond_init();
93 current_thread_id = xbt_os_thread_self();
96 init_context->exception = xbt_new(ex_ctx_t, 1);
97 XBT_CTX_INITIALIZE(init_context->exception);
98 __xbt_ex_ctx = _context_ex_ctx;
99 __xbt_ex_terminate = _context_ex_terminate;
105 * This function kill all existing context and free all the memory
106 * that has been allocated in this module.
108 void xbt_context_exit(void)
110 xbt_context_t context = NULL;
112 xbt_context_empty_trash();
114 while ((context = xbt_swag_extract(context_living))) {
115 if (context != init_context) {
116 xbt_context_kill(context);
120 #ifdef CONTEXT_THREADS
121 xbt_os_mutex_destroy(creation_mutex);
122 xbt_os_cond_destroy(creation_cond);
123 xbt_os_mutex_destroy(master_mutex);
124 xbt_os_cond_destroy(master_cond);
126 free(init_context->exception);
130 init_context = current_context = NULL;
132 xbt_context_empty_trash();
133 xbt_swag_free(context_to_destroy);
134 xbt_swag_free(context_living);
138 /*******************************/
139 /* Object creation/destruction */
140 /*******************************/
142 * \param code a main function
143 * \param startup_func a function to call when running the context for
144 * the first time and just before the main function \a code
145 * \param startup_arg the argument passed to the previous function (\a startup_func)
146 * \param cleanup_func a function to call when running the context, just after
147 the termination of the main function \a code
148 * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
149 * \param argc first argument of function \a code
150 * \param argv seconde argument of function \a code
153 xbt_context_new(const char *name,
154 xbt_main_func_t code,
155 void_f_pvoid_t startup_func,
157 void_f_pvoid_t cleanup_func,
158 void *cleanup_arg, int argc, char *argv[]
161 xbt_context_t res = NULL;
163 res = xbt_new0(s_xbt_context_t, 1);
166 res->name = xbt_strdup(name);
168 #ifdef CONTEXT_THREADS
169 res->mutex = xbt_os_mutex_init();
170 res->cond = xbt_os_cond_init();
173 xbt_assert2(getcontext(&(res->uc)) == 0,
174 "Error in context saving: %d (%s)", errno, strerror(errno));
175 res->uc.uc_link = NULL;
176 /* res->uc.uc_link = &(current_context->uc); */
177 /* WARNING : when this context is over, the current_context (i.e. the
178 father), is awaken... Theorically, the wrapper should prevent using
180 res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack, STACK_SIZE);
181 res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack, STACK_SIZE);
183 res->exception = xbt_new(ex_ctx_t, 1);
184 XBT_CTX_INITIALIZE(res->exception);
185 #endif /* CONTEXT_THREADS or not */
187 res->iwannadie = 0; /* useless but makes valgrind happy */
191 res->startup_func = startup_func;
192 res->startup_arg = startup_arg;
193 res->cleanup_func = cleanup_func;
194 res->cleanup_arg = cleanup_arg;
196 xbt_swag_insert(res, context_living);
201 /* Scenario for the end of a context:
203 * CASE 1: death after end of function
204 * __context_wrapper, called by os thread, calls xbt_context_stop after user code stops
205 * xbt_context_stop calls user cleanup_func if any (in context settings),
206 * add current to trashbin
207 * yields back to maestro (destroy os thread on need)
208 * From time to time, maestro calls xbt_context_empty_trash,
209 * which maps xbt_context_free on the content
210 * xbt_context_free frees some more memory,
213 * CASE 2: brutal death
214 * xbt_context_kill (from any context)
215 * set context->wannadie to 1
216 * yields to the context
217 * the context is awaken in the middle of __yield.
218 * At the end of it, it checks that wannadie == 1, and call xbt_context_stop
219 * (same than first case afterward)
222 /* Argument must be stopped first -- runs in maestro context */
223 static void xbt_context_free(xbt_context_t context)
230 DEBUG1("Freeing %p", context);
233 DEBUG0("Freeing arguments");
235 for (i = 0; i < context->argc; i++)
236 if (context->argv[i])
237 free(context->argv[i]);
242 #ifdef CONTEXT_THREADS
243 DEBUG1("\t joining %p", (void *) context->thread);
245 xbt_os_thread_join(context->thread, NULL);
247 xbt_os_mutex_destroy(context->mutex);
248 xbt_os_cond_destroy(context->cond);
250 context->thread = NULL;
251 context->mutex = NULL;
252 context->cond = NULL;
254 if (context->exception)
255 free(context->exception);
261 /************************/
262 /* Start/stop a context */
263 /************************/
264 static void xbt_context_stop(int retvalue);
265 static void __xbt_context_yield(xbt_context_t context);
267 static void *__context_wrapper(void *c)
269 xbt_context_t context = current_context;
271 #ifdef CONTEXT_THREADS
272 context = (xbt_context_t) c;
273 context->thread = xbt_os_thread_self();
275 DEBUG3("**[ctx:%p;self:%p]** Lock creation_mutex %p ****", context,
276 (void *) xbt_os_thread_self(), creation_mutex);
277 xbt_os_mutex_lock(creation_mutex);
278 xbt_os_mutex_lock(context->mutex);
281 ("**[ctx:%p;self:%p]** Releasing the creator (creation_cond %p,%p) ****",
282 context, (void *) xbt_os_thread_self(), creation_cond, creation_mutex);
283 xbt_os_cond_signal(creation_cond);
284 xbt_os_mutex_unlock(creation_mutex);
286 DEBUG4("**[ctx:%p;self:%p]** Going to Jail on lock %p and cond %p ****",
287 context, (void *) xbt_os_thread_self(), context->mutex,
289 xbt_os_cond_wait(context->cond, context->mutex);
291 DEBUG3("**[ctx:%p;self:%p]** Unlocking individual %p ****", context,
292 (void *) xbt_os_thread_self(), context->mutex);
293 xbt_os_mutex_unlock(context->mutex);
297 if (context->startup_func)
298 context->startup_func(context->startup_arg);
300 DEBUG0("Calling the main function");
302 xbt_context_stop((context->code) (context->argc, context->argv));
307 * \param context the context to start
309 * Calling this function prepares \a context to be run. It will
310 however run effectively only when calling #xbt_context_schedule
312 void xbt_context_start(xbt_context_t context)
314 #ifdef CONTEXT_THREADS
315 /* Launch the thread */
317 DEBUG3("**[ctx:%p;self:%p]** Locking creation_mutex %p ****", context,
318 xbt_os_thread_self(), creation_mutex);
319 xbt_os_mutex_lock(creation_mutex);
321 DEBUG2("**[ctx:%p;self:%p]** Thread create ****", context,
322 xbt_os_thread_self());
324 xbt_os_thread_create(context->name, __context_wrapper, context);
325 DEBUG3("**[ctx:%p;self:%p]** Thread created : %p ****", context,
326 xbt_os_thread_self(), context->thread);
329 ("**[ctx:%p;self:%p]** Going to jail on creation_cond/mutex (%p,%p) ****",
330 context, xbt_os_thread_self(), creation_cond, creation_mutex);
331 xbt_os_cond_wait(creation_cond, creation_mutex);
332 DEBUG3("**[ctx:%p;self:%p]** Unlocking creation %p ****", context,
333 xbt_os_thread_self(), creation_mutex);
334 xbt_os_mutex_unlock(creation_mutex);
336 makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1, context);
340 /* Stops current context: calls user's cleanup function, kills os thread, and yields back to maestro */
341 static void xbt_context_stop(int retvalue)
343 DEBUG1("--------- %p is exiting ---------", current_context);
345 if (current_context->cleanup_func) {
346 DEBUG0("Calling cleanup function");
347 current_context->cleanup_func(current_context->cleanup_arg);
350 DEBUG0("Putting context in the to_destroy set");
351 xbt_swag_remove(current_context, context_living);
352 xbt_swag_insert(current_context, context_to_destroy);
356 #ifdef CONTEXT_THREADS
357 /* a java thread has called this function
358 * - update the current context
359 * - signal the condition of the main thread
360 * - wait on its condition
361 * - restore thr current contex
364 xbt_os_mutex_lock(master_mutex);
365 xbt_os_cond_signal(master_cond);
366 xbt_os_mutex_unlock(master_mutex);
367 xbt_os_thread_exit(NULL); /* We should provide return value in case other wants it */
371 __xbt_context_yield(current_context);
378 /** Garbage collection
380 * Should be called some time to time to free the memory allocated for contexts
381 * that have finished executing their main functions.
383 void xbt_context_empty_trash(void)
385 xbt_context_t context = NULL;
387 DEBUG1("Emptying trashbin (%d contexts to free)",
388 xbt_swag_size(context_to_destroy));
390 while ((context = xbt_swag_extract(context_to_destroy)))
391 xbt_context_free(context);
394 /*********************/
395 /* context switching */
396 /*********************/
398 static void __xbt_context_yield(xbt_context_t context)
400 #ifdef CONTEXT_THREADS
404 xbt_assert0(current_context, "You have to call context_init() first.");
405 xbt_assert0(context, "Invalid argument");
407 if (current_context == context) {
409 ("--------- current_context (%p) is yielding back to maestro ---------",
413 ("--------- current_context (%p) is yielding to context(%p) ---------",
414 current_context, context);
417 #ifdef CONTEXT_THREADS
419 self = current_context;
421 if (is_main_thread()) {
422 /* the main thread has called this function
423 * - update the current context
424 * - signal the condition of the process to run
425 * - wait on its condition
426 * - restore thr current contex
429 xbt_os_mutex_lock(master_mutex);
430 xbt_os_mutex_lock(context->mutex);
432 /* update the current context */
433 current_context = context;
434 xbt_os_cond_signal(context->cond);
435 xbt_os_mutex_unlock(context->mutex);
437 xbt_os_cond_wait(master_cond, master_mutex);
438 xbt_os_mutex_unlock(master_mutex);
439 /* retore the current context */
440 current_context = self;
443 /* a java thread has called this function
444 * - update the current context
445 * - signal the condition of the main thread
446 * - wait on its condition
447 * - restore thr current contex
450 xbt_os_mutex_lock(master_mutex);
451 xbt_os_mutex_lock(context->mutex);
452 /* update the current context */
453 current_context = context;
454 xbt_os_cond_signal(master_cond);
455 xbt_os_mutex_unlock(master_mutex);
456 xbt_os_cond_wait(context->cond, context->mutex);
457 xbt_os_mutex_unlock(context->mutex);
458 /* retore the current context */
459 current_context = self;
462 #else /* use SUSv2 contexts */
463 VOIRP(current_context);
464 VOIRP(current_context->save);
467 VOIRP(context->save);
469 int return_value = 0;
471 if (context->save == NULL) {
472 DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
473 DEBUG2("Saving current_context value (%p) to context(%p)->save",
474 current_context, context);
475 context->save = current_context;
476 DEBUG1("current_context becomes context(%p) ", context);
477 current_context = context;
479 ("Current position memorized (context->save). Jumping to context (%p)",
481 return_value = swapcontext(&(context->save->uc), &(context->uc));
482 xbt_assert0((return_value == 0), "Context swapping failure");
483 DEBUG1("I am (%p). Coming back\n", context);
485 xbt_context_t old_context = context->save;
487 DEBUG1("[%p] **** Back ! ****", context);
488 DEBUG2("Setting current_context (%p) to context(%p)->save",
489 current_context, context);
490 current_context = context->save;
491 DEBUG1("Setting context(%p)->save to NULL", context);
492 context->save = NULL;
493 DEBUG2("Current position memorized (%p). Jumping to context (%p)",
494 context, old_context);
495 return_value = swapcontext(&(context->uc), &(old_context->uc));
496 xbt_assert0((return_value == 0), "Context swapping failure");
497 DEBUG1("I am (%p). Coming back\n", context);
501 if (current_context->iwannadie)
510 * Calling this function makes the current context yield. The context
511 * that scheduled it returns from xbt_context_schedule as if nothing
514 * Only the processes can call this function, giving back the control
517 void xbt_context_yield(void)
519 __xbt_context_yield(current_context);
523 * \param context the winner
525 * Calling this function blocks the current context and schedule \a context.
526 * When \a context will call xbt_context_yield, it will return
527 * to this function as if nothing had happened.
529 * Only the maestro can call this function to run a given process.
531 void xbt_context_schedule(xbt_context_t context)
533 DEBUG1("Scheduling %p", context);
534 xbt_assert0((current_context == init_context),
535 "You are not supposed to run this function here!");
536 __xbt_context_yield(context);
541 * \param context poor victim
543 * This function simply kills \a context... scarry isn't it ?
545 void xbt_context_kill(xbt_context_t context)
547 DEBUG1("Killing %p", context);
549 context->iwannadie = 1;
551 DEBUG1("Scheduling %p", context);
552 __xbt_context_yield(context);
553 DEBUG1("End of Scheduling %p", context);
556 /* Java cruft I'm gonna kill in the next cleanup round */
557 void xbt_context_set_jprocess(xbt_context_t context, void *jp)
560 void *xbt_context_get_jprocess(xbt_context_t context)
564 void xbt_context_set_jenv(xbt_context_t context, void *je)
567 void *xbt_context_get_jenv(xbt_context_t context)