Logo AND Algorithmique Numérique Distribuée

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