allocatestack.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. /* Copyright (C) 2002-2007, 2009 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <signal.h>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <sys/mman.h>
  22. #include <sys/param.h>
  23. #include <tls.h>
  24. #include <lowlevellock.h>
  25. #include <link.h>
  26. #include <bits/kernel-features.h>
  27. #ifndef NEED_SEPARATE_REGISTER_STACK
  28. /* Most architectures have exactly one stack pointer. Some have more. */
  29. # define STACK_VARIABLES void *stackaddr = NULL
  30. /* How to pass the values to the 'create_thread' function. */
  31. # define STACK_VARIABLES_ARGS stackaddr
  32. /* How to declare function which gets there parameters. */
  33. # define STACK_VARIABLES_PARMS void *stackaddr
  34. /* How to declare allocate_stack. */
  35. # define ALLOCATE_STACK_PARMS void **stack
  36. /* This is how the function is called. We do it this way to allow
  37. other variants of the function to have more parameters. */
  38. # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
  39. #else
  40. /* We need two stacks. The kernel will place them but we have to tell
  41. the kernel about the size of the reserved address space. */
  42. # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
  43. /* How to pass the values to the 'create_thread' function. */
  44. # define STACK_VARIABLES_ARGS stackaddr, stacksize
  45. /* How to declare function which gets there parameters. */
  46. # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
  47. /* How to declare allocate_stack. */
  48. # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
  49. /* This is how the function is called. We do it this way to allow
  50. other variants of the function to have more parameters. */
  51. # define ALLOCATE_STACK(attr, pd) \
  52. allocate_stack (attr, pd, &stackaddr, &stacksize)
  53. #endif
  54. /* Default alignment of stack. */
  55. #ifndef STACK_ALIGN
  56. # define STACK_ALIGN __alignof__ (long double)
  57. #endif
  58. /* Default value for minimal stack size after allocating thread
  59. descriptor and guard. */
  60. #ifndef MINIMAL_REST_STACK
  61. # define MINIMAL_REST_STACK 4096
  62. #endif
  63. /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
  64. a stack. Use it when possible. */
  65. #ifndef MAP_STACK
  66. # define MAP_STACK 0
  67. #endif
  68. /* This yields the pointer that TLS support code calls the thread pointer. */
  69. #if defined(TLS_TCB_AT_TP)
  70. # define TLS_TPADJ(pd) (pd)
  71. #elif defined(TLS_DTV_AT_TP)
  72. # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
  73. #endif
  74. /* Cache handling for not-yet free stacks. */
  75. /*
  76. Maximum size in kB of cache. GNU libc default is 40MiB
  77. embedded systems don't have enough ram for big dirty stack caches,
  78. reduce it to 16MiB. 4 does not work, f.e. tst-kill4 segfaults.
  79. */
  80. static size_t stack_cache_maxsize = 16 * 1024 * 1024;
  81. static size_t stack_cache_actsize;
  82. /* Mutex protecting this variable. */
  83. static int stack_cache_lock = LLL_LOCK_INITIALIZER;
  84. /* List of queued stack frames. */
  85. static LIST_HEAD (stack_cache);
  86. /* List of the stacks in use. */
  87. static LIST_HEAD (stack_used);
  88. /* We need to record what list operations we are going to do so that,
  89. in case of an asynchronous interruption due to a fork() call, we
  90. can correct for the work. */
  91. static uintptr_t in_flight_stack;
  92. /* List of the threads with user provided stacks in use. No need to
  93. initialize this, since it's done in __pthread_initialize_minimal. */
  94. list_t __stack_user __attribute__ ((nocommon));
  95. hidden_data_def (__stack_user)
  96. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  97. /* Number of threads created. */
  98. static unsigned int nptl_ncreated;
  99. #endif
  100. /* Check whether the stack is still used or not. */
  101. #define FREE_P(descr) ((descr)->tid <= 0)
  102. static void
  103. stack_list_del (list_t *elem)
  104. {
  105. in_flight_stack = (uintptr_t) elem;
  106. atomic_write_barrier ();
  107. list_del (elem);
  108. atomic_write_barrier ();
  109. in_flight_stack = 0;
  110. }
  111. static void
  112. stack_list_add (list_t *elem, list_t *list)
  113. {
  114. in_flight_stack = (uintptr_t) elem | 1;
  115. atomic_write_barrier ();
  116. list_add (elem, list);
  117. atomic_write_barrier ();
  118. in_flight_stack = 0;
  119. }
  120. /* We create a double linked list of all cache entries. Double linked
  121. because this allows removing entries from the end. */
  122. /* Get a stack frame from the cache. We have to match by size since
  123. some blocks might be too small or far too large. */
  124. static struct pthread *
  125. get_cached_stack (size_t *sizep, void **memp)
  126. {
  127. size_t size = *sizep;
  128. struct pthread *result = NULL;
  129. list_t *entry;
  130. lll_lock (stack_cache_lock, LLL_PRIVATE);
  131. /* Search the cache for a matching entry. We search for the
  132. smallest stack which has at least the required size. Note that
  133. in normal situations the size of all allocated stacks is the
  134. same. As the very least there are only a few different sizes.
  135. Therefore this loop will exit early most of the time with an
  136. exact match. */
  137. list_for_each (entry, &stack_cache)
  138. {
  139. struct pthread *curr;
  140. curr = list_entry (entry, struct pthread, list);
  141. if (FREE_P (curr) && curr->stackblock_size >= size)
  142. {
  143. if (curr->stackblock_size == size)
  144. {
  145. result = curr;
  146. break;
  147. }
  148. if (result == NULL
  149. || result->stackblock_size > curr->stackblock_size)
  150. result = curr;
  151. }
  152. }
  153. if (__builtin_expect (result == NULL, 0)
  154. /* Make sure the size difference is not too excessive. In that
  155. case we do not use the block. */
  156. || __builtin_expect (result->stackblock_size > 4 * size, 0))
  157. {
  158. /* Release the lock. */
  159. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  160. return NULL;
  161. }
  162. /* Dequeue the entry. */
  163. stack_list_del (&result->list);
  164. /* And add to the list of stacks in use. */
  165. stack_list_add (&result->list, &stack_used);
  166. /* And decrease the cache size. */
  167. stack_cache_actsize -= result->stackblock_size;
  168. /* Release the lock early. */
  169. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  170. /* Report size and location of the stack to the caller. */
  171. *sizep = result->stackblock_size;
  172. *memp = result->stackblock;
  173. /* Cancellation handling is back to the default. */
  174. result->cancelhandling = 0;
  175. result->cleanup = NULL;
  176. /* No pending event. */
  177. result->nextevent = NULL;
  178. /* Clear the DTV. */
  179. dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
  180. memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
  181. /* Re-initialize the TLS. */
  182. _dl_allocate_tls_init (TLS_TPADJ (result));
  183. return result;
  184. }
  185. /* Free stacks until cache size is lower than LIMIT. */
  186. void
  187. __free_stacks (size_t limit)
  188. {
  189. /* We reduce the size of the cache. Remove the last entries until
  190. the size is below the limit. */
  191. list_t *entry;
  192. list_t *prev;
  193. /* Search from the end of the list. */
  194. list_for_each_prev_safe (entry, prev, &stack_cache)
  195. {
  196. struct pthread *curr;
  197. curr = list_entry (entry, struct pthread, list);
  198. if (FREE_P (curr))
  199. {
  200. /* Unlink the block. */
  201. stack_list_del (entry);
  202. /* Account for the freed memory. */
  203. stack_cache_actsize -= curr->stackblock_size;
  204. /* Free the memory associated with the ELF TLS. */
  205. _dl_deallocate_tls (TLS_TPADJ (curr), false);
  206. /* Remove this block. This should never fail. If it does
  207. something is really wrong. */
  208. if (munmap (curr->stackblock, curr->stackblock_size) != 0)
  209. abort ();
  210. /* Maybe we have freed enough. */
  211. if (stack_cache_actsize <= limit)
  212. break;
  213. }
  214. }
  215. }
  216. /* Add a stack frame which is not used anymore to the stack. Must be
  217. called with the cache lock held. */
  218. static inline void
  219. __attribute ((always_inline))
  220. queue_stack (struct pthread *stack)
  221. {
  222. /* We unconditionally add the stack to the list. The memory may
  223. still be in use but it will not be reused until the kernel marks
  224. the stack as not used anymore. */
  225. stack_list_add (&stack->list, &stack_cache);
  226. stack_cache_actsize += stack->stackblock_size;
  227. if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
  228. __free_stacks (stack_cache_maxsize);
  229. }
  230. static int
  231. internal_function
  232. change_stack_perm (struct pthread *pd
  233. #ifdef NEED_SEPARATE_REGISTER_STACK
  234. , size_t pagemask
  235. #endif
  236. )
  237. {
  238. #ifdef NEED_SEPARATE_REGISTER_STACK
  239. void *stack = (pd->stackblock
  240. + (((((pd->stackblock_size - pd->guardsize) / 2)
  241. & pagemask) + pd->guardsize) & pagemask));
  242. size_t len = pd->stackblock + pd->stackblock_size - stack;
  243. #elif defined _STACK_GROWS_DOWN
  244. void *stack = pd->stackblock + pd->guardsize;
  245. size_t len = pd->stackblock_size - pd->guardsize;
  246. #elif defined _STACK_GROWS_UP
  247. void *stack = pd->stackblock;
  248. size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
  249. #else
  250. # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
  251. #endif
  252. #ifdef __ARCH_USE_MMU__
  253. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  254. return errno;
  255. #endif
  256. return 0;
  257. }
  258. static int
  259. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  260. ALLOCATE_STACK_PARMS)
  261. {
  262. struct pthread *pd;
  263. size_t size;
  264. size_t pagesize_m1 = __getpagesize () - 1;
  265. void *stacktop;
  266. assert (attr != NULL);
  267. assert (powerof2 (pagesize_m1 + 1));
  268. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  269. /* Get the stack size from the attribute if it is set. Otherwise we
  270. use the default we determined at start time. */
  271. size = attr->stacksize ?: __default_stacksize;
  272. /* Get memory for the stack. */
  273. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  274. {
  275. uintptr_t adj;
  276. /* If the user also specified the size of the stack make sure it
  277. is large enough. */
  278. if (attr->stacksize != 0
  279. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  280. return EINVAL;
  281. /* Adjust stack size for alignment of the TLS block. */
  282. #if defined(TLS_TCB_AT_TP)
  283. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  284. & __static_tls_align_m1;
  285. assert (size > adj + TLS_TCB_SIZE);
  286. #elif defined(TLS_DTV_AT_TP)
  287. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  288. & __static_tls_align_m1;
  289. assert (size > adj);
  290. #endif
  291. /* The user provided some memory. Let's hope it matches the
  292. size... We do not allocate guard pages if the user provided
  293. the stack. It is the user's responsibility to do this if it
  294. is wanted. */
  295. #if defined(TLS_TCB_AT_TP)
  296. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  297. - TLS_TCB_SIZE - adj);
  298. #elif defined(TLS_DTV_AT_TP)
  299. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  300. - __static_tls_size - adj)
  301. - TLS_PRE_TCB_SIZE);
  302. #endif
  303. /* The user provided stack memory needs to be cleared. */
  304. memset (pd, '\0', sizeof (struct pthread));
  305. /* The first TSD block is included in the TCB. */
  306. pd->specific[0] = pd->specific_1stblock;
  307. /* Remember the stack-related values. */
  308. pd->stackblock = (char *) attr->stackaddr - size;
  309. pd->stackblock_size = size;
  310. /* This is a user-provided stack. It will not be queued in the
  311. stack cache nor will the memory (except the TLS memory) be freed. */
  312. pd->user_stack = true;
  313. /* This is at least the second thread. */
  314. pd->header.multiple_threads = 1;
  315. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  316. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  317. #endif
  318. #ifndef __ASSUME_PRIVATE_FUTEX
  319. /* The thread must know when private futexes are supported. */
  320. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  321. header.private_futex);
  322. #endif
  323. #ifdef NEED_DL_SYSINFO
  324. /* Copy the sysinfo value from the parent. */
  325. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  326. #endif
  327. /* Allocate the DTV for this thread. */
  328. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  329. {
  330. /* Something went wrong. */
  331. assert (errno == ENOMEM);
  332. return EAGAIN;
  333. }
  334. /* Prepare to modify global data. */
  335. lll_lock (stack_cache_lock, LLL_PRIVATE);
  336. /* And add to the list of stacks in use. */
  337. list_add (&pd->list, &__stack_user);
  338. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  339. }
  340. else
  341. {
  342. /* Allocate some anonymous memory. If possible use the cache. */
  343. size_t guardsize;
  344. size_t reqsize;
  345. void *mem = 0;
  346. const int prot = (PROT_READ | PROT_WRITE);
  347. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  348. /* Add one more page for stack coloring. Don't do it for stacks
  349. with 16 times pagesize or larger. This might just cause
  350. unnecessary misalignment. */
  351. if (size <= 16 * pagesize_m1)
  352. size += pagesize_m1 + 1;
  353. #endif
  354. /* Adjust the stack size for alignment. */
  355. size &= ~__static_tls_align_m1;
  356. assert (size != 0);
  357. /* Make sure the size of the stack is enough for the guard and
  358. eventually the thread descriptor. */
  359. guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
  360. if (__builtin_expect (size < ((guardsize + __static_tls_size
  361. + MINIMAL_REST_STACK + pagesize_m1)
  362. & ~pagesize_m1),
  363. 0))
  364. /* The stack is too small (or the guard too large). */
  365. return EINVAL;
  366. /* Try to get a stack from the cache. */
  367. reqsize = size;
  368. pd = get_cached_stack (&size, &mem);
  369. if (pd == NULL)
  370. {
  371. /* To avoid aliasing effects on a larger scale than pages we
  372. adjust the allocated stack size if necessary. This way
  373. allocations directly following each other will not have
  374. aliasing problems. */
  375. #if defined MULTI_PAGE_ALIASING && MULTI_PAGE_ALIASING != 0
  376. if ((size % MULTI_PAGE_ALIASING) == 0)
  377. size += pagesize_m1 + 1;
  378. #endif
  379. mem = mmap (NULL, size, prot,
  380. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  381. if (__builtin_expect (mem == MAP_FAILED, 0))
  382. {
  383. if (errno == ENOMEM)
  384. __set_errno (EAGAIN);
  385. return errno;
  386. }
  387. /* SIZE is guaranteed to be greater than zero.
  388. So we can never get a null pointer back from mmap. */
  389. assert (mem != NULL);
  390. #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
  391. /* Atomically increment NCREATED. */
  392. unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
  393. /* We chose the offset for coloring by incrementing it for
  394. every new thread by a fixed amount. The offset used
  395. module the page size. Even if coloring would be better
  396. relative to higher alignment values it makes no sense to
  397. do it since the mmap() interface does not allow us to
  398. specify any alignment for the returned memory block. */
  399. size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
  400. /* Make sure the coloring offsets does not disturb the alignment
  401. of the TCB and static TLS block. */
  402. if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
  403. coloring = (((coloring + __static_tls_align_m1)
  404. & ~(__static_tls_align_m1))
  405. & ~pagesize_m1);
  406. #else
  407. /* Unless specified we do not make any adjustments. */
  408. # define coloring 0
  409. #endif
  410. /* Place the thread descriptor at the end of the stack. */
  411. #if defined(TLS_TCB_AT_TP)
  412. pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
  413. #elif defined(TLS_DTV_AT_TP)
  414. pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
  415. - __static_tls_size)
  416. & ~__static_tls_align_m1)
  417. - TLS_PRE_TCB_SIZE);
  418. #endif
  419. /* Remember the stack-related values. */
  420. pd->stackblock = mem;
  421. pd->stackblock_size = size;
  422. /* We allocated the first block thread-specific data array.
  423. This address will not change for the lifetime of this
  424. descriptor. */
  425. pd->specific[0] = pd->specific_1stblock;
  426. /* This is at least the second thread. */
  427. pd->header.multiple_threads = 1;
  428. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  429. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  430. #endif
  431. #ifndef __ASSUME_PRIVATE_FUTEX
  432. /* The thread must know when private futexes are supported. */
  433. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  434. header.private_futex);
  435. #endif
  436. #ifdef NEED_DL_SYSINFO
  437. /* Copy the sysinfo value from the parent. */
  438. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  439. #endif
  440. /* Allocate the DTV for this thread. */
  441. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  442. {
  443. /* Something went wrong. */
  444. assert (errno == ENOMEM);
  445. /* Free the stack memory we just allocated. */
  446. (void) munmap (mem, size);
  447. return EAGAIN;
  448. }
  449. /* Prepare to modify global data. */
  450. lll_lock (stack_cache_lock, LLL_PRIVATE);
  451. /* And add to the list of stacks in use. */
  452. stack_list_add (&pd->list, &stack_used);
  453. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  454. /* Note that all of the stack and the thread descriptor is
  455. zeroed. This means we do not have to initialize fields
  456. with initial value zero. This is specifically true for
  457. the 'tid' field which is always set back to zero once the
  458. stack is not used anymore and for the 'guardsize' field
  459. which will be read next. */
  460. }
  461. /* Create or resize the guard area if necessary. */
  462. if (__builtin_expect (guardsize > pd->guardsize, 0))
  463. {
  464. #ifdef NEED_SEPARATE_REGISTER_STACK
  465. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  466. #elif defined _STACK_GROWS_DOWN
  467. char *guard = mem;
  468. #elif defined _STACK_GROWS_UP
  469. char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
  470. #endif
  471. #ifdef __ARCH_USE_MMU__
  472. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  473. {
  474. int err;
  475. #ifdef NEED_SEPARATE_REGISTER_STACK
  476. mprot_error:
  477. #endif
  478. err = errno;
  479. lll_lock (stack_cache_lock, LLL_PRIVATE);
  480. /* Remove the thread from the list. */
  481. stack_list_del (&pd->list);
  482. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  483. /* Get rid of the TLS block we allocated. */
  484. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  485. /* Free the stack memory regardless of whether the size
  486. of the cache is over the limit or not. If this piece
  487. of memory caused problems we better do not use it
  488. anymore. Uh, and we ignore possible errors. There
  489. is nothing we could do. */
  490. (void) munmap (mem, size);
  491. return err;
  492. }
  493. #endif
  494. pd->guardsize = guardsize;
  495. }
  496. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  497. 0))
  498. {
  499. /* The old guard area is too large. */
  500. #ifdef NEED_SEPARATE_REGISTER_STACK
  501. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  502. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  503. #ifdef __ARCH_USE_MMU__
  504. if (oldguard < guard
  505. && mprotect (oldguard, guard - oldguard, prot) != 0)
  506. goto mprot_error;
  507. if (mprotect (guard + guardsize,
  508. oldguard + pd->guardsize - guard - guardsize,
  509. prot) != 0)
  510. goto mprot_error;
  511. #elif defined _STACK_GROWS_DOWN
  512. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  513. prot) != 0)
  514. goto mprot_error;
  515. #elif defined _STACK_GROWS_UP
  516. if (mprotect ((char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1),
  517. pd->guardsize - guardsize, prot) != 0)
  518. goto mprot_error;
  519. #endif
  520. #endif
  521. pd->guardsize = guardsize;
  522. }
  523. /* The pthread_getattr_np() calls need to get passed the size
  524. requested in the attribute, regardless of how large the
  525. actually used guardsize is. */
  526. pd->reported_guardsize = guardsize;
  527. }
  528. /* Initialize the lock. We have to do this unconditionally since the
  529. stillborn thread could be canceled while the lock is taken. */
  530. pd->lock = LLL_LOCK_INITIALIZER;
  531. /* The robust mutex lists also need to be initialized
  532. unconditionally because the cleanup for the previous stack owner
  533. might have happened in the kernel. */
  534. pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
  535. - offsetof (pthread_mutex_t,
  536. __data.__list.__next));
  537. pd->robust_head.list_op_pending = NULL;
  538. #ifdef __PTHREAD_MUTEX_HAVE_PREV
  539. pd->robust_prev = &pd->robust_head;
  540. #endif
  541. pd->robust_head.list = &pd->robust_head;
  542. /* We place the thread descriptor at the end of the stack. */
  543. *pdp = pd;
  544. #if defined(TLS_TCB_AT_TP)
  545. /* The stack begins before the TCB and the static TLS block. */
  546. stacktop = ((char *) (pd + 1) - __static_tls_size);
  547. #elif defined(TLS_DTV_AT_TP)
  548. stacktop = (char *) (pd - 1);
  549. #endif
  550. #ifdef NEED_SEPARATE_REGISTER_STACK
  551. *stack = pd->stackblock;
  552. *stacksize = stacktop - *stack;
  553. #elif defined _STACK_GROWS_DOWN
  554. *stack = stacktop;
  555. #elif defined _STACK_GROWS_UP
  556. *stack = pd->stackblock;
  557. assert (*stack > 0);
  558. #endif
  559. return 0;
  560. }
  561. void
  562. internal_function
  563. __deallocate_stack (struct pthread *pd)
  564. {
  565. lll_lock (stack_cache_lock, LLL_PRIVATE);
  566. /* Remove the thread from the list of threads with user defined
  567. stacks. */
  568. stack_list_del (&pd->list);
  569. /* Not much to do. Just free the mmap()ed memory. Note that we do
  570. not reset the 'used' flag in the 'tid' field. This is done by
  571. the kernel. If no thread has been created yet this field is
  572. still zero. */
  573. if (__builtin_expect (! pd->user_stack, 1))
  574. (void) queue_stack (pd);
  575. else
  576. /* Free the memory associated with the ELF TLS. */
  577. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  578. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  579. }
  580. int
  581. internal_function
  582. __make_stacks_executable (void **stack_endp)
  583. {
  584. /* First the main thread's stack. */
  585. int err = EPERM;
  586. if (err != 0)
  587. return err;
  588. #ifdef NEED_SEPARATE_REGISTER_STACK
  589. const size_t pagemask = ~(__getpagesize () - 1);
  590. #endif
  591. lll_lock (stack_cache_lock, LLL_PRIVATE);
  592. list_t *runp;
  593. list_for_each (runp, &stack_used)
  594. {
  595. err = change_stack_perm (list_entry (runp, struct pthread, list)
  596. #ifdef NEED_SEPARATE_REGISTER_STACK
  597. , pagemask
  598. #endif
  599. );
  600. if (err != 0)
  601. break;
  602. }
  603. /* Also change the permission for the currently unused stacks. This
  604. might be wasted time but better spend it here than adding a check
  605. in the fast path. */
  606. if (err == 0)
  607. list_for_each (runp, &stack_cache)
  608. {
  609. err = change_stack_perm (list_entry (runp, struct pthread, list)
  610. #ifdef NEED_SEPARATE_REGISTER_STACK
  611. , pagemask
  612. #endif
  613. );
  614. if (err != 0)
  615. break;
  616. }
  617. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  618. return err;
  619. }
  620. /* In case of a fork() call the memory allocation in the child will be
  621. the same but only one thread is running. All stacks except that of
  622. the one running thread are not used anymore. We have to recycle
  623. them. */
  624. void
  625. __reclaim_stacks (void)
  626. {
  627. struct pthread *self = (struct pthread *) THREAD_SELF;
  628. /* No locking necessary. The caller is the only stack in use. But
  629. we have to be aware that we might have interrupted a list
  630. operation. */
  631. if (in_flight_stack != 0)
  632. {
  633. bool add_p = in_flight_stack & 1;
  634. list_t *elem = (list_t *)(uintptr_t)(in_flight_stack & ~UINTMAX_C (1));
  635. if (add_p)
  636. {
  637. /* We always add at the beginning of the list. So in this
  638. case we only need to check the beginning of these lists. */
  639. int check_list (list_t *l)
  640. {
  641. if (l->next->prev != l)
  642. {
  643. assert (l->next->prev == elem);
  644. elem->next = l->next;
  645. elem->prev = l;
  646. l->next = elem;
  647. return 1;
  648. }
  649. return 0;
  650. }
  651. if (check_list (&stack_used) == 0)
  652. (void) check_list (&stack_cache);
  653. }
  654. else
  655. {
  656. /* We can simply always replay the delete operation. */
  657. elem->next->prev = elem->prev;
  658. elem->prev->next = elem->next;
  659. }
  660. }
  661. /* Mark all stacks except the still running one as free. */
  662. list_t *runp;
  663. list_for_each (runp, &stack_used)
  664. {
  665. struct pthread *curp = list_entry (runp, struct pthread, list);
  666. if (curp != self)
  667. {
  668. /* This marks the stack as free. */
  669. curp->tid = 0;
  670. /* Account for the size of the stack. */
  671. stack_cache_actsize += curp->stackblock_size;
  672. if (curp->specific_used)
  673. {
  674. /* Clear the thread-specific data. */
  675. memset (curp->specific_1stblock, '\0',
  676. sizeof (curp->specific_1stblock));
  677. curp->specific_used = false;
  678. size_t cnt;
  679. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  680. if (curp->specific[cnt] != NULL)
  681. {
  682. memset (curp->specific[cnt], '\0',
  683. sizeof (curp->specific_1stblock));
  684. /* We have allocated the block which we do not
  685. free here so re-set the bit. */
  686. curp->specific_used = true;
  687. }
  688. }
  689. }
  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. static void
  711. internal_function
  712. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  713. {
  714. int ch;
  715. /* Don't let the thread exit before the setxid handler runs. */
  716. t->setxid_futex = 0;
  717. do
  718. {
  719. ch = t->cancelhandling;
  720. /* If the thread is exiting right now, ignore it. */
  721. if ((ch & EXITING_BITMASK) != 0)
  722. return;
  723. }
  724. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  725. ch | SETXID_BITMASK, ch));
  726. }
  727. static void
  728. internal_function
  729. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  730. {
  731. int ch;
  732. do
  733. {
  734. ch = t->cancelhandling;
  735. if ((ch & SETXID_BITMASK) == 0)
  736. return;
  737. }
  738. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  739. ch & ~SETXID_BITMASK, ch));
  740. /* Release the futex just in case. */
  741. t->setxid_futex = 1;
  742. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  743. }
  744. static int
  745. internal_function
  746. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  747. {
  748. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  749. return 0;
  750. int val;
  751. pid_t pid = getpid ();
  752. INTERNAL_SYSCALL_DECL (err);
  753. val = INTERNAL_SYSCALL (tgkill, err, 3, pid, t->tid, SIGSETXID);
  754. /* If this failed, it must have had not started yet or else exited. */
  755. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  756. {
  757. atomic_increment (&cmdp->cntr);
  758. return 1;
  759. }
  760. else
  761. return 0;
  762. }
  763. int
  764. attribute_hidden
  765. __nptl_setxid (struct xid_command *cmdp)
  766. {
  767. int signalled;
  768. int result;
  769. lll_lock (stack_cache_lock, LLL_PRIVATE);
  770. __xidcmd = cmdp;
  771. cmdp->cntr = 0;
  772. struct pthread *self = THREAD_SELF;
  773. /* Iterate over the list with system-allocated threads first. */
  774. list_t *runp;
  775. list_for_each (runp, &stack_used)
  776. {
  777. struct pthread *t = list_entry (runp, struct pthread, list);
  778. if (t == self)
  779. continue;
  780. setxid_mark_thread (cmdp, t);
  781. }
  782. /* Now the list with threads using user-allocated stacks. */
  783. list_for_each (runp, &__stack_user)
  784. {
  785. struct pthread *t = list_entry (runp, struct pthread, list);
  786. if (t == self)
  787. continue;
  788. setxid_mark_thread (cmdp, t);
  789. }
  790. /* Iterate until we don't succeed in signalling anyone. That means
  791. we have gotten all running threads, and their children will be
  792. automatically correct once started. */
  793. do
  794. {
  795. signalled = 0;
  796. list_for_each (runp, &stack_used)
  797. {
  798. struct pthread *t = list_entry (runp, struct pthread, list);
  799. if (t == self)
  800. continue;
  801. signalled += setxid_signal_thread (cmdp, t);
  802. }
  803. list_for_each (runp, &__stack_user)
  804. {
  805. struct pthread *t = list_entry (runp, struct pthread, list);
  806. if (t == self)
  807. continue;
  808. signalled += setxid_signal_thread (cmdp, t);
  809. }
  810. int cur = cmdp->cntr;
  811. while (cur != 0)
  812. {
  813. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  814. cur = cmdp->cntr;
  815. }
  816. }
  817. while (signalled != 0);
  818. /* Clean up flags, so that no thread blocks during exit waiting
  819. for a signal which will never come. */
  820. list_for_each (runp, &stack_used)
  821. {
  822. struct pthread *t = list_entry (runp, struct pthread, list);
  823. if (t == self)
  824. continue;
  825. setxid_unmark_thread (cmdp, t);
  826. }
  827. list_for_each (runp, &__stack_user)
  828. {
  829. struct pthread *t = list_entry (runp, struct pthread, list);
  830. if (t == self)
  831. continue;
  832. setxid_unmark_thread (cmdp, t);
  833. }
  834. /* This must be last, otherwise the current thread might not have
  835. permissions to send SIGSETXID syscall to the other threads. */
  836. INTERNAL_SYSCALL_DECL (err);
  837. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  838. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  839. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  840. {
  841. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  842. result = -1;
  843. }
  844. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  845. return result;
  846. }
  847. static inline void __attribute__((always_inline))
  848. init_one_static_tls (struct pthread *curp, struct link_map *map)
  849. {
  850. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  851. # if defined(TLS_TCB_AT_TP)
  852. void *dest = (char *) curp - map->l_tls_offset;
  853. # elif defined(TLS_DTV_AT_TP)
  854. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  855. # else
  856. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  857. # endif
  858. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  859. dtv[map->l_tls_modid].pointer.val = dest;
  860. dtv[map->l_tls_modid].pointer.is_static = true;
  861. /* Initialize the memory. */
  862. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  863. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  864. }
  865. void
  866. attribute_hidden
  867. __pthread_init_static_tls (struct link_map *map)
  868. {
  869. lll_lock (stack_cache_lock, LLL_PRIVATE);
  870. /* Iterate over the list with system-allocated threads first. */
  871. list_t *runp;
  872. list_for_each (runp, &stack_used)
  873. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  874. /* Now the list with threads using user-allocated stacks. */
  875. list_for_each (runp, &__stack_user)
  876. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  877. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  878. }
  879. void
  880. attribute_hidden
  881. __wait_lookup_done (void)
  882. {
  883. lll_lock (stack_cache_lock, LLL_PRIVATE);
  884. struct pthread *self = THREAD_SELF;
  885. /* Iterate over the list with system-allocated threads first. */
  886. list_t *runp;
  887. list_for_each (runp, &stack_used)
  888. {
  889. struct pthread *t = list_entry (runp, struct pthread, list);
  890. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  891. continue;
  892. int *const gscope_flagp = &t->header.gscope_flag;
  893. /* We have to wait until this thread is done with the global
  894. scope. First tell the thread that we are waiting and
  895. possibly have to be woken. */
  896. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  897. THREAD_GSCOPE_FLAG_WAIT,
  898. THREAD_GSCOPE_FLAG_USED))
  899. continue;
  900. do
  901. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  902. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  903. }
  904. /* Now the list with threads using user-allocated stacks. */
  905. list_for_each (runp, &__stack_user)
  906. {
  907. struct pthread *t = list_entry (runp, struct pthread, list);
  908. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  909. continue;
  910. int *const gscope_flagp = &t->header.gscope_flag;
  911. /* We have to wait until this thread is done with the global
  912. scope. First tell the thread that we are waiting and
  913. possibly have to be woken. */
  914. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  915. THREAD_GSCOPE_FLAG_WAIT,
  916. THREAD_GSCOPE_FLAG_USED))
  917. continue;
  918. do
  919. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  920. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  921. }
  922. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  923. }