pthread.c 42 KB

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