Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Cosmetics on error messages
[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
28
29
30 /********************/
31 /* Module init/exit */
32 /********************/
33 #ifndef CONTEXT_THREADS
34 /* callback: context fetching (used only with ucontext, os_thread deal with it
35                                for us otherwise) */
36 static ex_ctx_t *_context_ex_ctx(void)
37 {
38   return current_context->exception;
39 }
40
41 /* callback: termination */
42 static void _context_ex_terminate(xbt_ex_t * e)
43 {
44   xbt_ex_display(e);
45
46   abort();
47   /* FIXME: there should be a configuration variable to 
48      choose to kill everyone or only this one */
49 }
50 #endif
51
52 #ifdef CONTEXT_THREADS
53
54 static void 
55 schedule(xbt_context_t c);
56
57 static void 
58 yield(xbt_context_t c);
59
60 static void 
61 schedule(xbt_context_t c) 
62 {
63         xbt_os_sem_release(c->begin);   
64         xbt_os_sem_acquire(c->end);     
65 }
66
67 static void yield(xbt_context_t c) 
68 {
69         xbt_os_sem_release(c->end);             
70         xbt_os_sem_acquire(c->begin);
71 }
72 #endif
73
74 /** \name Functions 
75  *  \ingroup XBT_context
76  */
77 /* @{ */
78 /** Context module initialization
79  *
80  * \warning It has to be called before using any other function of this module.
81  */
82 void xbt_context_init(void)
83 {
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 */
88     context_to_destroy =
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);
92     
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;
98 #endif
99   }
100 }
101
102 /** 
103  * This function kill all existing context and free all the memory
104  * that has been allocated in this module.
105  */
106 void xbt_context_exit(void)
107 {
108   xbt_context_t context = NULL;
109
110   xbt_context_empty_trash();
111
112   while ((context = xbt_swag_extract(context_living))) {
113     if (context != init_context) {
114       xbt_context_kill(context);
115     }
116   }
117
118 #ifndef CONTEXT_THREADS
119   free(init_context->exception);
120 #endif
121
122   free(init_context);
123   init_context = current_context = NULL;
124
125   xbt_context_empty_trash();
126   xbt_swag_free(context_to_destroy);
127   xbt_swag_free(context_living);
128
129 }
130
131
132 /*******************************/
133 /* Object creation/destruction */
134 /*******************************/
135 /** 
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
145  */
146 xbt_context_t
147 xbt_context_new(const char *name,
148                 xbt_main_func_t code,
149                 void_f_pvoid_t startup_func,
150                 void *startup_arg,
151                 void_f_pvoid_t cleanup_func,
152                 void *cleanup_arg, int argc, char *argv[]
153   )
154 {
155   xbt_context_t res = NULL;
156
157   res = xbt_new0(s_xbt_context_t, 1);
158
159   res->code = code;
160   res->name = xbt_strdup(name);
161
162 #ifdef CONTEXT_THREADS
163   /* 
164    * initialize the semaphores used to schedule/yield 
165    * the process associated to the newly created context 
166    */
167   res->begin = xbt_os_sem_init(0);
168   res->end = xbt_os_sem_init(0);
169 #else
170
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 
177      this feature. */
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);
180
181   res->exception = xbt_new(ex_ctx_t, 1);
182   XBT_CTX_INITIALIZE(res->exception);
183 #endif /* CONTEXT_THREADS or not */
184
185   res->iwannadie = 0;           /* useless but makes valgrind happy */
186
187   res->argc = argc;
188   res->argv = argv;
189   res->startup_func = startup_func;
190   res->startup_arg = startup_arg;
191   res->cleanup_func = cleanup_func;
192   res->cleanup_arg = cleanup_arg;
193
194   xbt_swag_insert(res, context_living);
195
196   return res;
197 }
198
199 /* Scenario for the end of a context:
200  * 
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, 
209  *                    joins os thread
210  * 
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)
218  */
219
220
221 /* Argument must be stopped first -- runs in maestro context */
222 static void xbt_context_free(xbt_context_t context)
223 {
224   int i;
225
226   if (!context)
227     return;
228
229   DEBUG1("Freeing %p", context);
230   free(context->name);
231
232   DEBUG0("Freeing arguments");
233
234   for (i = 0; i < context->argc; i++)
235     if (context->argv[i])
236       free(context->argv[i]);
237
238   if (context->argv)
239     free(context->argv);
240
241 #ifdef CONTEXT_THREADS
242   DEBUG1("\t joining %p", (void *) context->thread);
243
244   xbt_os_thread_join(context->thread, NULL);
245
246   /* destroy the semaphore used to schedule/unshedule the process */
247         xbt_os_sem_destroy(context->begin);
248         xbt_os_sem_destroy(context->end);
249
250   context->thread = NULL;
251   context->begin = NULL;
252   context->end = NULL;
253 #else
254   if (context->exception)
255     free(context->exception);
256 #endif
257
258   free(context);
259 }
260
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);
266
267 static void *__context_wrapper(void *c)
268 {
269   xbt_context_t context = current_context;
270
271 #ifdef CONTEXT_THREADS
272   context = (xbt_context_t) c;
273   /*context->thread = xbt_os_thread_self();*/
274
275   /* signal its starting to the maestro and wait to start its job*/
276   yield(context);
277
278 #endif
279
280   if (context->startup_func)
281     context->startup_func(context->startup_arg);
282
283   DEBUG0("Calling the main function");
284
285   xbt_context_stop((context->code) (context->argc, context->argv));
286   return NULL;
287 }
288 /** 
289  * \param context the context to start
290  * 
291  * Calling this function prepares \a context to be run. It will 
292    however run effectively only when calling #xbt_context_schedule
293  */
294 void xbt_context_start(xbt_context_t context)
295 {
296 #ifdef CONTEXT_THREADS
297   /* create the process and start it */
298   context->thread = xbt_os_thread_create(context->name,__context_wrapper, context);
299         
300   /* wait the starting of the newly created process */
301   xbt_os_sem_acquire(context->end);
302 #else
303   makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1, context);
304 #endif
305 }
306
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)
309 {
310   DEBUG1("--------- %p is exiting ---------", current_context);
311
312   if (current_context->cleanup_func) {
313     DEBUG0("Calling cleanup function");
314     current_context->cleanup_func(current_context->cleanup_arg);
315   }
316
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);
320
321   DEBUG0("Yielding");
322
323 #ifdef CONTEXT_THREADS
324   /* signal to the maestro that it has finished */
325         xbt_os_sem_release(current_context->end);
326         /* exit*/
327         xbt_os_thread_exit(NULL);       /* We should provide return value in case other wants it */
328 #else
329   __xbt_context_yield(current_context);
330 #endif
331   THROW_IMPOSSIBLE;
332 }
333
334
335
336 /** Garbage collection
337  *
338  * Should be called some time to time to free the memory allocated for contexts
339  * that have finished executing their main functions.
340  */
341 void xbt_context_empty_trash(void)
342 {
343   xbt_context_t context = NULL;
344
345   DEBUG1("Emptying trashbin (%d contexts to free)",
346          xbt_swag_size(context_to_destroy));
347
348   while ((context = xbt_swag_extract(context_to_destroy)))
349     xbt_context_free(context);
350 }
351
352 /*********************/
353 /* context switching */
354 /*********************/
355
356 static void __xbt_context_yield(xbt_context_t context)
357 {
358   xbt_assert0(current_context, "You have to call context_init() first.");
359   xbt_assert0(context, "Invalid argument");
360
361   if (current_context == context) {
362     DEBUG1
363       ("--------- current_context (%p) is yielding back to maestro ---------",
364        context);
365   } else {
366     DEBUG2
367       ("--------- current_context (%p) is yielding to context(%p) ---------",
368        current_context, context);
369   }
370
371 #ifdef CONTEXT_THREADS
372
373   if(current_context != init_context && !context->iwannadie)
374         {/* it's a process and it doesn't wants to die (xbt_context_yield()) */
375                 
376                 /* save the current context */
377                 xbt_context_t self = current_context;
378
379                 /* update the current context to this context */
380                 current_context = context;
381                 
382                 /* yield itself */
383                 yield(context);
384                 
385                 /* restore the current context to the previously saved context */
386                 current_context = self;
387         }
388         else
389         { /* maestro wants to schedule a process or a process wants to die (xbt_context_schedule() or xbt_context_kill())*/
390                 
391                 /* save the current context */
392                 xbt_context_t self = current_context;
393                 
394                 /* update the current context */
395                 current_context = context;
396
397                 /* schedule the process associated with this context */
398                 schedule(context);
399
400                 /* restore the current context to the previously saved context */
401                 current_context = self;
402         }
403
404 #else /* use SUSv2 contexts */
405   VOIRP(current_context);
406   VOIRP(current_context->save);
407
408   VOIRP(context);
409   VOIRP(context->save);
410
411   int return_value = 0;
412
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;
420     DEBUG1
421       ("Current position memorized (context->save). Jumping to context (%p)",
422        context);
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);
426   } else {
427     xbt_context_t old_context = context->save;
428
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);
440   }
441 #endif
442
443   if (current_context->iwannadie)
444     xbt_context_stop(1);
445 }
446
447 /** 
448  * Calling this function makes the current context yield. The context
449  * that scheduled it returns from xbt_context_schedule as if nothing
450  * had happened.
451  * 
452  * Only the processes can call this function, giving back the control
453  * to the maestro
454  */
455 void xbt_context_yield(void)
456 {
457   __xbt_context_yield(current_context);
458 }
459
460 /** 
461  * \param context the winner
462  *
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.
466  * 
467  * Only the maestro can call this function to run a given process.
468  */
469 void xbt_context_schedule(xbt_context_t context)
470 {
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);
475 }
476
477
478 /** 
479  * \param context poor victim
480  *
481  * This function simply kills \a context... scarry isn't it ?
482  */
483 void xbt_context_kill(xbt_context_t context)
484 {
485   DEBUG1("Killing %p", context);
486
487   context->iwannadie = 1;
488
489   DEBUG1("Scheduling %p", context);
490   __xbt_context_yield(context);
491   DEBUG1("End of Scheduling %p", context);
492 }
493
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;}
499
500 /* @} */