Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0cfcb36eff8d77a91defe09a6531e3adaf0b8b00
[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                 DEBUG1("[%p] **** Locking ****", self);
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                 DEBUG1("[%p] **** Going to jail ****", self);
58                 xbt_thcond_wait(context->cond, context->mutex);
59                 DEBUG1("[%p] **** Unlocking ****", self);
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         DEBUG1("[%p] **** Locking ****", context);
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         DEBUG1("[%p] **** Unlocking ****", context);
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         DEBUG2("**[%p:%p]** Lock ****",context,(void*)xbt_thread_self());
189         xbt_mutex_lock(creation_mutex);
190         xbt_mutex_lock(context->mutex);
191         
192         DEBUG2("**[%p:%p]** Releasing the creator ****",context,(void*)xbt_thread_self());
193         xbt_thcond_signal(creation_cond);
194         xbt_mutex_unlock(creation_mutex);
195         
196         DEBUG2("**[%p:%p]** Going to Jail ****",context,(void*)xbt_thread_self());
197         xbt_thcond_wait(context->cond, context->mutex);
198         
199         DEBUG2("**[%p:%p]** Unlocking ****",context,(void*)xbt_thread_self());
200         xbt_mutex_unlock(context->mutex);
201         
202         #endif
203         
204         if(context->startup_func)
205                 context->startup_func(context->startup_arg);
206         
207         DEBUG0("Calling the main function");
208         
209         __context_exit(context, (context->code) (context->argc,context->argv));
210         return NULL;
211 }
212
213 /* callback: context fetching */
214 static ex_ctx_t *__context_ex_ctx(void)
215 {
216         return current_context->exception;
217 }
218
219 /* callback: termination */
220 static void __context_ex_terminate(xbt_ex_t *e) {
221   xbt_ex_display(e);
222
223   abort();
224    /* FIXME: there should be a configuration variable to choose this
225   if(current_context!=init_context) 
226     __context_exit(current_context, e->value);
227   else
228     abort();
229     */
230 }
231
232 /** \name Functions 
233  *  \ingroup XBT_context
234  */
235 /* @{ */
236 /** Context module initialization
237  *
238  * \warning It has to be called before using any other function of this module.
239  */
240 void xbt_context_init(void)
241 {
242         if(!current_context){
243                 current_context = init_context = xbt_new0(s_xbt_context_t,1);
244                 DEBUG1("Init Context (%p)",init_context);
245                 
246                 init_context->exception = xbt_new(ex_ctx_t,1);
247                 XBT_CTX_INITIALIZE(init_context->exception);
248                 __xbt_ex_ctx       = __context_ex_ctx;
249                 __xbt_ex_terminate = __context_ex_terminate;
250                 context_to_destroy = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
251                 context_living = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
252                 xbt_swag_insert(init_context, context_living);
253 #ifdef CONTEXT_THREADS     
254                 creation_mutex = xbt_mutex_init();
255                 creation_cond = xbt_thcond_init();
256 #endif     
257         }
258 }
259
260 /** Garbage collection
261  *
262  * Should be called some time to time to free the memory allocated for contexts
263  * that have finished executing their main functions.
264  */
265 void xbt_context_empty_trash(void)
266 {
267         xbt_context_t context=NULL;
268         DEBUG1("Emptying trashbin (%d contexts to free)",
269                xbt_swag_size(context_to_destroy));
270         while((context=xbt_swag_extract(context_to_destroy)))
271                 xbt_context_free(context);
272 }
273
274 /** 
275  * \param context the context to start
276  * 
277  * Calling this function prepares \a context to be run. It will 
278    however run effectively only when calling #xbt_context_schedule
279  */
280 void xbt_context_start(xbt_context_t context) 
281 {
282         #ifdef CONTEXT_THREADS
283         /* Launch the thread */
284         DEBUG1("**[%p]** Locking ****",context);
285         xbt_mutex_lock(creation_mutex);
286    
287         DEBUG1("**[%p]** Thread create ****",context);
288         context->thread = xbt_thread_create(__context_wrapper, context);   
289         DEBUG2("**[%p]** Thread created : %p ****",context,context->thread);
290    
291         DEBUG1("**[%p]** Going to jail ****",context);
292         xbt_thcond_wait(creation_cond, creation_mutex);
293         DEBUG1("**[%p]** Unlocking ****",context);
294         xbt_mutex_unlock(creation_mutex);
295         #else
296         makecontext (&(context->uc), (void (*) (void)) __context_wrapper,1, context);
297         #endif
298         return;
299 }
300
301 /** 
302  * \param code a main function
303  * \param startup_func a function to call when running the context for
304  *      the first time and just before the main function \a code
305  * \param startup_arg the argument passed to the previous function (\a startup_func)
306  * \param cleanup_func a function to call when running the context, just after 
307         the termination of the main function \a code
308  * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
309  * \param argc first argument of function \a code
310  * \param argv seconde argument of function \a code
311  */
312 xbt_context_t xbt_context_new(xbt_context_function_t code, 
313                               void_f_pvoid_t startup_func, void *startup_arg,
314                               void_f_pvoid_t cleanup_func, void *cleanup_arg,
315                               int argc, char *argv[])
316 {
317         xbt_context_t res = NULL;
318         
319         res = xbt_new0(s_xbt_context_t,1);
320         
321         res->code = code;
322         #ifdef CONTEXT_THREADS
323         res->mutex = xbt_mutex_init();
324         res->cond = xbt_thcond_init();
325         #else 
326
327         xbt_assert2(getcontext(&(res->uc))==0,"Error in context saving: %d (%s)", errno, strerror(errno));
328         res->uc.uc_link = NULL;
329         /*   res->uc.uc_link = &(current_context->uc); */
330         /* WARNING : when this context is over, the current_context (i.e. the 
331         father), is awaken... Theorically, the wrapper should prevent using 
332         this feature. */
333         res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack,STACK_SIZE);
334         res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack,STACK_SIZE);
335         #endif /* CONTEXT_THREADS or not */
336         
337         res->argc = argc;
338         res->argv = argv;
339         res->startup_func = startup_func;
340         res->startup_arg = startup_arg;
341         res->cleanup_func = cleanup_func;
342         res->cleanup_arg = cleanup_arg;
343         res->exception = xbt_new(ex_ctx_t,1);
344         XBT_CTX_INITIALIZE(res->exception);
345         
346         xbt_swag_insert(res, context_living);
347         
348         return res;
349 }
350
351 /** 
352  * Calling this function makes the current context yield. The context
353  * that scheduled it returns from xbt_context_schedule as if nothing
354  * had happened.
355  */
356 void xbt_context_yield(void)
357 {
358         __xbt_context_yield(current_context);
359 }
360
361 /** 
362  * \param context the winner
363  *
364  * Calling this function blocks the current context and schedule \a context.  
365  * When \a context will call xbt_context_yield, it will return
366  * to this function as if nothing had happened.
367  */
368 void xbt_context_schedule(xbt_context_t context)
369 {
370         DEBUG1("Scheduling %p",context);
371         xbt_assert0((current_context==init_context),"You are not supposed to run this function here!");
372         __xbt_context_yield(context);
373 }
374
375 /** 
376  * This function kill all existing context and free all the memory
377  * that has been allocated in this module.
378  */
379 void xbt_context_exit(void) {
380         xbt_context_t context=NULL;
381         
382         xbt_context_empty_trash();
383         while((context=xbt_swag_extract(context_living))) {
384           if(context!=init_context) {
385             xbt_context_kill(context);
386           }
387         }
388         free(init_context->exception);   
389         free(init_context);   
390         init_context = current_context = NULL ;
391
392         xbt_context_empty_trash();
393         xbt_swag_free(context_to_destroy);
394         xbt_swag_free(context_living);
395         
396 #ifdef CONTEXT_THREADS     
397         xbt_mutex_destroy(creation_mutex);
398         xbt_thcond_destroy(creation_cond);
399 #endif   
400 }
401
402 /** 
403  * \param context poor victim
404  *
405  * This function simply kills \a context... scarry isn't it ?
406  */
407 void xbt_context_kill(xbt_context_t context)
408 {
409         DEBUG1("Killing %p", context);
410
411         context->iwannadie=1;
412         DEBUG1("Scheduling %p",context);
413         __xbt_context_yield(context);
414         DEBUG1("End of Scheduling %p",context);
415         
416         return;
417 }
418 /* @} */