allocatestack.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. /* Allocate the DTV for this thread. */
  326. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  327. {
  328. /* Something went wrong. */
  329. assert (errno == ENOMEM);
  330. return EAGAIN;
  331. }
  332. /* Prepare to modify global data. */
  333. lll_lock (stack_cache_lock, LLL_PRIVATE);
  334. /* And add to the list of stacks in use. */
  335. list_add (&pd->list, &__stack_user);
  336. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  337. }
  338. else
  339. {
  340. /* Allocate some anonymous memory. If possible use the cache. */
  341. size_t guardsize;
  342. size_t reqsize;
  343. void *mem = 0;
  344. const int prot = (PROT_READ | PROT_WRITE);
  345. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  346. /* Add one more page for stack coloring. Don't do it for stacks
  347. with 16 times pagesize or larger. This might just cause
  348. unnecessary misalignment. */
  349. if (size <= 16 * pagesize_m1)
  350. size += pagesize_m1 + 1;
  351. #endif
  352. /* Adjust the stack size for alignment. */
  353. size &= ~__static_tls_align_m1;
  354. assert (size != 0);
  355. /* Make sure the size of the stack is enough for the guard and
  356. eventually the thread descriptor. */
  357. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  358. if (__builtin_expect (size < ((guardsize + __static_tls_size
  359. + MINIMAL_REST_STACK + pagesize_m1)
  360. & ~pagesize_m1),
  361. 0))
  362. /* The stack is too small (or the guard too large). */
  363. return EINVAL;
  364. /* Try to get a stack from the cache. */
  365. reqsize = size;
  366. pd = get_cached_stack (&size, &mem);
  367. if (pd == NULL)
  368. {
  369. /* To avoid aliasing effects on a larger scale than pages we
  370. adjust the allocated stack size if necessary. This way
  371. allocations directly following each other will not have
  372. aliasing problems. */
  373. #if defined MULTI_PAGE_ALIASING && MULTI_PAGE_ALIASING != 0
  374. if ((size % MULTI_PAGE_ALIASING) == 0)
  375. size += pagesize_m1 + 1;
  376. #endif
  377. mem = mmap (NULL, size, prot,
  378. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  379. if (__builtin_expect (mem == MAP_FAILED, 0))
  380. {
  381. if (errno == ENOMEM)
  382. __set_errno (EAGAIN);
  383. return errno;
  384. }
  385. /* SIZE is guaranteed to be greater than zero.
  386. So we can never get a null pointer back from mmap. */
  387. assert (mem != NULL);
  388. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  389. /* Atomically increment NCREATED. */
  390. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  391. /* We chose the offset for coloring by incrementing it for
  392. every new thread by a fixed amount. The offset used
  393. module the page size. Even if coloring would be better
  394. relative to higher alignment values it makes no sense to
  395. do it since the mmap() interface does not allow us to
  396. specify any alignment for the returned memory block. */
  397. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  398. /* Make sure the coloring offsets does not disturb the alignment
  399. of the TCB and static TLS block. */
  400. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  401. coloring = (((coloring + __static_tls_align_m1)
  402. & ~(__static_tls_align_m1))
  403. & ~pagesize_m1);
  404. #else
  405. /* Unless specified we do not make any adjustments. */
  406. # define coloring 0
  407. #endif
  408. /* Place the thread descriptor at the end of the stack. */
  409. #if defined(TLS_TCB_AT_TP)
  410. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  411. #elif defined(TLS_DTV_AT_TP)
  412. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  413. - __static_tls_size)
  414. & ~__static_tls_align_m1)
  415. - TLS_PRE_TCB_SIZE);
  416. #endif
  417. /* Remember the stack-related values. */
  418. pd->stackblock = mem;
  419. pd->stackblock_size = size;
  420. /* We allocated the first block thread-specific data array.
  421. This address will not change for the lifetime of this
  422. descriptor. */
  423. pd->specific[0] = pd->specific_1stblock;
  424. /* This is at least the second thread. */
  425. pd->header.multiple_threads = 1;
  426. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  427. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  428. #endif
  429. #ifndef __ASSUME_PRIVATE_FUTEX
  430. /* The thread must know when private futexes are supported. */
  431. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  432. header.private_futex);
  433. #endif
  434. #ifdef NEED_DL_SYSINFO
  435. /* Copy the sysinfo value from the parent. */
  436. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  437. #endif
  438. /* Allocate the DTV for this thread. */
  439. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  440. {
  441. /* Something went wrong. */
  442. assert (errno == ENOMEM);
  443. /* Free the stack memory we just allocated. */
  444. (void) munmap (mem, size);
  445. return EAGAIN;
  446. }
  447. /* Prepare to modify global data. */
  448. lll_lock (stack_cache_lock, LLL_PRIVATE);
  449. /* And add to the list of stacks in use. */
  450. stack_list_add (&pd->list, &stack_used);
  451. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  452. /* Note that all of the stack and the thread descriptor is
  453. zeroed. This means we do not have to initialize fields
  454. with initial value zero. This is specifically true for
  455. the 'tid' field which is always set back to zero once the
  456. stack is not used anymore and for the 'guardsize' field
  457. which will be read next. */
  458. }
  459. /* Create or resize the guard area if necessary. */
  460. if (__builtin_expect (guardsize > pd->guardsize, 0))
  461. {
  462. #ifdef NEED_SEPARATE_REGISTER_STACK
  463. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  464. #elif defined _STACK_GROWS_DOWN
  465. char *guard = mem;
  466. #elif defined _STACK_GROWS_UP
  467. char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
  468. #endif
  469. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  470. {
  471. int err;
  472. mprot_error:
  473. err = errno;
  474. lll_lock (stack_cache_lock, LLL_PRIVATE);
  475. /* Remove the thread from the list. */
  476. stack_list_del (&pd->list);
  477. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  478. /* Get rid of the TLS block we allocated. */
  479. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  480. /* Free the stack memory regardless of whether the size
  481. of the cache is over the limit or not. If this piece
  482. of memory caused problems we better do not use it
  483. anymore. Uh, and we ignore possible errors. There
  484. is nothing we could do. */
  485. (void) munmap (mem, size);
  486. return err;
  487. }
  488. pd->guardsize = guardsize;
  489. }
  490. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  491. 0))
  492. {
  493. /* The old guard area is too large. */
  494. #ifdef NEED_SEPARATE_REGISTER_STACK
  495. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  496. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  497. if (oldguard < guard
  498. && mprotect (oldguard, guard - oldguard, prot) != 0)
  499. goto mprot_error;
  500. if (mprotect (guard + guardsize,
  501. oldguard + pd->guardsize - guard - guardsize,
  502. prot) != 0)
  503. goto mprot_error;
  504. #elif defined _STACK_GROWS_DOWN
  505. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  506. prot) != 0)
  507. goto mprot_error;
  508. #elif defined _STACK_GROWS_UP
  509. if (mprotect ((char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1),
  510. pd->guardsize - guardsize, prot) != 0)
  511. goto mprot_error;
  512. #endif
  513. pd->guardsize = guardsize;
  514. }
  515. /* The pthread_getattr_np() calls need to get passed the size
  516. requested in the attribute, regardless of how large the
  517. actually used guardsize is. */
  518. pd->reported_guardsize = guardsize;
  519. }
  520. /* Initialize the lock. We have to do this unconditionally since the
  521. stillborn thread could be canceled while the lock is taken. */
  522. pd->lock = LLL_LOCK_INITIALIZER;
  523. /* The robust mutex lists also need to be initialized
  524. unconditionally because the cleanup for the previous stack owner
  525. might have happened in the kernel. */
  526. pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
  527. - offsetof (pthread_mutex_t,
  528. __data.__list.__next));
  529. pd->robust_head.list_op_pending = NULL;
  530. #ifdef __PTHREAD_MUTEX_HAVE_PREV
  531. pd->robust_prev = &pd->robust_head;
  532. #endif
  533. pd->robust_head.list = &pd->robust_head;
  534. /* We place the thread descriptor at the end of the stack. */
  535. *pdp = pd;
  536. #if defined(TLS_TCB_AT_TP)
  537. /* The stack begins before the TCB and the static TLS block. */
  538. stacktop = ((char *) (pd + 1) - __static_tls_size);
  539. #elif defined(TLS_DTV_AT_TP)
  540. stacktop = (char *) (pd - 1);
  541. #endif
  542. #ifdef NEED_SEPARATE_REGISTER_STACK
  543. *stack = pd->stackblock;
  544. *stacksize = stacktop - *stack;
  545. #elif defined _STACK_GROWS_DOWN
  546. *stack = stacktop;
  547. #elif defined _STACK_GROWS_UP
  548. *stack = pd->stackblock;
  549. assert (*stack > 0);
  550. #endif
  551. return 0;
  552. }
  553. void
  554. internal_function
  555. __deallocate_stack (struct pthread *pd)
  556. {
  557. lll_lock (stack_cache_lock, LLL_PRIVATE);
  558. /* Remove the thread from the list of threads with user defined
  559. stacks. */
  560. stack_list_del (&pd->list);
  561. /* Not much to do. Just free the mmap()ed memory. Note that we do
  562. not reset the 'used' flag in the 'tid' field. This is done by
  563. the kernel. If no thread has been created yet this field is
  564. still zero. */
  565. if (__builtin_expect (! pd->user_stack, 1))
  566. (void) queue_stack (pd);
  567. else
  568. /* Free the memory associated with the ELF TLS. */
  569. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  570. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  571. }
  572. int
  573. internal_function
  574. __make_stacks_executable (void **stack_endp)
  575. {
  576. /* First the main thread's stack. */
  577. int err = EPERM;
  578. if (err != 0)
  579. return err;
  580. #ifdef NEED_SEPARATE_REGISTER_STACK
  581. const size_t pagemask = ~(__getpagesize () - 1);
  582. #endif
  583. lll_lock (stack_cache_lock, LLL_PRIVATE);
  584. list_t *runp;
  585. list_for_each (runp, &stack_used)
  586. {
  587. err = change_stack_perm (list_entry (runp, struct pthread, list)
  588. #ifdef NEED_SEPARATE_REGISTER_STACK
  589. , pagemask
  590. #endif
  591. );
  592. if (err != 0)
  593. break;
  594. }
  595. /* Also change the permission for the currently unused stacks. This
  596. might be wasted time but better spend it here than adding a check
  597. in the fast path. */
  598. if (err == 0)
  599. list_for_each (runp, &stack_cache)
  600. {
  601. err = change_stack_perm (list_entry (runp, struct pthread, list)
  602. #ifdef NEED_SEPARATE_REGISTER_STACK
  603. , pagemask
  604. #endif
  605. );
  606. if (err != 0)
  607. break;
  608. }
  609. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  610. return err;
  611. }
  612. /* In case of a fork() call the memory allocation in the child will be
  613. the same but only one thread is running. All stacks except that of
  614. the one running thread are not used anymore. We have to recycle
  615. them. */
  616. void
  617. __reclaim_stacks (void)
  618. {
  619. struct pthread *self = (struct pthread *) THREAD_SELF;
  620. /* No locking necessary. The caller is the only stack in use. But
  621. we have to be aware that we might have interrupted a list
  622. operation. */
  623. if (in_flight_stack != 0)
  624. {
  625. bool add_p = in_flight_stack & 1;
  626. list_t *elem = (list_t *)(uintptr_t)(in_flight_stack & ~UINTMAX_C (1));
  627. if (add_p)
  628. {
  629. /* We always add at the beginning of the list. So in this
  630. case we only need to check the beginning of these lists. */
  631. int check_list (list_t *l)
  632. {
  633. if (l->next->prev != l)
  634. {
  635. assert (l->next->prev == elem);
  636. elem->next = l->next;
  637. elem->prev = l;
  638. l->next = elem;
  639. return 1;
  640. }
  641. return 0;
  642. }
  643. if (check_list (&stack_used) == 0)
  644. (void) check_list (&stack_cache);
  645. }
  646. else
  647. {
  648. /* We can simply always replay the delete operation. */
  649. elem->next->prev = elem->prev;
  650. elem->prev->next = elem->next;
  651. }
  652. }
  653. /* Mark all stacks except the still running one as free. */
  654. list_t *runp;
  655. list_for_each (runp, &stack_used)
  656. {
  657. struct pthread *curp = list_entry (runp, struct pthread, list);
  658. if (curp != self)
  659. {
  660. /* This marks the stack as free. */
  661. curp->tid = 0;
  662. /* Account for the size of the stack. */
  663. stack_cache_actsize += curp->stackblock_size;
  664. if (curp->specific_used)
  665. {
  666. /* Clear the thread-specific data. */
  667. memset (curp->specific_1stblock, '\0',
  668. sizeof (curp->specific_1stblock));
  669. curp->specific_used = false;
  670. size_t cnt;
  671. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  672. if (curp->specific[cnt] != NULL)
  673. {
  674. memset (curp->specific[cnt], '\0',
  675. sizeof (curp->specific_1stblock));
  676. /* We have allocated the block which we do not
  677. free here so re-set the bit. */
  678. curp->specific_used = true;
  679. }
  680. }
  681. }
  682. }
  683. /* Add the stack of all running threads to the cache. */
  684. list_splice (&stack_used, &stack_cache);
  685. /* Remove the entry for the current thread to from the cache list
  686. and add it to the list of running threads. Which of the two
  687. lists is decided by the user_stack flag. */
  688. stack_list_del (&self->list);
  689. /* Re-initialize the lists for all the threads. */
  690. INIT_LIST_HEAD (&stack_used);
  691. INIT_LIST_HEAD (&__stack_user);
  692. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  693. list_add (&self->list, &__stack_user);
  694. else
  695. list_add (&self->list, &stack_used);
  696. /* There is one thread running. */
  697. __nptl_nthreads = 1;
  698. in_flight_stack = 0;
  699. /* Initialize the lock. */
  700. stack_cache_lock = LLL_LOCK_INITIALIZER;
  701. }
  702. static void
  703. internal_function
  704. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  705. {
  706. int ch;
  707. /* Don't let the thread exit before the setxid handler runs. */
  708. t->setxid_futex = 0;
  709. do
  710. {
  711. ch = t->cancelhandling;
  712. /* If the thread is exiting right now, ignore it. */
  713. if ((ch & EXITING_BITMASK) != 0)
  714. return;
  715. }
  716. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  717. ch | SETXID_BITMASK, ch));
  718. }
  719. static void
  720. internal_function
  721. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  722. {
  723. int ch;
  724. do
  725. {
  726. ch = t->cancelhandling;
  727. if ((ch & SETXID_BITMASK) == 0)
  728. return;
  729. }
  730. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  731. ch & ~SETXID_BITMASK, ch));
  732. /* Release the futex just in case. */
  733. t->setxid_futex = 1;
  734. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  735. }
  736. static int
  737. internal_function
  738. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  739. {
  740. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  741. return 0;
  742. int val;
  743. pid_t pid = getpid ();
  744. INTERNAL_SYSCALL_DECL (err);
  745. val = INTERNAL_SYSCALL (tgkill, err, 3, pid, t->tid, SIGSETXID);
  746. /* If this failed, it must have had not started yet or else exited. */
  747. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  748. {
  749. atomic_increment (&cmdp->cntr);
  750. return 1;
  751. }
  752. else
  753. return 0;
  754. }
  755. int
  756. attribute_hidden
  757. __nptl_setxid (struct xid_command *cmdp)
  758. {
  759. int signalled;
  760. int result;
  761. lll_lock (stack_cache_lock, LLL_PRIVATE);
  762. __xidcmd = cmdp;
  763. cmdp->cntr = 0;
  764. struct pthread *self = THREAD_SELF;
  765. /* Iterate over the list with system-allocated threads first. */
  766. list_t *runp;
  767. list_for_each (runp, &stack_used)
  768. {
  769. struct pthread *t = list_entry (runp, struct pthread, list);
  770. if (t == self)
  771. continue;
  772. setxid_mark_thread (cmdp, t);
  773. }
  774. /* Now the list with threads using user-allocated stacks. */
  775. list_for_each (runp, &__stack_user)
  776. {
  777. struct pthread *t = list_entry (runp, struct pthread, list);
  778. if (t == self)
  779. continue;
  780. setxid_mark_thread (cmdp, t);
  781. }
  782. /* Iterate until we don't succeed in signalling anyone. That means
  783. we have gotten all running threads, and their children will be
  784. automatically correct once started. */
  785. do
  786. {
  787. signalled = 0;
  788. list_for_each (runp, &stack_used)
  789. {
  790. struct pthread *t = list_entry (runp, struct pthread, list);
  791. if (t == self)
  792. continue;
  793. signalled += setxid_signal_thread (cmdp, t);
  794. }
  795. list_for_each (runp, &__stack_user)
  796. {
  797. struct pthread *t = list_entry (runp, struct pthread, list);
  798. if (t == self)
  799. continue;
  800. signalled += setxid_signal_thread (cmdp, t);
  801. }
  802. int cur = cmdp->cntr;
  803. while (cur != 0)
  804. {
  805. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  806. cur = cmdp->cntr;
  807. }
  808. }
  809. while (signalled != 0);
  810. /* Clean up flags, so that no thread blocks during exit waiting
  811. for a signal which will never come. */
  812. list_for_each (runp, &stack_used)
  813. {
  814. struct pthread *t = list_entry (runp, struct pthread, list);
  815. if (t == self)
  816. continue;
  817. setxid_unmark_thread (cmdp, t);
  818. }
  819. list_for_each (runp, &__stack_user)
  820. {
  821. struct pthread *t = list_entry (runp, struct pthread, list);
  822. if (t == self)
  823. continue;
  824. setxid_unmark_thread (cmdp, t);
  825. }
  826. /* This must be last, otherwise the current thread might not have
  827. permissions to send SIGSETXID syscall to the other threads. */
  828. INTERNAL_SYSCALL_DECL (err);
  829. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  830. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  831. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  832. {
  833. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  834. result = -1;
  835. }
  836. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  837. return result;
  838. }
  839. static inline void __attribute__((always_inline))
  840. init_one_static_tls (struct pthread *curp, struct link_map *map)
  841. {
  842. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  843. # if defined(TLS_TCB_AT_TP)
  844. void *dest = (char *) curp - map->l_tls_offset;
  845. # elif defined(TLS_DTV_AT_TP)
  846. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  847. # else
  848. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  849. # endif
  850. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  851. dtv[map->l_tls_modid].pointer.val = dest;
  852. dtv[map->l_tls_modid].pointer.is_static = true;
  853. /* Initialize the memory. */
  854. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  855. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  856. }
  857. void
  858. attribute_hidden
  859. __pthread_init_static_tls (struct link_map *map)
  860. {
  861. lll_lock (stack_cache_lock, LLL_PRIVATE);
  862. /* Iterate over the list with system-allocated threads first. */
  863. list_t *runp;
  864. list_for_each (runp, &stack_used)
  865. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  866. /* Now the list with threads using user-allocated stacks. */
  867. list_for_each (runp, &__stack_user)
  868. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  869. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  870. }
  871. void
  872. attribute_hidden
  873. __wait_lookup_done (void)
  874. {
  875. lll_lock (stack_cache_lock, LLL_PRIVATE);
  876. struct pthread *self = THREAD_SELF;
  877. /* Iterate over the list with system-allocated threads first. */
  878. list_t *runp;
  879. list_for_each (runp, &stack_used)
  880. {
  881. struct pthread *t = list_entry (runp, struct pthread, list);
  882. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  883. continue;
  884. int *const gscope_flagp = &t->header.gscope_flag;
  885. /* We have to wait until this thread is done with the global
  886. scope. First tell the thread that we are waiting and
  887. possibly have to be woken. */
  888. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  889. THREAD_GSCOPE_FLAG_WAIT,
  890. THREAD_GSCOPE_FLAG_USED))
  891. continue;
  892. do
  893. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  894. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  895. }
  896. /* Now the list with threads using user-allocated stacks. */
  897. list_for_each (runp, &__stack_user)
  898. {
  899. struct pthread *t = list_entry (runp, struct pthread, list);
  900. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  901. continue;
  902. int *const gscope_flagp = &t->header.gscope_flag;
  903. /* We have to wait until this thread is done with the global
  904. scope. First tell the thread that we are waiting and
  905. possibly have to be woken. */
  906. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  907. THREAD_GSCOPE_FLAG_WAIT,
  908. THREAD_GSCOPE_FLAG_USED))
  909. continue;
  910. do
  911. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  912. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  913. }
  914. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  915. }