Logo AND Algorithmique Numérique Distribuée

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