pthread.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. // sa.sa_flags = 0;
  332. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  333. if (__pthread_sig_debug > 0) {
  334. sa.sa_handler = pthread_handle_sigdebug;
  335. sigemptyset(&sa.sa_mask);
  336. // sa.sa_flags = 0;
  337. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  338. }
  339. /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  340. sigemptyset(&mask);
  341. sigaddset(&mask, __pthread_sig_restart);
  342. sigprocmask(SIG_BLOCK, &mask, NULL);
  343. /* Register an exit function to kill all other threads. */
  344. /* Do it early so that user-registered atexit functions are called
  345. before pthread_onexit_process. */
  346. on_exit(pthread_onexit_process, NULL);
  347. }
  348. void __pthread_initialize(void)
  349. {
  350. pthread_initialize();
  351. }
  352. int __pthread_initialize_manager(void)
  353. {
  354. int manager_pipe[2];
  355. int pid;
  356. int report_events;
  357. struct pthread_request request;
  358. /* If basic initialization not done yet (e.g. we're called from a
  359. constructor run before our constructor), do it now */
  360. if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  361. /* Setup stack for thread manager */
  362. __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  363. if (__pthread_manager_thread_bos == NULL) return -1;
  364. __pthread_manager_thread_tos =
  365. __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
  366. /* On non-MMU systems we make sure that the initial thread bounds don't overlap
  367. * with the manager stack frame */
  368. NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
  369. PDEBUG("manager stack: size=%d, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
  370. __pthread_manager_thread_bos, __pthread_manager_thread_tos);
  371. #if 0
  372. PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
  373. __pthread_initial_thread_bos, __pthread_initial_thread_tos);
  374. #endif
  375. /* Setup pipe to communicate with thread manager */
  376. if (pipe(manager_pipe) == -1) {
  377. free(__pthread_manager_thread_bos);
  378. return -1;
  379. }
  380. /* Start the thread manager */
  381. pid = 0;
  382. #ifdef USE_TLS
  383. if (__linuxthreads_initial_report_events != 0)
  384. THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
  385. __linuxthreads_initial_report_events);
  386. report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
  387. #else
  388. if (__linuxthreads_initial_report_events != 0)
  389. __pthread_initial_thread.p_report_events
  390. = __linuxthreads_initial_report_events;
  391. report_events = __pthread_initial_thread.p_report_events;
  392. #endif
  393. if (__builtin_expect (report_events, 0))
  394. {
  395. /* It's a bit more complicated. We have to report the creation of
  396. the manager thread. */
  397. int idx = __td_eventword (TD_CREATE);
  398. uint32_t mask = __td_eventmask (TD_CREATE);
  399. if ((mask & (__pthread_threads_events.event_bits[idx]
  400. | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
  401. != 0)
  402. {
  403. __pthread_lock(__pthread_manager_thread.p_lock, NULL);
  404. pid = clone(__pthread_manager_event,
  405. (void **) __pthread_manager_thread_tos,
  406. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  407. (void *)(long)manager_pipe[0]);
  408. if (pid != -1)
  409. {
  410. /* Now fill in the information about the new thread in
  411. the newly created thread's data structure. We cannot let
  412. the new thread do this since we don't know whether it was
  413. already scheduled when we send the event. */
  414. __pthread_manager_thread.p_eventbuf.eventdata =
  415. &__pthread_manager_thread;
  416. __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
  417. __pthread_last_event = &__pthread_manager_thread;
  418. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  419. __pthread_manager_thread.p_pid = pid;
  420. /* Now call the function which signals the event. */
  421. __linuxthreads_create_event ();
  422. }
  423. /* Now restart the thread. */
  424. __pthread_unlock(__pthread_manager_thread.p_lock);
  425. }
  426. }
  427. if (pid == 0) {
  428. pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
  429. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  430. (void *)(long)manager_pipe[0]);
  431. }
  432. if (pid == -1) {
  433. free(__pthread_manager_thread_bos);
  434. __libc_close(manager_pipe[0]);
  435. __libc_close(manager_pipe[1]);
  436. return -1;
  437. }
  438. __pthread_manager_request = manager_pipe[1]; /* writing end */
  439. __pthread_manager_reader = manager_pipe[0]; /* reading end */
  440. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  441. __pthread_manager_thread.p_pid = pid;
  442. /* Make gdb aware of new thread manager */
  443. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  444. {
  445. raise(__pthread_sig_debug);
  446. /* We suspend ourself and gdb will wake us up when it is
  447. ready to handle us. */
  448. __pthread_wait_for_restart_signal(thread_self());
  449. }
  450. /* Synchronize debugging of the thread manager */
  451. PDEBUG("send REQ_DEBUG to manager thread\n");
  452. request.req_kind = REQ_DEBUG;
  453. TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
  454. (char *) &request, sizeof(request)));
  455. return 0;
  456. }
  457. /* Thread creation */
  458. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  459. void * (*start_routine)(void *), void *arg)
  460. {
  461. pthread_descr self = thread_self();
  462. struct pthread_request request;
  463. if (__pthread_manager_request < 0) {
  464. if (__pthread_initialize_manager() < 0) return EAGAIN;
  465. }
  466. request.req_thread = self;
  467. request.req_kind = REQ_CREATE;
  468. request.req_args.create.attr = attr;
  469. request.req_args.create.fn = start_routine;
  470. request.req_args.create.arg = arg;
  471. sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
  472. &request.req_args.create.mask);
  473. PDEBUG("write REQ_CREATE to manager thread\n");
  474. TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
  475. (char *) &request, sizeof(request)));
  476. PDEBUG("before suspend(self)\n");
  477. suspend(self);
  478. PDEBUG("after suspend(self)\n");
  479. if (THREAD_GETMEM(self, p_retcode) == 0)
  480. *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  481. return THREAD_GETMEM(self, p_retcode);
  482. }
  483. /* Simple operations on thread identifiers */
  484. pthread_t pthread_self(void)
  485. {
  486. pthread_descr self = thread_self();
  487. return THREAD_GETMEM(self, p_tid);
  488. }
  489. int pthread_equal(pthread_t thread1, pthread_t thread2)
  490. {
  491. return thread1 == thread2;
  492. }
  493. /* Helper function for thread_self in the case of user-provided stacks */
  494. #ifndef THREAD_SELF
  495. pthread_descr __pthread_find_self()
  496. {
  497. char * sp = CURRENT_STACK_FRAME;
  498. pthread_handle h;
  499. /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
  500. the manager threads handled specially in thread_self(), so start at 2 */
  501. h = __pthread_handles + 2;
  502. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
  503. #ifdef DEBUG_PT
  504. if (h->h_descr == NULL) {
  505. printf("*** "__FUNCTION__" ERROR descriptor is NULL!!!!! ***\n\n");
  506. _exit(1);
  507. }
  508. #endif
  509. return h->h_descr;
  510. }
  511. #else
  512. static pthread_descr thread_self_stack(void)
  513. {
  514. char *sp = CURRENT_STACK_FRAME;
  515. pthread_handle h;
  516. if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
  517. return manager_thread;
  518. h = __pthread_handles + 2;
  519. # ifdef USE_TLS
  520. while (h->h_descr == NULL
  521. || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
  522. h++;
  523. # else
  524. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
  525. h++;
  526. # endif
  527. return h->h_descr;
  528. }
  529. #endif
  530. /* Thread scheduling */
  531. int pthread_setschedparam(pthread_t thread, int policy,
  532. const struct sched_param *param)
  533. {
  534. pthread_handle handle = thread_handle(thread);
  535. pthread_descr th;
  536. __pthread_lock(&handle->h_lock, NULL);
  537. if (invalid_handle(handle, thread)) {
  538. __pthread_unlock(&handle->h_lock);
  539. return ESRCH;
  540. }
  541. th = handle->h_descr;
  542. if (sched_setscheduler(th->p_pid, policy, param) == -1) {
  543. __pthread_unlock(&handle->h_lock);
  544. return errno;
  545. }
  546. th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  547. __pthread_unlock(&handle->h_lock);
  548. if (__pthread_manager_request >= 0)
  549. __pthread_manager_adjust_prio(th->p_priority);
  550. return 0;
  551. }
  552. int pthread_getschedparam(pthread_t thread, int *policy,
  553. struct sched_param *param)
  554. {
  555. pthread_handle handle = thread_handle(thread);
  556. int pid, pol;
  557. __pthread_lock(&handle->h_lock, NULL);
  558. if (invalid_handle(handle, thread)) {
  559. __pthread_unlock(&handle->h_lock);
  560. return ESRCH;
  561. }
  562. pid = handle->h_descr->p_pid;
  563. __pthread_unlock(&handle->h_lock);
  564. pol = sched_getscheduler(pid);
  565. if (pol == -1) return errno;
  566. if (sched_getparam(pid, param) == -1) return errno;
  567. *policy = pol;
  568. return 0;
  569. }
  570. /* Process-wide exit() request */
  571. static void pthread_onexit_process(int retcode, void *arg)
  572. {
  573. struct pthread_request request;
  574. pthread_descr self = thread_self();
  575. if (__pthread_manager_request >= 0) {
  576. request.req_thread = self;
  577. request.req_kind = REQ_PROCESS_EXIT;
  578. request.req_args.exit.code = retcode;
  579. TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
  580. (char *) &request, sizeof(request)));
  581. suspend(self);
  582. /* Main thread should accumulate times for thread manager and its
  583. children, so that timings for main thread account for all threads. */
  584. if (self == __pthread_main_thread) {
  585. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  586. /* Since all threads have been asynchronously terminated
  587. * (possibly holding locks), free cannot be used any more. */
  588. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  589. }
  590. }
  591. }
  592. /* The handler for the RESTART signal just records the signal received
  593. in the thread descriptor, and optionally performs a siglongjmp
  594. (for pthread_cond_timedwait). */
  595. static void pthread_handle_sigrestart(int sig)
  596. {
  597. pthread_descr self = thread_self();
  598. THREAD_SETMEM(self, p_signal, sig);
  599. if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
  600. siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
  601. }
  602. /* The handler for the CANCEL signal checks for cancellation
  603. (in asynchronous mode), for process-wide exit and exec requests.
  604. For the thread manager thread, redirect the signal to
  605. __pthread_manager_sighandler. */
  606. static void pthread_handle_sigcancel(int sig)
  607. {
  608. pthread_descr self = thread_self();
  609. sigjmp_buf * jmpbuf;
  610. if (self == &__pthread_manager_thread)
  611. {
  612. #ifdef THREAD_SELF
  613. /* A new thread might get a cancel signal before it is fully
  614. initialized, so that the thread register might still point to the
  615. manager thread. Double check that this is really the manager
  616. thread. */
  617. pthread_descr real_self = thread_self_stack();
  618. if (real_self == &__pthread_manager_thread)
  619. {
  620. __pthread_manager_sighandler(sig);
  621. return;
  622. }
  623. /* Oops, thread_self() isn't working yet.. */
  624. self = real_self;
  625. # ifdef INIT_THREAD_SELF
  626. INIT_THREAD_SELF(self, self->p_nr);
  627. # endif
  628. #else
  629. __pthread_manager_sighandler(sig);
  630. return;
  631. #endif
  632. }
  633. if (__builtin_expect (__pthread_exit_requested, 0)) {
  634. /* Main thread should accumulate times for thread manager and its
  635. children, so that timings for main thread account for all threads. */
  636. if (self == __pthread_main_thread) {
  637. #ifdef USE_TLS
  638. waitpid(__pthread_manager_thread->p_pid, NULL, __WCLONE);
  639. #else
  640. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  641. #endif
  642. }
  643. _exit(__pthread_exit_code);
  644. }
  645. if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
  646. && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
  647. if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
  648. pthread_exit(PTHREAD_CANCELED);
  649. jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
  650. if (jmpbuf != NULL) {
  651. THREAD_SETMEM(self, p_cancel_jmp, NULL);
  652. siglongjmp(*jmpbuf, 1);
  653. }
  654. }
  655. }
  656. /* Handler for the DEBUG signal.
  657. The debugging strategy is as follows:
  658. On reception of a REQ_DEBUG request (sent by new threads created to
  659. the thread manager under debugging mode), the thread manager throws
  660. __pthread_sig_debug to itself. The debugger (if active) intercepts
  661. this signal, takes into account new threads and continue execution
  662. of the thread manager by propagating the signal because it doesn't
  663. know what it is specifically done for. In the current implementation,
  664. the thread manager simply discards it. */
  665. static void pthread_handle_sigdebug(int sig)
  666. {
  667. /* Nothing */
  668. }
  669. /* Reset the state of the thread machinery after a fork().
  670. Close the pipe used for requests and set the main thread to the forked
  671. thread.
  672. Notice that we can't free the stack segments, as the forked thread
  673. may hold pointers into them. */
  674. void __pthread_reset_main_thread()
  675. {
  676. pthread_descr self = thread_self();
  677. if (__pthread_manager_request != -1) {
  678. /* Free the thread manager stack */
  679. free(__pthread_manager_thread_bos);
  680. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  681. /* Close the two ends of the pipe */
  682. __libc_close(__pthread_manager_request);
  683. __libc_close(__pthread_manager_reader);
  684. __pthread_manager_request = __pthread_manager_reader = -1;
  685. }
  686. /* Update the pid of the main thread */
  687. THREAD_SETMEM(self, p_pid, __getpid());
  688. /* Make the forked thread the main thread */
  689. __pthread_main_thread = self;
  690. THREAD_SETMEM(self, p_nextlive, self);
  691. THREAD_SETMEM(self, p_prevlive, self);
  692. /* Now this thread modifies the global variables. */
  693. THREAD_SETMEM(self, p_errnop, &_errno);
  694. THREAD_SETMEM(self, p_h_errnop, &_h_errno);
  695. }
  696. /* Process-wide exec() request */
  697. void __pthread_kill_other_threads_np(void)
  698. {
  699. struct sigaction sa;
  700. /* Terminate all other threads and thread manager */
  701. pthread_onexit_process(0, NULL);
  702. /* Make current thread the main thread in case the calling thread
  703. changes its mind, does not exec(), and creates new threads instead. */
  704. __pthread_reset_main_thread();
  705. /* Reset the signal handlers behaviour for the signals the
  706. implementation uses since this would be passed to the new
  707. process. */
  708. sigemptyset(&sa.sa_mask);
  709. sa.sa_flags = 0;
  710. sa.sa_handler = SIG_DFL;
  711. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  712. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  713. if (__pthread_sig_debug > 0)
  714. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  715. }
  716. weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
  717. /* Concurrency symbol level. */
  718. static int current_level;
  719. int __pthread_setconcurrency(int level)
  720. {
  721. /* We don't do anything unless we have found a useful interpretation. */
  722. current_level = level;
  723. return 0;
  724. }
  725. weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
  726. int __pthread_getconcurrency(void)
  727. {
  728. return current_level;
  729. }
  730. weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
  731. /* Primitives for controlling thread execution */
  732. void __pthread_wait_for_restart_signal(pthread_descr self)
  733. {
  734. sigset_t mask;
  735. sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  736. sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  737. THREAD_SETMEM(self, p_signal, 0);
  738. do {
  739. sigsuspend(&mask); /* Wait for signal */
  740. } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
  741. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  742. }
  743. #ifndef __NR_rt_sigaction
  744. /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
  745. signals.
  746. On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
  747. Since the restart signal does not queue, we use an atomic counter to create
  748. queuing semantics. This is needed to resolve a rare race condition in
  749. pthread_cond_timedwait_relative. */
  750. void __pthread_restart_old(pthread_descr th)
  751. {
  752. if (atomic_increment(&th->p_resume_count) == -1)
  753. kill(th->p_pid, __pthread_sig_restart);
  754. }
  755. void __pthread_suspend_old(pthread_descr self)
  756. {
  757. if (atomic_decrement(&self->p_resume_count) <= 0)
  758. __pthread_wait_for_restart_signal(self);
  759. }
  760. int
  761. __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
  762. {
  763. sigset_t unblock, initial_mask;
  764. int was_signalled = 0;
  765. sigjmp_buf jmpbuf;
  766. if (atomic_decrement(&self->p_resume_count) == 0) {
  767. /* Set up a longjmp handler for the restart signal, unblock
  768. the signal and sleep. */
  769. if (sigsetjmp(jmpbuf, 1) == 0) {
  770. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  771. THREAD_SETMEM(self, p_signal, 0);
  772. /* Unblock the restart signal */
  773. sigemptyset(&unblock);
  774. sigaddset(&unblock, __pthread_sig_restart);
  775. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  776. while (1) {
  777. struct timeval now;
  778. struct timespec reltime;
  779. /* Compute a time offset relative to now. */
  780. __libc_gettimeofday (&now, NULL);
  781. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  782. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  783. if (reltime.tv_nsec < 0) {
  784. reltime.tv_nsec += 1000000000;
  785. reltime.tv_sec -= 1;
  786. }
  787. /* Sleep for the required duration. If woken by a signal,
  788. resume waiting as required by Single Unix Specification. */
  789. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  790. break;
  791. }
  792. /* Block the restart signal again */
  793. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  794. was_signalled = 0;
  795. } else {
  796. was_signalled = 1;
  797. }
  798. THREAD_SETMEM(self, p_signal_jmp, NULL);
  799. }
  800. /* Now was_signalled is true if we exited the above code
  801. due to the delivery of a restart signal. In that case,
  802. we know we have been dequeued and resumed and that the
  803. resume count is balanced. Otherwise, there are some
  804. cases to consider. First, try to bump up the resume count
  805. back to zero. If it goes to 1, it means restart() was
  806. invoked on this thread. The signal must be consumed
  807. and the count bumped down and everything is cool. We
  808. can return a 1 to the caller.
  809. Otherwise, no restart was delivered yet, so a potential
  810. race exists; we return a 0 to the caller which must deal
  811. with this race in an appropriate way; for example by
  812. atomically removing the thread from consideration for a
  813. wakeup---if such a thing fails, it means a restart is
  814. being delivered. */
  815. if (!was_signalled) {
  816. if (atomic_increment(&self->p_resume_count) != -1) {
  817. __pthread_wait_for_restart_signal(self);
  818. atomic_decrement(&self->p_resume_count); /* should be zero now! */
  819. /* woke spontaneously and consumed restart signal */
  820. return 1;
  821. }
  822. /* woke spontaneously but did not consume restart---caller must resolve */
  823. return 0;
  824. }
  825. /* woken due to restart signal */
  826. return 1;
  827. }
  828. #endif /* __NR_rt_sigaction */
  829. #ifdef __NR_rt_sigaction
  830. void __pthread_restart_new(pthread_descr th)
  831. {
  832. /* The barrier is proabably not needed, in which case it still documents
  833. our assumptions. The intent is to commit previous writes to shared
  834. memory so the woken thread will have a consistent view. Complementary
  835. read barriers are present to the suspend functions. */
  836. WRITE_MEMORY_BARRIER();
  837. kill(th->p_pid, __pthread_sig_restart);
  838. }
  839. int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
  840. {
  841. sigset_t unblock, initial_mask;
  842. int was_signalled = 0;
  843. sigjmp_buf jmpbuf;
  844. if (sigsetjmp(jmpbuf, 1) == 0) {
  845. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  846. THREAD_SETMEM(self, p_signal, 0);
  847. /* Unblock the restart signal */
  848. sigemptyset(&unblock);
  849. sigaddset(&unblock, __pthread_sig_restart);
  850. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  851. while (1) {
  852. struct timeval now;
  853. struct timespec reltime;
  854. /* Compute a time offset relative to now. */
  855. __libc_gettimeofday (&now, NULL);
  856. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  857. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  858. if (reltime.tv_nsec < 0) {
  859. reltime.tv_nsec += 1000000000;
  860. reltime.tv_sec -= 1;
  861. }
  862. /* Sleep for the required duration. If woken by a signal,
  863. resume waiting as required by Single Unix Specification. */
  864. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  865. break;
  866. }
  867. /* Block the restart signal again */
  868. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  869. was_signalled = 0;
  870. } else {
  871. was_signalled = 1;
  872. }
  873. THREAD_SETMEM(self, p_signal_jmp, NULL);
  874. /* Now was_signalled is true if we exited the above code
  875. due to the delivery of a restart signal. In that case,
  876. everything is cool. We have been removed from whatever
  877. we were waiting on by the other thread, and consumed its signal.
  878. Otherwise we this thread woke up spontaneously, or due to a signal other
  879. than restart. This is an ambiguous case that must be resolved by
  880. the caller; the thread is still eligible for a restart wakeup
  881. so there is a race. */
  882. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  883. return was_signalled;
  884. }
  885. #endif
  886. /* Debugging aid */
  887. #ifdef DEBUG_PT
  888. #include <stdarg.h>
  889. void __pthread_message(char * fmt, ...)
  890. {
  891. char buffer[1024];
  892. va_list args;
  893. sprintf(buffer, "%05d : ", __getpid());
  894. va_start(args, fmt);
  895. vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  896. va_end(args);
  897. TEMP_FAILURE_RETRY(__libc_write(2, buffer, strlen(buffer)));
  898. }
  899. #endif
  900. #ifndef __PIC__
  901. /* We need a hook to force the cancelation wrappers to be linked in when
  902. static libpthread is used. */
  903. extern const int __pthread_provide_wrappers;
  904. static const int *const __pthread_require_wrappers =
  905. &__pthread_provide_wrappers;
  906. #endif