Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c7320426949841bd0a8d47af8b2e32334efb2261
[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_thread.h"
17 /*#include <pthread.h>*/ /* I need pthread_join that is not yet available in xbt_thread.*/
18
19 #ifdef CONTEXT_THREADS
20  /* This file (context.c) is only loaded in libsimgrid, not libgras.
21   * xbt_thread is only loaded in libgras explicitly, and we need it in 
22   *    libsimgrid, but only when it is the backend used to implement the 
23   *    xbt_context. So, do load it on need.
24   */
25 #include "xbt/xbt_thread.c"
26 #endif
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ctx, xbt, "Context");
29
30 #define VOIRP(expr) DEBUG1("  {" #expr " = %p }", expr)
31
32 static xbt_context_t current_context = NULL;
33 static xbt_context_t init_context = NULL;
34 static xbt_swag_t context_to_destroy = NULL;
35 static xbt_swag_t context_living = NULL;
36 static xbt_mutex_t creation_mutex;
37 static xbt_thcond_t creation_cond;
38
39 static void __context_exit(xbt_context_t context ,int value);
40 static void __xbt_context_yield(xbt_context_t context)
41 {
42         xbt_assert0(current_context,"You have to call context_init() first.");
43
44         DEBUG2("--------- current_context (%p) is yielding to context(%p) ---------",current_context,context);
45    
46         #ifdef CONTEXT_THREADS
47         if (context){
48                 xbt_context_t self = current_context;
49                 DEBUG1("[%p] **** Locking ****", self);
50                 xbt_mutex_lock(context->mutex);
51                 DEBUG1("[%p] **** Updating current_context ****", self);
52                 current_context = context;
53                 DEBUG1("[%p] **** Releasing the prisonner ****", self);
54                 xbt_thcond_signal(context->cond);
55                 DEBUG1("[%p] **** Going to jail ****", self);
56                 xbt_thcond_wait(context->cond, context->mutex);
57                 DEBUG1("[%p] **** Unlocking ****", self);
58                 xbt_mutex_unlock(context->mutex);
59                 DEBUG1("[%p] **** Updating current_context ****", self);
60                 current_context = self;
61         }
62         #else /* use SUSv2 contexts */
63         if(current_context)
64                 VOIRP(current_context->save);
65         
66         VOIRP(context);
67         
68         if(context) 
69                 VOIRP(context->save);
70         
71         if (context){
72         
73                 int return_value = 0;
74                 
75                 if(context->save==NULL){
76                 
77                   DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
78                         DEBUG2("Saving current_context value (%p) to context(%p)->save",current_context,context);
79                         context->save = current_context ;
80                         DEBUG1("current_context becomes  context(%p) ",context);
81                         current_context = context ;
82                         DEBUG1("Current position memorized (context->save). Jumping to context (%p)",context);
83                         return_value = swapcontext (&(context->save->uc), &(context->uc));
84                         xbt_assert0((return_value==0),"Context swapping failure");
85                         DEBUG1("I am (%p). Coming back\n",context);
86                 } else {
87                         xbt_context_t old_context = context->save ;
88                         DEBUG1("[%p] **** Back ! ****", context);
89                         DEBUG2("Setting current_context (%p) to context(%p)->save",current_context,context);
90                         current_context = context->save ;
91                         DEBUG1("Setting context(%p)->save to NULL",context);
92                         context->save = NULL ;
93                         DEBUG2("Current position memorized (%p). Jumping to context (%p)",context,old_context);
94                         return_value = swapcontext (&(context->uc), &(old_context->uc));
95                         xbt_assert0((return_value==0),"Context swapping failure");
96                         DEBUG1("I am (%p). Coming back\n",context);
97                 
98                 }
99         }
100         #endif
101         if(current_context->iwannadie)
102           __context_exit(current_context, 1);
103
104         return;
105 }
106
107 static void xbt_context_free(xbt_context_t context)
108 {
109         if (!context) return;
110         DEBUG1("Freeing %p",context);
111 #ifdef CONTEXT_THREADS
112         /*DEBUG1("\t joining %p",(void *)context->thread->t);*/
113         DEBUG1("\t joining %p",(void *)context->thread);
114         /*pthread_join(context->thread->t,NULL);*/
115         xbt_thread_join(context->thread,NULL);
116         DEBUG1("\t xbt_free %p",(void *)context->thread);
117         xbt_free(context->thread);
118         DEBUG1("\t mutex_destroy %p",(void *)context->mutex);
119         xbt_mutex_destroy(context->mutex);
120         DEBUG1("\t cond_destroy %p",(void *)context->cond);
121         xbt_thcond_destroy(context->cond);
122
123         context->thread = NULL;
124         context->mutex = NULL;
125         context->cond = NULL;
126 #endif
127         
128         if(context->exception) 
129                 free(context->exception);
130                 
131         free(context);
132         return;
133 }
134         
135 static void __context_exit(xbt_context_t context ,int value)
136 {
137         int i;
138
139         DEBUG1("--------- %p is exiting ---------",context);
140
141         DEBUG0("Calling cleanup functions");
142         if(context->cleanup_func){
143                 DEBUG0("Calling cleanup function");
144                 context->cleanup_func(context->cleanup_arg);
145         }
146
147         DEBUG0("Freeing arguments");
148         for(i=0;i<context->argc; i++) 
149                 if(context->argv[i]) 
150                         free(context->argv[i]);
151         
152         if(context->argv) 
153                 free(context->argv);
154                 
155         DEBUG0("Putting context in the to_destroy set");
156         xbt_swag_remove(context, context_living);
157         xbt_swag_insert(context, context_to_destroy);
158         DEBUG0("Context put in the to_destroy set");
159
160         DEBUG0("Yielding");
161         
162         #ifdef CONTEXT_THREADS
163         DEBUG1("[%p] **** Locking ****", context);
164         xbt_mutex_lock(context->mutex);
165 /*      DEBUG1("[%p] **** Updating current_context ****"); */
166 /*      current_context = context; */
167         DEBUG1("[%p] **** Releasing the prisonner ****", context);
168         xbt_thcond_signal(context->cond);
169         DEBUG1("[%p] **** Unlocking ****", context);
170         xbt_mutex_unlock(context->mutex);
171         DEBUG1("[%p] **** Exiting ****", context);
172         xbt_thread_exit(NULL); // We should provide return value in case other wants it
173         #else
174         __xbt_context_yield(context);
175         #endif
176         xbt_assert0(0,"You can't be here!");
177 }
178
179 static void *
180 __context_wrapper(void* c) {
181         xbt_context_t context = (xbt_context_t)c;
182         
183         #ifdef CONTEXT_THREADS
184         context->thread = xbt_thread_self();
185         
186         DEBUG2("**[%p:%p]** Lock ****",context,(void*)xbt_thread_self());
187         xbt_mutex_lock(creation_mutex);
188         
189         DEBUG2("**[%p:%p]** Releasing the creator ****",context,(void*)xbt_thread_self());
190         xbt_thcond_signal(creation_cond);
191         xbt_mutex_unlock(creation_mutex);
192         
193         DEBUG2("**[%p:%p]** Going to Jail ****",context,(void*)xbt_thread_self());
194         xbt_mutex_lock(context->mutex);
195         xbt_thcond_wait(context->cond, context->mutex);
196         
197         DEBUG2("**[%p:%p]** Unlocking ****",context,(void*)xbt_thread_self());
198         xbt_mutex_unlock(context->mutex);
199         
200         #endif
201         
202         if(context->startup_func)
203                 context->startup_func(context->startup_arg);
204         
205         DEBUG0("Calling the main function");
206         
207         __context_exit(context, (context->code) (context->argc,context->argv));
208         return NULL;
209 }
210
211 /* callback: context fetching */
212 static ex_ctx_t *__context_ex_ctx(void)
213 {
214         return current_context->exception;
215 }
216
217 /* callback: termination */
218 static void __context_ex_terminate(xbt_ex_t *e) {
219   xbt_ex_display(e);
220
221   abort();
222    /* FIXME: there should be a configuration variable to choose this
223   if(current_context!=init_context) 
224     __context_exit(current_context, e->value);
225   else
226     abort();
227     */
228 }
229
230 /** \name Functions 
231  *  \ingroup XBT_context
232  */
233 /* @{ */
234 /** Context module initialization
235  *
236  * \warning It has to be called before using any other function of this module.
237  */
238 void xbt_context_init(void)
239 {
240         if(!current_context){
241                 current_context = init_context = xbt_new0(s_xbt_context_t,1);
242                 DEBUG1("Init Context (%p)",init_context);
243                 
244                 init_context->exception = xbt_new(ex_ctx_t,1);
245                 XBT_CTX_INITIALIZE(init_context->exception);
246                 __xbt_ex_ctx       = __context_ex_ctx;
247                 __xbt_ex_terminate = __context_ex_terminate;
248                 context_to_destroy = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
249                 context_living = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
250                 xbt_swag_insert(init_context, context_living);
251 #ifdef CONTEXT_THREADS     
252                 creation_mutex = xbt_mutex_init();
253                 creation_cond = xbt_thcond_init();
254 #endif     
255         }
256 }
257
258 /** Garbage collection
259  *
260  * Should be called some time to time to free the memory allocated for contexts
261  * that have finished executing their main functions.
262  */
263 void xbt_context_empty_trash(void)
264 {
265         xbt_context_t context=NULL;
266         DEBUG1("Emptying trashbin (%d contexts to free)",
267                xbt_swag_size(context_to_destroy));
268         while((context=xbt_swag_extract(context_to_destroy)))
269                 xbt_context_free(context);
270 }
271
272 /** 
273  * \param context the context to start
274  * 
275  * Calling this function prepares \a context to be run. It will 
276    however run effectively only when calling #xbt_context_schedule
277  */
278 void xbt_context_start(xbt_context_t context) 
279 {
280         #ifdef CONTEXT_THREADS
281         /* Launch the thread */
282         DEBUG1("**[%p]** Locking ****",context);
283         xbt_mutex_lock(creation_mutex);
284    
285         DEBUG1("**[%p]** Thread create ****",context);
286         context->thread = xbt_thread_create(__context_wrapper, context);   
287         DEBUG2("**[%p]** Thread created : %p ****",context,context->thread);
288    
289         DEBUG1("**[%p]** Going to jail ****",context);
290         xbt_thcond_wait(creation_cond, creation_mutex);
291         DEBUG1("**[%p]** Unlocking ****",context);
292         xbt_mutex_unlock(creation_mutex);
293         #else
294         makecontext (&(context->uc), (void (*) (void)) __context_wrapper,1, context);
295         #endif
296         return;
297 }
298
299 /** 
300  * \param code a main function
301  * \param startup_func a function to call when running the context for
302  *      the first time and just before the main function \a code
303  * \param startup_arg the argument passed to the previous function (\a startup_func)
304  * \param cleanup_func a function to call when running the context, just after 
305         the termination of the main function \a code
306  * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
307  * \param argc first argument of function \a code
308  * \param argv seconde argument of function \a code
309  */
310 xbt_context_t xbt_context_new(xbt_context_function_t code, 
311                               void_f_pvoid_t startup_func, void *startup_arg,
312                               void_f_pvoid_t cleanup_func, void *cleanup_arg,
313                               int argc, char *argv[])
314 {
315         xbt_context_t res = NULL;
316         
317         res = xbt_new0(s_xbt_context_t,1);
318         
319         res->code = code;
320         #ifdef CONTEXT_THREADS
321         res->mutex = xbt_mutex_init();
322         res->cond = xbt_thcond_init();
323         #else 
324
325         xbt_assert2(getcontext(&(res->uc))==0,"Error in context saving: %d (%s)", errno, strerror(errno));
326         res->uc.uc_link = NULL;
327         /*   res->uc.uc_link = &(current_context->uc); */
328         /* WARNING : when this context is over, the current_context (i.e. the 
329         father), is awaken... Theorically, the wrapper should prevent using 
330         this feature. */
331         res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack,STACK_SIZE);
332         res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack,STACK_SIZE);
333         #endif /* CONTEXT_THREADS or not */
334         
335         res->argc = argc;
336         res->argv = argv;
337         res->startup_func = startup_func;
338         res->startup_arg = startup_arg;
339         res->cleanup_func = cleanup_func;
340         res->cleanup_arg = cleanup_arg;
341         res->exception = xbt_new(ex_ctx_t,1);
342         XBT_CTX_INITIALIZE(res->exception);
343         
344         xbt_swag_insert(res, context_living);
345         
346         return res;
347 }
348
349 /** 
350  * Calling this function makes the current context yield. The context
351  * that scheduled it returns from xbt_context_schedule as if nothing
352  * had happened.
353  */
354 void xbt_context_yield(void)
355 {
356         __xbt_context_yield(current_context);
357 }
358
359 /** 
360  * \param context the winner
361  *
362  * Calling this function blocks the current context and schedule \a context.  
363  * When \a context will call xbt_context_yield, it will return
364  * to this function as if nothing had happened.
365  */
366 void xbt_context_schedule(xbt_context_t context)
367 {
368         DEBUG1("Scheduling %p",context);
369         xbt_assert0((current_context==init_context),"You are not supposed to run this function here!");
370         __xbt_context_yield(context);
371 }
372
373 /** 
374  * This function kill all existing context and free all the memory
375  * that has been allocated in this module.
376  */
377 void xbt_context_exit(void) {
378         xbt_context_t context=NULL;
379         
380         xbt_context_empty_trash();
381         while((context=xbt_swag_extract(context_living))) {
382           if(context!=init_context) {
383             xbt_context_kill(context);
384           }
385         }
386         //      xbt_context_kill(init_context);
387
388         xbt_context_empty_trash();
389         xbt_swag_free(context_to_destroy);
390         xbt_swag_free(context_living);
391         
392         init_context = current_context = NULL ;
393 #ifdef CONTEXT_THREADS     
394         xbt_mutex_destroy(creation_mutex);
395         xbt_thcond_destroy(creation_cond);
396 #endif   
397 }
398
399 /** 
400  * \param context poor victim
401  *
402  * This function simply kills \a context... scarry isn't it ?
403  */
404 void xbt_context_kill(xbt_context_t context)
405 {
406         DEBUG1("Killing %p", context);
407
408         context->iwannadie=1;
409         DEBUG1("Scheduling %p",context);
410         __xbt_context_yield(context);
411         DEBUG1("End of Scheduling %p",context);
412         
413         return;
414 }
415 /* @} */