pthread.c 37 KB

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