allocatestack.c 26 KB

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