Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c697ae7bf42839c8bba4d1fa59bb837ba91e81c7
[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 /** Calls pthread_atfork() if present, and raise an exception otherwise.
154  *
155  * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
156  * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
157  * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
158  */
159
160 /* this function is critical to tesh+mmalloc, don't mess with it */
161 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
162 {
163   return pthread_atfork(prepare, parent, child);
164 }
165
166 static void *wrapper_start_routine(void *s)
167 {
168   xbt_os_thread_t t = s;
169
170   int errcode = pthread_setspecific(xbt_self_thread_key, t);
171   xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
172
173   void *res = t->start_routine(t->param);
174   if (t->detached)
175     xbt_os_thread_free_thread_data(t);
176   return res;
177 }
178
179
180 xbt_os_thread_t xbt_os_thread_create(const char *name,  pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
181 {
182   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
183   res_thread->detached = 0;
184   res_thread->name = xbt_strdup(name);
185   res_thread->start_routine = start_routine;
186   res_thread->param = param;
187   res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
188   XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
189   res_thread->extra_data = extra_data;
190   
191   int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
192   xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
193
194   return res_thread;
195 }
196
197 /** Bind the thread to the given core, if possible.
198  *
199  * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
200  */
201 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
202   int errcode = 0;
203 #ifdef HAVE_PTHREAD_SETAFFINITY
204   pthread_t pthread = thread->t;
205   cpu_set_t cpuset;
206   CPU_ZERO(&cpuset);
207   CPU_SET(cpu, &cpuset);
208   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
209 #endif
210   return errcode;
211 }
212
213 void xbt_os_thread_setstacksize(int stack_size)
214 {
215   size_t alignment[] = {
216     xbt_pagesize,
217 #ifdef PTHREAD_STACK_MIN
218     PTHREAD_STACK_MIN,
219 #endif
220     0
221   };
222
223   xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
224
225   size_t sz = stack_size;
226   int res = pthread_attr_setstacksize(&thread_attr, sz);
227
228   for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
229     /* Invalid size, try again with next multiple of alignment[i]. */
230     size_t rem = sz % alignment[i];
231     if (rem != 0 || sz == 0) {
232       size_t sz2 = sz - rem + alignment[i];
233       XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd", sz, sz2);
234       sz = sz2;
235       res = pthread_attr_setstacksize(&thread_attr, sz);
236     }
237   }
238
239   if (res == EINVAL)
240     XBT_WARN("invalid stack size (maybe too big): %zd", sz);
241   else if (res != 0)
242     XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
243 }
244
245 void xbt_os_thread_setguardsize(int guard_size)
246 {
247 #ifdef WIN32
248   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
249 #else
250   size_t sz = guard_size;
251   int res = pthread_attr_setguardsize(&thread_attr, sz);
252   if (res)
253     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
254 #endif
255 }
256
257 const char *xbt_os_thread_name(xbt_os_thread_t t)
258 {
259   return t->name;
260 }
261
262 const char *xbt_os_thread_self_name(void)
263 {
264   xbt_os_thread_t me = xbt_os_thread_self();
265   return me ? me->name : "main";
266 }
267
268 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
269 {
270   int errcode = pthread_join(thread->t, thread_return);
271
272   xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
273   xbt_os_thread_free_thread_data(thread);
274 }
275
276 void xbt_os_thread_exit(int *retval)
277 {
278   pthread_exit(retval);
279 }
280
281 xbt_os_thread_t xbt_os_thread_self(void)
282 {
283   if (!thread_mod_inited)
284     return NULL;
285
286   return pthread_getspecific(xbt_self_thread_key);
287 }
288
289 void xbt_os_thread_key_create(xbt_os_thread_key_t* key)
290 {
291   int errcode = pthread_key_create(key, NULL);
292   xbt_assert(errcode==0 , "pthread_key_create failed");
293 }
294
295 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
296
297   int errcode = pthread_setspecific(key, value);
298   xbt_assert(errcode==0, "pthread_setspecific failed");
299 }
300
301 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
302   return pthread_getspecific(key);
303 }
304
305 void xbt_os_thread_detach(xbt_os_thread_t thread)
306 {
307   thread->detached = 1;
308   pthread_detach(thread->t);
309 }
310
311 #include <sched.h>
312 void xbt_os_thread_yield(void)
313 {
314   sched_yield();
315 }
316
317 void xbt_os_thread_cancel(xbt_os_thread_t t)
318 {
319   pthread_cancel(t->t);
320 }
321
322 /****** mutex related functions ******/
323 typedef struct xbt_os_mutex_ {
324   pthread_mutex_t m;
325 } s_xbt_os_mutex_t;
326
327 #include <time.h>
328 #include <math.h>
329
330 xbt_os_mutex_t xbt_os_mutex_init(void)
331 {
332   pthread_mutexattr_t Attr;
333   pthread_mutexattr_init(&Attr);
334   pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
335
336   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
337   int errcode = pthread_mutex_init(&(res->m), &Attr);
338   xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
339
340   return res;
341 }
342
343 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
344 {
345   int errcode = pthread_mutex_lock(&(mutex->m));
346   xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
347 }
348
349 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
350 {
351   int errcode = pthread_mutex_unlock(&(mutex->m));
352   xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
353 }
354
355 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
356 {
357   if (!mutex)
358     return;
359
360   int errcode = pthread_mutex_destroy(&(mutex->m));
361   xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
362   free(mutex);
363 }
364
365 /***** condition related functions *****/
366 typedef struct xbt_os_cond_ {
367   pthread_cond_t c;
368 } s_xbt_os_cond_t;
369
370 xbt_os_cond_t xbt_os_cond_init(void)
371 {
372   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
373   int errcode = pthread_cond_init(&(res->c), NULL);
374   xbt_assert(errcode==0, "pthread_cond_init() failed: %s", strerror(errcode));
375   return res;
376 }
377
378 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
379 {
380   int errcode = pthread_cond_wait(&(cond->c), &(mutex->m));
381   xbt_assert(errcode==0, "pthread_cond_wait(%p,%p) failed: %s", cond, mutex, strerror(errcode));
382 }
383
384 void xbt_os_cond_signal(xbt_os_cond_t cond)
385 {
386   int errcode = pthread_cond_signal(&(cond->c));
387   xbt_assert(errcode==0, "pthread_cond_signal(%p) failed: %s", cond, strerror(errcode));
388 }
389
390 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
391 {
392   int errcode = pthread_cond_broadcast(&(cond->c));
393   xbt_assert(errcode==0, "pthread_cond_broadcast(%p) failed: %s", cond, strerror(errcode));
394 }
395
396 void xbt_os_cond_destroy(xbt_os_cond_t cond)
397 {
398   if (!cond)
399     return;
400
401   int errcode = pthread_cond_destroy(&(cond->c));
402   xbt_assert(errcode==0, "pthread_cond_destroy(%p) failed: %s", cond, strerror(errcode));
403   free(cond);
404 }
405
406 typedef struct xbt_os_sem_ {
407 #ifndef HAVE_SEM_INIT
408   char *name;
409 #endif
410   sem_t s;
411   sem_t *ps;
412 } s_xbt_os_sem_t;
413
414 #ifndef SEM_FAILED
415 #define SEM_FAILED (-1)
416 #endif
417
418 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
419 {
420   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
421
422   /* On some systems (MAC OS X), only the stub of sem_init is to be found.
423    * Any attempt to use it leads to ENOSYS (function not implemented).
424    * If such a prehistoric system is detected, do the job with sem_open instead
425    */
426 #ifdef HAVE_SEM_INIT
427   if (sem_init(&(res->s), 0, value) != 0)
428     THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
429   res->ps = &(res->s);
430
431 #else                           /* damn, no sem_init(). Reimplement it */
432
433   xbt_os_mutex_acquire(next_sem_ID_lock);
434   res->name = bprintf("/%d", ++next_sem_ID);
435   xbt_os_mutex_release(next_sem_ID_lock);
436
437   res->ps = sem_open(res->name, O_CREAT, 0644, value);
438   if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
439     /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
440     res->name[13] = '\0';
441     res->ps = sem_open(res->name, O_CREAT, 0644, value);
442   }
443   if (res->ps == (sem_t *) SEM_FAILED)
444     THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
445
446   /* Remove the name from the semaphore namespace: we never join on it */
447   if (sem_unlink(res->name) < 0)
448     THROWF(system_error, errno, "sem_unlink() failed: %s",
449            strerror(errno));
450
451 #endif
452
453   return res;
454 }
455
456 void xbt_os_sem_acquire(xbt_os_sem_t sem)
457 {
458   if (sem_wait(sem->ps) < 0)
459     THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
460 }
461
462 void xbt_os_sem_release(xbt_os_sem_t sem)
463 {
464   if (sem_post(sem->ps) < 0)
465     THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
466 }
467
468 void xbt_os_sem_destroy(xbt_os_sem_t sem)
469 {
470 #ifdef HAVE_SEM_INIT
471   if (sem_destroy(sem->ps) < 0)
472     THROWF(system_error, errno, "sem_destroy() failed: %s",
473            strerror(errno));
474 #else
475   if (sem_close(sem->ps) < 0)
476     THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
477   xbt_free(sem->name);
478
479 #endif
480   xbt_free(sem);
481 }
482
483 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
484 {
485   if (sem_getvalue(&(sem->s), svalue) < 0)
486     THROWF(system_error, errno, "sem_getvalue() failed: %s",
487            strerror(errno));
488 }
489
490
491 /** @brief Returns the amount of cores on the current host */
492 int xbt_os_get_numcores(void) {
493 #ifdef WIN32
494     SYSTEM_INFO sysinfo;
495     GetSystemInfo(&sysinfo);
496     return sysinfo.dwNumberOfProcessors;
497 #elif defined(__APPLE__) && defined(__MACH__)
498     int nm[2];
499     size_t len = 4;
500     uint32_t count;
501
502     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
503     sysctl(nm, 2, &count, &len, NULL, 0);
504
505     if(count < 1) {
506         nm[1] = HW_NCPU;
507         sysctl(nm, 2, &count, &len, NULL, 0);
508         if(count < 1) { count = 1; }
509     }
510     return count;
511 #else
512     return sysconf(_SC_NPROCESSORS_ONLN);
513 #endif
514 }
515
516 void xbt_os_thread_set_extra_data(void *data)
517 {
518   xbt_os_thread_self()->extra_data = data;
519 }
520
521 void *xbt_os_thread_get_extra_data(void)
522 {
523   xbt_os_thread_t thread = xbt_os_thread_self();
524   return thread ? thread->extra_data : NULL;
525 }