pthread.c 36 KB

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