pthread.c 34 KB

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