pthread.c 36 KB

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