Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
7449725ce23f86c7b774d3afe8187e2d3759af27
[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 #ifdef 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 #elif defined(__MACH__) && defined(__APPLE__)
30 #include <stdint.h>
31 #include <sys/types.h>
32 #include <sys/sysctl.h>
33 #else
34 #include <unistd.h>
35 #endif
36
37 #include "xbt/sysdep.h"
38 #include "xbt/ex.h"
39 #include "src/xbt/ex_interface.h"  /* We play crude games with exceptions */
40 #include "src/portable.h"
41 #include "xbt/xbt_os_time.h"       /* Portable time facilities */
42 #include "xbt/xbt_os_thread.h"     /* This module */
43 #include "src/xbt_modinter.h"      /* Initialization/finalization of this module */
44
45 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
46
47
48 /* use named sempahore when sem_init() does not work */
49 #ifndef HAVE_SEM_INIT
50 static int next_sem_ID = 0;
51 static xbt_os_mutex_t next_sem_ID_lock;
52 #endif
53
54 typedef struct xbt_os_thread_ {
55   pthread_t t;
56   int detached;
57   char *name;
58   void *param;
59   pvoid_f_pvoid_t start_routine;
60   xbt_running_ctx_t *running_ctx;
61   void *extra_data;
62 } s_xbt_os_thread_t;
63 static xbt_os_thread_t main_thread = NULL;
64
65 /* thread-specific data containing the xbt_os_thread_t structure */
66 static pthread_key_t xbt_self_thread_key;
67 static int thread_mod_inited = 0;
68
69 /* defaults attribute for pthreads */
70 //FIXME: find where to put this
71 static pthread_attr_t thread_attr;
72
73 /* frees the xbt_os_thread_t corresponding to the current thread */
74 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
75 {
76   if (thread == main_thread)    /* just killed main thread */
77     main_thread = NULL;
78
79   free(thread->running_ctx);
80   free(thread->name);
81   free(thread);
82 }
83
84 /* callback: context fetching */
85 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
86 {
87   return xbt_os_thread_self()->running_ctx;
88 }
89
90 /* callback: termination */
91 static void _os_thread_ex_terminate(xbt_ex_t * e)
92 {
93   xbt_ex_display(e);
94   xbt_abort();
95   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
96 }
97
98 void xbt_os_thread_mod_preinit(void)
99 {
100   if (thread_mod_inited)
101     return;
102
103   int errcode = pthread_key_create(&xbt_self_thread_key, NULL);
104   xbt_assert(errcode == 0, "pthread_key_create failed for xbt_self_thread_key");
105   
106   main_thread = xbt_new(s_xbt_os_thread_t, 1);
107   main_thread->name = NULL;
108   main_thread->detached = 0;
109   main_thread->name = (char *) "main";
110   main_thread->param = NULL;
111   main_thread->start_routine = NULL;
112   main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
113   main_thread->extra_data = NULL;
114   XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
115
116   if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
117     THROWF(system_error, errcode,
118            "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
119   
120   __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
121   __xbt_ex_terminate = _os_thread_ex_terminate;
122
123   pthread_attr_init(&thread_attr);
124
125   thread_mod_inited = 1;
126
127 #ifndef HAVE_SEM_INIT
128   next_sem_ID_lock = xbt_os_mutex_init();
129 #endif
130 }
131
132 void xbt_os_thread_mod_postexit(void)
133 {
134   /* FIXME: don't try to free our key on shutdown.
135      Valgrind detects no leak if we don't, and whine if we try to */
136   //   int errcode;
137
138   //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
139   //     THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
140   free(main_thread->running_ctx);
141   free(main_thread);
142   main_thread = NULL;
143   thread_mod_inited = 0;
144 #ifndef HAVE_SEM_INIT
145   xbt_os_mutex_destroy(next_sem_ID_lock);
146 #endif
147
148   /* Restore the default exception setup */
149   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
150   __xbt_ex_terminate = &__xbt_ex_terminate_default;
151 }
152
153 /* this function is critical to tesh+mmalloc, don't mess with it */
154 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
155 {
156   return pthread_atfork(prepare, parent, child);
157 }
158
159 static void *wrapper_start_routine(void *s)
160 {
161   xbt_os_thread_t t = s;
162
163   int errcode = pthread_setspecific(xbt_self_thread_key, t);
164   xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
165
166   void *res = t->start_routine(t->param);
167   if (t->detached)
168     xbt_os_thread_free_thread_data(t);
169   return res;
170 }
171
172
173 xbt_os_thread_t xbt_os_thread_create(const char *name,  pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
174 {
175   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
176   res_thread->detached = 0;
177   res_thread->name = xbt_strdup(name);
178   res_thread->start_routine = start_routine;
179   res_thread->param = param;
180   res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
181   XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
182   res_thread->extra_data = extra_data;
183   
184   int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
185   xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
186
187   return res_thread;
188 }
189
190 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
191   int errcode = 0;
192 #ifdef HAVE_PTHREAD_SETAFFINITY
193   pthread_t pthread = thread->t;
194   cpu_set_t cpuset;
195   CPU_ZERO(&cpuset);
196   CPU_SET(cpu, &cpuset);
197   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
198 #endif
199   return errcode;
200 }
201
202 void xbt_os_thread_setstacksize(int stack_size)
203 {
204   size_t alignment[] = {
205     xbt_pagesize,
206 #ifdef PTHREAD_STACK_MIN
207     PTHREAD_STACK_MIN,
208 #endif
209     0
210   };
211
212   xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
213
214   size_t sz = stack_size;
215   int res = pthread_attr_setstacksize(&thread_attr, sz);
216
217   for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
218     /* Invalid size, try again with next multiple of alignment[i]. */
219     size_t rem = sz % alignment[i];
220     if (rem != 0 || sz == 0) {
221       size_t sz2 = sz - rem + alignment[i];
222       XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd", sz, sz2);
223       sz = sz2;
224       res = pthread_attr_setstacksize(&thread_attr, sz);
225     }
226   }
227
228   if (res == EINVAL)
229     XBT_WARN("invalid stack size (maybe too big): %zd", sz);
230   else if (res != 0)
231     XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
232 }
233
234 void xbt_os_thread_setguardsize(int guard_size)
235 {
236 #ifdef WIN32
237   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
238 #else
239   size_t sz = guard_size;
240   int res = pthread_attr_setguardsize(&thread_attr, sz);
241   if (res)
242     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
243 #endif
244 }
245
246 const char *xbt_os_thread_name(xbt_os_thread_t t)
247 {
248   return t->name;
249 }
250
251 const char *xbt_os_thread_self_name(void)
252 {
253   xbt_os_thread_t me = xbt_os_thread_self();
254   return me ? me->name : "main";
255 }
256
257 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
258 {
259   int errcode = pthread_join(thread->t, thread_return);
260
261   xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
262   xbt_os_thread_free_thread_data(thread);
263 }
264
265 void xbt_os_thread_exit(int *retval)
266 {
267   pthread_exit(retval);
268 }
269
270 xbt_os_thread_t xbt_os_thread_self(void)
271 {
272   if (!thread_mod_inited)
273     return NULL;
274
275   return pthread_getspecific(xbt_self_thread_key);
276 }
277
278 void xbt_os_thread_key_create(xbt_os_thread_key_t* key)
279 {
280   int errcode = pthread_key_create(key, NULL);
281   xbt_assert(errcode==0 , "pthread_key_create failed");
282 }
283
284 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
285
286   int errcode = pthread_setspecific(key, value);
287   xbt_assert(errcode==0, "pthread_setspecific failed");
288 }
289
290 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
291   return pthread_getspecific(key);
292 }
293
294 void xbt_os_thread_detach(xbt_os_thread_t thread)
295 {
296   thread->detached = 1;
297   pthread_detach(thread->t);
298 }
299
300 #include <sched.h>
301 void xbt_os_thread_yield(void)
302 {
303   sched_yield();
304 }
305
306 void xbt_os_thread_cancel(xbt_os_thread_t t)
307 {
308   pthread_cancel(t->t);
309 }
310
311 /****** mutex related functions ******/
312 typedef struct xbt_os_mutex_ {
313   /* KEEP IT IN SYNC WITH xbt_thread.c */
314   pthread_mutex_t m;
315 } s_xbt_os_mutex_t;
316
317 #include <time.h>
318 #include <math.h>
319
320 xbt_os_mutex_t xbt_os_mutex_init(void)
321 {
322   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
323   int errcode = pthread_mutex_init(&(res->m), NULL);
324   xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
325
326   return res;
327 }
328
329 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
330 {
331   int errcode = pthread_mutex_lock(&(mutex->m));
332   xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
333 }
334
335 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
336 {
337   int errcode = pthread_mutex_unlock(&(mutex->m));
338   xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
339 }
340
341 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
342 {
343   if (!mutex)
344     return;
345
346   int errcode = pthread_mutex_destroy(&(mutex->m));
347   xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
348   free(mutex);
349 }
350
351 /***** condition related functions *****/
352 typedef struct xbt_os_cond_ {
353   /* KEEP IT IN SYNC WITH xbt_thread.c */
354   pthread_cond_t c;
355 } s_xbt_os_cond_t;
356
357 xbt_os_cond_t xbt_os_cond_init(void)
358 {
359   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
360   int errcode = pthread_cond_init(&(res->c), NULL);
361   xbt_assert(errcode==0, "pthread_cond_init() failed: %s", strerror(errcode));
362   return res;
363 }
364
365 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
366 {
367   int errcode = pthread_cond_wait(&(cond->c), &(mutex->m));
368   xbt_assert(errcode==0, "pthread_cond_wait(%p,%p) failed: %s", cond, mutex, strerror(errcode));
369 }
370
371
372 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay)
373 {
374   int errcode;
375   struct timespec ts_end;
376   double end = delay + xbt_os_time();
377
378   if (delay < 0) {
379     xbt_os_cond_wait(cond, mutex);
380   } else {
381     ts_end.tv_sec = (time_t) floor(end);
382     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
383     XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m), &ts_end);
384     switch ((errcode = pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
385     case 0:
386       return;
387     case ETIMEDOUT:
388       THROWF(timeout_error, errcode,
389              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
390              cond, mutex, delay);
391     default:
392       THROWF(system_error, errcode, "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex, delay, strerror(errcode));
393     }
394   }
395 }
396
397 void xbt_os_cond_signal(xbt_os_cond_t cond)
398 {
399   int errcode = pthread_cond_signal(&(cond->c));
400   xbt_assert(errcode==0, "pthread_cond_signal(%p) failed: %s", cond, strerror(errcode));
401 }
402
403 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
404 {
405   int errcode = pthread_cond_broadcast(&(cond->c));
406   xbt_assert(errcode==0, "pthread_cond_broadcast(%p) failed: %s", cond, strerror(errcode));
407 }
408
409 void xbt_os_cond_destroy(xbt_os_cond_t cond)
410 {
411   if (!cond)
412     return;
413
414   int errcode = pthread_cond_destroy(&(cond->c));
415   xbt_assert(errcode==0, "pthread_cond_destroy(%p) failed: %s", cond, strerror(errcode));
416   free(cond);
417 }
418
419 typedef struct xbt_os_sem_ {
420 #ifndef HAVE_SEM_INIT
421   char *name;
422 #endif
423   sem_t s;
424   sem_t *ps;
425 } s_xbt_os_sem_t;
426
427 #ifndef SEM_FAILED
428 #define SEM_FAILED (-1)
429 #endif
430
431 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
432 {
433   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
434
435   /* On some systems (MAC OS X), only the stub of sem_init is to be found.
436    * Any attempt to use it leads to ENOSYS (function not implemented).
437    * If such a prehistoric system is detected, do the job with sem_open instead
438    */
439 #ifdef HAVE_SEM_INIT
440   if (sem_init(&(res->s), 0, value) != 0)
441     THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
442   res->ps = &(res->s);
443
444 #else                           /* damn, no sem_init(). Reimplement it */
445
446   xbt_os_mutex_acquire(next_sem_ID_lock);
447   res->name = bprintf("/%d", ++next_sem_ID);
448   xbt_os_mutex_release(next_sem_ID_lock);
449
450   res->ps = sem_open(res->name, O_CREAT, 0644, value);
451   if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
452     /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
453     res->name[13] = '\0';
454     res->ps = sem_open(res->name, O_CREAT, 0644, value);
455   }
456   if (res->ps == (sem_t *) SEM_FAILED)
457     THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
458
459   /* Remove the name from the semaphore namespace: we never join on it */
460   if (sem_unlink(res->name) < 0)
461     THROWF(system_error, errno, "sem_unlink() failed: %s",
462            strerror(errno));
463
464 #endif
465
466   return res;
467 }
468
469 void xbt_os_sem_acquire(xbt_os_sem_t sem)
470 {
471   if (sem_wait(sem->ps) < 0)
472     THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
473 }
474
475 void xbt_os_sem_release(xbt_os_sem_t sem)
476 {
477   if (sem_post(sem->ps) < 0)
478     THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
479 }
480
481 void xbt_os_sem_destroy(xbt_os_sem_t sem)
482 {
483 #ifdef HAVE_SEM_INIT
484   if (sem_destroy(sem->ps) < 0)
485     THROWF(system_error, errno, "sem_destroy() failed: %s",
486            strerror(errno));
487 #else
488   if (sem_close(sem->ps) < 0)
489     THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
490   xbt_free(sem->name);
491
492 #endif
493   xbt_free(sem);
494 }
495
496 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
497 {
498   if (sem_getvalue(&(sem->s), svalue) < 0)
499     THROWF(system_error, errno, "sem_getvalue() failed: %s",
500            strerror(errno));
501 }
502
503
504 /** @brief Returns the amount of cores on the current host */
505 int xbt_os_get_numcores(void) {
506 #ifdef WIN32
507     SYSTEM_INFO sysinfo;
508     GetSystemInfo(&sysinfo);
509     return sysinfo.dwNumberOfProcessors;
510 #elif defined(__APPLE__) && defined(__MACH__)
511     int nm[2];
512     size_t len = 4;
513     uint32_t count;
514
515     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
516     sysctl(nm, 2, &count, &len, NULL, 0);
517
518     if(count < 1) {
519         nm[1] = HW_NCPU;
520         sysctl(nm, 2, &count, &len, NULL, 0);
521         if(count < 1) { count = 1; }
522     }
523     return count;
524 #else
525     return sysconf(_SC_NPROCESSORS_ONLN);
526 #endif
527 }
528
529 void xbt_os_thread_set_extra_data(void *data)
530 {
531   xbt_os_thread_self()->extra_data = data;
532 }
533
534 void *xbt_os_thread_get_extra_data(void)
535 {
536   xbt_os_thread_t thread = xbt_os_thread_self();
537   return thread ? thread->extra_data : NULL;
538 }
539
540 /***** reentrant mutexes *****/
541 typedef struct xbt_os_rmutex_ {
542   xbt_os_mutex_t mutex;
543   xbt_os_thread_t owner;
544   int count;
545 } s_xbt_os_rmutex_t;
546
547 xbt_os_rmutex_t xbt_os_rmutex_init(void)
548 {
549   xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
550   rmutex->mutex = xbt_os_mutex_init();
551   rmutex->owner = NULL;
552   rmutex->count = 0;
553   return rmutex;
554 }
555
556 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
557 {
558   xbt_os_thread_t self = xbt_os_thread_self();
559
560   if (self == NULL) {
561     /* the thread module is not initialized yet */
562     rmutex->owner = NULL;
563     return;
564   }
565
566   if (self != rmutex->owner) {
567     xbt_os_mutex_acquire(rmutex->mutex);
568     rmutex->owner = self;
569     rmutex->count = 1;
570   } else {
571     rmutex->count++;
572  }
573 }
574
575 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
576 {
577   if (rmutex->owner == NULL) {
578     /* the thread module was not initialized */
579     return;
580   }
581
582   xbt_assert(rmutex->owner == xbt_os_thread_self());
583
584   if (--rmutex->count == 0) {
585     rmutex->owner = NULL;
586     xbt_os_mutex_release(rmutex->mutex);
587   }
588 }
589
590 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
591 {
592   xbt_os_mutex_destroy(rmutex->mutex);
593   xbt_free(rmutex);
594 }