Logo AND Algorithmique Numérique Distribuée

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