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, 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. #include <bits/kernel-features.h>
  28. #ifndef NEED_SEPARATE_REGISTER_STACK
  29. /* Most architectures have exactly one stack pointer. Some have more. */
  30. # define STACK_VARIABLES void *stackaddr = NULL
  31. /* How to pass the values to the 'create_thread' function. */
  32. # define STACK_VARIABLES_ARGS stackaddr
  33. /* How to declare function which gets there parameters. */
  34. # define STACK_VARIABLES_PARMS void *stackaddr
  35. /* How to declare allocate_stack. */
  36. # define ALLOCATE_STACK_PARMS void **stack
  37. /* This is how the function is called. We do it this way to allow
  38. other variants of the function to have more parameters. */
  39. # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
  40. #else
  41. /* We need two stacks. The kernel will place them but we have to tell
  42. the kernel about the size of the reserved address space. */
  43. # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
  44. /* How to pass the values to the 'create_thread' function. */
  45. # define STACK_VARIABLES_ARGS stackaddr, stacksize
  46. /* How to declare function which gets there parameters. */
  47. # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
  48. /* How to declare allocate_stack. */
  49. # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
  50. /* This is how the function is called. We do it this way to allow
  51. other variants of the function to have more parameters. */
  52. # define ALLOCATE_STACK(attr, pd) \
  53. allocate_stack (attr, pd, &stackaddr, &stacksize)
  54. #endif
  55. /* Default alignment of stack. */
  56. #ifndef STACK_ALIGN
  57. # define STACK_ALIGN __alignof__ (long double)
  58. #endif
  59. /* Default value for minimal stack size after allocating thread
  60. descriptor and guard. */
  61. #ifndef MINIMAL_REST_STACK
  62. # define MINIMAL_REST_STACK 4096
  63. #endif
  64. /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
  65. a stack. Use it when possible. */
  66. #ifndef MAP_STACK
  67. # define MAP_STACK 0
  68. #endif
  69. /* This yields the pointer that TLS support code calls the thread pointer. */
  70. #if defined(TLS_TCB_AT_TP)
  71. # define TLS_TPADJ(pd) (pd)
  72. #elif defined(TLS_DTV_AT_TP)
  73. # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
  74. #endif
  75. /* Cache handling for not-yet free stacks. */
  76. /* 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 int 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. /* We need to record what list operations we are going to do so that,
  86. in case of an asynchronous interruption due to a fork() call, we
  87. can correct for the work. */
  88. static uintptr_t in_flight_stack;
  89. /* List of the threads with user provided stacks in use. No need to
  90. initialize this, since it's done in __pthread_initialize_minimal. */
  91. list_t __stack_user __attribute__ ((nocommon));
  92. hidden_data_def (__stack_user)
  93. #if COLORING_INCREMENT != 0
  94. /* Number of threads created. */
  95. static unsigned int nptl_ncreated;
  96. #endif
  97. /* Check whether the stack is still used or not. */
  98. #define FREE_P(descr) ((descr)->tid <= 0)
  99. static void
  100. stack_list_del (list_t *elem)
  101. {
  102. in_flight_stack = (uintptr_t) elem;
  103. atomic_write_barrier ();
  104. list_del (elem);
  105. atomic_write_barrier ();
  106. in_flight_stack = 0;
  107. }
  108. static void
  109. stack_list_add (list_t *elem, list_t *list)
  110. {
  111. in_flight_stack = (uintptr_t) elem | 1;
  112. atomic_write_barrier ();
  113. list_add (elem, list);
  114. atomic_write_barrier ();
  115. in_flight_stack = 0;
  116. }
  117. /* We create a double linked list of all cache entries. Double linked
  118. because this allows removing entries from the end. */
  119. /* Get a stack frame from the cache. We have to match by size since
  120. some blocks might be too small or far too large. */
  121. static struct pthread *
  122. get_cached_stack (size_t *sizep, void **memp)
  123. {
  124. size_t size = *sizep;
  125. struct pthread *result = NULL;
  126. list_t *entry;
  127. lll_lock (stack_cache_lock, LLL_PRIVATE);
  128. /* Search the cache for a matching entry. We search for the
  129. smallest stack which has at least the required size. Note that
  130. in normal situations the size of all allocated stacks is the
  131. same. As the very least there are only a few different sizes.
  132. Therefore this loop will exit early most of the time with an
  133. exact match. */
  134. list_for_each (entry, &stack_cache)
  135. {
  136. struct pthread *curr;
  137. curr = list_entry (entry, struct pthread, list);
  138. if (FREE_P (curr) && curr->stackblock_size >= size)
  139. {
  140. if (curr->stackblock_size == size)
  141. {
  142. result = curr;
  143. break;
  144. }
  145. if (result == NULL
  146. || result->stackblock_size > curr->stackblock_size)
  147. result = curr;
  148. }
  149. }
  150. if (__builtin_expect (result == NULL, 0)
  151. /* Make sure the size difference is not too excessive. In that
  152. case we do not use the block. */
  153. || __builtin_expect (result->stackblock_size > 4 * size, 0))
  154. {
  155. /* Release the lock. */
  156. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  157. return NULL;
  158. }
  159. /* Dequeue the entry. */
  160. stack_list_del (&result->list);
  161. /* And add to the list of stacks in use. */
  162. stack_list_add (&result->list, &stack_used);
  163. /* And decrease the cache size. */
  164. stack_cache_actsize -= result->stackblock_size;
  165. /* Release the lock early. */
  166. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  167. /* Report size and location of the stack to the caller. */
  168. *sizep = result->stackblock_size;
  169. *memp = result->stackblock;
  170. /* Cancellation handling is back to the default. */
  171. result->cancelhandling = 0;
  172. result->cleanup = NULL;
  173. /* No pending event. */
  174. result->nextevent = NULL;
  175. /* Clear the DTV. */
  176. dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
  177. memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
  178. /* Re-initialize the TLS. */
  179. _dl_allocate_tls_init (TLS_TPADJ (result));
  180. return result;
  181. }
  182. /* Free stacks until cache size is lower than LIMIT. */
  183. void
  184. __free_stacks (size_t limit)
  185. {
  186. /* We reduce the size of the cache. Remove the last entries until
  187. the size is below the limit. */
  188. list_t *entry;
  189. list_t *prev;
  190. /* Search from the end of the list. */
  191. list_for_each_prev_safe (entry, prev, &stack_cache)
  192. {
  193. struct pthread *curr;
  194. curr = list_entry (entry, struct pthread, list);
  195. if (FREE_P (curr))
  196. {
  197. /* Unlink the block. */
  198. stack_list_del (entry);
  199. /* Account for the freed memory. */
  200. stack_cache_actsize -= curr->stackblock_size;
  201. /* Free the memory associated with the ELF TLS. */
  202. _dl_deallocate_tls (TLS_TPADJ (curr), false);
  203. /* Remove this block. This should never fail. If it does
  204. something is really wrong. */
  205. if (munmap (curr->stackblock, curr->stackblock_size) != 0)
  206. abort ();
  207. /* Maybe we have freed enough. */
  208. if (stack_cache_actsize <= limit)
  209. break;
  210. }
  211. }
  212. }
  213. /* Add a stack frame which is not used anymore to the stack. Must be
  214. called with the cache lock held. */
  215. static inline void
  216. __attribute ((always_inline))
  217. queue_stack (struct pthread *stack)
  218. {
  219. /* We unconditionally add the stack to the list. The memory may
  220. still be in use but it will not be reused until the kernel marks
  221. the stack as not used anymore. */
  222. stack_list_add (&stack->list, &stack_cache);
  223. stack_cache_actsize += stack->stackblock_size;
  224. if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
  225. __free_stacks (stack_cache_maxsize);
  226. }
  227. static int
  228. internal_function
  229. change_stack_perm (struct pthread *pd
  230. #ifdef NEED_SEPARATE_REGISTER_STACK
  231. , size_t pagemask
  232. #endif
  233. )
  234. {
  235. #ifdef NEED_SEPARATE_REGISTER_STACK
  236. void *stack = (pd->stackblock
  237. + (((((pd->stackblock_size - pd->guardsize) / 2)
  238. & pagemask) + pd->guardsize) & pagemask));
  239. size_t len = pd->stackblock + pd->stackblock_size - stack;
  240. #elif _STACK_GROWS_DOWN
  241. void *stack = pd->stackblock + pd->guardsize;
  242. size_t len = pd->stackblock_size - pd->guardsize;
  243. #elif _STACK_GROWS_UP
  244. void *stack = pd->stackblock;
  245. size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
  246. #else
  247. # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
  248. #endif
  249. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  250. return errno;
  251. return 0;
  252. }
  253. static int
  254. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  255. ALLOCATE_STACK_PARMS)
  256. {
  257. struct pthread *pd;
  258. size_t size;
  259. size_t pagesize_m1 = __getpagesize () - 1;
  260. void *stacktop;
  261. assert (attr != NULL);
  262. assert (powerof2 (pagesize_m1 + 1));
  263. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  264. /* Get the stack size from the attribute if it is set. Otherwise we
  265. use the default we determined at start time. */
  266. size = attr->stacksize ?: __default_stacksize;
  267. /* Get memory for the stack. */
  268. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  269. {
  270. uintptr_t adj;
  271. /* If the user also specified the size of the stack make sure it
  272. is large enough. */
  273. if (attr->stacksize != 0
  274. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  275. return EINVAL;
  276. /* Adjust stack size for alignment of the TLS block. */
  277. #if defined(TLS_TCB_AT_TP)
  278. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  279. & __static_tls_align_m1;
  280. assert (size > adj + TLS_TCB_SIZE);
  281. #elif defined(TLS_DTV_AT_TP)
  282. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  283. & __static_tls_align_m1;
  284. assert (size > adj);
  285. #endif
  286. /* The user provided some memory. Let's hope it matches the
  287. size... We do not allocate guard pages if the user provided
  288. the stack. It is the user's responsibility to do this if it
  289. is wanted. */
  290. #if defined(TLS_TCB_AT_TP)
  291. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  292. - TLS_TCB_SIZE - adj);
  293. #elif defined(TLS_DTV_AT_TP)
  294. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  295. - __static_tls_size - adj)
  296. - TLS_PRE_TCB_SIZE);
  297. #endif
  298. /* The user provided stack memory needs to be cleared. */
  299. memset (pd, '\0', sizeof (struct pthread));
  300. /* The first TSD block is included in the TCB. */
  301. pd->specific[0] = pd->specific_1stblock;
  302. /* Remember the stack-related values. */
  303. pd->stackblock = (char *) attr->stackaddr - size;
  304. pd->stackblock_size = size;
  305. /* This is a user-provided stack. It will not be queued in the
  306. stack cache nor will the memory (except the TLS memory) be freed. */
  307. pd->user_stack = true;
  308. /* This is at least the second thread. */
  309. pd->header.multiple_threads = 1;
  310. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  311. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  312. #endif
  313. #ifndef __ASSUME_PRIVATE_FUTEX
  314. /* The thread must know when private futexes are supported. */
  315. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  316. header.private_futex);
  317. #endif
  318. #ifdef NEED_DL_SYSINFO
  319. /* Copy the sysinfo value from the parent. */
  320. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  321. #endif
  322. /* The process ID is also the same as that of the caller. */
  323. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  324. /* Allocate the DTV for this thread. */
  325. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  326. {
  327. /* Something went wrong. */
  328. assert (errno == ENOMEM);
  329. return EAGAIN;
  330. }
  331. /* Prepare to modify global data. */
  332. lll_lock (stack_cache_lock, LLL_PRIVATE);
  333. /* And add to the list of stacks in use. */
  334. list_add (&pd->list, &__stack_user);
  335. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  336. }
  337. else
  338. {
  339. /* Allocate some anonymous memory. If possible use the cache. */
  340. size_t guardsize;
  341. size_t reqsize;
  342. void *mem = 0;
  343. const int prot = (PROT_READ | PROT_WRITE);
  344. #if COLORING_INCREMENT != 0
  345. /* Add one more page for stack coloring. Don't do it for stacks
  346. with 16 times pagesize or larger. This might just cause
  347. unnecessary misalignment. */
  348. if (size <= 16 * pagesize_m1)
  349. size += pagesize_m1 + 1;
  350. #endif
  351. /* Adjust the stack size for alignment. */
  352. size &= ~__static_tls_align_m1;
  353. assert (size != 0);
  354. /* Make sure the size of the stack is enough for the guard and
  355. eventually the thread descriptor. */
  356. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  357. if (__builtin_expect (size < ((guardsize + __static_tls_size
  358. + MINIMAL_REST_STACK + pagesize_m1)
  359. & ~pagesize_m1),
  360. 0))
  361. /* The stack is too small (or the guard too large). */
  362. return EINVAL;
  363. /* Try to get a stack from the cache. */
  364. reqsize = size;
  365. pd = get_cached_stack (&size, &mem);
  366. if (pd == NULL)
  367. {
  368. /* To avoid aliasing effects on a larger scale than pages we
  369. adjust the allocated stack size if necessary. This way
  370. allocations directly following each other will not have
  371. aliasing problems. */
  372. #if MULTI_PAGE_ALIASING != 0
  373. if ((size % MULTI_PAGE_ALIASING) == 0)
  374. size += pagesize_m1 + 1;
  375. #endif
  376. mem = mmap (NULL, size, prot,
  377. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  378. if (__builtin_expect (mem == MAP_FAILED, 0))
  379. {
  380. if (errno == ENOMEM)
  381. __set_errno (EAGAIN);
  382. return errno;
  383. }
  384. /* SIZE is guaranteed to be greater than zero.
  385. So we can never get a null pointer back from mmap. */
  386. assert (mem != NULL);
  387. #if COLORING_INCREMENT != 0
  388. /* Atomically increment NCREATED. */
  389. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  390. /* We chose the offset for coloring by incrementing it for
  391. every new thread by a fixed amount. The offset used
  392. module the page size. Even if coloring would be better
  393. relative to higher alignment values it makes no sense to
  394. do it since the mmap() interface does not allow us to
  395. specify any alignment for the returned memory block. */
  396. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  397. /* Make sure the coloring offsets does not disturb the alignment
  398. of the TCB and static TLS block. */
  399. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  400. coloring = (((coloring + __static_tls_align_m1)
  401. & ~(__static_tls_align_m1))
  402. & ~pagesize_m1);
  403. #else
  404. /* Unless specified we do not make any adjustments. */
  405. # define coloring 0
  406. #endif
  407. /* Place the thread descriptor at the end of the stack. */
  408. #if defined(TLS_TCB_AT_TP)
  409. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  410. #elif defined(TLS_DTV_AT_TP)
  411. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  412. - __static_tls_size)
  413. & ~__static_tls_align_m1)
  414. - TLS_PRE_TCB_SIZE);
  415. #endif
  416. /* Remember the stack-related values. */
  417. pd->stackblock = mem;
  418. pd->stackblock_size = size;
  419. /* We allocated the first block thread-specific data array.
  420. This address will not change for the lifetime of this
  421. descriptor. */
  422. pd->specific[0] = pd->specific_1stblock;
  423. /* This is at least the second thread. */
  424. pd->header.multiple_threads = 1;
  425. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  426. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  427. #endif
  428. #ifndef __ASSUME_PRIVATE_FUTEX
  429. /* The thread must know when private futexes are supported. */
  430. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  431. header.private_futex);
  432. #endif
  433. #ifdef NEED_DL_SYSINFO
  434. /* Copy the sysinfo value from the parent. */
  435. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  436. #endif
  437. /* The process ID is also the same as that of the caller. */
  438. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  439. /* Allocate the DTV for this thread. */
  440. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  441. {
  442. /* Something went wrong. */
  443. assert (errno == ENOMEM);
  444. /* Free the stack memory we just allocated. */
  445. (void) munmap (mem, size);
  446. return EAGAIN;
  447. }
  448. /* Prepare to modify global data. */
  449. lll_lock (stack_cache_lock, LLL_PRIVATE);
  450. /* And add to the list of stacks in use. */
  451. stack_list_add (&pd->list, &stack_used);
  452. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  453. /* Note that all of the stack and the thread descriptor is
  454. zeroed. This means we do not have to initialize fields
  455. with initial value zero. This is specifically true for
  456. the 'tid' field which is always set back to zero once the
  457. stack is not used anymore and for the 'guardsize' field
  458. which will be read next. */
  459. }
  460. /* Create or resize the guard area if necessary. */
  461. if (__builtin_expect (guardsize > pd->guardsize, 0))
  462. {
  463. #ifdef NEED_SEPARATE_REGISTER_STACK
  464. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  465. #elif _STACK_GROWS_DOWN
  466. char *guard = mem;
  467. # elif _STACK_GROWS_UP
  468. char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
  469. #endif
  470. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  471. {
  472. int err;
  473. mprot_error:
  474. err = errno;
  475. lll_lock (stack_cache_lock, LLL_PRIVATE);
  476. /* Remove the thread from the list. */
  477. stack_list_del (&pd->list);
  478. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  479. /* Get rid of the TLS block we allocated. */
  480. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  481. /* Free the stack memory regardless of whether the size
  482. of the cache is over the limit or not. If this piece
  483. of memory caused problems we better do not use it
  484. anymore. Uh, and we ignore possible errors. There
  485. is nothing we could do. */
  486. (void) munmap (mem, size);
  487. return err;
  488. }
  489. pd->guardsize = guardsize;
  490. }
  491. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  492. 0))
  493. {
  494. /* The old guard area is too large. */
  495. #ifdef NEED_SEPARATE_REGISTER_STACK
  496. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  497. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  498. if (oldguard < guard
  499. && mprotect (oldguard, guard - oldguard, prot) != 0)
  500. goto mprot_error;
  501. if (mprotect (guard + guardsize,
  502. oldguard + pd->guardsize - guard - guardsize,
  503. prot) != 0)
  504. goto mprot_error;
  505. #elif _STACK_GROWS_DOWN
  506. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  507. prot) != 0)
  508. goto mprot_error;
  509. #elif _STACK_GROWS_UP
  510. if (mprotect ((char *) pd - pd->guardsize,
  511. pd->guardsize - guardsize, prot) != 0)
  512. goto mprot_error;
  513. #endif
  514. pd->guardsize = guardsize;
  515. }
  516. /* The pthread_getattr_np() calls need to get passed the size
  517. requested in the attribute, regardless of how large the
  518. actually used guardsize is. */
  519. pd->reported_guardsize = guardsize;
  520. }
  521. /* Initialize the lock. We have to do this unconditionally since the
  522. stillborn thread could be canceled while the lock is taken. */
  523. pd->lock = LLL_LOCK_INITIALIZER;
  524. /* The robust mutex lists also need to be initialized
  525. unconditionally because the cleanup for the previous stack owner
  526. might have happened in the kernel. */
  527. pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
  528. - offsetof (pthread_mutex_t,
  529. __data.__list.__next));
  530. pd->robust_head.list_op_pending = NULL;
  531. #ifdef __PTHREAD_MUTEX_HAVE_PREV
  532. pd->robust_prev = &pd->robust_head;
  533. #endif
  534. pd->robust_head.list = &pd->robust_head;
  535. /* We place the thread descriptor at the end of the stack. */
  536. *pdp = pd;
  537. #if defined(TLS_TCB_AT_TP)
  538. /* The stack begins before the TCB and the static TLS block. */
  539. stacktop = ((char *) (pd + 1) - __static_tls_size);
  540. #elif defined(TLS_DTV_AT_TP)
  541. stacktop = (char *) (pd - 1);
  542. #endif
  543. #ifdef NEED_SEPARATE_REGISTER_STACK
  544. *stack = pd->stackblock;
  545. *stacksize = stacktop - *stack;
  546. #elif _STACK_GROWS_DOWN
  547. *stack = stacktop;
  548. #elif _STACK_GROWS_UP
  549. *stack = pd->stackblock;
  550. assert (*stack > 0);
  551. #endif
  552. return 0;
  553. }
  554. void
  555. internal_function
  556. __deallocate_stack (struct pthread *pd)
  557. {
  558. lll_lock (stack_cache_lock, LLL_PRIVATE);
  559. /* Remove the thread from the list of threads with user defined
  560. stacks. */
  561. stack_list_del (&pd->list);
  562. /* Not much to do. Just free the mmap()ed memory. Note that we do
  563. not reset the 'used' flag in the 'tid' field. This is done by
  564. the kernel. If no thread has been created yet this field is
  565. still zero. */
  566. if (__builtin_expect (! pd->user_stack, 1))
  567. (void) queue_stack (pd);
  568. else
  569. /* Free the memory associated with the ELF TLS. */
  570. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  571. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  572. }
  573. int
  574. internal_function
  575. __make_stacks_executable (void **stack_endp)
  576. {
  577. /* First the main thread's stack. */
  578. int err = EPERM;
  579. if (err != 0)
  580. return err;
  581. #ifdef NEED_SEPARATE_REGISTER_STACK
  582. const size_t pagemask = ~(__getpagesize () - 1);
  583. #endif
  584. lll_lock (stack_cache_lock, LLL_PRIVATE);
  585. list_t *runp;
  586. list_for_each (runp, &stack_used)
  587. {
  588. err = change_stack_perm (list_entry (runp, struct pthread, list)
  589. #ifdef NEED_SEPARATE_REGISTER_STACK
  590. , pagemask
  591. #endif
  592. );
  593. if (err != 0)
  594. break;
  595. }
  596. /* Also change the permission for the currently unused stacks. This
  597. might be wasted time but better spend it here than adding a check
  598. in the fast path. */
  599. if (err == 0)
  600. list_for_each (runp, &stack_cache)
  601. {
  602. err = change_stack_perm (list_entry (runp, struct pthread, list)
  603. #ifdef NEED_SEPARATE_REGISTER_STACK
  604. , pagemask
  605. #endif
  606. );
  607. if (err != 0)
  608. break;
  609. }
  610. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  611. return err;
  612. }
  613. /* In case of a fork() call the memory allocation in the child will be
  614. the same but only one thread is running. All stacks except that of
  615. the one running thread are not used anymore. We have to recycle
  616. them. */
  617. void
  618. __reclaim_stacks (void)
  619. {
  620. struct pthread *self = (struct pthread *) THREAD_SELF;
  621. /* No locking necessary. The caller is the only stack in use. But
  622. we have to be aware that we might have interrupted a list
  623. operation. */
  624. if (in_flight_stack != 0)
  625. {
  626. bool add_p = in_flight_stack & 1;
  627. list_t *elem = (list_t *) (in_flight_stack & ~UINTMAX_C (1));
  628. if (add_p)
  629. {
  630. /* We always add at the beginning of the list. So in this
  631. case we only need to check the beginning of these lists. */
  632. int check_list (list_t *l)
  633. {
  634. if (l->next->prev != l)
  635. {
  636. assert (l->next->prev == elem);
  637. elem->next = l->next;
  638. elem->prev = l;
  639. l->next = elem;
  640. return 1;
  641. }
  642. return 0;
  643. }
  644. if (check_list (&stack_used) == 0)
  645. (void) check_list (&stack_cache);
  646. }
  647. else
  648. {
  649. /* We can simply always replay the delete operation. */
  650. elem->next->prev = elem->prev;
  651. elem->prev->next = elem->next;
  652. }
  653. }
  654. /* Mark all stacks except the still running one as free. */
  655. list_t *runp;
  656. list_for_each (runp, &stack_used)
  657. {
  658. struct pthread *curp = list_entry (runp, struct pthread, list);
  659. if (curp != self)
  660. {
  661. /* This marks the stack as free. */
  662. curp->tid = 0;
  663. /* The PID field must be initialized for the new process. */
  664. curp->pid = self->pid;
  665. /* Account for the size of the stack. */
  666. stack_cache_actsize += curp->stackblock_size;
  667. if (curp->specific_used)
  668. {
  669. /* Clear the thread-specific data. */
  670. memset (curp->specific_1stblock, '\0',
  671. sizeof (curp->specific_1stblock));
  672. curp->specific_used = false;
  673. for (size_t 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 __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. }