Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
take care of new dll import and dll export in Windows
[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         
104 #ifdef USE_WIN_CONTEXT          
105   if(context->uc.uc_stack.ss_sp)
106     free (context->uc.uc_stack.ss_sp);
107 #endif
108         
109   free(context);
110   return;
111 }
112
113 static void __context_exit(xbt_context_t context ,int value)
114 {
115   int i;
116   DEBUG0("Freeing arguments");
117   for(i=0;i<context->argc; i++) 
118     if(context->argv[i]) free(context->argv[i]);
119   if(context->argv) free(context->argv);
120
121   if(context->cleanup_func) {
122     DEBUG0("Calling cleanup function");
123     context->cleanup_func(context->cleanup_arg);
124   }
125
126   DEBUG0("Putting context in the to_destroy set");
127   xbt_swag_remove(context, context_living);
128   xbt_swag_insert(context, context_to_destroy);
129   DEBUG0("Context put in the to_destroy set");
130
131   DEBUG0("Yielding");
132 #ifdef USE_PTHREADS
133   DEBUG0("**** Locking ****");
134   pthread_mutex_lock(&(context->mutex));
135   DEBUG0("**** Updating current_context ****");
136   current_context = context;
137   DEBUG0("**** Releasing the prisonner ****");
138   pthread_cond_signal(&(context->cond));  
139   DEBUG0("**** Unlocking ****");
140   pthread_mutex_unlock(&(context->mutex));
141   DEBUG0("**** Exiting ****");
142   pthread_exit(0);
143 #else
144   __xbt_context_yield(context);
145 #endif
146   xbt_assert0(0,"You can't be here!");
147 }
148
149 static void *__context_wrapper(void *c)
150 {
151   xbt_context_t context = c;
152
153 #ifdef USE_PTHREADS
154   DEBUG2("**[%p:%p]** Lock ****",context,(void*)pthread_self());
155   pthread_mutex_lock(&(context->mutex));
156   DEBUG2("**[%p:%p]** Releasing the prisonner ****",context,(void*)pthread_self());
157   pthread_cond_signal(&(context->cond));
158   DEBUG2("**[%p:%p]** Going to Jail ****",context,(void*)pthread_self());
159   pthread_cond_wait(&(context->cond), &(context->mutex));
160   DEBUG2("**[%p:%p]** Unlocking ****",context,(void*)pthread_self());
161   pthread_mutex_unlock(&(context->mutex));
162 #endif
163
164   if(context->startup_func)
165     context->startup_func(context->startup_arg);
166
167   DEBUG0("Calling the main function");
168
169   __context_exit(context, (context->code) (context->argc,context->argv));
170   return NULL;
171 }
172
173 /* callback: context fetching */
174 static ex_ctx_t *__context_ex_ctx(void)
175 {
176   return current_context->exception;
177 }
178
179 /* callback: termination */
180 static void __context_ex_terminate(xbt_ex_t *e) {
181   xbt_ex_display(e);
182
183   abort();
184    /* FIXME: there should be a configuration variable to choose this
185   if(current_context!=init_context) 
186     __context_exit(current_context, e->value);
187   else
188     abort();
189     */
190 }
191
192 /** \name Functions 
193  *  \ingroup XBT_context
194  */
195 /* @{ */
196 /** Context module initialization
197  *
198  * \warning It has to be called before using any other function of this module.
199  */
200 void xbt_context_init(void)
201 {
202   if(!current_context) {
203     current_context = init_context = xbt_new0(s_xbt_context_t,1);
204     init_context->exception = xbt_new(ex_ctx_t,1);
205     XBT_CTX_INITIALIZE(init_context->exception);
206     __xbt_ex_ctx       = __context_ex_ctx;
207     __xbt_ex_terminate = __context_ex_terminate;
208     context_to_destroy = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
209     context_living = xbt_swag_new(xbt_swag_offset(*current_context,hookup));
210     xbt_swag_insert(init_context, context_living);
211   }
212 }
213
214 /** Garbage collection
215  *
216  * Should be called some time to time to free the memory allocated for contexts
217  * that have finished executing their main functions.
218  */
219 void xbt_context_empty_trash(void)
220 {
221   xbt_context_t context=NULL;
222
223   while((context=xbt_swag_extract(context_to_destroy)))
224     xbt_context_destroy(context);
225 }
226
227 /** 
228  * \param context the context to start
229  * 
230  * Calling this function prepares \a context to be run. It will 
231    however run effectively only when calling #xbt_context_schedule
232  */
233 void xbt_context_start(xbt_context_t context) 
234 {
235 #ifdef USE_PTHREADS
236   /* Launch the thread */
237   DEBUG1("**[%p]** Locking ****",context);
238   pthread_mutex_lock(&(context->mutex));
239   DEBUG1("**[%p]** Pthread create ****",context);
240   xbt_assert0(!pthread_create(context->thread, NULL, __context_wrapper, context),
241               "Unable to create a thread.");
242   DEBUG2("**[%p]** Pthread created : %p ****",context,(void*)(*(context->thread)));
243   DEBUG1("**[%p]** Going to jail ****",context);
244   pthread_cond_wait(&(context->cond), &(context->mutex));
245   DEBUG1("**[%p]** Unlocking ****",context);
246   pthread_mutex_unlock(&(context->mutex));  
247 #else
248   makecontext (&(context->uc), (void (*) (void)) __context_wrapper,
249                1, context);
250 #endif
251   return;
252 }
253
254 /** 
255  * \param code a main function
256  * \param startup_func a function to call when running the context for
257  *      the first time and just before the main function \a code
258  * \param startup_arg the argument passed to the previous function (\a startup_func)
259  * \param cleanup_func a function to call when running the context, just after 
260         the termination of the main function \a code
261  * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
262  * \param argc first argument of function \a code
263  * \param argv seconde argument of function \a code
264  */
265 xbt_context_t xbt_context_new(xbt_context_function_t code, 
266                               void_f_pvoid_t startup_func, void *startup_arg,
267                               void_f_pvoid_t cleanup_func, void *cleanup_arg,
268                               int argc, char *argv[])
269 {
270   xbt_context_t res = NULL;
271
272   res = xbt_new0(s_xbt_context_t,1);
273
274   res->code = code;
275 #ifdef USE_PTHREADS
276   res->thread = xbt_new0(pthread_t,1);
277   xbt_assert0(!pthread_mutex_init(&(res->mutex), NULL), "Mutex initialization error");
278   xbt_assert0(!pthread_cond_init(&(res->cond), NULL), "Condition initialization error");
279 #else 
280   /* FIXME: strerror is not thread safe */
281   xbt_assert2(getcontext(&(res->uc))==0,"Error in context saving: %d (%s)", errno, strerror(errno));
282   res->uc.uc_link = NULL;
283   /*   res->uc.uc_link = &(current_context->uc); */
284   /* WARNING : when this context is over, the current_context (i.e. the 
285      father), is awaken... Theorically, the wrapper should prevent using 
286      this feature. */
287 # ifdef USE_WIN_CONTEXT    
288   res->uc.uc_stack.ss_sp = xbt_malloc(STACK_SIZE);
289   res->uc.uc_stack.ss_size = STACK_SIZE ;
290 #else
291   res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack,STACK_SIZE);
292   res->uc.uc_stack.ss_size = pth_sksize_makecontext(res->stack,STACK_SIZE);
293 # endif /* USE_WIN_CONTEXT */
294 #endif /* USE_PTHREADS or not */
295   res->argc = argc;
296   res->argv = argv;
297   res->startup_func = startup_func;
298   res->startup_arg = startup_arg;
299   res->cleanup_func = cleanup_func;
300   res->cleanup_arg = cleanup_arg;
301   res->exception = xbt_new(ex_ctx_t,1);
302   XBT_CTX_INITIALIZE(res->exception);
303
304   xbt_swag_insert(res, context_living);
305
306   return res;
307 }
308
309 /** 
310  * Calling this function makes the current context yield. The context
311  * that scheduled it returns from xbt_context_schedule as if nothing
312  * had happened.
313  */
314 void xbt_context_yield(void)
315 {
316   __xbt_context_yield(current_context);
317 }
318
319 /** 
320  * \param context the winner
321  *
322  * Calling this function blocks the current context and schedule \a context.  
323  * When \a context will call xbt_context_yield, it will return
324  * to this function as if nothing had happened.
325  */
326 void xbt_context_schedule(xbt_context_t context)
327 {
328   DEBUG1("Scheduling %p",context);
329   xbt_assert0((current_context==init_context),
330               "You are not supposed to run this function here!");
331   __xbt_context_yield(context);
332 }
333
334 /** 
335  * This function kill all existing context and free all the memory
336  * that has been allocated in this module.
337  */
338 void xbt_context_exit(void) {
339   xbt_context_t context=NULL;
340
341   xbt_context_empty_trash();
342   xbt_swag_free(context_to_destroy);
343
344   while((context=xbt_swag_extract(context_living)))
345     xbt_context_free(context);
346
347   xbt_swag_free(context_living);
348
349   init_context = current_context = NULL ;
350 }
351
352 /** 
353  * \param context poor victim
354  *
355  * This function simply kills \a context... scarry isn't it ?
356  */
357 void xbt_context_free(xbt_context_t context)
358 {
359   int i ;
360
361   xbt_swag_remove(context, context_living);  
362   for(i=0;i<context->argc; i++) 
363     if(context->argv[i]) free(context->argv[i]);
364   if(context->argv) free(context->argv);
365   
366   if(context->cleanup_func)
367     context->cleanup_func(context->cleanup_arg);
368   xbt_context_destroy(context);
369
370   return;
371 }
372 /* @} */