Logo AND Algorithmique Numérique Distribuée

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