Logo AND Algorithmique Numérique Distribuée

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