pthread.c 35 KB

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