allocatestack.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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. /* 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 int 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. /* We need to record what list operations we are going to do so that,
  85. in case of an asynchronous interruption due to a fork() call, we
  86. can correct for the work. */
  87. static uintptr_t in_flight_stack;
  88. /* List of the threads with user provided stacks in use. No need to
  89. initialize this, since it's done in __pthread_initialize_minimal. */
  90. list_t __stack_user __attribute__ ((nocommon));
  91. hidden_data_def (__stack_user)
  92. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  93. /* Number of threads created. */
  94. static unsigned int nptl_ncreated;
  95. #endif
  96. /* Check whether the stack is still used or not. */
  97. #define FREE_P(descr) ((descr)->tid <= 0)
  98. static void
  99. stack_list_del (list_t *elem)
  100. {
  101. in_flight_stack = (uintptr_t) elem;
  102. atomic_write_barrier ();
  103. list_del (elem);
  104. atomic_write_barrier ();
  105. in_flight_stack = 0;
  106. }
  107. static void
  108. stack_list_add (list_t *elem, list_t *list)
  109. {
  110. in_flight_stack = (uintptr_t) elem | 1;
  111. atomic_write_barrier ();
  112. list_add (elem, list);
  113. atomic_write_barrier ();
  114. in_flight_stack = 0;
  115. }
  116. /* We create a double linked list of all cache entries. Double linked
  117. because this allows removing entries from the end. */
  118. /* Get a stack frame from the cache. We have to match by size since
  119. some blocks might be too small or far too large. */
  120. static struct pthread *
  121. get_cached_stack (size_t *sizep, void **memp)
  122. {
  123. size_t size = *sizep;
  124. struct pthread *result = NULL;
  125. list_t *entry;
  126. lll_lock (stack_cache_lock, LLL_PRIVATE);
  127. /* Search the cache for a matching entry. We search for the
  128. smallest stack which has at least the required size. Note that
  129. in normal situations the size of all allocated stacks is the
  130. same. As the very least there are only a few different sizes.
  131. Therefore this loop will exit early most of the time with an
  132. exact match. */
  133. list_for_each (entry, &stack_cache)
  134. {
  135. struct pthread *curr;
  136. curr = list_entry (entry, struct pthread, list);
  137. if (FREE_P (curr) && curr->stackblock_size >= size)
  138. {
  139. if (curr->stackblock_size == size)
  140. {
  141. result = curr;
  142. break;
  143. }
  144. if (result == NULL
  145. || result->stackblock_size > curr->stackblock_size)
  146. result = curr;
  147. }
  148. }
  149. if (__builtin_expect (result == NULL, 0)
  150. /* Make sure the size difference is not too excessive. In that
  151. case we do not use the block. */
  152. || __builtin_expect (result->stackblock_size > 4 * size, 0))
  153. {
  154. /* Release the lock. */
  155. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  156. return NULL;
  157. }
  158. /* Dequeue the entry. */
  159. stack_list_del (&result->list);
  160. /* And add to the list of stacks in use. */
  161. stack_list_add (&result->list, &stack_used);
  162. /* And decrease the cache size. */
  163. stack_cache_actsize -= result->stackblock_size;
  164. /* Release the lock early. */
  165. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  166. /* Report size and location of the stack to the caller. */
  167. *sizep = result->stackblock_size;
  168. *memp = result->stackblock;
  169. /* Cancellation handling is back to the default. */
  170. result->cancelhandling = 0;
  171. result->cleanup = NULL;
  172. /* No pending event. */
  173. result->nextevent = NULL;
  174. /* Clear the DTV. */
  175. dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
  176. memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
  177. /* Re-initialize the TLS. */
  178. _dl_allocate_tls_init (TLS_TPADJ (result));
  179. return result;
  180. }
  181. /* Free stacks until cache size is lower than LIMIT. */
  182. void
  183. __free_stacks (size_t limit)
  184. {
  185. /* We reduce the size of the cache. Remove the last entries until
  186. the size is below the limit. */
  187. list_t *entry;
  188. list_t *prev;
  189. /* Search from the end of the list. */
  190. list_for_each_prev_safe (entry, prev, &stack_cache)
  191. {
  192. struct pthread *curr;
  193. curr = list_entry (entry, struct pthread, list);
  194. if (FREE_P (curr))
  195. {
  196. /* Unlink the block. */
  197. stack_list_del (entry);
  198. /* Account for the freed memory. */
  199. stack_cache_actsize -= curr->stackblock_size;
  200. /* Free the memory associated with the ELF TLS. */
  201. _dl_deallocate_tls (TLS_TPADJ (curr), false);
  202. /* Remove this block. This should never fail. If it does
  203. something is really wrong. */
  204. if (munmap (curr->stackblock, curr->stackblock_size) != 0)
  205. abort ();
  206. /* Maybe we have freed enough. */
  207. if (stack_cache_actsize <= limit)
  208. break;
  209. }
  210. }
  211. }
  212. /* Add a stack frame which is not used anymore to the stack. Must be
  213. called with the cache lock held. */
  214. static inline void
  215. __attribute ((always_inline))
  216. queue_stack (struct pthread *stack)
  217. {
  218. /* We unconditionally add the stack to the list. The memory may
  219. still be in use but it will not be reused until the kernel marks
  220. the stack as not used anymore. */
  221. stack_list_add (&stack->list, &stack_cache);
  222. stack_cache_actsize += stack->stackblock_size;
  223. if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
  224. __free_stacks (stack_cache_maxsize);
  225. }
  226. static int
  227. internal_function
  228. change_stack_perm (struct pthread *pd
  229. #ifdef NEED_SEPARATE_REGISTER_STACK
  230. , size_t pagemask
  231. #endif
  232. )
  233. {
  234. #ifdef NEED_SEPARATE_REGISTER_STACK
  235. void *stack = (pd->stackblock
  236. + (((((pd->stackblock_size - pd->guardsize) / 2)
  237. & pagemask) + pd->guardsize) & pagemask));
  238. size_t len = pd->stackblock + pd->stackblock_size - stack;
  239. #elif defined _STACK_GROWS_DOWN
  240. void *stack = pd->stackblock + pd->guardsize;
  241. size_t len = pd->stackblock_size - pd->guardsize;
  242. #elif defined _STACK_GROWS_UP
  243. void *stack = pd->stackblock;
  244. size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
  245. #else
  246. # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
  247. #endif
  248. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  249. return errno;
  250. return 0;
  251. }
  252. static int
  253. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  254. ALLOCATE_STACK_PARMS)
  255. {
  256. struct pthread *pd;
  257. size_t size;
  258. size_t pagesize_m1 = __getpagesize () - 1;
  259. void *stacktop;
  260. assert (attr != NULL);
  261. assert (powerof2 (pagesize_m1 + 1));
  262. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  263. /* Get the stack size from the attribute if it is set. Otherwise we
  264. use the default we determined at start time. */
  265. size = attr->stacksize ?: __default_stacksize;
  266. /* Get memory for the stack. */
  267. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  268. {
  269. uintptr_t adj;
  270. /* If the user also specified the size of the stack make sure it
  271. is large enough. */
  272. if (attr->stacksize != 0
  273. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  274. return EINVAL;
  275. /* Adjust stack size for alignment of the TLS block. */
  276. #if defined(TLS_TCB_AT_TP)
  277. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  278. & __static_tls_align_m1;
  279. assert (size > adj + TLS_TCB_SIZE);
  280. #elif defined(TLS_DTV_AT_TP)
  281. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  282. & __static_tls_align_m1;
  283. assert (size > adj);
  284. #endif
  285. /* The user provided some memory. Let's hope it matches the
  286. size... We do not allocate guard pages if the user provided
  287. the stack. It is the user's responsibility to do this if it
  288. is wanted. */
  289. #if defined(TLS_TCB_AT_TP)
  290. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  291. - TLS_TCB_SIZE - adj);
  292. #elif defined(TLS_DTV_AT_TP)
  293. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  294. - __static_tls_size - adj)
  295. - TLS_PRE_TCB_SIZE);
  296. #endif
  297. /* The user provided stack memory needs to be cleared. */
  298. memset (pd, '\0', sizeof (struct pthread));
  299. /* The first TSD block is included in the TCB. */
  300. pd->specific[0] = pd->specific_1stblock;
  301. /* Remember the stack-related values. */
  302. pd->stackblock = (char *) attr->stackaddr - size;
  303. pd->stackblock_size = size;
  304. /* This is a user-provided stack. It will not be queued in the
  305. stack cache nor will the memory (except the TLS memory) be freed. */
  306. pd->user_stack = true;
  307. /* This is at least the second thread. */
  308. pd->header.multiple_threads = 1;
  309. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  310. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  311. #endif
  312. #ifndef __ASSUME_PRIVATE_FUTEX
  313. /* The thread must know when private futexes are supported. */
  314. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  315. header.private_futex);
  316. #endif
  317. #ifdef NEED_DL_SYSINFO
  318. /* Copy the sysinfo value from the parent. */
  319. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  320. #endif
  321. /* The process ID is also the same as that of the caller. */
  322. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  323. /* Allocate the DTV for this thread. */
  324. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  325. {
  326. /* Something went wrong. */
  327. assert (errno == ENOMEM);
  328. return EAGAIN;
  329. }
  330. /* Prepare to modify global data. */
  331. lll_lock (stack_cache_lock, LLL_PRIVATE);
  332. /* And add to the list of stacks in use. */
  333. list_add (&pd->list, &__stack_user);
  334. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  335. }
  336. else
  337. {
  338. /* Allocate some anonymous memory. If possible use the cache. */
  339. size_t guardsize;
  340. size_t reqsize;
  341. void *mem = 0;
  342. const int prot = (PROT_READ | PROT_WRITE);
  343. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  344. /* Add one more page for stack coloring. Don't do it for stacks
  345. with 16 times pagesize or larger. This might just cause
  346. unnecessary misalignment. */
  347. if (size <= 16 * pagesize_m1)
  348. size += pagesize_m1 + 1;
  349. #endif
  350. /* Adjust the stack size for alignment. */
  351. size &= ~__static_tls_align_m1;
  352. assert (size != 0);
  353. /* Make sure the size of the stack is enough for the guard and
  354. eventually the thread descriptor. */
  355. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  356. if (__builtin_expect (size < ((guardsize + __static_tls_size
  357. + MINIMAL_REST_STACK + pagesize_m1)
  358. & ~pagesize_m1),
  359. 0))
  360. /* The stack is too small (or the guard too large). */
  361. return EINVAL;
  362. /* Try to get a stack from the cache. */
  363. reqsize = size;
  364. pd = get_cached_stack (&size, &mem);
  365. if (pd == NULL)
  366. {
  367. /* To avoid aliasing effects on a larger scale than pages we
  368. adjust the allocated stack size if necessary. This way
  369. allocations directly following each other will not have
  370. aliasing problems. */
  371. #if defined MULTI_PAGE_ALIASING && MULTI_PAGE_ALIASING != 0
  372. if ((size % MULTI_PAGE_ALIASING) == 0)
  373. size += pagesize_m1 + 1;
  374. #endif
  375. mem = mmap (NULL, size, prot,
  376. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  377. if (__builtin_expect (mem == MAP_FAILED, 0))
  378. {
  379. if (errno == ENOMEM)
  380. __set_errno (EAGAIN);
  381. return errno;
  382. }
  383. /* SIZE is guaranteed to be greater than zero.
  384. So we can never get a null pointer back from mmap. */
  385. assert (mem != NULL);
  386. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  387. /* Atomically increment NCREATED. */
  388. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  389. /* We chose the offset for coloring by incrementing it for
  390. every new thread by a fixed amount. The offset used
  391. module the page size. Even if coloring would be better
  392. relative to higher alignment values it makes no sense to
  393. do it since the mmap() interface does not allow us to
  394. specify any alignment for the returned memory block. */
  395. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  396. /* Make sure the coloring offsets does not disturb the alignment
  397. of the TCB and static TLS block. */
  398. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  399. coloring = (((coloring + __static_tls_align_m1)
  400. & ~(__static_tls_align_m1))
  401. & ~pagesize_m1);
  402. #else
  403. /* Unless specified we do not make any adjustments. */
  404. # define coloring 0
  405. #endif
  406. /* Place the thread descriptor at the end of the stack. */
  407. #if defined(TLS_TCB_AT_TP)
  408. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  409. #elif defined(TLS_DTV_AT_TP)
  410. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  411. - __static_tls_size)
  412. & ~__static_tls_align_m1)
  413. - TLS_PRE_TCB_SIZE);
  414. #endif
  415. /* Remember the stack-related values. */
  416. pd->stackblock = mem;
  417. pd->stackblock_size = size;
  418. /* We allocated the first block thread-specific data array.
  419. This address will not change for the lifetime of this
  420. descriptor. */
  421. pd->specific[0] = pd->specific_1stblock;
  422. /* This is at least the second thread. */
  423. pd->header.multiple_threads = 1;
  424. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  425. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  426. #endif
  427. #ifndef __ASSUME_PRIVATE_FUTEX
  428. /* The thread must know when private futexes are supported. */
  429. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  430. header.private_futex);
  431. #endif
  432. #ifdef NEED_DL_SYSINFO
  433. /* Copy the sysinfo value from the parent. */
  434. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  435. #endif
  436. /* The process ID is also the same as that of the caller. */
  437. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  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 *) (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. /* The PID field must be initialized for the new process. */
  663. curp->pid = self->pid;
  664. /* Account for the size of the stack. */
  665. stack_cache_actsize += curp->stackblock_size;
  666. if (curp->specific_used)
  667. {
  668. /* Clear the thread-specific data. */
  669. memset (curp->specific_1stblock, '\0',
  670. sizeof (curp->specific_1stblock));
  671. curp->specific_used = false;
  672. size_t cnt;
  673. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  674. if (curp->specific[cnt] != NULL)
  675. {
  676. memset (curp->specific[cnt], '\0',
  677. sizeof (curp->specific_1stblock));
  678. /* We have allocated the block which we do not
  679. free here so re-set the bit. */
  680. curp->specific_used = true;
  681. }
  682. }
  683. }
  684. }
  685. /* Reset the PIDs in any cached stacks. */
  686. list_for_each (runp, &stack_cache)
  687. {
  688. struct pthread *curp = list_entry (runp, struct pthread, list);
  689. curp->pid = self->pid;
  690. }
  691. /* Add the stack of all running threads to the cache. */
  692. list_splice (&stack_used, &stack_cache);
  693. /* Remove the entry for the current thread to from the cache list
  694. and add it to the list of running threads. Which of the two
  695. lists is decided by the user_stack flag. */
  696. stack_list_del (&self->list);
  697. /* Re-initialize the lists for all the threads. */
  698. INIT_LIST_HEAD (&stack_used);
  699. INIT_LIST_HEAD (&__stack_user);
  700. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  701. list_add (&self->list, &__stack_user);
  702. else
  703. list_add (&self->list, &stack_used);
  704. /* There is one thread running. */
  705. __nptl_nthreads = 1;
  706. in_flight_stack = 0;
  707. /* Initialize the lock. */
  708. stack_cache_lock = LLL_LOCK_INITIALIZER;
  709. }
  710. #if HP_TIMING_AVAIL
  711. # undef __find_thread_by_id
  712. /* Find a thread given the thread ID. */
  713. attribute_hidden
  714. struct pthread *
  715. __find_thread_by_id (pid_t tid)
  716. {
  717. struct pthread *result = NULL;
  718. lll_lock (stack_cache_lock, LLL_PRIVATE);
  719. /* Iterate over the list with system-allocated threads first. */
  720. list_t *runp;
  721. list_for_each (runp, &stack_used)
  722. {
  723. struct pthread *curp;
  724. curp = list_entry (runp, struct pthread, list);
  725. if (curp->tid == tid)
  726. {
  727. result = curp;
  728. goto out;
  729. }
  730. }
  731. /* Now the list with threads using user-allocated stacks. */
  732. list_for_each (runp, &__stack_user)
  733. {
  734. struct pthread *curp;
  735. curp = list_entry (runp, struct pthread, list);
  736. if (curp->tid == tid)
  737. {
  738. result = curp;
  739. goto out;
  740. }
  741. }
  742. out:
  743. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  744. return result;
  745. }
  746. #endif
  747. static void
  748. internal_function
  749. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  750. {
  751. int ch;
  752. /* Don't let the thread exit before the setxid handler runs. */
  753. t->setxid_futex = 0;
  754. do
  755. {
  756. ch = t->cancelhandling;
  757. /* If the thread is exiting right now, ignore it. */
  758. if ((ch & EXITING_BITMASK) != 0)
  759. return;
  760. }
  761. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  762. ch | SETXID_BITMASK, ch));
  763. }
  764. static void
  765. internal_function
  766. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  767. {
  768. int ch;
  769. do
  770. {
  771. ch = t->cancelhandling;
  772. if ((ch & SETXID_BITMASK) == 0)
  773. return;
  774. }
  775. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  776. ch & ~SETXID_BITMASK, ch));
  777. /* Release the futex just in case. */
  778. t->setxid_futex = 1;
  779. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  780. }
  781. static int
  782. internal_function
  783. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  784. {
  785. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  786. return 0;
  787. int val;
  788. INTERNAL_SYSCALL_DECL (err);
  789. #if defined (__ASSUME_TGKILL) && __ASSUME_TGKILL
  790. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  791. t->tid, SIGSETXID);
  792. #else
  793. # ifdef __NR_tgkill
  794. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  795. t->tid, SIGSETXID);
  796. if (INTERNAL_SYSCALL_ERROR_P (val, err)
  797. && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
  798. # endif
  799. val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
  800. #endif
  801. /* If this failed, it must have had not started yet or else exited. */
  802. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  803. {
  804. atomic_increment (&cmdp->cntr);
  805. return 1;
  806. }
  807. else
  808. return 0;
  809. }
  810. int
  811. attribute_hidden
  812. __nptl_setxid (struct xid_command *cmdp)
  813. {
  814. int signalled;
  815. int result;
  816. lll_lock (stack_cache_lock, LLL_PRIVATE);
  817. __xidcmd = cmdp;
  818. cmdp->cntr = 0;
  819. struct pthread *self = THREAD_SELF;
  820. /* Iterate over the list with system-allocated threads first. */
  821. list_t *runp;
  822. list_for_each (runp, &stack_used)
  823. {
  824. struct pthread *t = list_entry (runp, struct pthread, list);
  825. if (t == self)
  826. continue;
  827. setxid_mark_thread (cmdp, t);
  828. }
  829. /* Now the list with threads using user-allocated stacks. */
  830. list_for_each (runp, &__stack_user)
  831. {
  832. struct pthread *t = list_entry (runp, struct pthread, list);
  833. if (t == self)
  834. continue;
  835. setxid_mark_thread (cmdp, t);
  836. }
  837. /* Iterate until we don't succeed in signalling anyone. That means
  838. we have gotten all running threads, and their children will be
  839. automatically correct once started. */
  840. do
  841. {
  842. signalled = 0;
  843. list_for_each (runp, &stack_used)
  844. {
  845. struct pthread *t = list_entry (runp, struct pthread, list);
  846. if (t == self)
  847. continue;
  848. signalled += setxid_signal_thread (cmdp, t);
  849. }
  850. list_for_each (runp, &__stack_user)
  851. {
  852. struct pthread *t = list_entry (runp, struct pthread, list);
  853. if (t == self)
  854. continue;
  855. signalled += setxid_signal_thread (cmdp, t);
  856. }
  857. int cur = cmdp->cntr;
  858. while (cur != 0)
  859. {
  860. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  861. cur = cmdp->cntr;
  862. }
  863. }
  864. while (signalled != 0);
  865. /* Clean up flags, so that no thread blocks during exit waiting
  866. for a signal which will never come. */
  867. list_for_each (runp, &stack_used)
  868. {
  869. struct pthread *t = list_entry (runp, struct pthread, list);
  870. if (t == self)
  871. continue;
  872. setxid_unmark_thread (cmdp, t);
  873. }
  874. list_for_each (runp, &__stack_user)
  875. {
  876. struct pthread *t = list_entry (runp, struct pthread, list);
  877. if (t == self)
  878. continue;
  879. setxid_unmark_thread (cmdp, t);
  880. }
  881. /* This must be last, otherwise the current thread might not have
  882. permissions to send SIGSETXID syscall to the other threads. */
  883. INTERNAL_SYSCALL_DECL (err);
  884. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  885. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  886. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  887. {
  888. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  889. result = -1;
  890. }
  891. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  892. return result;
  893. }
  894. static inline void __attribute__((always_inline))
  895. init_one_static_tls (struct pthread *curp, struct link_map *map)
  896. {
  897. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  898. # if defined(TLS_TCB_AT_TP)
  899. void *dest = (char *) curp - map->l_tls_offset;
  900. # elif defined(TLS_DTV_AT_TP)
  901. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  902. # else
  903. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  904. # endif
  905. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  906. dtv[map->l_tls_modid].pointer.val = dest;
  907. dtv[map->l_tls_modid].pointer.is_static = true;
  908. /* Initialize the memory. */
  909. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  910. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  911. }
  912. void
  913. attribute_hidden
  914. __pthread_init_static_tls (struct link_map *map)
  915. {
  916. lll_lock (stack_cache_lock, LLL_PRIVATE);
  917. /* Iterate over the list with system-allocated threads first. */
  918. list_t *runp;
  919. list_for_each (runp, &stack_used)
  920. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  921. /* Now the list with threads using user-allocated stacks. */
  922. list_for_each (runp, &__stack_user)
  923. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  924. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  925. }
  926. void
  927. attribute_hidden
  928. __wait_lookup_done (void)
  929. {
  930. lll_lock (stack_cache_lock, LLL_PRIVATE);
  931. struct pthread *self = THREAD_SELF;
  932. /* Iterate over the list with system-allocated threads first. */
  933. list_t *runp;
  934. list_for_each (runp, &stack_used)
  935. {
  936. struct pthread *t = list_entry (runp, struct pthread, list);
  937. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  938. continue;
  939. int *const gscope_flagp = &t->header.gscope_flag;
  940. /* We have to wait until this thread is done with the global
  941. scope. First tell the thread that we are waiting and
  942. possibly have to be woken. */
  943. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  944. THREAD_GSCOPE_FLAG_WAIT,
  945. THREAD_GSCOPE_FLAG_USED))
  946. continue;
  947. do
  948. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  949. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  950. }
  951. /* Now the list with threads using user-allocated stacks. */
  952. list_for_each (runp, &__stack_user)
  953. {
  954. struct pthread *t = list_entry (runp, struct pthread, list);
  955. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  956. continue;
  957. int *const gscope_flagp = &t->header.gscope_flag;
  958. /* We have to wait until this thread is done with the global
  959. scope. First tell the thread that we are waiting and
  960. possibly have to be woken. */
  961. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  962. THREAD_GSCOPE_FLAG_WAIT,
  963. THREAD_GSCOPE_FLAG_USED))
  964. continue;
  965. do
  966. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  967. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  968. }
  969. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  970. }