Logo AND Algorithmique Numérique Distribuée

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