allocatestack.c 32 KB

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