Logo AND Algorithmique Numérique Distribuée

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