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;
30 /********************/
31 /* Module init/exit */
32 /********************/
33 #ifndef CONTEXT_THREADS
34 /* callback: context fetching (used only with ucontext, os_thread deal with it
36 static ex_ctx_t *_context_ex_ctx(void)
38 return current_context->exception;
41 /* callback: termination */
42 static void _context_ex_terminate(xbt_ex_t * e)
47 /* FIXME: there should be a configuration variable to
48 choose to kill everyone or only this one */
54 schedule(xbt_context_t c);
57 unschedule(xbt_context_t c);
61 schedule(xbt_context_t c)
63 xbt_os_sem_post(c->begin);
64 xbt_os_sem_wait(c->end);
67 static void unschedule(xbt_context_t c)
69 xbt_os_sem_post(c->end);
70 xbt_os_sem_wait(c->begin);
74 * \ingroup XBT_context
77 /** Context module initialization
79 * \warning It has to be called before using any other function of this module.
81 void xbt_context_init(void)
83 if (!current_context) {
84 current_context = init_context = xbt_new0(s_xbt_context_t, 1);
85 DEBUG1("Init Context (%p)", init_context);
86 init_context->iwannadie = 0; /* useless but makes valgrind happy */
88 xbt_swag_new(xbt_swag_offset(*current_context, hookup));
89 context_living = xbt_swag_new(xbt_swag_offset(*current_context, hookup));
90 xbt_swag_insert(init_context, context_living);
92 #ifndef CONTEXT_THREADS
93 init_context->exception = xbt_new(ex_ctx_t, 1);
94 XBT_CTX_INITIALIZE(init_context->exception);
95 __xbt_ex_ctx = _context_ex_ctx;
96 __xbt_ex_terminate = _context_ex_terminate;
102 * This function kill all existing context and free all the memory
103 * that has been allocated in this module.
105 void xbt_context_exit(void)
107 xbt_context_t context = NULL;
109 xbt_context_empty_trash();
111 while ((context = xbt_swag_extract(context_living))) {
112 if (context != init_context) {
113 xbt_context_kill(context);
117 #ifndef CONTEXT_THREADS
118 free(init_context->exception);
122 init_context = current_context = NULL;
124 xbt_context_empty_trash();
125 xbt_swag_free(context_to_destroy);
126 xbt_swag_free(context_living);
131 /*******************************/
132 /* Object creation/destruction */
133 /*******************************/
135 * \param code a main function
136 * \param startup_func a function to call when running the context for
137 * the first time and just before the main function \a code
138 * \param startup_arg the argument passed to the previous function (\a startup_func)
139 * \param cleanup_func a function to call when running the context, just after
140 the termination of the main function \a code
141 * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
142 * \param argc first argument of function \a code
143 * \param argv seconde argument of function \a code
146 xbt_context_new(const char *name,
147 xbt_main_func_t code,
148 void_f_pvoid_t startup_func,
150 void_f_pvoid_t cleanup_func,
151 void *cleanup_arg, int argc, char *argv[]
154 xbt_context_t res = NULL;
156 res = xbt_new0(s_xbt_context_t, 1);
159 res->name = xbt_strdup(name);
161 #ifdef CONTEXT_THREADS
163 * initialize the semaphores used to schedule/unschedule
164 * the process associated to the newly created context
166 res->begin = xbt_os_sem_init(0,0);
167 res->end = xbt_os_sem_init(0,0);
170 xbt_assert2(getcontext(&(res->uc)) == 0,
171 "Error in context saving: %d (%s)", errno, strerror(errno));
172 res->uc.uc_link = NULL;
173 /* res->uc.uc_link = &(current_context->uc); */
174 /* WARNING : when this context is over, the current_context (i.e. the
175 father), is awaken... Theorically, the wrapper should prevent using
177 res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack, STACK_SIZE);
178 res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack, STACK_SIZE);
180 res->exception = xbt_new(ex_ctx_t, 1);
181 XBT_CTX_INITIALIZE(res->exception);
182 #endif /* CONTEXT_THREADS or not */
184 res->iwannadie = 0; /* useless but makes valgrind happy */
188 res->startup_func = startup_func;
189 res->startup_arg = startup_arg;
190 res->cleanup_func = cleanup_func;
191 res->cleanup_arg = cleanup_arg;
193 xbt_swag_insert(res, context_living);
198 /* Scenario for the end of a context:
200 * CASE 1: death after end of function
201 * __context_wrapper, called by os thread, calls xbt_context_stop after user code stops
202 * xbt_context_stop calls user cleanup_func if any (in context settings),
203 * add current to trashbin
204 * yields back to maestro (destroy os thread on need)
205 * From time to time, maestro calls xbt_context_empty_trash,
206 * which maps xbt_context_free on the content
207 * xbt_context_free frees some more memory,
210 * CASE 2: brutal death
211 * xbt_context_kill (from any context)
212 * set context->wannadie to 1
213 * yields to the context
214 * the context is awaken in the middle of __yield.
215 * At the end of it, it checks that wannadie == 1, and call xbt_context_stop
216 * (same than first case afterward)
220 /* Argument must be stopped first -- runs in maestro context */
221 static void xbt_context_free(xbt_context_t context)
228 DEBUG1("Freeing %p", context);
231 DEBUG0("Freeing arguments");
233 for (i = 0; i < context->argc; i++)
234 if (context->argv[i])
235 free(context->argv[i]);
240 #ifdef CONTEXT_THREADS
241 DEBUG1("\t joining %p", (void *) context->thread);
243 xbt_os_thread_join(context->thread, NULL);
245 /* destroy the semaphore used to schedule/unshedule the process */
246 xbt_os_sem_destroy(context->begin);
247 xbt_os_sem_destroy(context->end);
249 context->thread = NULL;
250 context->begin = NULL;
253 if (context->exception)
254 free(context->exception);
260 /************************/
261 /* Start/stop a context */
262 /************************/
263 static void xbt_context_stop(int retvalue);
264 static void __xbt_context_yield(xbt_context_t context);
266 static void *__context_wrapper(void *c)
268 xbt_context_t context = current_context;
270 #ifdef CONTEXT_THREADS
271 context = (xbt_context_t) c;
272 /*context->thread = xbt_os_thread_self();*/
274 /* signal its starting to the maestro and wait to start its job*/
279 if (context->startup_func)
280 context->startup_func(context->startup_arg);
282 DEBUG0("Calling the main function");
284 xbt_context_stop((context->code) (context->argc, context->argv));
288 * \param context the context to start
290 * Calling this function prepares \a context to be run. It will
291 however run effectively only when calling #xbt_context_schedule
293 void xbt_context_start(xbt_context_t context)
295 #ifdef CONTEXT_THREADS
296 /* create the process and start it */
297 context->thread = xbt_os_thread_create(context->name,__context_wrapper, context);
299 /* wait the starting of the newly created process */
300 xbt_os_sem_wait(context->end);
302 makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1, context);
306 /* Stops current context: calls user's cleanup function, kills os thread, and yields back to maestro */
307 static void xbt_context_stop(int retvalue)
309 DEBUG1("--------- %p is exiting ---------", current_context);
311 if (current_context->cleanup_func) {
312 DEBUG0("Calling cleanup function");
313 current_context->cleanup_func(current_context->cleanup_arg);
316 DEBUG0("Putting context in the to_destroy set");
317 xbt_swag_remove(current_context, context_living);
318 xbt_swag_insert(current_context, context_to_destroy);
322 #ifdef CONTEXT_THREADS
323 /* signal to the maestro that it has finished */
324 xbt_os_sem_post(current_context->end);
326 xbt_os_thread_exit(NULL); /* We should provide return value in case other wants it */
328 __xbt_context_yield(current_context);
335 /** Garbage collection
337 * Should be called some time to time to free the memory allocated for contexts
338 * that have finished executing their main functions.
340 void xbt_context_empty_trash(void)
342 xbt_context_t context = NULL;
344 DEBUG1("Emptying trashbin (%d contexts to free)",
345 xbt_swag_size(context_to_destroy));
347 while ((context = xbt_swag_extract(context_to_destroy)))
348 xbt_context_free(context);
351 /*********************/
352 /* context switching */
353 /*********************/
355 static void __xbt_context_yield(xbt_context_t context)
357 xbt_assert0(current_context, "You have to call context_init() first.");
358 xbt_assert0(context, "Invalid argument");
360 if (current_context == context) {
362 ("--------- current_context (%p) is yielding back to maestro ---------",
366 ("--------- current_context (%p) is yielding to context(%p) ---------",
367 current_context, context);
370 #ifdef CONTEXT_THREADS
372 if(current_context != init_context && !context->iwannadie)
373 {/* it's a process and it doesn't wants to die (xbt_context_yield()) */
375 /* save the current context */
376 xbt_context_t self = current_context;
378 /* update the current context to this context */
379 current_context = context;
384 /* restore the current context to the previously saved context */
385 current_context = self;
388 { /* maestro wants to schedule a process or a process wants to die (xbt_context_schedule() or xbt_context_kill())*/
390 /* save the current context */
391 xbt_context_t self = current_context;
393 /* update the current context */
394 current_context = context;
396 /* schedule the process associated with this context */
399 /* restore the current context to the previously saved context */
400 current_context = self;
403 #else /* use SUSv2 contexts */
404 VOIRP(current_context);
405 VOIRP(current_context->save);
408 VOIRP(context->save);
410 int return_value = 0;
412 if (context->save == NULL) {
413 DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
414 DEBUG2("Saving current_context value (%p) to context(%p)->save",
415 current_context, context);
416 context->save = current_context;
417 DEBUG1("current_context becomes context(%p) ", context);
418 current_context = context;
420 ("Current position memorized (context->save). Jumping to context (%p)",
422 return_value = swapcontext(&(context->save->uc), &(context->uc));
423 xbt_assert0((return_value == 0), "Context swapping failure");
424 DEBUG1("I am (%p). Coming back\n", context);
426 xbt_context_t old_context = context->save;
428 DEBUG1("[%p] **** Back ! ****", context);
429 DEBUG2("Setting current_context (%p) to context(%p)->save",
430 current_context, context);
431 current_context = context->save;
432 DEBUG1("Setting context(%p)->save to NULL", context);
433 context->save = NULL;
434 DEBUG2("Current position memorized (%p). Jumping to context (%p)",
435 context, old_context);
436 return_value = swapcontext(&(context->uc), &(old_context->uc));
437 xbt_assert0((return_value == 0), "Context swapping failure");
438 DEBUG1("I am (%p). Coming back\n", context);
442 if (current_context->iwannadie)
447 * Calling this function makes the current context yield. The context
448 * that scheduled it returns from xbt_context_schedule as if nothing
451 * Only the processes can call this function, giving back the control
454 void xbt_context_yield(void)
456 __xbt_context_yield(current_context);
460 * \param context the winner
462 * Calling this function blocks the current context and schedule \a context.
463 * When \a context will call xbt_context_yield, it will return
464 * to this function as if nothing had happened.
466 * Only the maestro can call this function to run a given process.
468 void xbt_context_schedule(xbt_context_t context)
470 DEBUG1("Scheduling %p", context);
471 xbt_assert0((current_context == init_context),
472 "You are not supposed to run this function here!");
473 __xbt_context_yield(context);
478 * \param context poor victim
480 * This function simply kills \a context... scarry isn't it ?
482 void xbt_context_kill(xbt_context_t context)
484 DEBUG1("Killing %p", context);
486 context->iwannadie = 1;
488 DEBUG1("Scheduling %p", context);
489 __xbt_context_yield(context);
490 DEBUG1("End of Scheduling %p", context);
493 /* Java cruft I'm gonna kill in the next cleanup round */
494 void xbt_context_set_jprocess(xbt_context_t context, void *jp){}
495 void* xbt_context_get_jprocess(xbt_context_t context){return NULL;}
496 void xbt_context_set_jenv(xbt_context_t context,void* je){}
497 void* xbt_context_get_jenv(xbt_context_t context){return NULL;}