Logo AND Algorithmique Numérique Distribuée

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