pthread.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. /* Linuxthreads - a simple clone()-based implementation of Posix */
  2. /* threads for Linux. */
  3. /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
  4. /* */
  5. /* This program is free software; you can redistribute it and/or */
  6. /* modify it under the terms of the GNU Library General Public License */
  7. /* as published by the Free Software Foundation; either version 2 */
  8. /* of the License, or (at your option) any later version. */
  9. /* */
  10. /* This program is distributed in the hope that it will be useful, */
  11. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  12. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  13. /* GNU Library General Public License for more details. */
  14. /* Thread creation, initialization, and basic low-level routines */
  15. #include <errno.h>
  16. #include <netdb.h> /* for h_errno */
  17. #include <stddef.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <sys/wait.h>
  24. #include <sys/resource.h>
  25. #include "pthread.h"
  26. #include "internals.h"
  27. #include "spinlock.h"
  28. #include "restart.h"
  29. #include "debug.h" /* added to linuxthreads -StS */
  30. /* Mods for uClibc: Some includes */
  31. #include <signal.h>
  32. #include <sys/types.h>
  33. #include <sys/syscall.h>
  34. /* These variables are used by the setup code. */
  35. extern int _errno;
  36. extern int _h_errno;
  37. /* Descriptor of the initial thread */
  38. struct _pthread_descr_struct __pthread_initial_thread = {
  39. &__pthread_initial_thread, /* pthread_descr p_nextlive */
  40. &__pthread_initial_thread, /* pthread_descr p_prevlive */
  41. NULL, /* pthread_descr p_nextwaiting */
  42. NULL, /* pthread_descr p_nextlock */
  43. PTHREAD_THREADS_MAX, /* pthread_t p_tid */
  44. 0, /* int p_pid */
  45. 0, /* int p_priority */
  46. &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
  47. 0, /* int p_signal */
  48. NULL, /* sigjmp_buf * p_signal_buf */
  49. NULL, /* sigjmp_buf * p_cancel_buf */
  50. 0, /* char p_terminated */
  51. 0, /* char p_detached */
  52. 0, /* char p_exited */
  53. NULL, /* void * p_retval */
  54. 0, /* int p_retval */
  55. NULL, /* pthread_descr p_joining */
  56. NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
  57. 0, /* char p_cancelstate */
  58. 0, /* char p_canceltype */
  59. 0, /* char p_canceled */
  60. &_errno, /* int *p_errnop */
  61. 0, /* int p_errno */
  62. &_h_errno, /* int *p_h_errnop */
  63. 0, /* int p_h_errno */
  64. NULL, /* char * p_in_sighandler */
  65. 0, /* char p_sigwaiting */
  66. PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  67. {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  68. {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  69. 0, /* int p_userstack */
  70. NULL, /* void * p_guardaddr */
  71. 0, /* size_t p_guardsize */
  72. &__pthread_initial_thread, /* pthread_descr p_self */
  73. 0, /* Always index 0 */
  74. 0, /* int p_report_events */
  75. {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
  76. __ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
  77. 0, /* char p_woken_by_cancel */
  78. 0, /* char p_condvar_avail */
  79. 0, /* char p_sem_avail */
  80. NULL, /* struct pthread_extricate_if *p_extricate */
  81. NULL, /* pthread_readlock_info *p_readlock_list; */
  82. NULL, /* pthread_readlock_info *p_readlock_free; */
  83. 0 /* int p_untracked_readlock_count; */
  84. #ifdef __UCLIBC_HAS_XLOCALE__
  85. ,
  86. &__global_locale_data, /* __locale_t locale; */
  87. #endif /* __UCLIBC_HAS_XLOCALE__ */
  88. };
  89. /* Descriptor of the manager thread; none of this is used but the error
  90. variables, the p_pid and p_priority fields,
  91. and the address for identification. */
  92. #define manager_thread (&__pthread_manager_thread)
  93. struct _pthread_descr_struct __pthread_manager_thread = {
  94. NULL, /* pthread_descr p_nextlive */
  95. NULL, /* pthread_descr p_prevlive */
  96. NULL, /* pthread_descr p_nextwaiting */
  97. NULL, /* pthread_descr p_nextlock */
  98. 0, /* int p_tid */
  99. 0, /* int p_pid */
  100. 0, /* int p_priority */
  101. &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
  102. 0, /* int p_signal */
  103. NULL, /* sigjmp_buf * p_signal_buf */
  104. NULL, /* sigjmp_buf * p_cancel_buf */
  105. 0, /* char p_terminated */
  106. 0, /* char p_detached */
  107. 0, /* char p_exited */
  108. NULL, /* void * p_retval */
  109. 0, /* int p_retval */
  110. NULL, /* pthread_descr p_joining */
  111. NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
  112. 0, /* char p_cancelstate */
  113. 0, /* char p_canceltype */
  114. 0, /* char p_canceled */
  115. &__pthread_manager_thread.p_errno, /* int *p_errnop */
  116. 0, /* int p_errno */
  117. NULL, /* int *p_h_errnop */
  118. 0, /* int p_h_errno */
  119. NULL, /* char * p_in_sighandler */
  120. 0, /* char p_sigwaiting */
  121. PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  122. {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  123. {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  124. 0, /* int p_userstack */
  125. NULL, /* void * p_guardaddr */
  126. 0, /* size_t p_guardsize */
  127. &__pthread_manager_thread, /* pthread_descr p_self */
  128. 1, /* Always index 1 */
  129. 0, /* int p_report_events */
  130. {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
  131. __ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
  132. 0, /* char p_woken_by_cancel */
  133. 0, /* char p_condvar_avail */
  134. 0, /* char p_sem_avail */
  135. NULL, /* struct pthread_extricate_if *p_extricate */
  136. NULL, /* pthread_readlock_info *p_readlock_list; */
  137. NULL, /* pthread_readlock_info *p_readlock_free; */
  138. 0 /* int p_untracked_readlock_count; */
  139. #ifdef __UCLIBC_HAS_XLOCALE__
  140. ,
  141. &__global_locale_data, /* __locale_t locale; */
  142. #endif /* __UCLIBC_HAS_XLOCALE__ */
  143. };
  144. /* Pointer to the main thread (the father of the thread manager thread) */
  145. /* Originally, this is the initial thread, but this changes after fork() */
  146. pthread_descr __pthread_main_thread = &__pthread_initial_thread;
  147. /* Limit between the stack of the initial thread (above) and the
  148. stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
  149. char *__pthread_initial_thread_bos = NULL;
  150. #ifndef __ARCH_USE_MMU__
  151. /* See nommu notes in internals.h and pthread_initialize() below. */
  152. char *__pthread_initial_thread_tos = NULL;
  153. char *__pthread_initial_thread_mid = NULL;
  154. #endif /* __ARCH_USE_MMU__ */
  155. /* File descriptor for sending requests to the thread manager. */
  156. /* Initially -1, meaning that the thread manager is not running. */
  157. int __pthread_manager_request = -1;
  158. /* Other end of the pipe for sending requests to the thread manager. */
  159. int __pthread_manager_reader;
  160. /* Limits of the thread manager stack */
  161. char *__pthread_manager_thread_bos = NULL;
  162. char *__pthread_manager_thread_tos = NULL;
  163. /* For process-wide exit() */
  164. int __pthread_exit_requested = 0;
  165. int __pthread_exit_code = 0;
  166. /* Communicate relevant LinuxThreads constants to gdb */
  167. const int __pthread_threads_max = PTHREAD_THREADS_MAX;
  168. const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
  169. const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct, h_descr);
  170. const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
  171. p_pid);
  172. const int __linuxthreads_pthread_sizeof_descr
  173. = sizeof(struct _pthread_descr_struct);
  174. const int __linuxthreads_initial_report_events;
  175. const char __linuxthreads_version[] = VERSION;
  176. /* Forward declarations */
  177. static void pthread_onexit_process(int retcode, void *arg);
  178. static void pthread_handle_sigcancel(int sig);
  179. static void pthread_handle_sigrestart(int sig);
  180. static void pthread_handle_sigdebug(int sig);
  181. int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime);
  182. /* Signal numbers used for the communication.
  183. In these variables we keep track of the used variables. If the
  184. platform does not support any real-time signals we will define the
  185. values to some unreasonable value which will signal failing of all
  186. the functions below. */
  187. #ifndef __NR_rt_sigaction
  188. int __pthread_sig_restart = SIGUSR1;
  189. int __pthread_sig_cancel = SIGUSR2;
  190. int __pthread_sig_debug;
  191. #else
  192. #if __SIGRTMAX - __SIGRTMIN >= 3
  193. int __pthread_sig_restart = __SIGRTMIN;
  194. int __pthread_sig_cancel = __SIGRTMIN + 1;
  195. int __pthread_sig_debug = __SIGRTMIN + 2;
  196. void (*__pthread_restart)(pthread_descr) = __pthread_restart_new;
  197. void (*__pthread_suspend)(pthread_descr) = __pthread_wait_for_restart_signal;
  198. int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_new;
  199. #else
  200. int __pthread_sig_restart = SIGUSR1;
  201. int __pthread_sig_cancel = SIGUSR2;
  202. int __pthread_sig_debug;
  203. void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
  204. void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
  205. int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
  206. #endif
  207. #endif
  208. /* Initialize the pthread library.
  209. Initialization is split in two functions:
  210. - a constructor function that blocks the __pthread_sig_restart signal
  211. (must do this very early, since the program could capture the signal
  212. mask with e.g. sigsetjmp before creating the first thread);
  213. - a regular function called from pthread_create when needed. */
  214. static void pthread_initialize(void) __attribute__((constructor));
  215. libpthread_hidden_proto(pthread_attr_destroy)
  216. libpthread_hidden_proto(pthread_attr_init)
  217. libpthread_hidden_proto(pthread_attr_getdetachstate)
  218. libpthread_hidden_proto(pthread_attr_setdetachstate)
  219. libpthread_hidden_proto(pthread_attr_getinheritsched)
  220. libpthread_hidden_proto(pthread_attr_setinheritsched)
  221. libpthread_hidden_proto(pthread_attr_setschedparam)
  222. libpthread_hidden_proto(pthread_attr_getschedparam)
  223. libpthread_hidden_proto(pthread_attr_getschedpolicy)
  224. libpthread_hidden_proto(pthread_attr_setschedpolicy)
  225. libpthread_hidden_proto(pthread_attr_getscope)
  226. libpthread_hidden_proto(pthread_attr_setscope)
  227. libpthread_hidden_proto(pthread_exit)
  228. libpthread_hidden_proto(pthread_equal)
  229. libpthread_hidden_proto(pthread_self)
  230. libpthread_hidden_proto(pthread_getschedparam)
  231. libpthread_hidden_proto(pthread_setschedparam)
  232. libpthread_hidden_proto(pthread_setcancelstate)
  233. libpthread_hidden_proto(pthread_setcanceltype)
  234. libpthread_hidden_proto(_pthread_cleanup_push_defer)
  235. libpthread_hidden_proto(_pthread_cleanup_pop_restore)
  236. libpthread_hidden_proto(pthread_cond_broadcast)
  237. libpthread_hidden_proto(pthread_cond_destroy)
  238. libpthread_hidden_proto(pthread_cond_init)
  239. libpthread_hidden_proto(pthread_cond_signal)
  240. libpthread_hidden_proto(pthread_cond_wait)
  241. libpthread_hidden_proto(pthread_cond_timedwait)
  242. libpthread_hidden_proto(pthread_condattr_destroy)
  243. libpthread_hidden_proto(pthread_condattr_init)
  244. static int *__libc_multiple_threads_ptr;
  245. /* Do some minimal initialization which has to be done during the
  246. startup of the C library. */
  247. void __pthread_initialize_minimal(void)
  248. {
  249. /* If we have special thread_self processing, initialize
  250. * that for the main thread now. */
  251. #ifdef INIT_THREAD_SELF
  252. INIT_THREAD_SELF(&__pthread_initial_thread, 0);
  253. #endif
  254. __libc_multiple_threads_ptr = __libc_pthread_init ();
  255. }
  256. static void pthread_initialize(void)
  257. {
  258. struct sigaction sa;
  259. sigset_t mask;
  260. #ifdef __ARCH_USE_MMU__
  261. struct rlimit limit;
  262. rlim_t max_stack;
  263. #endif
  264. /* If already done (e.g. by a constructor called earlier!), bail out */
  265. if (__pthread_initial_thread_bos != NULL) return;
  266. #ifdef TEST_FOR_COMPARE_AND_SWAP
  267. /* Test if compare-and-swap is available */
  268. __pthread_has_cas = compare_and_swap_is_available();
  269. #endif
  270. /* For the initial stack, reserve at least STACK_SIZE bytes of stack
  271. below the current stack address, and align that on a
  272. STACK_SIZE boundary. */
  273. __pthread_initial_thread_bos =
  274. (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  275. /* Update the descriptor for the initial thread. */
  276. __pthread_initial_thread.p_pid = getpid();
  277. /* If we have special thread_self processing, initialize that for the
  278. main thread now. */
  279. #ifdef INIT_THREAD_SELF
  280. INIT_THREAD_SELF(&__pthread_initial_thread, 0);
  281. #endif
  282. /* The errno/h_errno variable of the main thread are the global ones. */
  283. __pthread_initial_thread.p_errnop = &_errno;
  284. __pthread_initial_thread.p_h_errnop = &_h_errno;
  285. #ifdef __UCLIBC_HAS_XLOCALE__
  286. /* The locale of the main thread is the current locale in use. */
  287. __pthread_initial_thread.locale = __curlocale_var;
  288. #endif /* __UCLIBC_HAS_XLOCALE__ */
  289. { /* uClibc-specific stdio initialization for threads. */
  290. FILE *fp;
  291. _stdio_user_locking = 0; /* 2 if threading not initialized */
  292. for (fp = _stdio_openlist; fp != NULL; fp = fp->__nextopen) {
  293. if (fp->__user_locking != 1) {
  294. fp->__user_locking = 0;
  295. }
  296. }
  297. }
  298. /* Play with the stack size limit to make sure that no stack ever grows
  299. beyond STACK_SIZE minus two pages (one page for the thread descriptor
  300. immediately beyond, and one page to act as a guard page). */
  301. #ifdef __ARCH_USE_MMU__
  302. /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
  303. * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
  304. getrlimit(RLIMIT_STACK, &limit);
  305. max_stack = STACK_SIZE - 2 * getpagesize();
  306. if (limit.rlim_cur > max_stack) {
  307. limit.rlim_cur = max_stack;
  308. setrlimit(RLIMIT_STACK, &limit);
  309. }
  310. #else
  311. /* For non-MMU, the initial thread stack can reside anywhere in memory.
  312. * We don't have a way of knowing where the kernel started things -- top
  313. * or bottom (well, that isn't exactly true, but the solution is fairly
  314. * complex and error prone). All we can determine here is an address
  315. * that lies within that stack. Save that address as a reference so that
  316. * as other thread stacks are created, we can adjust the estimated bounds
  317. * of the initial thread's stack appropriately.
  318. *
  319. * This checking is handled in NOMMU_INITIAL_THREAD_BOUNDS(), so see that
  320. * for a few more details.
  321. */
  322. __pthread_initial_thread_mid = CURRENT_STACK_FRAME;
  323. __pthread_initial_thread_tos = (char *) -1;
  324. __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
  325. PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
  326. __pthread_initial_thread_bos, __pthread_initial_thread_tos);
  327. #endif /* __ARCH_USE_MMU__ */
  328. /* Setup signal handlers for the initial thread.
  329. Since signal handlers are shared between threads, these settings
  330. will be inherited by all other threads. */
  331. memset(&sa, 0, sizeof(sa));
  332. sa.sa_handler = pthread_handle_sigrestart;
  333. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  334. sa.sa_handler = pthread_handle_sigcancel;
  335. sigaddset(&sa.sa_mask, __pthread_sig_restart);
  336. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  337. if (__pthread_sig_debug > 0) {
  338. sa.sa_handler = pthread_handle_sigdebug;
  339. __sigemptyset(&sa.sa_mask);
  340. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  341. }
  342. /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  343. __sigemptyset(&mask);
  344. sigaddset(&mask, __pthread_sig_restart);
  345. sigprocmask(SIG_BLOCK, &mask, NULL);
  346. /* And unblock __pthread_sig_cancel if it has been blocked. */
  347. sigdelset(&mask, __pthread_sig_restart);
  348. sigaddset(&mask, __pthread_sig_cancel);
  349. sigprocmask(SIG_UNBLOCK, &mask, NULL);
  350. /* Register an exit function to kill all other threads. */
  351. /* Do it early so that user-registered atexit functions are called
  352. before pthread_onexit_process. */
  353. on_exit(pthread_onexit_process, NULL);
  354. }
  355. void __pthread_initialize(void);
  356. void __pthread_initialize(void)
  357. {
  358. pthread_initialize();
  359. }
  360. int __pthread_initialize_manager(void)
  361. {
  362. int manager_pipe[2];
  363. int pid;
  364. int report_events;
  365. struct pthread_request request;
  366. *__libc_multiple_threads_ptr = 1;
  367. /* If basic initialization not done yet (e.g. we're called from a
  368. constructor run before our constructor), do it now */
  369. if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  370. /* Setup stack for thread manager */
  371. __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  372. if (__pthread_manager_thread_bos == NULL) return -1;
  373. __pthread_manager_thread_tos =
  374. __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
  375. /* On non-MMU systems we make sure that the initial thread bounds don't overlap
  376. * with the manager stack frame */
  377. NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
  378. PDEBUG("manager stack: size=%ld, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
  379. __pthread_manager_thread_bos, __pthread_manager_thread_tos);
  380. #if 0
  381. PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
  382. __pthread_initial_thread_bos, __pthread_initial_thread_tos);
  383. #endif
  384. /* Setup pipe to communicate with thread manager */
  385. if (pipe(manager_pipe) == -1) {
  386. free(__pthread_manager_thread_bos);
  387. return -1;
  388. }
  389. /* Start the thread manager */
  390. pid = 0;
  391. #if defined(USE_TLS) && USE_TLS
  392. if (__linuxthreads_initial_report_events != 0)
  393. THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
  394. __linuxthreads_initial_report_events);
  395. report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
  396. #else
  397. if (__linuxthreads_initial_report_events != 0)
  398. __pthread_initial_thread.p_report_events
  399. = __linuxthreads_initial_report_events;
  400. report_events = __pthread_initial_thread.p_report_events;
  401. #endif
  402. if (__builtin_expect (report_events, 0))
  403. {
  404. /* It's a bit more complicated. We have to report the creation of
  405. the manager thread. */
  406. int idx = __td_eventword (TD_CREATE);
  407. uint32_t mask = __td_eventmask (TD_CREATE);
  408. if ((mask & (__pthread_threads_events.event_bits[idx]
  409. | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
  410. != 0)
  411. {
  412. __pthread_lock(__pthread_manager_thread.p_lock, NULL);
  413. #ifdef __ia64__
  414. pid = __clone2(__pthread_manager_event,
  415. (void **) __pthread_manager_thread_tos,
  416. THREAD_MANAGER_STACK_SIZE,
  417. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  418. (void *)(long)manager_pipe[0]);
  419. #else
  420. pid = clone(__pthread_manager_event,
  421. (void **) __pthread_manager_thread_tos,
  422. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  423. (void *)(long)manager_pipe[0]);
  424. #endif
  425. if (pid != -1)
  426. {
  427. /* Now fill in the information about the new thread in
  428. the newly created thread's data structure. We cannot let
  429. the new thread do this since we don't know whether it was
  430. already scheduled when we send the event. */
  431. __pthread_manager_thread.p_eventbuf.eventdata =
  432. &__pthread_manager_thread;
  433. __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
  434. __pthread_last_event = &__pthread_manager_thread;
  435. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  436. __pthread_manager_thread.p_pid = pid;
  437. /* Now call the function which signals the event. */
  438. __linuxthreads_create_event ();
  439. }
  440. /* Now restart the thread. */
  441. __pthread_unlock(__pthread_manager_thread.p_lock);
  442. }
  443. }
  444. if (pid == 0) {
  445. #ifdef __ia64__
  446. pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_tos,
  447. THREAD_MANAGER_STACK_SIZE,
  448. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  449. (void *)(long)manager_pipe[0]);
  450. #else
  451. pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
  452. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  453. (void *)(long)manager_pipe[0]);
  454. #endif
  455. }
  456. if (pid == -1) {
  457. free(__pthread_manager_thread_bos);
  458. close(manager_pipe[0]);
  459. close(manager_pipe[1]);
  460. return -1;
  461. }
  462. __pthread_manager_request = manager_pipe[1]; /* writing end */
  463. __pthread_manager_reader = manager_pipe[0]; /* reading end */
  464. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  465. __pthread_manager_thread.p_pid = pid;
  466. /* Make gdb aware of new thread manager */
  467. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  468. {
  469. raise(__pthread_sig_debug);
  470. /* We suspend ourself and gdb will wake us up when it is
  471. ready to handle us. */
  472. __pthread_wait_for_restart_signal(thread_self());
  473. }
  474. /* Synchronize debugging of the thread manager */
  475. PDEBUG("send REQ_DEBUG to manager thread\n");
  476. request.req_kind = REQ_DEBUG;
  477. TEMP_FAILURE_RETRY(write(__pthread_manager_request,
  478. (char *) &request, sizeof(request)));
  479. return 0;
  480. }
  481. /* Thread creation */
  482. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  483. void * (*start_routine)(void *), void *arg)
  484. {
  485. pthread_descr self = thread_self();
  486. struct pthread_request request;
  487. if (__pthread_manager_request < 0) {
  488. if (__pthread_initialize_manager() < 0) return EAGAIN;
  489. }
  490. request.req_thread = self;
  491. request.req_kind = REQ_CREATE;
  492. request.req_args.create.attr = attr;
  493. request.req_args.create.fn = start_routine;
  494. request.req_args.create.arg = arg;
  495. sigprocmask(SIG_SETMASK, NULL, &request.req_args.create.mask);
  496. PDEBUG("write REQ_CREATE to manager thread\n");
  497. TEMP_FAILURE_RETRY(write(__pthread_manager_request,
  498. (char *) &request, sizeof(request)));
  499. PDEBUG("before suspend(self)\n");
  500. suspend(self);
  501. PDEBUG("after suspend(self)\n");
  502. if (THREAD_GETMEM(self, p_retcode) == 0)
  503. *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  504. return THREAD_GETMEM(self, p_retcode);
  505. }
  506. /* Simple operations on thread identifiers */
  507. pthread_t pthread_self(void)
  508. {
  509. pthread_descr self = thread_self();
  510. return THREAD_GETMEM(self, p_tid);
  511. }
  512. libpthread_hidden_def (pthread_self)
  513. int pthread_equal(pthread_t thread1, pthread_t thread2)
  514. {
  515. return thread1 == thread2;
  516. }
  517. libpthread_hidden_def (pthread_equal)
  518. /* Helper function for thread_self in the case of user-provided stacks */
  519. #ifndef THREAD_SELF
  520. pthread_descr __pthread_find_self(void)
  521. {
  522. char * sp = CURRENT_STACK_FRAME;
  523. pthread_handle h;
  524. /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
  525. the manager threads handled specially in thread_self(), so start at 2 */
  526. h = __pthread_handles + 2;
  527. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
  528. #ifdef DEBUG_PT
  529. if (h->h_descr == NULL) {
  530. printf("*** %s ERROR descriptor is NULL!!!!! ***\n\n", __FUNCTION__);
  531. _exit(1);
  532. }
  533. #endif
  534. return h->h_descr;
  535. }
  536. #else
  537. static pthread_descr thread_self_stack(void)
  538. {
  539. char *sp = CURRENT_STACK_FRAME;
  540. pthread_handle h;
  541. if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
  542. return manager_thread;
  543. h = __pthread_handles + 2;
  544. # if defined(USE_TLS) && USE_TLS
  545. while (h->h_descr == NULL
  546. || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
  547. h++;
  548. # else
  549. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
  550. h++;
  551. # endif
  552. return h->h_descr;
  553. }
  554. #endif
  555. /* Thread scheduling */
  556. int pthread_setschedparam(pthread_t thread, int policy,
  557. const struct sched_param *param)
  558. {
  559. pthread_handle handle = thread_handle(thread);
  560. pthread_descr th;
  561. __pthread_lock(&handle->h_lock, NULL);
  562. if (invalid_handle(handle, thread)) {
  563. __pthread_unlock(&handle->h_lock);
  564. return ESRCH;
  565. }
  566. th = handle->h_descr;
  567. if (sched_setscheduler(th->p_pid, policy, param) == -1) {
  568. __pthread_unlock(&handle->h_lock);
  569. return errno;
  570. }
  571. th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  572. __pthread_unlock(&handle->h_lock);
  573. if (__pthread_manager_request >= 0)
  574. __pthread_manager_adjust_prio(th->p_priority);
  575. return 0;
  576. }
  577. libpthread_hidden_def(pthread_setschedparam)
  578. int pthread_getschedparam(pthread_t thread, int *policy,
  579. struct sched_param *param)
  580. {
  581. pthread_handle handle = thread_handle(thread);
  582. int pid, pol;
  583. __pthread_lock(&handle->h_lock, NULL);
  584. if (invalid_handle(handle, thread)) {
  585. __pthread_unlock(&handle->h_lock);
  586. return ESRCH;
  587. }
  588. pid = handle->h_descr->p_pid;
  589. __pthread_unlock(&handle->h_lock);
  590. pol = sched_getscheduler(pid);
  591. if (pol == -1) return errno;
  592. if (sched_getparam(pid, param) == -1) return errno;
  593. *policy = pol;
  594. return 0;
  595. }
  596. libpthread_hidden_def(pthread_getschedparam)
  597. /* Process-wide exit() request */
  598. static void pthread_onexit_process(int retcode, void *arg attribute_unused)
  599. {
  600. struct pthread_request request;
  601. pthread_descr self = thread_self();
  602. if (__pthread_manager_request >= 0) {
  603. request.req_thread = self;
  604. request.req_kind = REQ_PROCESS_EXIT;
  605. request.req_args.exit.code = retcode;
  606. TEMP_FAILURE_RETRY(write(__pthread_manager_request,
  607. (char *) &request, sizeof(request)));
  608. suspend(self);
  609. /* Main thread should accumulate times for thread manager and its
  610. children, so that timings for main thread account for all threads. */
  611. if (self == __pthread_main_thread) {
  612. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  613. /* Since all threads have been asynchronously terminated
  614. * (possibly holding locks), free cannot be used any more. */
  615. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  616. }
  617. }
  618. }
  619. /* The handler for the RESTART signal just records the signal received
  620. in the thread descriptor, and optionally performs a siglongjmp
  621. (for pthread_cond_timedwait). */
  622. static void pthread_handle_sigrestart(int sig)
  623. {
  624. pthread_descr self = thread_self();
  625. THREAD_SETMEM(self, p_signal, sig);
  626. if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
  627. siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
  628. }
  629. /* The handler for the CANCEL signal checks for cancellation
  630. (in asynchronous mode), for process-wide exit and exec requests.
  631. For the thread manager thread, redirect the signal to
  632. __pthread_manager_sighandler. */
  633. static void pthread_handle_sigcancel(int sig)
  634. {
  635. pthread_descr self = thread_self();
  636. sigjmp_buf * jmpbuf;
  637. if (self == &__pthread_manager_thread)
  638. {
  639. #ifdef THREAD_SELF
  640. /* A new thread might get a cancel signal before it is fully
  641. initialized, so that the thread register might still point to the
  642. manager thread. Double check that this is really the manager
  643. thread. */
  644. pthread_descr real_self = thread_self_stack();
  645. if (real_self == &__pthread_manager_thread)
  646. {
  647. __pthread_manager_sighandler(sig);
  648. return;
  649. }
  650. /* Oops, thread_self() isn't working yet.. */
  651. self = real_self;
  652. # ifdef INIT_THREAD_SELF
  653. INIT_THREAD_SELF(self, self->p_nr);
  654. # endif
  655. #else
  656. __pthread_manager_sighandler(sig);
  657. return;
  658. #endif
  659. }
  660. if (__builtin_expect (__pthread_exit_requested, 0)) {
  661. /* Main thread should accumulate times for thread manager and its
  662. children, so that timings for main thread account for all threads. */
  663. if (self == __pthread_main_thread) {
  664. #if defined(USE_TLS) && USE_TLS
  665. waitpid(__pthread_manager_thread->p_pid, NULL, __WCLONE);
  666. #else
  667. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  668. #endif
  669. }
  670. _exit(__pthread_exit_code);
  671. }
  672. if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
  673. && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
  674. if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
  675. __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
  676. jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
  677. if (jmpbuf != NULL) {
  678. THREAD_SETMEM(self, p_cancel_jmp, NULL);
  679. siglongjmp(*jmpbuf, 1);
  680. }
  681. }
  682. }
  683. /* Handler for the DEBUG signal.
  684. The debugging strategy is as follows:
  685. On reception of a REQ_DEBUG request (sent by new threads created to
  686. the thread manager under debugging mode), the thread manager throws
  687. __pthread_sig_debug to itself. The debugger (if active) intercepts
  688. this signal, takes into account new threads and continue execution
  689. of the thread manager by propagating the signal because it doesn't
  690. know what it is specifically done for. In the current implementation,
  691. the thread manager simply discards it. */
  692. static void pthread_handle_sigdebug(int sig attribute_unused)
  693. {
  694. /* Nothing */
  695. }
  696. /* Reset the state of the thread machinery after a fork().
  697. Close the pipe used for requests and set the main thread to the forked
  698. thread.
  699. Notice that we can't free the stack segments, as the forked thread
  700. may hold pointers into them. */
  701. void __pthread_reset_main_thread(void)
  702. {
  703. pthread_descr self = thread_self();
  704. if (__pthread_manager_request != -1) {
  705. /* Free the thread manager stack */
  706. free(__pthread_manager_thread_bos);
  707. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  708. /* Close the two ends of the pipe */
  709. close(__pthread_manager_request);
  710. close(__pthread_manager_reader);
  711. __pthread_manager_request = __pthread_manager_reader = -1;
  712. }
  713. /* Update the pid of the main thread */
  714. THREAD_SETMEM(self, p_pid, getpid());
  715. /* Make the forked thread the main thread */
  716. __pthread_main_thread = self;
  717. THREAD_SETMEM(self, p_nextlive, self);
  718. THREAD_SETMEM(self, p_prevlive, self);
  719. /* Now this thread modifies the global variables. */
  720. THREAD_SETMEM(self, p_errnop, &_errno);
  721. THREAD_SETMEM(self, p_h_errnop, &_h_errno);
  722. }
  723. /* Process-wide exec() request */
  724. void __pthread_kill_other_threads_np(void)
  725. {
  726. struct sigaction sa;
  727. /* Terminate all other threads and thread manager */
  728. pthread_onexit_process(0, NULL);
  729. /* Make current thread the main thread in case the calling thread
  730. changes its mind, does not exec(), and creates new threads instead. */
  731. __pthread_reset_main_thread();
  732. /* Reset the signal handlers behaviour for the signals the
  733. implementation uses since this would be passed to the new
  734. process. */
  735. memset(&sa, 0, sizeof(sa));
  736. if (SIG_DFL) /* if it's constant zero, it's already done */
  737. sa.sa_handler = SIG_DFL;
  738. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  739. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  740. if (__pthread_sig_debug > 0)
  741. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  742. }
  743. weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
  744. /* Concurrency symbol level. */
  745. static int current_level;
  746. int __pthread_setconcurrency(int level)
  747. {
  748. /* We don't do anything unless we have found a useful interpretation. */
  749. current_level = level;
  750. return 0;
  751. }
  752. weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
  753. int __pthread_getconcurrency(void)
  754. {
  755. return current_level;
  756. }
  757. weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
  758. /* Primitives for controlling thread execution */
  759. void __pthread_wait_for_restart_signal(pthread_descr self)
  760. {
  761. sigset_t mask;
  762. sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  763. sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  764. THREAD_SETMEM(self, p_signal, 0);
  765. do {
  766. sigsuspend(&mask); /* Wait for signal */
  767. } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
  768. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  769. }
  770. #ifndef __NR_rt_sigaction
  771. /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
  772. signals.
  773. On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
  774. Since the restart signal does not queue, we use an atomic counter to create
  775. queuing semantics. This is needed to resolve a rare race condition in
  776. pthread_cond_timedwait_relative. */
  777. void __pthread_restart_old(pthread_descr th)
  778. {
  779. if (atomic_increment(&th->p_resume_count) == -1)
  780. kill(th->p_pid, __pthread_sig_restart);
  781. }
  782. void __pthread_suspend_old(pthread_descr self)
  783. {
  784. if (atomic_decrement(&self->p_resume_count) <= 0)
  785. __pthread_wait_for_restart_signal(self);
  786. }
  787. int
  788. __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
  789. {
  790. sigset_t unblock, initial_mask;
  791. int was_signalled = 0;
  792. sigjmp_buf jmpbuf;
  793. if (atomic_decrement(&self->p_resume_count) == 0) {
  794. /* Set up a longjmp handler for the restart signal, unblock
  795. the signal and sleep. */
  796. if (sigsetjmp(jmpbuf, 1) == 0) {
  797. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  798. THREAD_SETMEM(self, p_signal, 0);
  799. /* Unblock the restart signal */
  800. __sigemptyset(&unblock);
  801. sigaddset(&unblock, __pthread_sig_restart);
  802. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  803. while (1) {
  804. struct timeval now;
  805. struct timespec reltime;
  806. /* Compute a time offset relative to now. */
  807. gettimeofday (&now, NULL);
  808. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  809. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  810. if (reltime.tv_nsec < 0) {
  811. reltime.tv_nsec += 1000000000;
  812. reltime.tv_sec -= 1;
  813. }
  814. /* Sleep for the required duration. If woken by a signal,
  815. resume waiting as required by Single Unix Specification. */
  816. if (reltime.tv_sec < 0 || nanosleep(&reltime, NULL) == 0)
  817. break;
  818. }
  819. /* Block the restart signal again */
  820. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  821. was_signalled = 0;
  822. } else {
  823. was_signalled = 1;
  824. }
  825. THREAD_SETMEM(self, p_signal_jmp, NULL);
  826. }
  827. /* Now was_signalled is true if we exited the above code
  828. due to the delivery of a restart signal. In that case,
  829. we know we have been dequeued and resumed and that the
  830. resume count is balanced. Otherwise, there are some
  831. cases to consider. First, try to bump up the resume count
  832. back to zero. If it goes to 1, it means restart() was
  833. invoked on this thread. The signal must be consumed
  834. and the count bumped down and everything is cool. We
  835. can return a 1 to the caller.
  836. Otherwise, no restart was delivered yet, so a potential
  837. race exists; we return a 0 to the caller which must deal
  838. with this race in an appropriate way; for example by
  839. atomically removing the thread from consideration for a
  840. wakeup---if such a thing fails, it means a restart is
  841. being delivered. */
  842. if (!was_signalled) {
  843. if (atomic_increment(&self->p_resume_count) != -1) {
  844. __pthread_wait_for_restart_signal(self);
  845. atomic_decrement(&self->p_resume_count); /* should be zero now! */
  846. /* woke spontaneously and consumed restart signal */
  847. return 1;
  848. }
  849. /* woke spontaneously but did not consume restart---caller must resolve */
  850. return 0;
  851. }
  852. /* woken due to restart signal */
  853. return 1;
  854. }
  855. #endif /* __NR_rt_sigaction */
  856. #ifdef __NR_rt_sigaction
  857. void __pthread_restart_new(pthread_descr th)
  858. {
  859. /* The barrier is proabably not needed, in which case it still documents
  860. our assumptions. The intent is to commit previous writes to shared
  861. memory so the woken thread will have a consistent view. Complementary
  862. read barriers are present to the suspend functions. */
  863. WRITE_MEMORY_BARRIER();
  864. kill(th->p_pid, __pthread_sig_restart);
  865. }
  866. int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
  867. {
  868. sigset_t unblock, initial_mask;
  869. int was_signalled = 0;
  870. sigjmp_buf jmpbuf;
  871. if (sigsetjmp(jmpbuf, 1) == 0) {
  872. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  873. THREAD_SETMEM(self, p_signal, 0);
  874. /* Unblock the restart signal */
  875. __sigemptyset(&unblock);
  876. sigaddset(&unblock, __pthread_sig_restart);
  877. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  878. while (1) {
  879. struct timeval now;
  880. struct timespec reltime;
  881. /* Compute a time offset relative to now. */
  882. gettimeofday (&now, NULL);
  883. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  884. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  885. if (reltime.tv_nsec < 0) {
  886. reltime.tv_nsec += 1000000000;
  887. reltime.tv_sec -= 1;
  888. }
  889. /* Sleep for the required duration. If woken by a signal,
  890. resume waiting as required by Single Unix Specification. */
  891. if (reltime.tv_sec < 0 || nanosleep(&reltime, NULL) == 0)
  892. break;
  893. }
  894. /* Block the restart signal again */
  895. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  896. was_signalled = 0;
  897. } else {
  898. was_signalled = 1;
  899. }
  900. THREAD_SETMEM(self, p_signal_jmp, NULL);
  901. /* Now was_signalled is true if we exited the above code
  902. due to the delivery of a restart signal. In that case,
  903. everything is cool. We have been removed from whatever
  904. we were waiting on by the other thread, and consumed its signal.
  905. Otherwise we this thread woke up spontaneously, or due to a signal other
  906. than restart. This is an ambiguous case that must be resolved by
  907. the caller; the thread is still eligible for a restart wakeup
  908. so there is a race. */
  909. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  910. return was_signalled;
  911. }
  912. #endif
  913. /* Debugging aid */
  914. #ifdef DEBUG_PT
  915. #include <stdarg.h>
  916. void __pthread_message(char * fmt, ...)
  917. {
  918. char buffer[1024];
  919. va_list args;
  920. sprintf(buffer, "%05d : ", getpid());
  921. va_start(args, fmt);
  922. vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  923. va_end(args);
  924. TEMP_FAILURE_RETRY(write(2, buffer, strlen(buffer)));
  925. }
  926. #endif
  927. #ifndef __PIC__
  928. /* We need a hook to force the cancellation wrappers to be linked in when
  929. static libpthread is used. */
  930. extern const char __pthread_provide_wrappers;
  931. static const char *const __pthread_require_wrappers =
  932. &__pthread_provide_wrappers;
  933. #endif