pthread.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  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. #include <errno.h>
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <sys/wait.h>
  23. #include <sys/resource.h>
  24. #include <sys/time.h>
  25. #include "pthread.h"
  26. #include "internals.h"
  27. #include "spinlock.h"
  28. #include "restart.h"
  29. #include "smp.h"
  30. #include <not-cancel.h>
  31. #define __clone clone
  32. /* Sanity check. */
  33. #if !defined __SIGRTMIN || (__SIGRTMAX - __SIGRTMIN) < 3
  34. # error "This must not happen"
  35. #endif
  36. /* mods for uClibc: __libc_sigaction is not in any standard headers */
  37. extern int __libc_sigaction (int sig, const struct sigaction *act, struct sigaction *oact);
  38. extern int __cxa_atexit (void (*func) (void *), void *arg, void *d);
  39. #if !(USE_TLS && HAVE___THREAD)
  40. /* These variables are used by the setup code. */
  41. extern int _errno;
  42. extern int _h_errno;
  43. /* We need the global/static resolver state here. */
  44. # include <resolv.h>
  45. # undef _res
  46. extern struct __res_state _res;
  47. #endif
  48. #ifdef USE_TLS
  49. /* We need only a few variables. */
  50. #define manager_thread __pthread_manager_threadp
  51. pthread_descr __pthread_manager_threadp attribute_hidden;
  52. #else
  53. /* Descriptor of the initial thread */
  54. struct _pthread_descr_struct __pthread_initial_thread = {
  55. .p_header.data.self = &__pthread_initial_thread,
  56. .p_nextlive = &__pthread_initial_thread,
  57. .p_prevlive = &__pthread_initial_thread,
  58. .p_tid = PTHREAD_THREADS_MAX,
  59. .p_lock = &__pthread_handles[0].h_lock,
  60. .p_start_args = PTHREAD_START_ARGS_INITIALIZER(NULL),
  61. #if !(USE_TLS && HAVE___THREAD)
  62. .p_errnop = &_errno,
  63. .p_h_errnop = &_h_errno,
  64. .p_resp = &_res,
  65. #endif
  66. .p_userstack = 1,
  67. .p_resume_count = __ATOMIC_INITIALIZER,
  68. .p_alloca_cutoff = __MAX_ALLOCA_CUTOFF
  69. };
  70. /* Descriptor of the manager thread; none of this is used but the error
  71. variables, the p_pid and p_priority fields,
  72. and the address for identification. */
  73. #define manager_thread (&__pthread_manager_thread)
  74. struct _pthread_descr_struct __pthread_manager_thread = {
  75. .p_header.data.self = &__pthread_manager_thread,
  76. .p_header.data.multiple_threads = 1,
  77. .p_lock = &__pthread_handles[1].h_lock,
  78. .p_start_args = PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
  79. #if !(USE_TLS && HAVE___THREAD)
  80. .p_errnop = &__pthread_manager_thread.p_errno,
  81. #endif
  82. .p_nr = 1,
  83. .p_resume_count = __ATOMIC_INITIALIZER,
  84. .p_alloca_cutoff = PTHREAD_STACK_MIN / 4
  85. };
  86. #endif
  87. /* Pointer to the main thread (the father of the thread manager thread) */
  88. /* Originally, this is the initial thread, but this changes after fork() */
  89. #ifdef USE_TLS
  90. pthread_descr __pthread_main_thread;
  91. #else
  92. pthread_descr __pthread_main_thread = &__pthread_initial_thread;
  93. #endif
  94. /* Limit between the stack of the initial thread (above) and the
  95. stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
  96. char *__pthread_initial_thread_bos;
  97. /* File descriptor for sending requests to the thread manager. */
  98. /* Initially -1, meaning that the thread manager is not running. */
  99. int __pthread_manager_request = -1;
  100. int __pthread_multiple_threads attribute_hidden;
  101. /* Other end of the pipe for sending requests to the thread manager. */
  102. int __pthread_manager_reader;
  103. /* Limits of the thread manager stack */
  104. char *__pthread_manager_thread_bos;
  105. char *__pthread_manager_thread_tos;
  106. /* For process-wide exit() */
  107. int __pthread_exit_requested;
  108. int __pthread_exit_code;
  109. /* Maximum stack size. */
  110. size_t __pthread_max_stacksize;
  111. /* Nozero if the machine has more than one processor. */
  112. int __pthread_smp_kernel;
  113. #if !__ASSUME_REALTIME_SIGNALS
  114. /* Pointers that select new or old suspend/resume functions
  115. based on availability of rt signals. */
  116. void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
  117. void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
  118. int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
  119. #endif /* __ASSUME_REALTIME_SIGNALS */
  120. /* Communicate relevant LinuxThreads constants to gdb */
  121. const int __pthread_threads_max = PTHREAD_THREADS_MAX;
  122. const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
  123. const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
  124. h_descr);
  125. const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
  126. p_pid);
  127. const int __linuxthreads_pthread_sizeof_descr
  128. = sizeof(struct _pthread_descr_struct);
  129. const int __linuxthreads_initial_report_events;
  130. const char __linuxthreads_version[] = VERSION;
  131. /* Forward declarations */
  132. static void pthread_onexit_process(int retcode, void *arg);
  133. #ifndef HAVE_Z_NODELETE
  134. static void pthread_atexit_process(void *arg, int retcode);
  135. static void pthread_atexit_retcode(void *arg, int retcode);
  136. #endif
  137. static void pthread_handle_sigcancel(int sig);
  138. static void pthread_handle_sigrestart(int sig);
  139. static void pthread_handle_sigdebug(int sig);
  140. /* Signal numbers used for the communication.
  141. In these variables we keep track of the used variables. If the
  142. platform does not support any real-time signals we will define the
  143. values to some unreasonable value which will signal failing of all
  144. the functions below. */
  145. int __pthread_sig_restart = __SIGRTMIN;
  146. int __pthread_sig_cancel = __SIGRTMIN + 1;
  147. int __pthread_sig_debug = __SIGRTMIN + 2;
  148. extern int __libc_current_sigrtmin_private (void);
  149. #if !__ASSUME_REALTIME_SIGNALS
  150. static int rtsigs_initialized;
  151. static void
  152. init_rtsigs (void)
  153. {
  154. if (rtsigs_initialized)
  155. return;
  156. if (__libc_current_sigrtmin_private () == -1)
  157. {
  158. __pthread_sig_restart = SIGUSR1;
  159. __pthread_sig_cancel = SIGUSR2;
  160. __pthread_sig_debug = 0;
  161. }
  162. else
  163. {
  164. __pthread_restart = __pthread_restart_new;
  165. __pthread_suspend = __pthread_wait_for_restart_signal;
  166. __pthread_timedsuspend = __pthread_timedsuspend_new;
  167. }
  168. rtsigs_initialized = 1;
  169. }
  170. #endif
  171. /* Initialize the pthread library.
  172. Initialization is split in two functions:
  173. - a constructor function that blocks the __pthread_sig_restart signal
  174. (must do this very early, since the program could capture the signal
  175. mask with e.g. sigsetjmp before creating the first thread);
  176. - a regular function called from pthread_create when needed. */
  177. static void pthread_initialize(void) __attribute__((constructor));
  178. #ifndef HAVE_Z_NODELETE
  179. extern void *__dso_handle __attribute__ ((weak));
  180. #endif
  181. #if defined USE_TLS && !defined SHARED
  182. extern void __libc_setup_tls (size_t tcbsize, size_t tcbalign);
  183. #endif
  184. struct pthread_functions __pthread_functions =
  185. {
  186. #if !(USE_TLS && HAVE___THREAD)
  187. .ptr_pthread_internal_tsd_set = __pthread_internal_tsd_set,
  188. .ptr_pthread_internal_tsd_get = __pthread_internal_tsd_get,
  189. .ptr_pthread_internal_tsd_address = __pthread_internal_tsd_address,
  190. #endif
  191. .ptr_pthread_fork = __pthread_fork,
  192. .ptr_pthread_attr_destroy = __pthread_attr_destroy,
  193. .ptr___pthread_attr_init = __pthread_attr_init,
  194. .ptr_pthread_attr_getdetachstate = __pthread_attr_getdetachstate,
  195. .ptr_pthread_attr_setdetachstate = __pthread_attr_setdetachstate,
  196. .ptr_pthread_attr_getinheritsched = __pthread_attr_getinheritsched,
  197. .ptr_pthread_attr_setinheritsched = __pthread_attr_setinheritsched,
  198. .ptr_pthread_attr_getschedparam = __pthread_attr_getschedparam,
  199. .ptr_pthread_attr_setschedparam = __pthread_attr_setschedparam,
  200. .ptr_pthread_attr_getschedpolicy = __pthread_attr_getschedpolicy,
  201. .ptr_pthread_attr_setschedpolicy = __pthread_attr_setschedpolicy,
  202. .ptr_pthread_attr_getscope = __pthread_attr_getscope,
  203. .ptr_pthread_attr_setscope = __pthread_attr_setscope,
  204. .ptr_pthread_condattr_destroy = __pthread_condattr_destroy,
  205. .ptr_pthread_condattr_init = __pthread_condattr_init,
  206. .ptr_pthread_cond_broadcast = __pthread_cond_broadcast,
  207. .ptr_pthread_cond_destroy = __pthread_cond_destroy,
  208. .ptr_pthread_cond_init = __pthread_cond_init,
  209. .ptr_pthread_cond_signal = __pthread_cond_signal,
  210. .ptr_pthread_cond_wait = __pthread_cond_wait,
  211. .ptr_pthread_cond_timedwait = __pthread_cond_timedwait,
  212. .ptr_pthread_equal = __pthread_equal,
  213. .ptr___pthread_exit = __pthread_exit,
  214. .ptr_pthread_getschedparam = __pthread_getschedparam,
  215. .ptr_pthread_setschedparam = __pthread_setschedparam,
  216. .ptr_pthread_mutex_destroy = __pthread_mutex_destroy,
  217. .ptr_pthread_mutex_init = __pthread_mutex_init,
  218. .ptr_pthread_mutex_lock = __pthread_mutex_lock,
  219. .ptr_pthread_mutex_trylock = __pthread_mutex_trylock,
  220. .ptr_pthread_mutex_unlock = __pthread_mutex_unlock,
  221. .ptr_pthread_self = __pthread_self,
  222. .ptr_pthread_setcancelstate = __pthread_setcancelstate,
  223. .ptr_pthread_setcanceltype = __pthread_setcanceltype,
  224. .ptr_pthread_do_exit = __pthread_do_exit,
  225. .ptr_pthread_thread_self = __pthread_thread_self,
  226. .ptr_pthread_cleanup_upto = __pthread_cleanup_upto,
  227. .ptr_pthread_sigaction = __pthread_sigaction,
  228. .ptr_pthread_sigwait = __pthread_sigwait,
  229. .ptr_pthread_raise = __pthread_raise,
  230. .ptr__pthread_cleanup_push = _pthread_cleanup_push,
  231. .ptr__pthread_cleanup_pop = _pthread_cleanup_pop
  232. };
  233. #ifdef SHARED
  234. # define ptr_pthread_functions &__pthread_functions
  235. #else
  236. # define ptr_pthread_functions NULL
  237. #endif
  238. static int *__libc_multiple_threads_ptr;
  239. /* Do some minimal initialization which has to be done during the
  240. startup of the C library. */
  241. void
  242. __pthread_initialize_minimal(void)
  243. {
  244. #ifdef USE_TLS
  245. pthread_descr self;
  246. /* First of all init __pthread_handles[0] and [1] if needed. */
  247. # if __LT_SPINLOCK_INIT != 0
  248. __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
  249. __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
  250. # endif
  251. # ifndef SHARED
  252. /* Unlike in the dynamically linked case the dynamic linker has not
  253. taken care of initializing the TLS data structures. */
  254. __libc_setup_tls (TLS_TCB_SIZE, TLS_TCB_ALIGN);
  255. # elif !USE___THREAD
  256. if (__builtin_expect (GL(dl_tls_dtv_slotinfo_list) == NULL, 0))
  257. {
  258. tcbhead_t *tcbp;
  259. /* There is no actual TLS being used, so the thread register
  260. was not initialized in the dynamic linker. */
  261. /* We need to install special hooks so that the malloc and memalign
  262. calls in _dl_tls_setup and _dl_allocate_tls won't cause full
  263. malloc initialization that will try to set up its thread state. */
  264. extern void __libc_malloc_pthread_startup (bool first_time);
  265. __libc_malloc_pthread_startup (true);
  266. if (__builtin_expect (_dl_tls_setup (), 0)
  267. || __builtin_expect ((tcbp = _dl_allocate_tls (NULL)) == NULL, 0))
  268. {
  269. static const char msg[] = "\
  270. cannot allocate TLS data structures for initial thread\n";
  271. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  272. msg, sizeof msg - 1));
  273. abort ();
  274. }
  275. const char *lossage = TLS_INIT_TP (tcbp, 0);
  276. if (__builtin_expect (lossage != NULL, 0))
  277. {
  278. static const char msg[] = "cannot set up thread-local storage: ";
  279. const char nl = '\n';
  280. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  281. msg, sizeof msg - 1));
  282. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  283. lossage, strlen (lossage)));
  284. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO, &nl, 1));
  285. }
  286. /* Though it was allocated with libc's malloc, that was done without
  287. the user's __malloc_hook installed. A later realloc that uses
  288. the hooks might not work with that block from the plain malloc.
  289. So we record this block as unfreeable just as the dynamic linker
  290. does when it allocates the DTV before the libc malloc exists. */
  291. GL(dl_initial_dtv) = GET_DTV (tcbp);
  292. __libc_malloc_pthread_startup (false);
  293. }
  294. # endif
  295. self = THREAD_SELF;
  296. /* The memory for the thread descriptor was allocated elsewhere as
  297. part of the TLS allocation. We have to initialize the data
  298. structure by hand. This initialization must mirror the struct
  299. definition above. */
  300. self->p_nextlive = self->p_prevlive = self;
  301. self->p_tid = PTHREAD_THREADS_MAX;
  302. self->p_lock = &__pthread_handles[0].h_lock;
  303. # ifndef HAVE___THREAD
  304. self->p_errnop = &_errno;
  305. self->p_h_errnop = &_h_errno;
  306. # endif
  307. /* self->p_start_args need not be initialized, it's all zero. */
  308. self->p_userstack = 1;
  309. # if __LT_SPINLOCK_INIT != 0
  310. self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
  311. # endif
  312. self->p_alloca_cutoff = __MAX_ALLOCA_CUTOFF;
  313. /* Another variable which points to the thread descriptor. */
  314. __pthread_main_thread = self;
  315. /* And fill in the pointer the the thread __pthread_handles array. */
  316. __pthread_handles[0].h_descr = self;
  317. #else /* USE_TLS */
  318. /* First of all init __pthread_handles[0] and [1]. */
  319. # if __LT_SPINLOCK_INIT != 0
  320. __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
  321. __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
  322. # endif
  323. __pthread_handles[0].h_descr = &__pthread_initial_thread;
  324. __pthread_handles[1].h_descr = &__pthread_manager_thread;
  325. /* If we have special thread_self processing, initialize that for the
  326. main thread now. */
  327. # ifdef INIT_THREAD_SELF
  328. INIT_THREAD_SELF(&__pthread_initial_thread, 0);
  329. # endif
  330. #endif
  331. #if HP_TIMING_AVAIL
  332. # ifdef USE_TLS
  333. self->p_cpuclock_offset = GL(dl_cpuclock_offset);
  334. # else
  335. __pthread_initial_thread.p_cpuclock_offset = GL(dl_cpuclock_offset);
  336. # endif
  337. #endif
  338. __libc_multiple_threads_ptr = __libc_pthread_init (ptr_pthread_functions);
  339. }
  340. void
  341. __pthread_init_max_stacksize(void)
  342. {
  343. struct rlimit limit;
  344. size_t max_stack;
  345. getrlimit(RLIMIT_STACK, &limit);
  346. #ifdef FLOATING_STACKS
  347. if (limit.rlim_cur == RLIM_INFINITY)
  348. limit.rlim_cur = ARCH_STACK_MAX_SIZE;
  349. # ifdef NEED_SEPARATE_REGISTER_STACK
  350. max_stack = limit.rlim_cur / 2;
  351. # else
  352. max_stack = limit.rlim_cur;
  353. # endif
  354. #else
  355. /* Play with the stack size limit to make sure that no stack ever grows
  356. beyond STACK_SIZE minus one page (to act as a guard page). */
  357. # ifdef NEED_SEPARATE_REGISTER_STACK
  358. /* STACK_SIZE bytes hold both the main stack and register backing
  359. store. The rlimit value applies to each individually. */
  360. max_stack = STACK_SIZE/2 - __getpagesize ();
  361. # else
  362. max_stack = STACK_SIZE - __getpagesize();
  363. # endif
  364. if (limit.rlim_cur > max_stack) {
  365. limit.rlim_cur = max_stack;
  366. setrlimit(RLIMIT_STACK, &limit);
  367. }
  368. #endif
  369. __pthread_max_stacksize = max_stack;
  370. if (max_stack / 4 < __MAX_ALLOCA_CUTOFF)
  371. {
  372. #ifdef USE_TLS
  373. pthread_descr self = THREAD_SELF;
  374. self->p_alloca_cutoff = max_stack / 4;
  375. #else
  376. __pthread_initial_thread.p_alloca_cutoff = max_stack / 4;
  377. #endif
  378. }
  379. }
  380. #ifdef SHARED
  381. # if USE___THREAD
  382. /* When using __thread for this, we do it in libc so as not
  383. to give libpthread its own TLS segment just for this. */
  384. extern void **__libc_dl_error_tsd (void) __attribute__ ((const));
  385. # else
  386. static void ** __attribute__ ((const))
  387. __libc_dl_error_tsd (void)
  388. {
  389. return &thread_self ()->p_libc_specific[_LIBC_TSD_KEY_DL_ERROR];
  390. }
  391. # endif
  392. #endif
  393. #ifdef USE_TLS
  394. static inline void __attribute__((always_inline))
  395. init_one_static_tls (pthread_descr descr, struct link_map *map)
  396. {
  397. # if TLS_TCB_AT_TP
  398. dtv_t *dtv = GET_DTV (descr);
  399. void *dest = (char *) descr - map->l_tls_offset;
  400. # elif TLS_DTV_AT_TP
  401. dtv_t *dtv = GET_DTV ((pthread_descr) ((char *) descr + TLS_PRE_TCB_SIZE));
  402. void *dest = (char *) descr + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  403. # else
  404. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  405. # endif
  406. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  407. dtv[map->l_tls_modid].pointer.val = dest;
  408. dtv[map->l_tls_modid].pointer.is_static = true;
  409. /* Initialize the memory. */
  410. memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  411. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  412. }
  413. static void
  414. __pthread_init_static_tls (struct link_map *map)
  415. {
  416. size_t i;
  417. for (i = 0; i < PTHREAD_THREADS_MAX; ++i)
  418. if (__pthread_handles[i].h_descr != NULL && i != 1)
  419. {
  420. __pthread_lock (&__pthread_handles[i].h_lock, NULL);
  421. if (__pthread_handles[i].h_descr != NULL)
  422. init_one_static_tls (__pthread_handles[i].h_descr, map);
  423. __pthread_unlock (&__pthread_handles[i].h_lock);
  424. }
  425. }
  426. #endif
  427. static void pthread_initialize(void)
  428. {
  429. struct sigaction sa;
  430. sigset_t mask;
  431. /* If already done (e.g. by a constructor called earlier!), bail out */
  432. if (__pthread_initial_thread_bos != NULL) return;
  433. #ifdef TEST_FOR_COMPARE_AND_SWAP
  434. /* Test if compare-and-swap is available */
  435. __pthread_has_cas = compare_and_swap_is_available();
  436. #endif
  437. #ifdef FLOATING_STACKS
  438. /* We don't need to know the bottom of the stack. Give the pointer some
  439. value to signal that initialization happened. */
  440. __pthread_initial_thread_bos = (void *) -1l;
  441. #else
  442. /* Determine stack size limits . */
  443. __pthread_init_max_stacksize ();
  444. # ifdef _STACK_GROWS_UP
  445. /* The initial thread already has all the stack it needs */
  446. __pthread_initial_thread_bos = (char *)
  447. ((long)CURRENT_STACK_FRAME &~ (STACK_SIZE - 1));
  448. # else
  449. /* For the initial stack, reserve at least STACK_SIZE bytes of stack
  450. below the current stack address, and align that on a
  451. STACK_SIZE boundary. */
  452. __pthread_initial_thread_bos =
  453. (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  454. # endif
  455. #endif
  456. #ifdef USE_TLS
  457. /* Update the descriptor for the initial thread. */
  458. THREAD_SETMEM (((pthread_descr) NULL), p_pid, __getpid());
  459. # ifndef HAVE___THREAD
  460. /* Likewise for the resolver state _res. */
  461. THREAD_SETMEM (((pthread_descr) NULL), p_resp, &_res);
  462. # endif
  463. #else
  464. /* Update the descriptor for the initial thread. */
  465. __pthread_initial_thread.p_pid = __getpid();
  466. /* Likewise for the resolver state _res. */
  467. __pthread_initial_thread.p_resp = &_res;
  468. #endif
  469. #if !__ASSUME_REALTIME_SIGNALS
  470. /* Initialize real-time signals. */
  471. init_rtsigs ();
  472. #endif
  473. /* Setup signal handlers for the initial thread.
  474. Since signal handlers are shared between threads, these settings
  475. will be inherited by all other threads. */
  476. sa.sa_handler = pthread_handle_sigrestart;
  477. sigemptyset(&sa.sa_mask);
  478. sa.sa_flags = 0;
  479. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  480. sa.sa_handler = pthread_handle_sigcancel;
  481. sigaddset(&sa.sa_mask, __pthread_sig_restart);
  482. // sa.sa_flags = 0;
  483. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  484. if (__pthread_sig_debug > 0) {
  485. sa.sa_handler = pthread_handle_sigdebug;
  486. sigemptyset(&sa.sa_mask);
  487. // sa.sa_flags = 0;
  488. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  489. }
  490. /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  491. sigemptyset(&mask);
  492. sigaddset(&mask, __pthread_sig_restart);
  493. sigprocmask(SIG_BLOCK, &mask, NULL);
  494. /* And unblock __pthread_sig_cancel if it has been blocked. */
  495. sigdelset(&mask, __pthread_sig_restart);
  496. sigaddset(&mask, __pthread_sig_cancel);
  497. sigprocmask(SIG_UNBLOCK, &mask, NULL);
  498. /* Register an exit function to kill all other threads. */
  499. /* Do it early so that user-registered atexit functions are called
  500. before pthread_*exit_process. */
  501. #ifndef HAVE_Z_NODELETE
  502. if (__builtin_expect (&__dso_handle != NULL, 1))
  503. __cxa_atexit ((void (*) (void *)) pthread_atexit_process, NULL,
  504. __dso_handle);
  505. else
  506. #endif
  507. __on_exit (pthread_onexit_process, NULL);
  508. /* How many processors. */
  509. __pthread_smp_kernel = is_smp_system ();
  510. #ifdef SHARED
  511. /* Transfer the old value from the dynamic linker's internal location. */
  512. *__libc_dl_error_tsd () = *(*GL(dl_error_catch_tsd)) ();
  513. GL(dl_error_catch_tsd) = &__libc_dl_error_tsd;
  514. /* Make __rtld_lock_{,un}lock_recursive use pthread_mutex_{,un}lock,
  515. keep the lock count from the ld.so implementation. */
  516. GL(dl_rtld_lock_recursive) = (void *) __pthread_mutex_lock;
  517. GL(dl_rtld_unlock_recursive) = (void *) __pthread_mutex_unlock;
  518. unsigned int rtld_lock_count = GL(dl_load_lock).mutex.__m_count;
  519. GL(dl_load_lock).mutex.__m_count = 0;
  520. while (rtld_lock_count-- > 0)
  521. __pthread_mutex_lock (&GL(dl_load_lock).mutex);
  522. #endif
  523. #ifdef USE_TLS
  524. GL(dl_init_static_tls) = &__pthread_init_static_tls;
  525. #endif
  526. }
  527. void __pthread_initialize(void)
  528. {
  529. pthread_initialize();
  530. }
  531. int __pthread_initialize_manager(void)
  532. {
  533. int manager_pipe[2];
  534. int pid;
  535. struct pthread_request request;
  536. int report_events;
  537. pthread_descr mgr;
  538. #ifdef USE_TLS
  539. tcbhead_t *tcbp;
  540. #endif
  541. __pthread_multiple_threads = 1;
  542. #if TLS_MULTIPLE_THREADS_IN_TCB || !defined USE_TLS || !TLS_DTV_AT_TP
  543. __pthread_main_thread->p_multiple_threads = 1;
  544. #endif
  545. *__libc_multiple_threads_ptr = 1;
  546. #ifndef HAVE_Z_NODELETE
  547. if (__builtin_expect (&__dso_handle != NULL, 1))
  548. __cxa_atexit ((void (*) (void *)) pthread_atexit_retcode, NULL,
  549. __dso_handle);
  550. #endif
  551. if (__pthread_max_stacksize == 0)
  552. __pthread_init_max_stacksize ();
  553. /* If basic initialization not done yet (e.g. we're called from a
  554. constructor run before our constructor), do it now */
  555. if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  556. /* Setup stack for thread manager */
  557. __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  558. if (__pthread_manager_thread_bos == NULL) return -1;
  559. __pthread_manager_thread_tos =
  560. __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
  561. /* Setup pipe to communicate with thread manager */
  562. if (pipe(manager_pipe) == -1) {
  563. free(__pthread_manager_thread_bos);
  564. return -1;
  565. }
  566. #ifdef USE_TLS
  567. /* Allocate memory for the thread descriptor and the dtv. */
  568. tcbp = _dl_allocate_tls (NULL);
  569. if (tcbp == NULL) {
  570. free(__pthread_manager_thread_bos);
  571. close_not_cancel(manager_pipe[0]);
  572. close_not_cancel(manager_pipe[1]);
  573. return -1;
  574. }
  575. # if TLS_TCB_AT_TP
  576. mgr = (pthread_descr) tcbp;
  577. # elif TLS_DTV_AT_TP
  578. /* pthread_descr is located right below tcbhead_t which _dl_allocate_tls
  579. returns. */
  580. mgr = (pthread_descr) ((char *) tcbp - TLS_PRE_TCB_SIZE);
  581. # endif
  582. __pthread_handles[1].h_descr = manager_thread = mgr;
  583. /* Initialize the descriptor. */
  584. #if !defined USE_TLS || !TLS_DTV_AT_TP
  585. mgr->p_header.data.tcb = tcbp;
  586. mgr->p_header.data.self = mgr;
  587. mgr->p_header.data.multiple_threads = 1;
  588. #elif TLS_MULTIPLE_THREADS_IN_TCB
  589. mgr->p_multiple_threads = 1;
  590. #endif
  591. mgr->p_lock = &__pthread_handles[1].h_lock;
  592. # ifndef HAVE___THREAD
  593. mgr->p_errnop = &mgr->p_errno;
  594. # endif
  595. mgr->p_start_args = (struct pthread_start_args) PTHREAD_START_ARGS_INITIALIZER(__pthread_manager);
  596. mgr->p_nr = 1;
  597. # if __LT_SPINLOCK_INIT != 0
  598. self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
  599. # endif
  600. mgr->p_alloca_cutoff = PTHREAD_STACK_MIN / 4;
  601. #else
  602. mgr = &__pthread_manager_thread;
  603. #endif
  604. __pthread_manager_request = manager_pipe[1]; /* writing end */
  605. __pthread_manager_reader = manager_pipe[0]; /* reading end */
  606. /* Start the thread manager */
  607. pid = 0;
  608. #ifdef USE_TLS
  609. if (__linuxthreads_initial_report_events != 0)
  610. THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
  611. __linuxthreads_initial_report_events);
  612. report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
  613. #else
  614. if (__linuxthreads_initial_report_events != 0)
  615. __pthread_initial_thread.p_report_events
  616. = __linuxthreads_initial_report_events;
  617. report_events = __pthread_initial_thread.p_report_events;
  618. #endif
  619. if (__builtin_expect (report_events, 0))
  620. {
  621. /* It's a bit more complicated. We have to report the creation of
  622. the manager thread. */
  623. int idx = __td_eventword (TD_CREATE);
  624. uint32_t mask = __td_eventmask (TD_CREATE);
  625. uint32_t event_bits;
  626. #ifdef USE_TLS
  627. event_bits = THREAD_GETMEM_NC (((pthread_descr) NULL),
  628. p_eventbuf.eventmask.event_bits[idx]);
  629. #else
  630. event_bits = __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx];
  631. #endif
  632. if ((mask & (__pthread_threads_events.event_bits[idx] | event_bits))
  633. != 0)
  634. {
  635. __pthread_lock(mgr->p_lock, NULL);
  636. #ifdef NEED_SEPARATE_REGISTER_STACK
  637. pid = __clone2(__pthread_manager_event,
  638. (void **) __pthread_manager_thread_bos,
  639. THREAD_MANAGER_STACK_SIZE,
  640. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  641. mgr);
  642. #elif _STACK_GROWS_UP
  643. pid = __clone(__pthread_manager_event,
  644. (void **) __pthread_manager_thread_bos,
  645. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  646. mgr);
  647. #else
  648. pid = __clone(__pthread_manager_event,
  649. (void **) __pthread_manager_thread_tos,
  650. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  651. mgr);
  652. #endif
  653. if (pid != -1)
  654. {
  655. /* Now fill in the information about the new thread in
  656. the newly created thread's data structure. We cannot let
  657. the new thread do this since we don't know whether it was
  658. already scheduled when we send the event. */
  659. mgr->p_eventbuf.eventdata = mgr;
  660. mgr->p_eventbuf.eventnum = TD_CREATE;
  661. __pthread_last_event = mgr;
  662. mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
  663. mgr->p_pid = pid;
  664. /* Now call the function which signals the event. */
  665. __linuxthreads_create_event ();
  666. }
  667. /* Now restart the thread. */
  668. __pthread_unlock(mgr->p_lock);
  669. }
  670. }
  671. if (__builtin_expect (pid, 0) == 0)
  672. {
  673. #ifdef NEED_SEPARATE_REGISTER_STACK
  674. pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
  675. THREAD_MANAGER_STACK_SIZE,
  676. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  677. #elif _STACK_GROWS_UP
  678. pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_bos,
  679. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  680. #else
  681. pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
  682. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  683. #endif
  684. }
  685. if (__builtin_expect (pid, 0) == -1) {
  686. #ifdef USE_TLS
  687. _dl_deallocate_tls (tcbp, true);
  688. #endif
  689. free(__pthread_manager_thread_bos);
  690. close_not_cancel(manager_pipe[0]);
  691. close_not_cancel(manager_pipe[1]);
  692. return -1;
  693. }
  694. mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
  695. mgr->p_pid = pid;
  696. /* Make gdb aware of new thread manager */
  697. if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
  698. {
  699. raise(__pthread_sig_debug);
  700. /* We suspend ourself and gdb will wake us up when it is
  701. ready to handle us. */
  702. __pthread_wait_for_restart_signal(thread_self());
  703. }
  704. /* Synchronize debugging of the thread manager */
  705. request.req_kind = REQ_DEBUG;
  706. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  707. (char *) &request, sizeof(request)));
  708. return 0;
  709. }
  710. /* Thread creation */
  711. int __pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  712. void * (*start_routine)(void *), void *arg)
  713. {
  714. pthread_descr self = thread_self();
  715. struct pthread_request request;
  716. int retval;
  717. if (__builtin_expect (__pthread_manager_request, 0) < 0) {
  718. if (__pthread_initialize_manager() < 0) return EAGAIN;
  719. }
  720. request.req_thread = self;
  721. request.req_kind = REQ_CREATE;
  722. request.req_args.create.attr = attr;
  723. request.req_args.create.fn = start_routine;
  724. request.req_args.create.arg = arg;
  725. sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
  726. &request.req_args.create.mask);
  727. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  728. (char *) &request, sizeof(request)));
  729. suspend(self);
  730. retval = THREAD_GETMEM(self, p_retcode);
  731. if (__builtin_expect (retval, 0) == 0)
  732. *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  733. return retval;
  734. }
  735. strong_alias (__pthread_create, pthread_create)
  736. /* Simple operations on thread identifiers */
  737. pthread_descr __pthread_thread_self(void)
  738. {
  739. return thread_self();
  740. }
  741. pthread_t __pthread_self(void)
  742. {
  743. pthread_descr self = thread_self();
  744. return THREAD_GETMEM(self, p_tid);
  745. }
  746. strong_alias (__pthread_self, pthread_self);
  747. int __pthread_equal(pthread_t thread1, pthread_t thread2)
  748. {
  749. return thread1 == thread2;
  750. }
  751. strong_alias (__pthread_equal, pthread_equal);
  752. /* Helper function for thread_self in the case of user-provided stacks */
  753. #ifndef THREAD_SELF
  754. pthread_descr __pthread_find_self(void)
  755. {
  756. char * sp = CURRENT_STACK_FRAME;
  757. pthread_handle h;
  758. /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
  759. the manager threads handled specially in thread_self(), so start at 2 */
  760. h = __pthread_handles + 2;
  761. # ifdef _STACK_GROWS_UP
  762. while (! (sp >= (char *) h->h_descr && sp < (char *) h->h_descr->p_guardaddr)) h++;
  763. # else
  764. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
  765. # endif
  766. return h->h_descr;
  767. }
  768. #else
  769. pthread_descr __pthread_self_stack(void)
  770. {
  771. char *sp = CURRENT_STACK_FRAME;
  772. pthread_handle h;
  773. if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
  774. return manager_thread;
  775. h = __pthread_handles + 2;
  776. # ifdef USE_TLS
  777. # ifdef _STACK_GROWS_UP
  778. while (h->h_descr == NULL
  779. || ! (sp >= h->h_descr->p_stackaddr && sp < h->h_descr->p_guardaddr))
  780. h++;
  781. # else
  782. while (h->h_descr == NULL
  783. || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
  784. h++;
  785. # endif
  786. # else
  787. # ifdef _STACK_GROWS_UP
  788. while (! (sp >= (char *) h->h_descr && sp < h->h_descr->p_guardaddr))
  789. h++;
  790. # else
  791. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
  792. h++;
  793. # endif
  794. # endif
  795. return h->h_descr;
  796. }
  797. #endif
  798. /* Thread scheduling */
  799. int __pthread_setschedparam(pthread_t thread, int policy,
  800. const struct sched_param *param)
  801. {
  802. pthread_handle handle = thread_handle(thread);
  803. pthread_descr th;
  804. __pthread_lock(&handle->h_lock, NULL);
  805. if (__builtin_expect (invalid_handle(handle, thread), 0)) {
  806. __pthread_unlock(&handle->h_lock);
  807. return ESRCH;
  808. }
  809. th = handle->h_descr;
  810. if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
  811. 0)) {
  812. __pthread_unlock(&handle->h_lock);
  813. return errno;
  814. }
  815. th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  816. __pthread_unlock(&handle->h_lock);
  817. if (__pthread_manager_request >= 0)
  818. __pthread_manager_adjust_prio(th->p_priority);
  819. return 0;
  820. }
  821. strong_alias (__pthread_setschedparam, pthread_setschedparam);
  822. int __pthread_getschedparam(pthread_t thread, int *policy,
  823. struct sched_param *param)
  824. {
  825. pthread_handle handle = thread_handle(thread);
  826. int pid, pol;
  827. __pthread_lock(&handle->h_lock, NULL);
  828. if (__builtin_expect (invalid_handle(handle, thread), 0)) {
  829. __pthread_unlock(&handle->h_lock);
  830. return ESRCH;
  831. }
  832. pid = handle->h_descr->p_pid;
  833. __pthread_unlock(&handle->h_lock);
  834. pol = __sched_getscheduler(pid);
  835. if (__builtin_expect (pol, 0) == -1) return errno;
  836. if (__sched_getparam(pid, param) == -1) return errno;
  837. *policy = pol;
  838. return 0;
  839. }
  840. strong_alias (__pthread_getschedparam, pthread_getschedparam);
  841. int __pthread_yield (void)
  842. {
  843. /* For now this is equivalent with the POSIX call. */
  844. return sched_yield ();
  845. }
  846. weak_alias (__pthread_yield, pthread_yield)
  847. /* Process-wide exit() request */
  848. static void pthread_onexit_process(int retcode, void *arg)
  849. {
  850. if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
  851. struct pthread_request request;
  852. pthread_descr self = thread_self();
  853. request.req_thread = self;
  854. request.req_kind = REQ_PROCESS_EXIT;
  855. request.req_args.exit.code = retcode;
  856. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  857. (char *) &request, sizeof(request)));
  858. suspend(self);
  859. /* Main thread should accumulate times for thread manager and its
  860. children, so that timings for main thread account for all threads. */
  861. if (self == __pthread_main_thread)
  862. {
  863. #ifdef USE_TLS
  864. waitpid(manager_thread->p_pid, NULL, __WCLONE);
  865. #else
  866. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  867. #endif
  868. /* Since all threads have been asynchronously terminated
  869. (possibly holding locks), free cannot be used any more.
  870. For mtrace, we'd like to print something though. */
  871. /* #ifdef USE_TLS
  872. tcbhead_t *tcbp = (tcbhead_t *) manager_thread;
  873. # if TLS_DTV_AT_TP
  874. tcbp = (tcbhead_t) ((char *) tcbp + TLS_PRE_TCB_SIZE);
  875. # endif
  876. _dl_deallocate_tls (tcbp, true);
  877. #endif
  878. free (__pthread_manager_thread_bos); */
  879. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  880. }
  881. }
  882. }
  883. #ifndef HAVE_Z_NODELETE
  884. static int __pthread_atexit_retcode;
  885. static void pthread_atexit_process(void *arg, int retcode)
  886. {
  887. pthread_onexit_process (retcode ?: __pthread_atexit_retcode, arg);
  888. }
  889. static void pthread_atexit_retcode(void *arg, int retcode)
  890. {
  891. __pthread_atexit_retcode = retcode;
  892. }
  893. #endif
  894. /* The handler for the RESTART signal just records the signal received
  895. in the thread descriptor, and optionally performs a siglongjmp
  896. (for pthread_cond_timedwait). */
  897. static void pthread_handle_sigrestart(int sig)
  898. {
  899. pthread_descr self = check_thread_self();
  900. THREAD_SETMEM(self, p_signal, sig);
  901. if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
  902. siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
  903. }
  904. /* The handler for the CANCEL signal checks for cancellation
  905. (in asynchronous mode), for process-wide exit and exec requests.
  906. For the thread manager thread, redirect the signal to
  907. __pthread_manager_sighandler. */
  908. static void pthread_handle_sigcancel(int sig)
  909. {
  910. pthread_descr self = check_thread_self();
  911. sigjmp_buf * jmpbuf;
  912. if (self == manager_thread)
  913. {
  914. __pthread_manager_sighandler(sig);
  915. return;
  916. }
  917. if (__builtin_expect (__pthread_exit_requested, 0)) {
  918. /* Main thread should accumulate times for thread manager and its
  919. children, so that timings for main thread account for all threads. */
  920. if (self == __pthread_main_thread) {
  921. #ifdef USE_TLS
  922. waitpid(manager_thread->p_pid, NULL, __WCLONE);
  923. #else
  924. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  925. #endif
  926. }
  927. _exit(__pthread_exit_code);
  928. }
  929. if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
  930. && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
  931. if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
  932. __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
  933. jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
  934. if (jmpbuf != NULL) {
  935. THREAD_SETMEM(self, p_cancel_jmp, NULL);
  936. siglongjmp(*jmpbuf, 1);
  937. }
  938. }
  939. }
  940. /* Handler for the DEBUG signal.
  941. The debugging strategy is as follows:
  942. On reception of a REQ_DEBUG request (sent by new threads created to
  943. the thread manager under debugging mode), the thread manager throws
  944. __pthread_sig_debug to itself. The debugger (if active) intercepts
  945. this signal, takes into account new threads and continue execution
  946. of the thread manager by propagating the signal because it doesn't
  947. know what it is specifically done for. In the current implementation,
  948. the thread manager simply discards it. */
  949. static void pthread_handle_sigdebug(int sig)
  950. {
  951. /* Nothing */
  952. }
  953. /* Reset the state of the thread machinery after a fork().
  954. Close the pipe used for requests and set the main thread to the forked
  955. thread.
  956. Notice that we can't free the stack segments, as the forked thread
  957. may hold pointers into them. */
  958. void __pthread_reset_main_thread(void)
  959. {
  960. pthread_descr self = thread_self();
  961. if (__pthread_manager_request != -1) {
  962. /* Free the thread manager stack */
  963. free(__pthread_manager_thread_bos);
  964. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  965. /* Close the two ends of the pipe */
  966. close_not_cancel(__pthread_manager_request);
  967. close_not_cancel(__pthread_manager_reader);
  968. __pthread_manager_request = __pthread_manager_reader = -1;
  969. }
  970. /* Update the pid of the main thread */
  971. THREAD_SETMEM(self, p_pid, __getpid());
  972. /* Make the forked thread the main thread */
  973. __pthread_main_thread = self;
  974. THREAD_SETMEM(self, p_nextlive, self);
  975. THREAD_SETMEM(self, p_prevlive, self);
  976. #if !(USE_TLS && HAVE___THREAD)
  977. /* Now this thread modifies the global variables. */
  978. THREAD_SETMEM(self, p_errnop, &_errno);
  979. THREAD_SETMEM(self, p_h_errnop, &_h_errno);
  980. THREAD_SETMEM(self, p_resp, &_res);
  981. #endif
  982. #ifndef FLOATING_STACKS
  983. /* This is to undo the setrlimit call in __pthread_init_max_stacksize.
  984. XXX This can be wrong if the user set the limit during the run. */
  985. {
  986. struct rlimit limit;
  987. if (getrlimit (RLIMIT_STACK, &limit) == 0
  988. && limit.rlim_cur != limit.rlim_max)
  989. {
  990. limit.rlim_cur = limit.rlim_max;
  991. setrlimit(RLIMIT_STACK, &limit);
  992. }
  993. }
  994. #endif
  995. }
  996. /* Process-wide exec() request */
  997. void __pthread_kill_other_threads_np(void)
  998. {
  999. struct sigaction sa;
  1000. /* Terminate all other threads and thread manager */
  1001. pthread_onexit_process(0, NULL);
  1002. /* Make current thread the main thread in case the calling thread
  1003. changes its mind, does not exec(), and creates new threads instead. */
  1004. __pthread_reset_main_thread();
  1005. /* Reset the signal handlers behaviour for the signals the
  1006. implementation uses since this would be passed to the new
  1007. process. */
  1008. sigemptyset(&sa.sa_mask);
  1009. sa.sa_flags = 0;
  1010. sa.sa_handler = SIG_DFL;
  1011. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  1012. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  1013. if (__pthread_sig_debug > 0)
  1014. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  1015. }
  1016. weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
  1017. /* Concurrency symbol level. */
  1018. static int current_level;
  1019. int __pthread_setconcurrency(int level)
  1020. {
  1021. /* We don't do anything unless we have found a useful interpretation. */
  1022. current_level = level;
  1023. return 0;
  1024. }
  1025. weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
  1026. int __pthread_getconcurrency(void)
  1027. {
  1028. return current_level;
  1029. }
  1030. weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
  1031. /* Primitives for controlling thread execution */
  1032. void __pthread_wait_for_restart_signal(pthread_descr self)
  1033. {
  1034. sigset_t mask;
  1035. sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  1036. sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  1037. THREAD_SETMEM(self, p_signal, 0);
  1038. do {
  1039. __pthread_sigsuspend(&mask); /* Wait for signal. Must not be a
  1040. cancellation point. */
  1041. } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
  1042. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  1043. }
  1044. #if !__ASSUME_REALTIME_SIGNALS
  1045. /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
  1046. signals.
  1047. On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
  1048. Since the restart signal does not queue, we use an atomic counter to create
  1049. queuing semantics. This is needed to resolve a rare race condition in
  1050. pthread_cond_timedwait_relative. */
  1051. void __pthread_restart_old(pthread_descr th)
  1052. {
  1053. if (atomic_increment(&th->p_resume_count) == -1)
  1054. kill(th->p_pid, __pthread_sig_restart);
  1055. }
  1056. void __pthread_suspend_old(pthread_descr self)
  1057. {
  1058. if (atomic_decrement(&self->p_resume_count) <= 0)
  1059. __pthread_wait_for_restart_signal(self);
  1060. }
  1061. int
  1062. __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
  1063. {
  1064. sigset_t unblock, initial_mask;
  1065. int was_signalled = 0;
  1066. sigjmp_buf jmpbuf;
  1067. if (atomic_decrement(&self->p_resume_count) == 0) {
  1068. /* Set up a longjmp handler for the restart signal, unblock
  1069. the signal and sleep. */
  1070. if (sigsetjmp(jmpbuf, 1) == 0) {
  1071. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  1072. THREAD_SETMEM(self, p_signal, 0);
  1073. /* Unblock the restart signal */
  1074. sigemptyset(&unblock);
  1075. sigaddset(&unblock, __pthread_sig_restart);
  1076. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  1077. while (1) {
  1078. struct timeval now;
  1079. struct timespec reltime;
  1080. /* Compute a time offset relative to now. */
  1081. __gettimeofday (&now, NULL);
  1082. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  1083. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  1084. if (reltime.tv_nsec < 0) {
  1085. reltime.tv_nsec += 1000000000;
  1086. reltime.tv_sec -= 1;
  1087. }
  1088. /* Sleep for the required duration. If woken by a signal,
  1089. resume waiting as required by Single Unix Specification. */
  1090. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  1091. break;
  1092. }
  1093. /* Block the restart signal again */
  1094. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  1095. was_signalled = 0;
  1096. } else {
  1097. was_signalled = 1;
  1098. }
  1099. THREAD_SETMEM(self, p_signal_jmp, NULL);
  1100. }
  1101. /* Now was_signalled is true if we exited the above code
  1102. due to the delivery of a restart signal. In that case,
  1103. we know we have been dequeued and resumed and that the
  1104. resume count is balanced. Otherwise, there are some
  1105. cases to consider. First, try to bump up the resume count
  1106. back to zero. If it goes to 1, it means restart() was
  1107. invoked on this thread. The signal must be consumed
  1108. and the count bumped down and everything is cool. We
  1109. can return a 1 to the caller.
  1110. Otherwise, no restart was delivered yet, so a potential
  1111. race exists; we return a 0 to the caller which must deal
  1112. with this race in an appropriate way; for example by
  1113. atomically removing the thread from consideration for a
  1114. wakeup---if such a thing fails, it means a restart is
  1115. being delivered. */
  1116. if (!was_signalled) {
  1117. if (atomic_increment(&self->p_resume_count) != -1) {
  1118. __pthread_wait_for_restart_signal(self);
  1119. atomic_decrement(&self->p_resume_count); /* should be zero now! */
  1120. /* woke spontaneously and consumed restart signal */
  1121. return 1;
  1122. }
  1123. /* woke spontaneously but did not consume restart---caller must resolve */
  1124. return 0;
  1125. }
  1126. /* woken due to restart signal */
  1127. return 1;
  1128. }
  1129. #endif /* __ASSUME_REALTIME_SIGNALS */
  1130. void __pthread_restart_new(pthread_descr th)
  1131. {
  1132. /* The barrier is proabably not needed, in which case it still documents
  1133. our assumptions. The intent is to commit previous writes to shared
  1134. memory so the woken thread will have a consistent view. Complementary
  1135. read barriers are present to the suspend functions. */
  1136. WRITE_MEMORY_BARRIER();
  1137. kill(th->p_pid, __pthread_sig_restart);
  1138. }
  1139. /* There is no __pthread_suspend_new because it would just
  1140. be a wasteful wrapper for __pthread_wait_for_restart_signal */
  1141. int
  1142. __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
  1143. {
  1144. sigset_t unblock, initial_mask;
  1145. int was_signalled = 0;
  1146. sigjmp_buf jmpbuf;
  1147. if (sigsetjmp(jmpbuf, 1) == 0) {
  1148. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  1149. THREAD_SETMEM(self, p_signal, 0);
  1150. /* Unblock the restart signal */
  1151. sigemptyset(&unblock);
  1152. sigaddset(&unblock, __pthread_sig_restart);
  1153. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  1154. while (1) {
  1155. struct timeval now;
  1156. struct timespec reltime;
  1157. /* Compute a time offset relative to now. */
  1158. __gettimeofday (&now, NULL);
  1159. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  1160. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  1161. if (reltime.tv_nsec < 0) {
  1162. reltime.tv_nsec += 1000000000;
  1163. reltime.tv_sec -= 1;
  1164. }
  1165. /* Sleep for the required duration. If woken by a signal,
  1166. resume waiting as required by Single Unix Specification. */
  1167. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  1168. break;
  1169. }
  1170. /* Block the restart signal again */
  1171. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  1172. was_signalled = 0;
  1173. } else {
  1174. was_signalled = 1;
  1175. }
  1176. THREAD_SETMEM(self, p_signal_jmp, NULL);
  1177. /* Now was_signalled is true if we exited the above code
  1178. due to the delivery of a restart signal. In that case,
  1179. everything is cool. We have been removed from whatever
  1180. we were waiting on by the other thread, and consumed its signal.
  1181. Otherwise we this thread woke up spontaneously, or due to a signal other
  1182. than restart. This is an ambiguous case that must be resolved by
  1183. the caller; the thread is still eligible for a restart wakeup
  1184. so there is a race. */
  1185. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  1186. return was_signalled;
  1187. }
  1188. /* Debugging aid */
  1189. #ifdef DEBUG
  1190. #include <stdarg.h>
  1191. void __pthread_message(const char * fmt, ...)
  1192. {
  1193. char buffer[1024];
  1194. va_list args;
  1195. sprintf(buffer, "%05d : ", __getpid());
  1196. va_start(args, fmt);
  1197. vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  1198. va_end(args);
  1199. TEMP_FAILURE_RETRY(write_not_cancel(2, buffer, strlen(buffer)));
  1200. }
  1201. #endif