Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
kill the portable header
[simgrid.git] / src / xbt / xbt_os_thread.c
1 /* xbt_os_thread -- portability layer over the pthread API                  */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD     */
3 /* in SG, when using HAVE_UCONTEXT_CONTEXTS, xbt_os_thread_stub is used instead   */
4
5 /* Copyright (c) 2007-2015. The SimGrid Team.
6  * All rights reserved.                                                     */
7
8 /* This program is free software; you can redistribute it and/or modify it
9  * under the terms of the license (GNU LGPL) which comes with this package. */
10
11 #include "src/internal_config.h"
12 #if HAVE_PTHREAD_SETAFFINITY
13 #define _GNU_SOURCE
14 #include <sched.h>
15 #endif
16
17 #include <pthread.h>
18
19 #if defined(__FreeBSD__)
20 #include "pthread_np.h"
21 #define cpu_set_t cpuset_t
22 #endif
23
24 #include <limits.h>
25 #include <semaphore.h>
26 #include <errno.h>
27
28 #if defined(_WIN32)
29 #include <windows.h>
30 #elif defined(__MACH__) && defined(__APPLE__)
31 #include <stdint.h>
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
34 #else
35 #include <unistd.h>
36 #endif
37
38 #include "xbt/sysdep.h"
39 #include "xbt/ex.h"
40 #include "src/xbt/ex_interface.h"  /* We play crude games with exceptions */
41 #include "src/internal_config.h"
42 #include "xbt/xbt_os_time.h"       /* Portable time facilities */
43 #include "xbt/xbt_os_thread.h"     /* This module */
44 #include "src/xbt_modinter.h"      /* Initialization/finalization of this module */
45
46 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
47
48
49 /* use named sempahore when sem_init() does not work */
50 #if !HAVE_SEM_INIT
51 static int next_sem_ID = 0;
52 static xbt_os_mutex_t next_sem_ID_lock;
53 #endif
54
55 typedef struct xbt_os_thread_ {
56   pthread_t t;
57   int detached;
58   char *name;
59   void *param;
60   pvoid_f_pvoid_t start_routine;
61   xbt_running_ctx_t *running_ctx;
62   void *extra_data;
63 } s_xbt_os_thread_t;
64 static xbt_os_thread_t main_thread = NULL;
65
66 /* thread-specific data containing the xbt_os_thread_t structure */
67 static pthread_key_t xbt_self_thread_key;
68 static int thread_mod_inited = 0;
69
70 /* defaults attribute for pthreads */
71 //FIXME: find where to put this
72 static pthread_attr_t thread_attr;
73
74 /* frees the xbt_os_thread_t corresponding to the current thread */
75 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
76 {
77   if (thread == main_thread)    /* just killed main thread */
78     main_thread = NULL;
79
80   free(thread->running_ctx);
81   free(thread->name);
82   free(thread);
83 }
84
85 /* callback: context fetching */
86 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
87 {
88   return xbt_os_thread_self()->running_ctx;
89 }
90
91 /* callback: termination */
92 static void _os_thread_ex_terminate(xbt_ex_t * e)
93 {
94   xbt_ex_display(e);
95   xbt_abort();
96   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
97 }
98
99 void xbt_os_thread_mod_preinit(void)
100 {
101   if (thread_mod_inited)
102     return;
103
104   int errcode = pthread_key_create(&xbt_self_thread_key, NULL);
105   xbt_assert(errcode == 0, "pthread_key_create failed for xbt_self_thread_key");
106   
107   main_thread = xbt_new(s_xbt_os_thread_t, 1);
108   main_thread->name = NULL;
109   main_thread->detached = 0;
110   main_thread->name = (char *) "main";
111   main_thread->param = NULL;
112   main_thread->start_routine = NULL;
113   main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
114   main_thread->extra_data = NULL;
115   XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
116
117   if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
118     THROWF(system_error, errcode,
119            "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
120   
121   __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
122   __xbt_ex_terminate = _os_thread_ex_terminate;
123
124   pthread_attr_init(&thread_attr);
125
126   thread_mod_inited = 1;
127
128 #if !HAVE_SEM_INIT
129   next_sem_ID_lock = xbt_os_mutex_init();
130 #endif
131 }
132
133 void xbt_os_thread_mod_postexit(void)
134 {
135   /* FIXME: don't try to free our key on shutdown.
136      Valgrind detects no leak if we don't, and whine if we try to */
137   //   int errcode;
138
139   //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
140   //     THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
141   free(main_thread->running_ctx);
142   free(main_thread);
143   main_thread = NULL;
144   thread_mod_inited = 0;
145 #if !HAVE_SEM_INIT
146   xbt_os_mutex_destroy(next_sem_ID_lock);
147 #endif
148
149   /* Restore the default exception setup */
150   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
151   __xbt_ex_terminate = &__xbt_ex_terminate_default;
152 }
153
154 /** Calls pthread_atfork() if present, and raise an exception otherwise.
155  *
156  * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
157  * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
158  * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
159  */
160
161 /* this function is critical to tesh+mmalloc, don't mess with it */
162 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
163 {
164   return pthread_atfork(prepare, parent, child);
165 }
166
167 static void *wrapper_start_routine(void *s)
168 {
169   xbt_os_thread_t t = s;
170
171   int errcode = pthread_setspecific(xbt_self_thread_key, t);
172   xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
173
174   void *res = t->start_routine(t->param);
175   if (t->detached)
176     xbt_os_thread_free_thread_data(t);
177   return res;
178 }
179
180
181 xbt_os_thread_t xbt_os_thread_create(const char *name,  pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
182 {
183   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
184   res_thread->detached = 0;
185   res_thread->name = xbt_strdup(name);
186   res_thread->start_routine = start_routine;
187   res_thread->param = param;
188   res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
189   XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
190   res_thread->extra_data = extra_data;
191   
192   int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
193   xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
194
195   return res_thread;
196 }
197
198 /** Bind the thread to the given core, if possible.
199  *
200  * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
201  */
202 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
203   int errcode = 0;
204 #if HAVE_PTHREAD_SETAFFINITY
205   pthread_t pthread = thread->t;
206   cpu_set_t cpuset;
207   CPU_ZERO(&cpuset);
208   CPU_SET(cpu, &cpuset);
209   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
210 #endif
211   return errcode;
212 }
213
214 void xbt_os_thread_setstacksize(int stack_size)
215 {
216   size_t alignment[] = {
217     xbt_pagesize,
218 #ifdef PTHREAD_STACK_MIN
219     PTHREAD_STACK_MIN,
220 #endif
221     0
222   };
223
224   xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
225
226   size_t sz = stack_size;
227   int res = pthread_attr_setstacksize(&thread_attr, sz);
228
229   for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
230     /* Invalid size, try again with next multiple of alignment[i]. */
231     size_t rem = sz % alignment[i];
232     if (rem != 0 || sz == 0) {
233       size_t sz2 = sz - rem + alignment[i];
234       XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd", sz, sz2);
235       sz = sz2;
236       res = pthread_attr_setstacksize(&thread_attr, sz);
237     }
238   }
239
240   if (res == EINVAL)
241     XBT_WARN("invalid stack size (maybe too big): %zd", sz);
242   else if (res != 0)
243     XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
244 }
245
246 void xbt_os_thread_setguardsize(int guard_size)
247 {
248 #ifdef WIN32
249   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
250 #else
251   size_t sz = guard_size;
252   int res = pthread_attr_setguardsize(&thread_attr, sz);
253   if (res)
254     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
255 #endif
256 }
257
258 const char *xbt_os_thread_self_name(void)
259 {
260   xbt_os_thread_t me = xbt_os_thread_self();
261   return me ? me->name : "main";
262 }
263
264 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
265 {
266   int errcode = pthread_join(thread->t, thread_return);
267
268   xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
269   xbt_os_thread_free_thread_data(thread);
270 }
271
272 void xbt_os_thread_exit(int *retval)
273 {
274   pthread_exit(retval);
275 }
276
277 xbt_os_thread_t xbt_os_thread_self(void)
278 {
279   if (!thread_mod_inited)
280     return NULL;
281
282   return pthread_getspecific(xbt_self_thread_key);
283 }
284
285 void xbt_os_thread_key_create(xbt_os_thread_key_t* key)
286 {
287   int errcode = pthread_key_create(key, NULL);
288   xbt_assert(errcode==0 , "pthread_key_create failed");
289 }
290
291 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
292
293   int errcode = pthread_setspecific(key, value);
294   xbt_assert(errcode==0, "pthread_setspecific failed");
295 }
296
297 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
298   return pthread_getspecific(key);
299 }
300
301 void xbt_os_thread_detach(xbt_os_thread_t thread)
302 {
303   thread->detached = 1;
304   pthread_detach(thread->t);
305 }
306
307 #include <sched.h>
308 void xbt_os_thread_yield(void)
309 {
310   sched_yield();
311 }
312
313 void xbt_os_thread_cancel(xbt_os_thread_t t)
314 {
315   pthread_cancel(t->t);
316 }
317
318 /****** mutex related functions ******/
319 typedef struct xbt_os_mutex_ {
320   pthread_mutex_t m;
321 } s_xbt_os_mutex_t;
322
323 #include <time.h>
324 #include <math.h>
325
326 xbt_os_mutex_t xbt_os_mutex_init(void)
327 {
328   pthread_mutexattr_t Attr;
329   pthread_mutexattr_init(&Attr);
330   pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
331
332   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
333   int errcode = pthread_mutex_init(&(res->m), &Attr);
334   xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
335
336   return res;
337 }
338
339 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
340 {
341   int errcode = pthread_mutex_lock(&(mutex->m));
342   xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
343 }
344
345 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
346 {
347   int errcode = pthread_mutex_unlock(&(mutex->m));
348   xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
349 }
350
351 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
352 {
353   if (!mutex)
354     return;
355
356   int errcode = pthread_mutex_destroy(&(mutex->m));
357   xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
358   free(mutex);
359 }
360
361 /***** condition related functions *****/
362 typedef struct xbt_os_cond_ {
363   pthread_cond_t c;
364 } s_xbt_os_cond_t;
365
366 xbt_os_cond_t xbt_os_cond_init(void)
367 {
368   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
369   int errcode = pthread_cond_init(&(res->c), NULL);
370   xbt_assert(errcode==0, "pthread_cond_init() failed: %s", strerror(errcode));
371   return res;
372 }
373
374 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
375 {
376   int errcode = pthread_cond_wait(&(cond->c), &(mutex->m));
377   xbt_assert(errcode==0, "pthread_cond_wait(%p,%p) failed: %s", cond, mutex, strerror(errcode));
378 }
379
380 void xbt_os_cond_signal(xbt_os_cond_t cond)
381 {
382   int errcode = pthread_cond_signal(&(cond->c));
383   xbt_assert(errcode==0, "pthread_cond_signal(%p) failed: %s", cond, strerror(errcode));
384 }
385
386 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
387 {
388   int errcode = pthread_cond_broadcast(&(cond->c));
389   xbt_assert(errcode==0, "pthread_cond_broadcast(%p) failed: %s", cond, strerror(errcode));
390 }
391
392 void xbt_os_cond_destroy(xbt_os_cond_t cond)
393 {
394   if (!cond)
395     return;
396
397   int errcode = pthread_cond_destroy(&(cond->c));
398   xbt_assert(errcode==0, "pthread_cond_destroy(%p) failed: %s", cond, strerror(errcode));
399   free(cond);
400 }
401
402 typedef struct xbt_os_sem_ {
403 #if !HAVE_SEM_INIT
404   char *name;
405 #endif
406   sem_t s;
407   sem_t *ps;
408 } s_xbt_os_sem_t;
409
410 #ifndef SEM_FAILED
411 #define SEM_FAILED (-1)
412 #endif
413
414 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
415 {
416   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
417
418   /* On some systems (MAC OS X), only the stub of sem_init is to be found.
419    * Any attempt to use it leads to ENOSYS (function not implemented).
420    * If such a prehistoric system is detected, do the job with sem_open instead
421    */
422 #if HAVE_SEM_INIT
423   if (sem_init(&(res->s), 0, value) != 0)
424     THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
425   res->ps = &(res->s);
426
427 #else                           /* damn, no sem_init(). Reimplement it */
428
429   xbt_os_mutex_acquire(next_sem_ID_lock);
430   res->name = bprintf("/%d", ++next_sem_ID);
431   xbt_os_mutex_release(next_sem_ID_lock);
432
433   res->ps = sem_open(res->name, O_CREAT, 0644, value);
434   if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
435     /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
436     res->name[13] = '\0';
437     res->ps = sem_open(res->name, O_CREAT, 0644, value);
438   }
439   if (res->ps == (sem_t *) SEM_FAILED)
440     THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
441
442   /* Remove the name from the semaphore namespace: we never join on it */
443   if (sem_unlink(res->name) < 0)
444     THROWF(system_error, errno, "sem_unlink() failed: %s",
445            strerror(errno));
446
447 #endif
448
449   return res;
450 }
451
452 void xbt_os_sem_acquire(xbt_os_sem_t sem)
453 {
454   if (sem_wait(sem->ps) < 0)
455     THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
456 }
457
458 void xbt_os_sem_release(xbt_os_sem_t sem)
459 {
460   if (sem_post(sem->ps) < 0)
461     THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
462 }
463
464 void xbt_os_sem_destroy(xbt_os_sem_t sem)
465 {
466 #if HAVE_SEM_INIT
467   if (sem_destroy(sem->ps) < 0)
468     THROWF(system_error, errno, "sem_destroy() failed: %s",
469            strerror(errno));
470 #else
471   if (sem_close(sem->ps) < 0)
472     THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
473   xbt_free(sem->name);
474
475 #endif
476   xbt_free(sem);
477 }
478
479 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
480 {
481   if (sem_getvalue(&(sem->s), svalue) < 0)
482     THROWF(system_error, errno, "sem_getvalue() failed: %s",
483            strerror(errno));
484 }
485
486
487 /** @brief Returns the amount of cores on the current host */
488 int xbt_os_get_numcores(void) {
489 #ifdef WIN32
490     SYSTEM_INFO sysinfo;
491     GetSystemInfo(&sysinfo);
492     return sysinfo.dwNumberOfProcessors;
493 #elif defined(__APPLE__) && defined(__MACH__)
494     int nm[2];
495     size_t len = 4;
496     uint32_t count;
497
498     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
499     sysctl(nm, 2, &count, &len, NULL, 0);
500
501     if(count < 1) {
502         nm[1] = HW_NCPU;
503         sysctl(nm, 2, &count, &len, NULL, 0);
504         if(count < 1) { count = 1; }
505     }
506     return count;
507 #else
508     return sysconf(_SC_NPROCESSORS_ONLN);
509 #endif
510 }
511
512 void xbt_os_thread_set_extra_data(void *data)
513 {
514   xbt_os_thread_self()->extra_data = data;
515 }
516
517 void *xbt_os_thread_get_extra_data(void)
518 {
519   xbt_os_thread_t thread = xbt_os_thread_self();
520   return thread ? thread->extra_data : NULL;
521 }