allocatestack.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /* Copyright (C) 2002, 2003, 2004 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, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #include <assert.h>
  17. #include <errno.h>
  18. #include <signal.h>
  19. #include <stdint.h>
  20. #include <string.h>
  21. #include <unistd.h>
  22. #include <sys/mman.h>
  23. #include <sys/param.h>
  24. #include <tls.h>
  25. #include <lowlevellock.h>
  26. #include <link.h>
  27. #define __getpagesize getpagesize
  28. #ifndef NEED_SEPARATE_REGISTER_STACK
  29. /* Most architectures have exactly one stack pointer. Some have more. */
  30. # define STACK_VARIABLES void *stackaddr = 0
  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 = 0; size_t stacksize
  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. /* Let the architecture add some flags to the mmap() call used to
  65. allocate stacks. */
  66. #ifndef ARCH_MAP_FLAGS
  67. # define ARCH_MAP_FLAGS 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. /* Maximum size in kB of cache. */
  77. static size_t stack_cache_maxsize = 40 * 1024 * 1024; /* 40MiBi by default. */
  78. static size_t stack_cache_actsize;
  79. /* Mutex protecting this variable. */
  80. static lll_lock_t stack_cache_lock = LLL_LOCK_INITIALIZER;
  81. /* List of queued stack frames. */
  82. static LIST_HEAD (stack_cache);
  83. /* List of the stacks in use. */
  84. static LIST_HEAD (stack_used);
  85. /* List of the threads with user provided stacks in use. No need to
  86. initialize this, since it's done in __pthread_initialize_minimal. */
  87. list_t __stack_user __attribute__ ((nocommon));
  88. hidden_def (__stack_user)
  89. #if COLORING_INCREMENT != 0
  90. /* Number of threads created. */
  91. static unsigned int nptl_ncreated;
  92. #endif
  93. /* Check whether the stack is still used or not. */
  94. #define FREE_P(descr) ((descr)->tid <= 0)
  95. /* We create a double linked list of all cache entries. Double linked
  96. because this allows removing entries from the end. */
  97. /* Get a stack frame from the cache. We have to match by size since
  98. some blocks might be too small or far too large. */
  99. static struct pthread *
  100. get_cached_stack (size_t *sizep, void **memp)
  101. {
  102. size_t size = *sizep;
  103. struct pthread *result = NULL;
  104. list_t *entry;
  105. lll_lock (stack_cache_lock);
  106. /* Search the cache for a matching entry. We search for the
  107. smallest stack which has at least the required size. Note that
  108. in normal situations the size of all allocated stacks is the
  109. same. As the very least there are only a few different sizes.
  110. Therefore this loop will exit early most of the time with an
  111. exact match. */
  112. list_for_each (entry, &stack_cache)
  113. {
  114. struct pthread *curr;
  115. curr = list_entry (entry, struct pthread, list);
  116. if (FREE_P (curr) && curr->stackblock_size >= size)
  117. {
  118. if (curr->stackblock_size == size)
  119. {
  120. result = curr;
  121. break;
  122. }
  123. if (result == NULL
  124. || result->stackblock_size > curr->stackblock_size)
  125. result = curr;
  126. }
  127. }
  128. if (__builtin_expect (result == NULL, 0)
  129. /* Make sure the size difference is not too excessive. In that
  130. case we do not use the block. */
  131. || __builtin_expect (result->stackblock_size > 4 * size, 0))
  132. {
  133. /* Release the lock. */
  134. lll_unlock (stack_cache_lock);
  135. return NULL;
  136. }
  137. /* Dequeue the entry. */
  138. list_del (&result->list);
  139. /* And add to the list of stacks in use. */
  140. list_add (&result->list, &stack_used);
  141. /* And decrease the cache size. */
  142. stack_cache_actsize -= result->stackblock_size;
  143. /* Release the lock early. */
  144. lll_unlock (stack_cache_lock);
  145. /* Report size and location of the stack to the caller. */
  146. *sizep = result->stackblock_size;
  147. *memp = result->stackblock;
  148. /* Cancellation handling is back to the default. */
  149. result->cancelhandling = 0;
  150. result->cleanup = NULL;
  151. /* No pending event. */
  152. result->nextevent = NULL;
  153. /* Clear the DTV. */
  154. dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
  155. memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
  156. /* Re-initialize the TLS. */
  157. _dl_allocate_tls_init (TLS_TPADJ (result));
  158. return result;
  159. }
  160. /* Add a stack frame which is not used anymore to the stack. Must be
  161. called with the cache lock held. */
  162. static inline void
  163. __attribute ((always_inline))
  164. queue_stack (struct pthread *stack)
  165. {
  166. /* We unconditionally add the stack to the list. The memory may
  167. still be in use but it will not be reused until the kernel marks
  168. the stack as not used anymore. */
  169. list_add (&stack->list, &stack_cache);
  170. stack_cache_actsize += stack->stackblock_size;
  171. if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
  172. {
  173. /* We reduce the size of the cache. Remove the last entries
  174. until the size is below the limit. */
  175. list_t *entry;
  176. list_t *prev;
  177. /* Search from the end of the list. */
  178. list_for_each_prev_safe (entry, prev, &stack_cache)
  179. {
  180. struct pthread *curr;
  181. curr = list_entry (entry, struct pthread, list);
  182. if (FREE_P (curr))
  183. {
  184. /* Unlink the block. */
  185. list_del (entry);
  186. /* Account for the freed memory. */
  187. stack_cache_actsize -= curr->stackblock_size;
  188. /* Free the memory associated with the ELF TLS. */
  189. _dl_deallocate_tls (TLS_TPADJ (curr), false);
  190. /* Remove this block. This should never fail. If it
  191. does something is really wrong. */
  192. if (munmap (curr->stackblock, curr->stackblock_size) != 0)
  193. abort ();
  194. /* Maybe we have freed enough. */
  195. if (stack_cache_actsize <= stack_cache_maxsize)
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. static int
  202. internal_function
  203. change_stack_perm (struct pthread *pd
  204. #ifdef NEED_SEPARATE_REGISTER_STACK
  205. , size_t pagemask
  206. #endif
  207. )
  208. {
  209. #ifdef NEED_SEPARATE_REGISTER_STACK
  210. void *stack = (pd->stackblock
  211. + (((((pd->stackblock_size - pd->guardsize) / 2)
  212. & pagemask) + pd->guardsize) & pagemask));
  213. size_t len = pd->stackblock + pd->stackblock_size - stack;
  214. #else
  215. void *stack = pd->stackblock + pd->guardsize;
  216. size_t len = pd->stackblock_size - pd->guardsize;
  217. #endif
  218. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  219. return errno;
  220. return 0;
  221. }
  222. static int
  223. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  224. ALLOCATE_STACK_PARMS)
  225. {
  226. struct pthread *pd;
  227. size_t size;
  228. size_t pagesize_m1 = __getpagesize () - 1;
  229. void *stacktop;
  230. assert (attr != NULL);
  231. assert (powerof2 (pagesize_m1 + 1));
  232. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  233. /* Get the stack size from the attribute if it is set. Otherwise we
  234. use the default we determined at start time. */
  235. size = attr->stacksize ?: __default_stacksize;
  236. /* Get memory for the stack. */
  237. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  238. {
  239. uintptr_t adj;
  240. /* If the user also specified the size of the stack make sure it
  241. is large enough. */
  242. if (attr->stacksize != 0
  243. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  244. return EINVAL;
  245. /* Adjust stack size for alignment of the TLS block. */
  246. #if defined(TLS_TCB_AT_TP)
  247. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  248. & __static_tls_align_m1;
  249. assert (size > adj + TLS_TCB_SIZE);
  250. #elif defined(TLS_DTV_AT_TP)
  251. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  252. & __static_tls_align_m1;
  253. assert (size > adj);
  254. #endif
  255. /* The user provided some memory. Let's hope it matches the
  256. size... We do not allocate guard pages if the user provided
  257. the stack. It is the user's responsibility to do this if it
  258. is wanted. */
  259. #if defined(TLS_TCB_AT_TP)
  260. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  261. - TLS_TCB_SIZE - adj);
  262. #elif defined(TLS_DTV_AT_TP)
  263. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  264. - __static_tls_size - adj)
  265. - TLS_PRE_TCB_SIZE);
  266. #endif
  267. /* The user provided stack memory needs to be cleared. */
  268. memset (pd, '\0', sizeof (struct pthread));
  269. /* The first TSD block is included in the TCB. */
  270. pd->specific[0] = pd->specific_1stblock;
  271. /* Remember the stack-related values. */
  272. pd->stackblock = (char *) attr->stackaddr - size;
  273. pd->stackblock_size = size;
  274. /* This is a user-provided stack. It will not be queued in the
  275. stack cache nor will the memory (except the TLS memory) be freed. */
  276. pd->user_stack = true;
  277. /* This is at least the second thread. */
  278. pd->header.multiple_threads = 1;
  279. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  280. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  281. #endif
  282. #ifdef NEED_DL_SYSINFO
  283. /* Copy the sysinfo value from the parent. */
  284. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  285. #endif
  286. /* The process ID is also the same as that of the caller. */
  287. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  288. /* Allocate the DTV for this thread. */
  289. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  290. {
  291. /* Something went wrong. */
  292. assert (errno == ENOMEM);
  293. return EAGAIN;
  294. }
  295. /* Prepare to modify global data. */
  296. lll_lock (stack_cache_lock);
  297. /* And add to the list of stacks in use. */
  298. list_add (&pd->list, &__stack_user);
  299. lll_unlock (stack_cache_lock);
  300. }
  301. else
  302. {
  303. /* Allocate some anonymous memory. If possible use the cache. */
  304. size_t guardsize;
  305. size_t reqsize;
  306. void *mem = 0;
  307. const int prot = (PROT_READ | PROT_WRITE);
  308. #if COLORING_INCREMENT != 0
  309. /* Add one more page for stack coloring. Don't do it for stacks
  310. with 16 times pagesize or larger. This might just cause
  311. unnecessary misalignment. */
  312. if (size <= 16 * pagesize_m1)
  313. size += pagesize_m1 + 1;
  314. #endif
  315. /* Adjust the stack size for alignment. */
  316. size &= ~__static_tls_align_m1;
  317. assert (size != 0);
  318. /* Make sure the size of the stack is enough for the guard and
  319. eventually the thread descriptor. */
  320. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  321. if (__builtin_expect (size < (guardsize + __static_tls_size
  322. + MINIMAL_REST_STACK + pagesize_m1 + 1),
  323. 0))
  324. /* The stack is too small (or the guard too large). */
  325. return EINVAL;
  326. /* Try to get a stack from the cache. */
  327. reqsize = size;
  328. pd = get_cached_stack (&size, &mem);
  329. if (pd == NULL)
  330. {
  331. /* To avoid aliasing effects on a larger scale than pages we
  332. adjust the allocated stack size if necessary. This way
  333. allocations directly following each other will not have
  334. aliasing problems. */
  335. #if MULTI_PAGE_ALIASING != 0
  336. if ((size % MULTI_PAGE_ALIASING) == 0)
  337. size += pagesize_m1 + 1;
  338. #endif
  339. mem = mmap (NULL, size, prot,
  340. MAP_PRIVATE | MAP_ANONYMOUS | ARCH_MAP_FLAGS, -1, 0);
  341. if (__builtin_expect (mem == MAP_FAILED, 0))
  342. {
  343. #ifdef ARCH_RETRY_MMAP
  344. mem = ARCH_RETRY_MMAP (size);
  345. if (__builtin_expect (mem == MAP_FAILED, 0))
  346. #endif
  347. return errno;
  348. }
  349. /* SIZE is guaranteed to be greater than zero.
  350. So we can never get a null pointer back from mmap. */
  351. assert (mem != NULL);
  352. #if COLORING_INCREMENT != 0
  353. /* Atomically increment NCREATED. */
  354. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  355. /* We chose the offset for coloring by incrementing it for
  356. every new thread by a fixed amount. The offset used
  357. module the page size. Even if coloring would be better
  358. relative to higher alignment values it makes no sense to
  359. do it since the mmap() interface does not allow us to
  360. specify any alignment for the returned memory block. */
  361. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  362. /* Make sure the coloring offsets does not disturb the alignment
  363. of the TCB and static TLS block. */
  364. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  365. coloring = (((coloring + __static_tls_align_m1)
  366. & ~(__static_tls_align_m1))
  367. & ~pagesize_m1);
  368. #else
  369. /* Unless specified we do not make any adjustments. */
  370. # define coloring 0
  371. #endif
  372. /* Place the thread descriptor at the end of the stack. */
  373. #if defined(TLS_TCB_AT_TP)
  374. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  375. #elif defined(TLS_DTV_AT_TP)
  376. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  377. - __static_tls_size)
  378. & ~__static_tls_align_m1)
  379. - TLS_PRE_TCB_SIZE);
  380. #endif
  381. /* Remember the stack-related values. */
  382. pd->stackblock = mem;
  383. pd->stackblock_size = size;
  384. /* We allocated the first block thread-specific data array.
  385. This address will not change for the lifetime of this
  386. descriptor. */
  387. pd->specific[0] = pd->specific_1stblock;
  388. /* This is at least the second thread. */
  389. pd->header.multiple_threads = 1;
  390. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  391. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  392. #endif
  393. #ifdef NEED_DL_SYSINFO
  394. /* Copy the sysinfo value from the parent. */
  395. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  396. #endif
  397. /* The process ID is also the same as that of the caller. */
  398. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  399. /* Allocate the DTV for this thread. */
  400. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  401. {
  402. /* Something went wrong. */
  403. assert (errno == ENOMEM);
  404. /* Free the stack memory we just allocated. */
  405. (void) munmap (mem, size);
  406. return EAGAIN;
  407. }
  408. /* Prepare to modify global data. */
  409. lll_lock (stack_cache_lock);
  410. /* And add to the list of stacks in use. */
  411. list_add (&pd->list, &stack_used);
  412. lll_unlock (stack_cache_lock);
  413. /* Note that all of the stack and the thread descriptor is
  414. zeroed. This means we do not have to initialize fields
  415. with initial value zero. This is specifically true for
  416. the 'tid' field which is always set back to zero once the
  417. stack is not used anymore and for the 'guardsize' field
  418. which will be read next. */
  419. }
  420. /* Create or resize the guard area if necessary. */
  421. if (__builtin_expect (guardsize > pd->guardsize, 0))
  422. {
  423. #ifdef NEED_SEPARATE_REGISTER_STACK
  424. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  425. #else
  426. char *guard = mem;
  427. #endif
  428. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  429. {
  430. int err;
  431. mprot_error:
  432. err = errno;
  433. lll_lock (stack_cache_lock);
  434. /* Remove the thread from the list. */
  435. list_del (&pd->list);
  436. lll_unlock (stack_cache_lock);
  437. /* Get rid of the TLS block we allocated. */
  438. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  439. /* Free the stack memory regardless of whether the size
  440. of the cache is over the limit or not. If this piece
  441. of memory caused problems we better do not use it
  442. anymore. Uh, and we ignore possible errors. There
  443. is nothing we could do. */
  444. (void) munmap (mem, size);
  445. return err;
  446. }
  447. pd->guardsize = guardsize;
  448. }
  449. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  450. 0))
  451. {
  452. /* The old guard area is too large. */
  453. #ifdef NEED_SEPARATE_REGISTER_STACK
  454. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  455. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  456. if (oldguard < guard
  457. && mprotect (oldguard, guard - oldguard, prot) != 0)
  458. goto mprot_error;
  459. if (mprotect (guard + guardsize,
  460. oldguard + pd->guardsize - guard - guardsize,
  461. prot) != 0)
  462. goto mprot_error;
  463. #else
  464. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  465. prot) != 0)
  466. goto mprot_error;
  467. #endif
  468. pd->guardsize = guardsize;
  469. }
  470. /* The pthread_getattr_np() calls need to get passed the size
  471. requested in the attribute, regardless of how large the
  472. actually used guardsize is. */
  473. pd->reported_guardsize = guardsize;
  474. }
  475. /* Initialize the lock. We have to do this unconditionally since the
  476. stillborn thread could be canceled while the lock is taken. */
  477. pd->lock = LLL_LOCK_INITIALIZER;
  478. /* We place the thread descriptor at the end of the stack. */
  479. *pdp = pd;
  480. #if defined(TLS_TCB_AT_TP)
  481. /* The stack begins before the TCB and the static TLS block. */
  482. stacktop = ((char *) (pd + 1) - __static_tls_size);
  483. #elif defined(TLS_DTV_AT_TP)
  484. stacktop = (char *) (pd - 1);
  485. #endif
  486. #ifdef NEED_SEPARATE_REGISTER_STACK
  487. *stack = pd->stackblock;
  488. *stacksize = stacktop - *stack;
  489. #else
  490. *stack = stacktop;
  491. #endif
  492. return 0;
  493. }
  494. void
  495. internal_function
  496. __deallocate_stack (struct pthread *pd)
  497. {
  498. lll_lock (stack_cache_lock);
  499. /* Remove the thread from the list of threads with user defined
  500. stacks. */
  501. list_del (&pd->list);
  502. /* Not much to do. Just free the mmap()ed memory. Note that we do
  503. not reset the 'used' flag in the 'tid' field. This is done by
  504. the kernel. If no thread has been created yet this field is
  505. still zero. */
  506. if (__builtin_expect (! pd->user_stack, 1))
  507. (void) queue_stack (pd);
  508. else
  509. /* Free the memory associated with the ELF TLS. */
  510. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  511. lll_unlock (stack_cache_lock);
  512. }
  513. int
  514. internal_function
  515. __make_stacks_executable (void **stack_endp)
  516. {
  517. /* First the main thread's stack. */
  518. int err = EPERM;
  519. if (err != 0)
  520. return err;
  521. #ifdef NEED_SEPARATE_REGISTER_STACK
  522. const size_t pagemask = ~(__getpagesize () - 1);
  523. #endif
  524. lll_lock (stack_cache_lock);
  525. list_t *runp;
  526. list_for_each (runp, &stack_used)
  527. {
  528. err = change_stack_perm (list_entry (runp, struct pthread, list)
  529. #ifdef NEED_SEPARATE_REGISTER_STACK
  530. , pagemask
  531. #endif
  532. );
  533. if (err != 0)
  534. break;
  535. }
  536. /* Also change the permission for the currently unused stacks. This
  537. might be wasted time but better spend it here than adding a check
  538. in the fast path. */
  539. if (err == 0)
  540. list_for_each (runp, &stack_cache)
  541. {
  542. err = change_stack_perm (list_entry (runp, struct pthread, list)
  543. #ifdef NEED_SEPARATE_REGISTER_STACK
  544. , pagemask
  545. #endif
  546. );
  547. if (err != 0)
  548. break;
  549. }
  550. lll_unlock (stack_cache_lock);
  551. return err;
  552. }
  553. /* In case of a fork() call the memory allocation in the child will be
  554. the same but only one thread is running. All stacks except that of
  555. the one running thread are not used anymore. We have to recycle
  556. them. */
  557. void
  558. __reclaim_stacks (void)
  559. {
  560. struct pthread *self = (struct pthread *) THREAD_SELF;
  561. /* No locking necessary. The caller is the only stack in use. */
  562. /* Mark all stacks except the still running one as free. */
  563. list_t *runp;
  564. list_for_each (runp, &stack_used)
  565. {
  566. struct pthread *curp;
  567. curp = list_entry (runp, struct pthread, list);
  568. if (curp != self)
  569. {
  570. /* This marks the stack as free. */
  571. curp->tid = 0;
  572. /* The PID field must be initialized for the new process. */
  573. curp->pid = self->pid;
  574. /* Account for the size of the stack. */
  575. stack_cache_actsize += curp->stackblock_size;
  576. }
  577. }
  578. /* Add the stack of all running threads to the cache. */
  579. list_splice (&stack_used, &stack_cache);
  580. /* Remove the entry for the current thread to from the cache list
  581. and add it to the list of running threads. Which of the two
  582. lists is decided by the user_stack flag. */
  583. list_del (&self->list);
  584. /* Re-initialize the lists for all the threads. */
  585. INIT_LIST_HEAD (&stack_used);
  586. INIT_LIST_HEAD (&__stack_user);
  587. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  588. list_add (&self->list, &__stack_user);
  589. else
  590. list_add (&self->list, &stack_used);
  591. /* There is one thread running. */
  592. __nptl_nthreads = 1;
  593. /* Initialize the lock. */
  594. stack_cache_lock = LLL_LOCK_INITIALIZER;
  595. }
  596. #if HP_TIMING_AVAIL
  597. # undef __find_thread_by_id
  598. /* Find a thread given the thread ID. */
  599. attribute_hidden
  600. struct pthread *
  601. __find_thread_by_id (pid_t tid)
  602. {
  603. struct pthread *result = NULL;
  604. lll_lock (stack_cache_lock);
  605. /* Iterate over the list with system-allocated threads first. */
  606. list_t *runp;
  607. list_for_each (runp, &stack_used)
  608. {
  609. struct pthread *curp;
  610. curp = list_entry (runp, struct pthread, list);
  611. if (curp->tid == tid)
  612. {
  613. result = curp;
  614. goto out;
  615. }
  616. }
  617. /* Now the list with threads using user-allocated stacks. */
  618. list_for_each (runp, &__stack_user)
  619. {
  620. struct pthread *curp;
  621. curp = list_entry (runp, struct pthread, list);
  622. if (curp->tid == tid)
  623. {
  624. result = curp;
  625. goto out;
  626. }
  627. }
  628. out:
  629. lll_unlock (stack_cache_lock);
  630. return result;
  631. }
  632. #endif
  633. int
  634. attribute_hidden
  635. __nptl_setxid (struct xid_command *cmdp)
  636. {
  637. int result;
  638. lll_lock (stack_cache_lock);
  639. __xidcmd = cmdp;
  640. cmdp->cntr = 0;
  641. INTERNAL_SYSCALL_DECL (err);
  642. struct pthread *self = THREAD_SELF;
  643. /* Iterate over the list with system-allocated threads first. */
  644. list_t *runp;
  645. list_for_each (runp, &stack_used)
  646. {
  647. struct pthread *t = list_entry (runp, struct pthread, list);
  648. if (t != self)
  649. {
  650. int val;
  651. #if __ASSUME_TGKILL
  652. val = INTERNAL_SYSCALL (tgkill, err, 3,
  653. THREAD_GETMEM (THREAD_SELF, pid),
  654. t->tid, SIGSETXID);
  655. #else
  656. # ifdef __NR_tgkill
  657. val = INTERNAL_SYSCALL (tgkill, err, 3,
  658. THREAD_GETMEM (THREAD_SELF, pid),
  659. t->tid, SIGSETXID);
  660. if (INTERNAL_SYSCALL_ERROR_P (val, err)
  661. && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
  662. # endif
  663. val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
  664. #endif
  665. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  666. atomic_increment (&cmdp->cntr);
  667. }
  668. }
  669. /* Now the list with threads using user-allocated stacks. */
  670. list_for_each (runp, &__stack_user)
  671. {
  672. struct pthread *t = list_entry (runp, struct pthread, list);
  673. if (t != self)
  674. {
  675. int val;
  676. #if __ASSUME_TGKILL
  677. val = INTERNAL_SYSCALL (tgkill, err, 3,
  678. THREAD_GETMEM (THREAD_SELF, pid),
  679. t->tid, SIGSETXID);
  680. #else
  681. # ifdef __NR_tgkill
  682. val = INTERNAL_SYSCALL (tgkill, err, 3,
  683. THREAD_GETMEM (THREAD_SELF, pid),
  684. t->tid, SIGSETXID);
  685. if (INTERNAL_SYSCALL_ERROR_P (val, err)
  686. && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
  687. # endif
  688. val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
  689. #endif
  690. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  691. atomic_increment (&cmdp->cntr);
  692. }
  693. }
  694. int cur = cmdp->cntr;
  695. while (cur != 0)
  696. {
  697. lll_futex_wait (&cmdp->cntr, cur);
  698. cur = cmdp->cntr;
  699. }
  700. /* This must be last, otherwise the current thread might not have
  701. permissions to send SIGSETXID syscall to the other threads. */
  702. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  703. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  704. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  705. {
  706. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  707. result = -1;
  708. }
  709. lll_unlock (stack_cache_lock);
  710. return result;
  711. }
  712. static inline void __attribute__((always_inline))
  713. init_one_static_tls (struct pthread *curp, struct link_map *map)
  714. {
  715. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  716. # if defined(TLS_TCB_AT_TP)
  717. void *dest = (char *) curp - map->l_tls_offset;
  718. # elif defined(TLS_DTV_AT_TP)
  719. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  720. # else
  721. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  722. # endif
  723. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  724. dtv[map->l_tls_modid].pointer.val = dest;
  725. dtv[map->l_tls_modid].pointer.is_static = true;
  726. /* Initialize the memory. */
  727. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  728. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  729. }
  730. void
  731. attribute_hidden
  732. __pthread_init_static_tls (struct link_map *map)
  733. {
  734. lll_lock (stack_cache_lock);
  735. /* Iterate over the list with system-allocated threads first. */
  736. list_t *runp;
  737. list_for_each (runp, &stack_used)
  738. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  739. /* Now the list with threads using user-allocated stacks. */
  740. list_for_each (runp, &__stack_user)
  741. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  742. lll_unlock (stack_cache_lock);
  743. }