allocatestack.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /* Copyright (C) 2002-2007, 2009 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <signal.h>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <sys/mman.h>
  22. #include <sys/param.h>
  23. #include <tls.h>
  24. #include <lowlevellock.h>
  25. #include <link.h>
  26. #include <bits/kernel-features.h>
  27. #ifndef NEED_SEPARATE_REGISTER_STACK
  28. /* Most architectures have exactly one stack pointer. Some have more. */
  29. # define STACK_VARIABLES void *stackaddr = NULL
  30. /* How to pass the values to the 'create_thread' function. */
  31. # define STACK_VARIABLES_ARGS stackaddr
  32. /* How to declare function which gets there parameters. */
  33. # define STACK_VARIABLES_PARMS void *stackaddr
  34. /* How to declare allocate_stack. */
  35. # define ALLOCATE_STACK_PARMS void **stack
  36. /* This is how the function is called. We do it this way to allow
  37. other variants of the function to have more parameters. */
  38. # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
  39. #else
  40. /* We need two stacks. The kernel will place them but we have to tell
  41. the kernel about the size of the reserved address space. */
  42. # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
  43. /* How to pass the values to the 'create_thread' function. */
  44. # define STACK_VARIABLES_ARGS stackaddr, stacksize
  45. /* How to declare function which gets there parameters. */
  46. # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
  47. /* How to declare allocate_stack. */
  48. # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
  49. /* This is how the function is called. We do it this way to allow
  50. other variants of the function to have more parameters. */
  51. # define ALLOCATE_STACK(attr, pd) \
  52. allocate_stack (attr, pd, &stackaddr, &stacksize)
  53. #endif
  54. /* Default alignment of stack. */
  55. #ifndef STACK_ALIGN
  56. # define STACK_ALIGN __alignof__ (long double)
  57. #endif
  58. /* Default value for minimal stack size after allocating thread
  59. descriptor and guard. */
  60. #ifndef MINIMAL_REST_STACK
  61. # define MINIMAL_REST_STACK 4096
  62. #endif
  63. /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
  64. a stack. Use it when possible. */
  65. #ifndef MAP_STACK
  66. # define MAP_STACK 0
  67. #endif
  68. /* This yields the pointer that TLS support code calls the thread pointer. */
  69. #if defined(TLS_TCB_AT_TP)
  70. # define TLS_TPADJ(pd) (pd)
  71. #elif defined(TLS_DTV_AT_TP)
  72. # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
  73. #endif
  74. /* Cache handling for not-yet free stacks. */
  75. /*
  76. Maximum size in kB of cache. GNU libc default is 40MiB
  77. embedded systems don't have enough ram for big dirty stack caches,
  78. reduce it to 16MiB. 4 does not work, f.e. tst-kill4 segfaults.
  79. */
  80. static size_t stack_cache_maxsize = 16 * 1024 * 1024;
  81. static size_t stack_cache_actsize;
  82. /* Mutex protecting this variable. */
  83. static int stack_cache_lock = LLL_LOCK_INITIALIZER;
  84. /* List of queued stack frames. */
  85. static LIST_HEAD (stack_cache);
  86. /* List of the stacks in use. */
  87. static LIST_HEAD (stack_used);
  88. /* We need to record what list operations we are going to do so that,
  89. in case of an asynchronous interruption due to a fork() call, we
  90. can correct for the work. */
  91. static uintptr_t in_flight_stack;
  92. /* List of the threads with user provided stacks in use. No need to
  93. initialize this, since it's done in __pthread_initialize_minimal. */
  94. list_t __stack_user __attribute__ ((nocommon));
  95. hidden_data_def (__stack_user)
  96. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  97. /* Number of threads created. */
  98. static unsigned int nptl_ncreated;
  99. #endif
  100. /* Check whether the stack is still used or not. */
  101. #define FREE_P(descr) ((descr)->tid <= 0)
  102. static void
  103. stack_list_del (list_t *elem)
  104. {
  105. in_flight_stack = (uintptr_t) elem;
  106. atomic_write_barrier ();
  107. list_del (elem);
  108. atomic_write_barrier ();
  109. in_flight_stack = 0;
  110. }
  111. static void
  112. stack_list_add (list_t *elem, list_t *list)
  113. {
  114. in_flight_stack = (uintptr_t) elem | 1;
  115. atomic_write_barrier ();
  116. list_add (elem, list);
  117. atomic_write_barrier ();
  118. in_flight_stack = 0;
  119. }
  120. /* We create a double linked list of all cache entries. Double linked
  121. because this allows removing entries from the end. */
  122. /* Get a stack frame from the cache. We have to match by size since
  123. some blocks might be too small or far too large. */
  124. static struct pthread *
  125. get_cached_stack (size_t *sizep, void **memp)
  126. {
  127. size_t size = *sizep;
  128. struct pthread *result = NULL;
  129. list_t *entry;
  130. lll_lock (stack_cache_lock, LLL_PRIVATE);
  131. /* Search the cache for a matching entry. We search for the
  132. smallest stack which has at least the required size. Note that
  133. in normal situations the size of all allocated stacks is the
  134. same. As the very least there are only a few different sizes.
  135. Therefore this loop will exit early most of the time with an
  136. exact match. */
  137. list_for_each (entry, &stack_cache)
  138. {
  139. struct pthread *curr;
  140. curr = list_entry (entry, struct pthread, list);
  141. if (FREE_P (curr) && curr->stackblock_size >= size)
  142. {
  143. if (curr->stackblock_size == size)
  144. {
  145. result = curr;
  146. break;
  147. }
  148. if (result == NULL
  149. || result->stackblock_size > curr->stackblock_size)
  150. result = curr;
  151. }
  152. }
  153. if (__builtin_expect (result == NULL, 0)
  154. /* Make sure the size difference is not too excessive. In that
  155. case we do not use the block. */
  156. || __builtin_expect (result->stackblock_size > 4 * size, 0))
  157. {
  158. /* Release the lock. */
  159. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  160. return NULL;
  161. }
  162. /* Dequeue the entry. */
  163. stack_list_del (&result->list);
  164. /* And add to the list of stacks in use. */
  165. stack_list_add (&result->list, &stack_used);
  166. /* And decrease the cache size. */
  167. stack_cache_actsize -= result->stackblock_size;
  168. /* Release the lock early. */
  169. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  170. /* Report size and location of the stack to the caller. */
  171. *sizep = result->stackblock_size;
  172. *memp = result->stackblock;
  173. /* Cancellation handling is back to the default. */
  174. result->cancelhandling = 0;
  175. result->cleanup = NULL;
  176. /* No pending event. */
  177. result->nextevent = NULL;
  178. /* Clear the DTV. */
  179. dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
  180. memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
  181. /* Re-initialize the TLS. */
  182. _dl_allocate_tls_init (TLS_TPADJ (result));
  183. return result;
  184. }
  185. /* Free stacks until cache size is lower than LIMIT. */
  186. void
  187. __free_stacks (size_t limit)
  188. {
  189. /* We reduce the size of the cache. Remove the last entries until
  190. the size is below the limit. */
  191. list_t *entry;
  192. list_t *prev;
  193. /* Search from the end of the list. */
  194. list_for_each_prev_safe (entry, prev, &stack_cache)
  195. {
  196. struct pthread *curr;
  197. curr = list_entry (entry, struct pthread, list);
  198. if (FREE_P (curr))
  199. {
  200. /* Unlink the block. */
  201. stack_list_del (entry);
  202. /* Account for the freed memory. */
  203. stack_cache_actsize -= curr->stackblock_size;
  204. /* Free the memory associated with the ELF TLS. */
  205. _dl_deallocate_tls (TLS_TPADJ (curr), false);
  206. /* Remove this block. This should never fail. If it does
  207. something is really wrong. */
  208. if (munmap (curr->stackblock, curr->stackblock_size) != 0)
  209. abort ();
  210. /* Maybe we have freed enough. */
  211. if (stack_cache_actsize <= limit)
  212. break;
  213. }
  214. }
  215. }
  216. /* Add a stack frame which is not used anymore to the stack. Must be
  217. called with the cache lock held. */
  218. static inline void
  219. __attribute ((always_inline))
  220. queue_stack (struct pthread *stack)
  221. {
  222. /* We unconditionally add the stack to the list. The memory may
  223. still be in use but it will not be reused until the kernel marks
  224. the stack as not used anymore. */
  225. stack_list_add (&stack->list, &stack_cache);
  226. stack_cache_actsize += stack->stackblock_size;
  227. if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
  228. __free_stacks (stack_cache_maxsize);
  229. }
  230. static int
  231. internal_function
  232. change_stack_perm (struct pthread *pd
  233. #ifdef NEED_SEPARATE_REGISTER_STACK
  234. , size_t pagemask
  235. #endif
  236. )
  237. {
  238. #ifdef NEED_SEPARATE_REGISTER_STACK
  239. void *stack = (pd->stackblock
  240. + (((((pd->stackblock_size - pd->guardsize) / 2)
  241. & pagemask) + pd->guardsize) & pagemask));
  242. size_t len = pd->stackblock + pd->stackblock_size - stack;
  243. #elif defined _STACK_GROWS_DOWN
  244. void *stack = pd->stackblock + pd->guardsize;
  245. size_t len = pd->stackblock_size - pd->guardsize;
  246. #elif defined _STACK_GROWS_UP
  247. void *stack = pd->stackblock;
  248. size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
  249. #else
  250. # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
  251. #endif
  252. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  253. return errno;
  254. return 0;
  255. }
  256. static int
  257. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  258. ALLOCATE_STACK_PARMS)
  259. {
  260. struct pthread *pd;
  261. size_t size;
  262. size_t pagesize_m1 = __getpagesize () - 1;
  263. void *stacktop;
  264. assert (attr != NULL);
  265. assert (powerof2 (pagesize_m1 + 1));
  266. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  267. /* Get the stack size from the attribute if it is set. Otherwise we
  268. use the default we determined at start time. */
  269. size = attr->stacksize ?: __default_stacksize;
  270. /* Get memory for the stack. */
  271. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  272. {
  273. uintptr_t adj;
  274. /* If the user also specified the size of the stack make sure it
  275. is large enough. */
  276. if (attr->stacksize != 0
  277. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  278. return EINVAL;
  279. /* Adjust stack size for alignment of the TLS block. */
  280. #if defined(TLS_TCB_AT_TP)
  281. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  282. & __static_tls_align_m1;
  283. assert (size > adj + TLS_TCB_SIZE);
  284. #elif defined(TLS_DTV_AT_TP)
  285. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  286. & __static_tls_align_m1;
  287. assert (size > adj);
  288. #endif
  289. /* The user provided some memory. Let's hope it matches the
  290. size... We do not allocate guard pages if the user provided
  291. the stack. It is the user's responsibility to do this if it
  292. is wanted. */
  293. #if defined(TLS_TCB_AT_TP)
  294. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  295. - TLS_TCB_SIZE - adj);
  296. #elif defined(TLS_DTV_AT_TP)
  297. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  298. - __static_tls_size - adj)
  299. - TLS_PRE_TCB_SIZE);
  300. #endif
  301. /* The user provided stack memory needs to be cleared. */
  302. memset (pd, '\0', sizeof (struct pthread));
  303. /* The first TSD block is included in the TCB. */
  304. pd->specific[0] = pd->specific_1stblock;
  305. /* Remember the stack-related values. */
  306. pd->stackblock = (char *) attr->stackaddr - size;
  307. pd->stackblock_size = size;
  308. /* This is a user-provided stack. It will not be queued in the
  309. stack cache nor will the memory (except the TLS memory) be freed. */
  310. pd->user_stack = true;
  311. /* This is at least the second thread. */
  312. pd->header.multiple_threads = 1;
  313. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  314. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  315. #endif
  316. #ifndef __ASSUME_PRIVATE_FUTEX
  317. /* The thread must know when private futexes are supported. */
  318. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  319. header.private_futex);
  320. #endif
  321. #ifdef NEED_DL_SYSINFO
  322. /* Copy the sysinfo value from the parent. */
  323. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  324. #endif
  325. /* The process ID is also the same as that of the caller. */
  326. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  327. /* Allocate the DTV for this thread. */
  328. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  329. {
  330. /* Something went wrong. */
  331. assert (errno == ENOMEM);
  332. return EAGAIN;
  333. }
  334. /* Prepare to modify global data. */
  335. lll_lock (stack_cache_lock, LLL_PRIVATE);
  336. /* And add to the list of stacks in use. */
  337. list_add (&pd->list, &__stack_user);
  338. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  339. }
  340. else
  341. {
  342. /* Allocate some anonymous memory. If possible use the cache. */
  343. size_t guardsize;
  344. size_t reqsize;
  345. void *mem = 0;
  346. const int prot = (PROT_READ | PROT_WRITE);
  347. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  348. /* Add one more page for stack coloring. Don't do it for stacks
  349. with 16 times pagesize or larger. This might just cause
  350. unnecessary misalignment. */
  351. if (size <= 16 * pagesize_m1)
  352. size += pagesize_m1 + 1;
  353. #endif
  354. /* Adjust the stack size for alignment. */
  355. size &= ~__static_tls_align_m1;
  356. assert (size != 0);
  357. /* Make sure the size of the stack is enough for the guard and
  358. eventually the thread descriptor. */
  359. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  360. if (__builtin_expect (size < ((guardsize + __static_tls_size
  361. + MINIMAL_REST_STACK + pagesize_m1)
  362. & ~pagesize_m1),
  363. 0))
  364. /* The stack is too small (or the guard too large). */
  365. return EINVAL;
  366. /* Try to get a stack from the cache. */
  367. reqsize = size;
  368. pd = get_cached_stack (&size, &mem);
  369. if (pd == NULL)
  370. {
  371. /* To avoid aliasing effects on a larger scale than pages we
  372. adjust the allocated stack size if necessary. This way
  373. allocations directly following each other will not have
  374. aliasing problems. */
  375. #if defined MULTI_PAGE_ALIASING && MULTI_PAGE_ALIASING != 0
  376. if ((size % MULTI_PAGE_ALIASING) == 0)
  377. size += pagesize_m1 + 1;
  378. #endif
  379. mem = mmap (NULL, size, prot,
  380. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  381. if (__builtin_expect (mem == MAP_FAILED, 0))
  382. {
  383. if (errno == ENOMEM)
  384. __set_errno (EAGAIN);
  385. return errno;
  386. }
  387. /* SIZE is guaranteed to be greater than zero.
  388. So we can never get a null pointer back from mmap. */
  389. assert (mem != NULL);
  390. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  391. /* Atomically increment NCREATED. */
  392. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  393. /* We chose the offset for coloring by incrementing it for
  394. every new thread by a fixed amount. The offset used
  395. module the page size. Even if coloring would be better
  396. relative to higher alignment values it makes no sense to
  397. do it since the mmap() interface does not allow us to
  398. specify any alignment for the returned memory block. */
  399. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  400. /* Make sure the coloring offsets does not disturb the alignment
  401. of the TCB and static TLS block. */
  402. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  403. coloring = (((coloring + __static_tls_align_m1)
  404. & ~(__static_tls_align_m1))
  405. & ~pagesize_m1);
  406. #else
  407. /* Unless specified we do not make any adjustments. */
  408. # define coloring 0
  409. #endif
  410. /* Place the thread descriptor at the end of the stack. */
  411. #if defined(TLS_TCB_AT_TP)
  412. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  413. #elif defined(TLS_DTV_AT_TP)
  414. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  415. - __static_tls_size)
  416. & ~__static_tls_align_m1)
  417. - TLS_PRE_TCB_SIZE);
  418. #endif
  419. /* Remember the stack-related values. */
  420. pd->stackblock = mem;
  421. pd->stackblock_size = size;
  422. /* We allocated the first block thread-specific data array.
  423. This address will not change for the lifetime of this
  424. descriptor. */
  425. pd->specific[0] = pd->specific_1stblock;
  426. /* This is at least the second thread. */
  427. pd->header.multiple_threads = 1;
  428. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  429. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  430. #endif
  431. #ifndef __ASSUME_PRIVATE_FUTEX
  432. /* The thread must know when private futexes are supported. */
  433. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  434. header.private_futex);
  435. #endif
  436. #ifdef NEED_DL_SYSINFO
  437. /* Copy the sysinfo value from the parent. */
  438. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  439. #endif
  440. /* The process ID is also the same as that of the caller. */
  441. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  442. /* Allocate the DTV for this thread. */
  443. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  444. {
  445. /* Something went wrong. */
  446. assert (errno == ENOMEM);
  447. /* Free the stack memory we just allocated. */
  448. (void) munmap (mem, size);
  449. return EAGAIN;
  450. }
  451. /* Prepare to modify global data. */
  452. lll_lock (stack_cache_lock, LLL_PRIVATE);
  453. /* And add to the list of stacks in use. */
  454. stack_list_add (&pd->list, &stack_used);
  455. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  456. /* Note that all of the stack and the thread descriptor is
  457. zeroed. This means we do not have to initialize fields
  458. with initial value zero. This is specifically true for
  459. the 'tid' field which is always set back to zero once the
  460. stack is not used anymore and for the 'guardsize' field
  461. which will be read next. */
  462. }
  463. /* Create or resize the guard area if necessary. */
  464. if (__builtin_expect (guardsize > pd->guardsize, 0))
  465. {
  466. #ifdef NEED_SEPARATE_REGISTER_STACK
  467. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  468. #elif defined _STACK_GROWS_DOWN
  469. char *guard = mem;
  470. #elif defined _STACK_GROWS_UP
  471. char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
  472. #endif
  473. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  474. {
  475. int err;
  476. mprot_error:
  477. err = errno;
  478. lll_lock (stack_cache_lock, LLL_PRIVATE);
  479. /* Remove the thread from the list. */
  480. stack_list_del (&pd->list);
  481. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  482. /* Get rid of the TLS block we allocated. */
  483. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  484. /* Free the stack memory regardless of whether the size
  485. of the cache is over the limit or not. If this piece
  486. of memory caused problems we better do not use it
  487. anymore. Uh, and we ignore possible errors. There
  488. is nothing we could do. */
  489. (void) munmap (mem, size);
  490. return err;
  491. }
  492. pd->guardsize = guardsize;
  493. }
  494. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  495. 0))
  496. {
  497. /* The old guard area is too large. */
  498. #ifdef NEED_SEPARATE_REGISTER_STACK
  499. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  500. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  501. if (oldguard < guard
  502. && mprotect (oldguard, guard - oldguard, prot) != 0)
  503. goto mprot_error;
  504. if (mprotect (guard + guardsize,
  505. oldguard + pd->guardsize - guard - guardsize,
  506. prot) != 0)
  507. goto mprot_error;
  508. #elif defined _STACK_GROWS_DOWN
  509. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  510. prot) != 0)
  511. goto mprot_error;
  512. #elif defined _STACK_GROWS_UP
  513. if (mprotect ((char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1),
  514. pd->guardsize - guardsize, prot) != 0)
  515. goto mprot_error;
  516. #endif
  517. pd->guardsize = guardsize;
  518. }
  519. /* The pthread_getattr_np() calls need to get passed the size
  520. requested in the attribute, regardless of how large the
  521. actually used guardsize is. */
  522. pd->reported_guardsize = guardsize;
  523. }
  524. /* Initialize the lock. We have to do this unconditionally since the
  525. stillborn thread could be canceled while the lock is taken. */
  526. pd->lock = LLL_LOCK_INITIALIZER;
  527. /* The robust mutex lists also need to be initialized
  528. unconditionally because the cleanup for the previous stack owner
  529. might have happened in the kernel. */
  530. pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
  531. - offsetof (pthread_mutex_t,
  532. __data.__list.__next));
  533. pd->robust_head.list_op_pending = NULL;
  534. #ifdef __PTHREAD_MUTEX_HAVE_PREV
  535. pd->robust_prev = &pd->robust_head;
  536. #endif
  537. pd->robust_head.list = &pd->robust_head;
  538. /* We place the thread descriptor at the end of the stack. */
  539. *pdp = pd;
  540. #if defined(TLS_TCB_AT_TP)
  541. /* The stack begins before the TCB and the static TLS block. */
  542. stacktop = ((char *) (pd + 1) - __static_tls_size);
  543. #elif defined(TLS_DTV_AT_TP)
  544. stacktop = (char *) (pd - 1);
  545. #endif
  546. #ifdef NEED_SEPARATE_REGISTER_STACK
  547. *stack = pd->stackblock;
  548. *stacksize = stacktop - *stack;
  549. #elif defined _STACK_GROWS_DOWN
  550. *stack = stacktop;
  551. #elif defined _STACK_GROWS_UP
  552. *stack = pd->stackblock;
  553. assert (*stack > 0);
  554. #endif
  555. return 0;
  556. }
  557. void
  558. internal_function
  559. __deallocate_stack (struct pthread *pd)
  560. {
  561. lll_lock (stack_cache_lock, LLL_PRIVATE);
  562. /* Remove the thread from the list of threads with user defined
  563. stacks. */
  564. stack_list_del (&pd->list);
  565. /* Not much to do. Just free the mmap()ed memory. Note that we do
  566. not reset the 'used' flag in the 'tid' field. This is done by
  567. the kernel. If no thread has been created yet this field is
  568. still zero. */
  569. if (__builtin_expect (! pd->user_stack, 1))
  570. (void) queue_stack (pd);
  571. else
  572. /* Free the memory associated with the ELF TLS. */
  573. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  574. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  575. }
  576. int
  577. internal_function
  578. __make_stacks_executable (void **stack_endp)
  579. {
  580. /* First the main thread's stack. */
  581. int err = EPERM;
  582. if (err != 0)
  583. return err;
  584. #ifdef NEED_SEPARATE_REGISTER_STACK
  585. const size_t pagemask = ~(__getpagesize () - 1);
  586. #endif
  587. lll_lock (stack_cache_lock, LLL_PRIVATE);
  588. list_t *runp;
  589. list_for_each (runp, &stack_used)
  590. {
  591. err = change_stack_perm (list_entry (runp, struct pthread, list)
  592. #ifdef NEED_SEPARATE_REGISTER_STACK
  593. , pagemask
  594. #endif
  595. );
  596. if (err != 0)
  597. break;
  598. }
  599. /* Also change the permission for the currently unused stacks. This
  600. might be wasted time but better spend it here than adding a check
  601. in the fast path. */
  602. if (err == 0)
  603. list_for_each (runp, &stack_cache)
  604. {
  605. err = change_stack_perm (list_entry (runp, struct pthread, list)
  606. #ifdef NEED_SEPARATE_REGISTER_STACK
  607. , pagemask
  608. #endif
  609. );
  610. if (err != 0)
  611. break;
  612. }
  613. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  614. return err;
  615. }
  616. /* In case of a fork() call the memory allocation in the child will be
  617. the same but only one thread is running. All stacks except that of
  618. the one running thread are not used anymore. We have to recycle
  619. them. */
  620. void
  621. __reclaim_stacks (void)
  622. {
  623. struct pthread *self = (struct pthread *) THREAD_SELF;
  624. /* No locking necessary. The caller is the only stack in use. But
  625. we have to be aware that we might have interrupted a list
  626. operation. */
  627. if (in_flight_stack != 0)
  628. {
  629. bool add_p = in_flight_stack & 1;
  630. list_t *elem = (list_t *)(uintptr_t)(in_flight_stack & ~UINTMAX_C (1));
  631. if (add_p)
  632. {
  633. /* We always add at the beginning of the list. So in this
  634. case we only need to check the beginning of these lists. */
  635. int check_list (list_t *l)
  636. {
  637. if (l->next->prev != l)
  638. {
  639. assert (l->next->prev == elem);
  640. elem->next = l->next;
  641. elem->prev = l;
  642. l->next = elem;
  643. return 1;
  644. }
  645. return 0;
  646. }
  647. if (check_list (&stack_used) == 0)
  648. (void) check_list (&stack_cache);
  649. }
  650. else
  651. {
  652. /* We can simply always replay the delete operation. */
  653. elem->next->prev = elem->prev;
  654. elem->prev->next = elem->next;
  655. }
  656. }
  657. /* Mark all stacks except the still running one as free. */
  658. list_t *runp;
  659. list_for_each (runp, &stack_used)
  660. {
  661. struct pthread *curp = list_entry (runp, struct pthread, list);
  662. if (curp != self)
  663. {
  664. /* This marks the stack as free. */
  665. curp->tid = 0;
  666. /* The PID field must be initialized for the new process. */
  667. curp->pid = self->pid;
  668. /* Account for the size of the stack. */
  669. stack_cache_actsize += curp->stackblock_size;
  670. if (curp->specific_used)
  671. {
  672. /* Clear the thread-specific data. */
  673. memset (curp->specific_1stblock, '\0',
  674. sizeof (curp->specific_1stblock));
  675. curp->specific_used = false;
  676. size_t cnt;
  677. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  678. if (curp->specific[cnt] != NULL)
  679. {
  680. memset (curp->specific[cnt], '\0',
  681. sizeof (curp->specific_1stblock));
  682. /* We have allocated the block which we do not
  683. free here so re-set the bit. */
  684. curp->specific_used = true;
  685. }
  686. }
  687. }
  688. }
  689. /* Reset the PIDs in any cached stacks. */
  690. list_for_each (runp, &stack_cache)
  691. {
  692. struct pthread *curp = list_entry (runp, struct pthread, list);
  693. curp->pid = self->pid;
  694. }
  695. /* Add the stack of all running threads to the cache. */
  696. list_splice (&stack_used, &stack_cache);
  697. /* Remove the entry for the current thread to from the cache list
  698. and add it to the list of running threads. Which of the two
  699. lists is decided by the user_stack flag. */
  700. stack_list_del (&self->list);
  701. /* Re-initialize the lists for all the threads. */
  702. INIT_LIST_HEAD (&stack_used);
  703. INIT_LIST_HEAD (&__stack_user);
  704. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  705. list_add (&self->list, &__stack_user);
  706. else
  707. list_add (&self->list, &stack_used);
  708. /* There is one thread running. */
  709. __nptl_nthreads = 1;
  710. in_flight_stack = 0;
  711. /* Initialize the lock. */
  712. stack_cache_lock = LLL_LOCK_INITIALIZER;
  713. }
  714. #if HP_TIMING_AVAIL
  715. # undef __find_thread_by_id
  716. /* Find a thread given the thread ID. */
  717. attribute_hidden
  718. struct pthread *
  719. __find_thread_by_id (pid_t tid)
  720. {
  721. struct pthread *result = NULL;
  722. lll_lock (stack_cache_lock, LLL_PRIVATE);
  723. /* Iterate over the list with system-allocated threads first. */
  724. list_t *runp;
  725. list_for_each (runp, &stack_used)
  726. {
  727. struct pthread *curp;
  728. curp = list_entry (runp, struct pthread, list);
  729. if (curp->tid == tid)
  730. {
  731. result = curp;
  732. goto out;
  733. }
  734. }
  735. /* Now the list with threads using user-allocated stacks. */
  736. list_for_each (runp, &__stack_user)
  737. {
  738. struct pthread *curp;
  739. curp = list_entry (runp, struct pthread, list);
  740. if (curp->tid == tid)
  741. {
  742. result = curp;
  743. goto out;
  744. }
  745. }
  746. out:
  747. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  748. return result;
  749. }
  750. #endif
  751. static void
  752. internal_function
  753. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  754. {
  755. int ch;
  756. /* Don't let the thread exit before the setxid handler runs. */
  757. t->setxid_futex = 0;
  758. do
  759. {
  760. ch = t->cancelhandling;
  761. /* If the thread is exiting right now, ignore it. */
  762. if ((ch & EXITING_BITMASK) != 0)
  763. return;
  764. }
  765. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  766. ch | SETXID_BITMASK, ch));
  767. }
  768. static void
  769. internal_function
  770. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  771. {
  772. int ch;
  773. do
  774. {
  775. ch = t->cancelhandling;
  776. if ((ch & SETXID_BITMASK) == 0)
  777. return;
  778. }
  779. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  780. ch & ~SETXID_BITMASK, ch));
  781. /* Release the futex just in case. */
  782. t->setxid_futex = 1;
  783. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  784. }
  785. static int
  786. internal_function
  787. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  788. {
  789. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  790. return 0;
  791. int val;
  792. INTERNAL_SYSCALL_DECL (err);
  793. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  794. t->tid, SIGSETXID);
  795. /* If this failed, it must have had not started yet or else exited. */
  796. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  797. {
  798. atomic_increment (&cmdp->cntr);
  799. return 1;
  800. }
  801. else
  802. return 0;
  803. }
  804. int
  805. attribute_hidden
  806. __nptl_setxid (struct xid_command *cmdp)
  807. {
  808. int signalled;
  809. int result;
  810. lll_lock (stack_cache_lock, LLL_PRIVATE);
  811. __xidcmd = cmdp;
  812. cmdp->cntr = 0;
  813. struct pthread *self = THREAD_SELF;
  814. /* Iterate over the list with system-allocated threads first. */
  815. list_t *runp;
  816. list_for_each (runp, &stack_used)
  817. {
  818. struct pthread *t = list_entry (runp, struct pthread, list);
  819. if (t == self)
  820. continue;
  821. setxid_mark_thread (cmdp, t);
  822. }
  823. /* Now the list with threads using user-allocated stacks. */
  824. list_for_each (runp, &__stack_user)
  825. {
  826. struct pthread *t = list_entry (runp, struct pthread, list);
  827. if (t == self)
  828. continue;
  829. setxid_mark_thread (cmdp, t);
  830. }
  831. /* Iterate until we don't succeed in signalling anyone. That means
  832. we have gotten all running threads, and their children will be
  833. automatically correct once started. */
  834. do
  835. {
  836. signalled = 0;
  837. list_for_each (runp, &stack_used)
  838. {
  839. struct pthread *t = list_entry (runp, struct pthread, list);
  840. if (t == self)
  841. continue;
  842. signalled += setxid_signal_thread (cmdp, t);
  843. }
  844. list_for_each (runp, &__stack_user)
  845. {
  846. struct pthread *t = list_entry (runp, struct pthread, list);
  847. if (t == self)
  848. continue;
  849. signalled += setxid_signal_thread (cmdp, t);
  850. }
  851. int cur = cmdp->cntr;
  852. while (cur != 0)
  853. {
  854. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  855. cur = cmdp->cntr;
  856. }
  857. }
  858. while (signalled != 0);
  859. /* Clean up flags, so that no thread blocks during exit waiting
  860. for a signal which will never come. */
  861. list_for_each (runp, &stack_used)
  862. {
  863. struct pthread *t = list_entry (runp, struct pthread, list);
  864. if (t == self)
  865. continue;
  866. setxid_unmark_thread (cmdp, t);
  867. }
  868. list_for_each (runp, &__stack_user)
  869. {
  870. struct pthread *t = list_entry (runp, struct pthread, list);
  871. if (t == self)
  872. continue;
  873. setxid_unmark_thread (cmdp, t);
  874. }
  875. /* This must be last, otherwise the current thread might not have
  876. permissions to send SIGSETXID syscall to the other threads. */
  877. INTERNAL_SYSCALL_DECL (err);
  878. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  879. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  880. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  881. {
  882. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  883. result = -1;
  884. }
  885. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  886. return result;
  887. }
  888. static inline void __attribute__((always_inline))
  889. init_one_static_tls (struct pthread *curp, struct link_map *map)
  890. {
  891. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  892. # if defined(TLS_TCB_AT_TP)
  893. void *dest = (char *) curp - map->l_tls_offset;
  894. # elif defined(TLS_DTV_AT_TP)
  895. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  896. # else
  897. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  898. # endif
  899. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  900. dtv[map->l_tls_modid].pointer.val = dest;
  901. dtv[map->l_tls_modid].pointer.is_static = true;
  902. /* Initialize the memory. */
  903. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  904. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  905. }
  906. void
  907. attribute_hidden
  908. __pthread_init_static_tls (struct link_map *map)
  909. {
  910. lll_lock (stack_cache_lock, LLL_PRIVATE);
  911. /* Iterate over the list with system-allocated threads first. */
  912. list_t *runp;
  913. list_for_each (runp, &stack_used)
  914. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  915. /* Now the list with threads using user-allocated stacks. */
  916. list_for_each (runp, &__stack_user)
  917. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  918. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  919. }
  920. void
  921. attribute_hidden
  922. __wait_lookup_done (void)
  923. {
  924. lll_lock (stack_cache_lock, LLL_PRIVATE);
  925. struct pthread *self = THREAD_SELF;
  926. /* Iterate over the list with system-allocated threads first. */
  927. list_t *runp;
  928. list_for_each (runp, &stack_used)
  929. {
  930. struct pthread *t = list_entry (runp, struct pthread, list);
  931. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  932. continue;
  933. int *const gscope_flagp = &t->header.gscope_flag;
  934. /* We have to wait until this thread is done with the global
  935. scope. First tell the thread that we are waiting and
  936. possibly have to be woken. */
  937. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  938. THREAD_GSCOPE_FLAG_WAIT,
  939. THREAD_GSCOPE_FLAG_USED))
  940. continue;
  941. do
  942. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  943. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  944. }
  945. /* Now the list with threads using user-allocated stacks. */
  946. list_for_each (runp, &__stack_user)
  947. {
  948. struct pthread *t = list_entry (runp, struct pthread, list);
  949. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  950. continue;
  951. int *const gscope_flagp = &t->header.gscope_flag;
  952. /* We have to wait until this thread is done with the global
  953. scope. First tell the thread that we are waiting and
  954. possibly have to be woken. */
  955. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  956. THREAD_GSCOPE_FLAG_WAIT,
  957. THREAD_GSCOPE_FLAG_USED))
  958. continue;
  959. do
  960. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  961. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  962. }
  963. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  964. }