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 */
52 #ifdef CONTEXT_THREADS
55 schedule(xbt_context_t c);
58 yield(xbt_context_t c);
61 schedule(xbt_context_t c)
63 xbt_os_sem_release(c->begin);
64 xbt_os_sem_acquire(c->end);
67 static void yield(xbt_context_t c)
69 xbt_os_sem_release(c->end);
70 xbt_os_sem_acquire(c->begin);
75 * \ingroup XBT_context
78 /** Context module initialization
80 * \warning It has to be called before using any other function of this module.
82 void xbt_context_init(void)
84 if (!current_context) {
85 current_context = init_context = xbt_new0(s_xbt_context_t, 1);
86 DEBUG1("Init Context (%p)", init_context);
87 init_context->iwannadie = 0; /* useless but makes valgrind happy */
89 xbt_swag_new(xbt_swag_offset(*current_context, hookup));
90 context_living = xbt_swag_new(xbt_swag_offset(*current_context, hookup));
91 xbt_swag_insert(init_context, context_living);
93 #ifndef CONTEXT_THREADS
94 init_context->exception = xbt_new(ex_ctx_t, 1);
95 XBT_CTX_INITIALIZE(init_context->exception);
96 __xbt_ex_ctx = _context_ex_ctx;
97 __xbt_ex_terminate = _context_ex_terminate;
103 * This function kill all existing context and free all the memory
104 * that has been allocated in this module.
106 void xbt_context_exit(void)
108 xbt_context_t context = NULL;
110 xbt_context_empty_trash();
112 while ((context = xbt_swag_extract(context_living))) {
113 if (context != init_context) {
114 xbt_context_kill(context);
118 #ifndef CONTEXT_THREADS
119 free(init_context->exception);
123 init_context = current_context = NULL;
125 xbt_context_empty_trash();
126 xbt_swag_free(context_to_destroy);
127 xbt_swag_free(context_living);
132 /*******************************/
133 /* Object creation/destruction */
134 /*******************************/
136 * \param code a main function
137 * \param startup_func a function to call when running the context for
138 * the first time and just before the main function \a code
139 * \param startup_arg the argument passed to the previous function (\a startup_func)
140 * \param cleanup_func a function to call when running the context, just after
141 the termination of the main function \a code
142 * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
143 * \param argc first argument of function \a code
144 * \param argv seconde argument of function \a code
147 xbt_context_new(const char *name,
148 xbt_main_func_t code,
149 void_f_pvoid_t startup_func,
151 void_f_pvoid_t cleanup_func,
152 void *cleanup_arg, int argc, char *argv[]
155 xbt_context_t res = NULL;
157 res = xbt_new0(s_xbt_context_t, 1);
160 res->name = xbt_strdup(name);
162 #ifdef CONTEXT_THREADS
164 * initialize the semaphores used to schedule/yield
165 * the process associated to the newly created context
167 res->begin = xbt_os_sem_init(0);
168 res->end = xbt_os_sem_init(0);
171 xbt_assert2(getcontext(&(res->uc)) == 0,
172 "Error in context saving: %d (%s)", errno, strerror(errno));
173 res->uc.uc_link = NULL;
174 /* res->uc.uc_link = &(current_context->uc); */
175 /* WARNING : when this context is over, the current_context (i.e. the
176 father), is awaken... Theorically, the wrapper should prevent using
178 res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack, STACK_SIZE);
179 res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack, STACK_SIZE);
181 res->exception = xbt_new(ex_ctx_t, 1);
182 XBT_CTX_INITIALIZE(res->exception);
183 #endif /* CONTEXT_THREADS or not */
185 res->iwannadie = 0; /* useless but makes valgrind happy */
189 res->startup_func = startup_func;
190 res->startup_arg = startup_arg;
191 res->cleanup_func = cleanup_func;
192 res->cleanup_arg = cleanup_arg;
194 xbt_swag_insert(res, context_living);
199 /* Scenario for the end of a context:
201 * CASE 1: death after end of function
202 * __context_wrapper, called by os thread, calls xbt_context_stop after user code stops
203 * xbt_context_stop calls user cleanup_func if any (in context settings),
204 * add current to trashbin
205 * yields back to maestro (destroy os thread on need)
206 * From time to time, maestro calls xbt_context_empty_trash,
207 * which maps xbt_context_free on the content
208 * xbt_context_free frees some more memory,
211 * CASE 2: brutal death
212 * xbt_context_kill (from any context)
213 * set context->wannadie to 1
214 * yields to the context
215 * the context is awaken in the middle of __yield.
216 * At the end of it, it checks that wannadie == 1, and call xbt_context_stop
217 * (same than first case afterward)
221 /* Argument must be stopped first -- runs in maestro context */
222 static void xbt_context_free(xbt_context_t context)
229 DEBUG1("Freeing %p", context);
232 DEBUG0("Freeing arguments");
234 for (i = 0; i < context->argc; i++)
235 if (context->argv[i])
236 free(context->argv[i]);
241 #ifdef CONTEXT_THREADS
242 DEBUG1("\t joining %p", (void *) context->thread);
244 xbt_os_thread_join(context->thread, NULL);
246 /* destroy the semaphore used to schedule/unshedule the process */
247 xbt_os_sem_destroy(context->begin);
248 xbt_os_sem_destroy(context->end);
250 context->thread = NULL;
251 context->begin = 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 /* signal its starting to the maestro and wait to start its job*/
280 if (context->startup_func)
281 context->startup_func(context->startup_arg);
283 DEBUG0("Calling the main function");
285 xbt_context_stop((context->code) (context->argc, context->argv));
289 * \param context the context to start
291 * Calling this function prepares \a context to be run. It will
292 however run effectively only when calling #xbt_context_schedule
294 void xbt_context_start(xbt_context_t context)
296 #ifdef CONTEXT_THREADS
297 /* create the process and start it */
298 context->thread = xbt_os_thread_create(context->name,__context_wrapper, context);
300 /* wait the starting of the newly created process */
301 xbt_os_sem_acquire(context->end);
303 makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1, context);
307 /* Stops current context: calls user's cleanup function, kills os thread, and yields back to maestro */
308 static void xbt_context_stop(int retvalue)
310 DEBUG1("--------- %p is exiting ---------", current_context);
312 if (current_context->cleanup_func) {
313 DEBUG0("Calling cleanup function");
314 current_context->cleanup_func(current_context->cleanup_arg);
317 DEBUG0("Putting context in the to_destroy set");
318 xbt_swag_remove(current_context, context_living);
319 xbt_swag_insert(current_context, context_to_destroy);
323 #ifdef CONTEXT_THREADS
324 /* signal to the maestro that it has finished */
325 xbt_os_sem_release(current_context->end);
327 xbt_os_thread_exit(NULL); /* We should provide return value in case other wants it */
329 __xbt_context_yield(current_context);
336 /** Garbage collection
338 * Should be called some time to time to free the memory allocated for contexts
339 * that have finished executing their main functions.
341 void xbt_context_empty_trash(void)
343 xbt_context_t context = NULL;
345 DEBUG1("Emptying trashbin (%d contexts to free)",
346 xbt_swag_size(context_to_destroy));
348 while ((context = xbt_swag_extract(context_to_destroy)))
349 xbt_context_free(context);
352 /*********************/
353 /* context switching */
354 /*********************/
356 static void __xbt_context_yield(xbt_context_t context)
358 xbt_assert0(current_context, "You have to call context_init() first.");
359 xbt_assert0(context, "Invalid argument");
361 if (current_context == context) {
363 ("--------- current_context (%p) is yielding back to maestro ---------",
367 ("--------- current_context (%p) is yielding to context(%p) ---------",
368 current_context, context);
371 #ifdef CONTEXT_THREADS
373 if(current_context != init_context && !context->iwannadie)
374 {/* it's a process and it doesn't wants to die (xbt_context_yield()) */
376 /* save the current context */
377 xbt_context_t self = current_context;
379 /* update the current context to this context */
380 current_context = context;
385 /* restore the current context to the previously saved context */
386 current_context = self;
389 { /* maestro wants to schedule a process or a process wants to die (xbt_context_schedule() or xbt_context_kill())*/
391 /* save the current context */
392 xbt_context_t self = current_context;
394 /* update the current context */
395 current_context = context;
397 /* schedule the process associated with this context */
400 /* restore the current context to the previously saved context */
401 current_context = self;
404 #else /* use SUSv2 contexts */
405 VOIRP(current_context);
406 VOIRP(current_context->save);
409 VOIRP(context->save);
411 int return_value = 0;
413 if (context->save == NULL) {
414 DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
415 DEBUG2("Saving current_context value (%p) to context(%p)->save",
416 current_context, context);
417 context->save = current_context;
418 DEBUG1("current_context becomes context(%p) ", context);
419 current_context = context;
421 ("Current position memorized (context->save). Jumping to context (%p)",
423 return_value = swapcontext(&(context->save->uc), &(context->uc));
424 xbt_assert0((return_value == 0), "Context swapping failure");
425 DEBUG1("I am (%p). Coming back\n", context);
427 xbt_context_t old_context = context->save;
429 DEBUG1("[%p] **** Back ! ****", context);
430 DEBUG2("Setting current_context (%p) to context(%p)->save",
431 current_context, context);
432 current_context = context->save;
433 DEBUG1("Setting context(%p)->save to NULL", context);
434 context->save = NULL;
435 DEBUG2("Current position memorized (%p). Jumping to context (%p)",
436 context, old_context);
437 return_value = swapcontext(&(context->uc), &(old_context->uc));
438 xbt_assert0((return_value == 0), "Context swapping failure");
439 DEBUG1("I am (%p). Coming back\n", context);
443 if (current_context->iwannadie)
448 * Calling this function makes the current context yield. The context
449 * that scheduled it returns from xbt_context_schedule as if nothing
452 * Only the processes can call this function, giving back the control
455 void xbt_context_yield(void)
457 __xbt_context_yield(current_context);
461 * \param context the winner
463 * Calling this function blocks the current context and schedule \a context.
464 * When \a context will call xbt_context_yield, it will return
465 * to this function as if nothing had happened.
467 * Only the maestro can call this function to run a given process.
469 void xbt_context_schedule(xbt_context_t context)
471 DEBUG1("Scheduling %p", context);
472 xbt_assert0((current_context == init_context),
473 "You are not supposed to run this function here!");
474 __xbt_context_yield(context);
479 * \param context poor victim
481 * This function simply kills \a context... scarry isn't it ?
483 void xbt_context_kill(xbt_context_t context)
485 DEBUG1("Killing %p", context);
487 context->iwannadie = 1;
489 DEBUG1("Scheduling %p", context);
490 __xbt_context_yield(context);
491 DEBUG1("End of Scheduling %p", context);
494 /* Java cruft I'm gonna kill in the next cleanup round */
495 void xbt_context_set_jprocess(xbt_context_t context, void *jp){}
496 void* xbt_context_get_jprocess(xbt_context_t context){return NULL;}
497 void xbt_context_set_jenv(xbt_context_t context,void* je){}
498 void* xbt_context_get_jenv(xbt_context_t context){return NULL;}