allocatestack.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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. if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
  253. return errno;
  254. return 0;
  255. }
  256. static int
  257. allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
  258. ALLOCATE_STACK_PARMS)
  259. {
  260. struct pthread *pd;
  261. size_t size;
  262. size_t pagesize_m1 = __getpagesize () - 1;
  263. void *stacktop;
  264. assert (attr != NULL);
  265. assert (powerof2 (pagesize_m1 + 1));
  266. assert (TCB_ALIGNMENT >= STACK_ALIGN);
  267. /* Get the stack size from the attribute if it is set. Otherwise we
  268. use the default we determined at start time. */
  269. size = attr->stacksize ?: __default_stacksize;
  270. /* Get memory for the stack. */
  271. if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
  272. {
  273. uintptr_t adj;
  274. /* If the user also specified the size of the stack make sure it
  275. is large enough. */
  276. if (attr->stacksize != 0
  277. && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
  278. return EINVAL;
  279. /* Adjust stack size for alignment of the TLS block. */
  280. #if defined(TLS_TCB_AT_TP)
  281. adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
  282. & __static_tls_align_m1;
  283. assert (size > adj + TLS_TCB_SIZE);
  284. #elif defined(TLS_DTV_AT_TP)
  285. adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
  286. & __static_tls_align_m1;
  287. assert (size > adj);
  288. #endif
  289. /* The user provided some memory. Let's hope it matches the
  290. size... We do not allocate guard pages if the user provided
  291. the stack. It is the user's responsibility to do this if it
  292. is wanted. */
  293. #if defined(TLS_TCB_AT_TP)
  294. pd = (struct pthread *) ((uintptr_t) attr->stackaddr
  295. - TLS_TCB_SIZE - adj);
  296. #elif defined(TLS_DTV_AT_TP)
  297. pd = (struct pthread *) (((uintptr_t) attr->stackaddr
  298. - __static_tls_size - adj)
  299. - TLS_PRE_TCB_SIZE);
  300. #endif
  301. /* The user provided stack memory needs to be cleared. */
  302. memset (pd, '\0', sizeof (struct pthread));
  303. /* The first TSD block is included in the TCB. */
  304. pd->specific[0] = pd->specific_1stblock;
  305. /* Remember the stack-related values. */
  306. pd->stackblock = (char *) attr->stackaddr - size;
  307. pd->stackblock_size = size;
  308. /* This is a user-provided stack. It will not be queued in the
  309. stack cache nor will the memory (except the TLS memory) be freed. */
  310. pd->user_stack = true;
  311. /* This is at least the second thread. */
  312. pd->header.multiple_threads = 1;
  313. #ifndef TLS_MULTIPLE_THREADS_IN_TCB
  314. __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
  315. #endif
  316. #ifndef __ASSUME_PRIVATE_FUTEX
  317. /* The thread must know when private futexes are supported. */
  318. pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
  319. header.private_futex);
  320. #endif
  321. #ifdef NEED_DL_SYSINFO
  322. /* Copy the sysinfo value from the parent. */
  323. THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
  324. #endif
  325. /* The process ID is also the same as that of the caller. */
  326. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  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. /* The process ID is also the same as that of the caller. */
  441. pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
  442. /* Allocate the DTV for this thread. */
  443. if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
  444. {
  445. /* Something went wrong. */
  446. assert (errno == ENOMEM);
  447. /* Free the stack memory we just allocated. */
  448. (void) munmap (mem, size);
  449. return EAGAIN;
  450. }
  451. /* Prepare to modify global data. */
  452. lll_lock (stack_cache_lock, LLL_PRIVATE);
  453. /* And add to the list of stacks in use. */
  454. stack_list_add (&pd->list, &stack_used);
  455. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  456. /* Note that all of the stack and the thread descriptor is
  457. zeroed. This means we do not have to initialize fields
  458. with initial value zero. This is specifically true for
  459. the 'tid' field which is always set back to zero once the
  460. stack is not used anymore and for the 'guardsize' field
  461. which will be read next. */
  462. }
  463. /* Create or resize the guard area if necessary. */
  464. if (__builtin_expect (guardsize > pd->guardsize, 0))
  465. {
  466. #ifdef NEED_SEPARATE_REGISTER_STACK
  467. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  468. #elif defined _STACK_GROWS_DOWN
  469. char *guard = mem;
  470. #elif defined _STACK_GROWS_UP
  471. char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
  472. #endif
  473. if (mprotect (guard, guardsize, PROT_NONE) != 0)
  474. {
  475. int err;
  476. mprot_error:
  477. err = errno;
  478. lll_lock (stack_cache_lock, LLL_PRIVATE);
  479. /* Remove the thread from the list. */
  480. stack_list_del (&pd->list);
  481. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  482. /* Get rid of the TLS block we allocated. */
  483. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  484. /* Free the stack memory regardless of whether the size
  485. of the cache is over the limit or not. If this piece
  486. of memory caused problems we better do not use it
  487. anymore. Uh, and we ignore possible errors. There
  488. is nothing we could do. */
  489. (void) munmap (mem, size);
  490. return err;
  491. }
  492. pd->guardsize = guardsize;
  493. }
  494. else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
  495. 0))
  496. {
  497. /* The old guard area is too large. */
  498. #ifdef NEED_SEPARATE_REGISTER_STACK
  499. char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
  500. char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
  501. if (oldguard < guard
  502. && mprotect (oldguard, guard - oldguard, prot) != 0)
  503. goto mprot_error;
  504. if (mprotect (guard + guardsize,
  505. oldguard + pd->guardsize - guard - guardsize,
  506. prot) != 0)
  507. goto mprot_error;
  508. #elif defined _STACK_GROWS_DOWN
  509. if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
  510. prot) != 0)
  511. goto mprot_error;
  512. #elif defined _STACK_GROWS_UP
  513. if (mprotect ((char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1),
  514. pd->guardsize - guardsize, prot) != 0)
  515. goto mprot_error;
  516. #endif
  517. pd->guardsize = guardsize;
  518. }
  519. /* The pthread_getattr_np() calls need to get passed the size
  520. requested in the attribute, regardless of how large the
  521. actually used guardsize is. */
  522. pd->reported_guardsize = guardsize;
  523. }
  524. /* Initialize the lock. We have to do this unconditionally since the
  525. stillborn thread could be canceled while the lock is taken. */
  526. pd->lock = LLL_LOCK_INITIALIZER;
  527. /* The robust mutex lists also need to be initialized
  528. unconditionally because the cleanup for the previous stack owner
  529. might have happened in the kernel. */
  530. pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
  531. - offsetof (pthread_mutex_t,
  532. __data.__list.__next));
  533. pd->robust_head.list_op_pending = NULL;
  534. #ifdef __PTHREAD_MUTEX_HAVE_PREV
  535. pd->robust_prev = &pd->robust_head;
  536. #endif
  537. pd->robust_head.list = &pd->robust_head;
  538. /* We place the thread descriptor at the end of the stack. */
  539. *pdp = pd;
  540. #if defined(TLS_TCB_AT_TP)
  541. /* The stack begins before the TCB and the static TLS block. */
  542. stacktop = ((char *) (pd + 1) - __static_tls_size);
  543. #elif defined(TLS_DTV_AT_TP)
  544. stacktop = (char *) (pd - 1);
  545. #endif
  546. #ifdef NEED_SEPARATE_REGISTER_STACK
  547. *stack = pd->stackblock;
  548. *stacksize = stacktop - *stack;
  549. #elif defined _STACK_GROWS_DOWN
  550. *stack = stacktop;
  551. #elif defined _STACK_GROWS_UP
  552. *stack = pd->stackblock;
  553. assert (*stack > 0);
  554. #endif
  555. return 0;
  556. }
  557. void
  558. internal_function
  559. __deallocate_stack (struct pthread *pd)
  560. {
  561. lll_lock (stack_cache_lock, LLL_PRIVATE);
  562. /* Remove the thread from the list of threads with user defined
  563. stacks. */
  564. stack_list_del (&pd->list);
  565. /* Not much to do. Just free the mmap()ed memory. Note that we do
  566. not reset the 'used' flag in the 'tid' field. This is done by
  567. the kernel. If no thread has been created yet this field is
  568. still zero. */
  569. if (__builtin_expect (! pd->user_stack, 1))
  570. (void) queue_stack (pd);
  571. else
  572. /* Free the memory associated with the ELF TLS. */
  573. _dl_deallocate_tls (TLS_TPADJ (pd), false);
  574. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  575. }
  576. int
  577. internal_function
  578. __make_stacks_executable (void **stack_endp)
  579. {
  580. /* First the main thread's stack. */
  581. int err = EPERM;
  582. if (err != 0)
  583. return err;
  584. #ifdef NEED_SEPARATE_REGISTER_STACK
  585. const size_t pagemask = ~(__getpagesize () - 1);
  586. #endif
  587. lll_lock (stack_cache_lock, LLL_PRIVATE);
  588. list_t *runp;
  589. list_for_each (runp, &stack_used)
  590. {
  591. err = change_stack_perm (list_entry (runp, struct pthread, list)
  592. #ifdef NEED_SEPARATE_REGISTER_STACK
  593. , pagemask
  594. #endif
  595. );
  596. if (err != 0)
  597. break;
  598. }
  599. /* Also change the permission for the currently unused stacks. This
  600. might be wasted time but better spend it here than adding a check
  601. in the fast path. */
  602. if (err == 0)
  603. list_for_each (runp, &stack_cache)
  604. {
  605. err = change_stack_perm (list_entry (runp, struct pthread, list)
  606. #ifdef NEED_SEPARATE_REGISTER_STACK
  607. , pagemask
  608. #endif
  609. );
  610. if (err != 0)
  611. break;
  612. }
  613. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  614. return err;
  615. }
  616. /* In case of a fork() call the memory allocation in the child will be
  617. the same but only one thread is running. All stacks except that of
  618. the one running thread are not used anymore. We have to recycle
  619. them. */
  620. void
  621. __reclaim_stacks (void)
  622. {
  623. struct pthread *self = (struct pthread *) THREAD_SELF;
  624. /* No locking necessary. The caller is the only stack in use. But
  625. we have to be aware that we might have interrupted a list
  626. operation. */
  627. if (in_flight_stack != 0)
  628. {
  629. bool add_p = in_flight_stack & 1;
  630. list_t *elem = (list_t *)(uintptr_t)(in_flight_stack & ~UINTMAX_C (1));
  631. if (add_p)
  632. {
  633. /* We always add at the beginning of the list. So in this
  634. case we only need to check the beginning of these lists. */
  635. int check_list (list_t *l)
  636. {
  637. if (l->next->prev != l)
  638. {
  639. assert (l->next->prev == elem);
  640. elem->next = l->next;
  641. elem->prev = l;
  642. l->next = elem;
  643. return 1;
  644. }
  645. return 0;
  646. }
  647. if (check_list (&stack_used) == 0)
  648. (void) check_list (&stack_cache);
  649. }
  650. else
  651. {
  652. /* We can simply always replay the delete operation. */
  653. elem->next->prev = elem->prev;
  654. elem->prev->next = elem->next;
  655. }
  656. }
  657. /* Mark all stacks except the still running one as free. */
  658. list_t *runp;
  659. list_for_each (runp, &stack_used)
  660. {
  661. struct pthread *curp = list_entry (runp, struct pthread, list);
  662. if (curp != self)
  663. {
  664. /* This marks the stack as free. */
  665. curp->tid = 0;
  666. /* The PID field must be initialized for the new process. */
  667. curp->pid = self->pid;
  668. /* Account for the size of the stack. */
  669. stack_cache_actsize += curp->stackblock_size;
  670. if (curp->specific_used)
  671. {
  672. /* Clear the thread-specific data. */
  673. memset (curp->specific_1stblock, '\0',
  674. sizeof (curp->specific_1stblock));
  675. curp->specific_used = false;
  676. size_t cnt;
  677. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  678. if (curp->specific[cnt] != NULL)
  679. {
  680. memset (curp->specific[cnt], '\0',
  681. sizeof (curp->specific_1stblock));
  682. /* We have allocated the block which we do not
  683. free here so re-set the bit. */
  684. curp->specific_used = true;
  685. }
  686. }
  687. }
  688. }
  689. /* Reset the PIDs in any cached stacks. */
  690. list_for_each (runp, &stack_cache)
  691. {
  692. struct pthread *curp = list_entry (runp, struct pthread, list);
  693. curp->pid = self->pid;
  694. }
  695. /* Add the stack of all running threads to the cache. */
  696. list_splice (&stack_used, &stack_cache);
  697. /* Remove the entry for the current thread to from the cache list
  698. and add it to the list of running threads. Which of the two
  699. lists is decided by the user_stack flag. */
  700. stack_list_del (&self->list);
  701. /* Re-initialize the lists for all the threads. */
  702. INIT_LIST_HEAD (&stack_used);
  703. INIT_LIST_HEAD (&__stack_user);
  704. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  705. list_add (&self->list, &__stack_user);
  706. else
  707. list_add (&self->list, &stack_used);
  708. /* There is one thread running. */
  709. __nptl_nthreads = 1;
  710. in_flight_stack = 0;
  711. /* Initialize the lock. */
  712. stack_cache_lock = LLL_LOCK_INITIALIZER;
  713. }
  714. #if HP_TIMING_AVAIL
  715. # undef __find_thread_by_id
  716. /* Find a thread given the thread ID. */
  717. attribute_hidden
  718. struct pthread *
  719. __find_thread_by_id (pid_t tid)
  720. {
  721. struct pthread *result = NULL;
  722. lll_lock (stack_cache_lock, LLL_PRIVATE);
  723. /* Iterate over the list with system-allocated threads first. */
  724. list_t *runp;
  725. list_for_each (runp, &stack_used)
  726. {
  727. struct pthread *curp;
  728. curp = list_entry (runp, struct pthread, list);
  729. if (curp->tid == tid)
  730. {
  731. result = curp;
  732. goto out;
  733. }
  734. }
  735. /* Now the list with threads using user-allocated stacks. */
  736. list_for_each (runp, &__stack_user)
  737. {
  738. struct pthread *curp;
  739. curp = list_entry (runp, struct pthread, list);
  740. if (curp->tid == tid)
  741. {
  742. result = curp;
  743. goto out;
  744. }
  745. }
  746. out:
  747. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  748. return result;
  749. }
  750. #endif
  751. static void
  752. internal_function
  753. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  754. {
  755. int ch;
  756. /* Don't let the thread exit before the setxid handler runs. */
  757. t->setxid_futex = 0;
  758. do
  759. {
  760. ch = t->cancelhandling;
  761. /* If the thread is exiting right now, ignore it. */
  762. if ((ch & EXITING_BITMASK) != 0)
  763. return;
  764. }
  765. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  766. ch | SETXID_BITMASK, ch));
  767. }
  768. static void
  769. internal_function
  770. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  771. {
  772. int ch;
  773. do
  774. {
  775. ch = t->cancelhandling;
  776. if ((ch & SETXID_BITMASK) == 0)
  777. return;
  778. }
  779. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  780. ch & ~SETXID_BITMASK, ch));
  781. /* Release the futex just in case. */
  782. t->setxid_futex = 1;
  783. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  784. }
  785. static int
  786. internal_function
  787. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  788. {
  789. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  790. return 0;
  791. int val;
  792. INTERNAL_SYSCALL_DECL (err);
  793. #if defined (__ASSUME_TGKILL) && __ASSUME_TGKILL
  794. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  795. t->tid, SIGSETXID);
  796. #else
  797. # ifdef __NR_tgkill
  798. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  799. t->tid, SIGSETXID);
  800. if (INTERNAL_SYSCALL_ERROR_P (val, err)
  801. && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
  802. # endif
  803. val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
  804. #endif
  805. /* If this failed, it must have had not started yet or else exited. */
  806. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  807. {
  808. atomic_increment (&cmdp->cntr);
  809. return 1;
  810. }
  811. else
  812. return 0;
  813. }
  814. int
  815. attribute_hidden
  816. __nptl_setxid (struct xid_command *cmdp)
  817. {
  818. int signalled;
  819. int result;
  820. lll_lock (stack_cache_lock, LLL_PRIVATE);
  821. __xidcmd = cmdp;
  822. cmdp->cntr = 0;
  823. struct pthread *self = THREAD_SELF;
  824. /* Iterate over the list with system-allocated threads first. */
  825. list_t *runp;
  826. list_for_each (runp, &stack_used)
  827. {
  828. struct pthread *t = list_entry (runp, struct pthread, list);
  829. if (t == self)
  830. continue;
  831. setxid_mark_thread (cmdp, t);
  832. }
  833. /* Now the list with threads using user-allocated stacks. */
  834. list_for_each (runp, &__stack_user)
  835. {
  836. struct pthread *t = list_entry (runp, struct pthread, list);
  837. if (t == self)
  838. continue;
  839. setxid_mark_thread (cmdp, t);
  840. }
  841. /* Iterate until we don't succeed in signalling anyone. That means
  842. we have gotten all running threads, and their children will be
  843. automatically correct once started. */
  844. do
  845. {
  846. signalled = 0;
  847. list_for_each (runp, &stack_used)
  848. {
  849. struct pthread *t = list_entry (runp, struct pthread, list);
  850. if (t == self)
  851. continue;
  852. signalled += setxid_signal_thread (cmdp, t);
  853. }
  854. list_for_each (runp, &__stack_user)
  855. {
  856. struct pthread *t = list_entry (runp, struct pthread, list);
  857. if (t == self)
  858. continue;
  859. signalled += setxid_signal_thread (cmdp, t);
  860. }
  861. int cur = cmdp->cntr;
  862. while (cur != 0)
  863. {
  864. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  865. cur = cmdp->cntr;
  866. }
  867. }
  868. while (signalled != 0);
  869. /* Clean up flags, so that no thread blocks during exit waiting
  870. for a signal which will never come. */
  871. list_for_each (runp, &stack_used)
  872. {
  873. struct pthread *t = list_entry (runp, struct pthread, list);
  874. if (t == self)
  875. continue;
  876. setxid_unmark_thread (cmdp, t);
  877. }
  878. list_for_each (runp, &__stack_user)
  879. {
  880. struct pthread *t = list_entry (runp, struct pthread, list);
  881. if (t == self)
  882. continue;
  883. setxid_unmark_thread (cmdp, t);
  884. }
  885. /* This must be last, otherwise the current thread might not have
  886. permissions to send SIGSETXID syscall to the other threads. */
  887. INTERNAL_SYSCALL_DECL (err);
  888. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  889. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  890. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  891. {
  892. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  893. result = -1;
  894. }
  895. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  896. return result;
  897. }
  898. static inline void __attribute__((always_inline))
  899. init_one_static_tls (struct pthread *curp, struct link_map *map)
  900. {
  901. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  902. # if defined(TLS_TCB_AT_TP)
  903. void *dest = (char *) curp - map->l_tls_offset;
  904. # elif defined(TLS_DTV_AT_TP)
  905. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  906. # else
  907. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  908. # endif
  909. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  910. dtv[map->l_tls_modid].pointer.val = dest;
  911. dtv[map->l_tls_modid].pointer.is_static = true;
  912. /* Initialize the memory. */
  913. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  914. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  915. }
  916. void
  917. attribute_hidden
  918. __pthread_init_static_tls (struct link_map *map)
  919. {
  920. lll_lock (stack_cache_lock, LLL_PRIVATE);
  921. /* Iterate over the list with system-allocated threads first. */
  922. list_t *runp;
  923. list_for_each (runp, &stack_used)
  924. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  925. /* Now the list with threads using user-allocated stacks. */
  926. list_for_each (runp, &__stack_user)
  927. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  928. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  929. }
  930. void
  931. attribute_hidden
  932. __wait_lookup_done (void)
  933. {
  934. lll_lock (stack_cache_lock, LLL_PRIVATE);
  935. struct pthread *self = THREAD_SELF;
  936. /* Iterate over the list with system-allocated threads first. */
  937. list_t *runp;
  938. list_for_each (runp, &stack_used)
  939. {
  940. struct pthread *t = list_entry (runp, struct pthread, list);
  941. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  942. continue;
  943. int *const gscope_flagp = &t->header.gscope_flag;
  944. /* We have to wait until this thread is done with the global
  945. scope. First tell the thread that we are waiting and
  946. possibly have to be woken. */
  947. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  948. THREAD_GSCOPE_FLAG_WAIT,
  949. THREAD_GSCOPE_FLAG_USED))
  950. continue;
  951. do
  952. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  953. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  954. }
  955. /* Now the list with threads using user-allocated stacks. */
  956. list_for_each (runp, &__stack_user)
  957. {
  958. struct pthread *t = list_entry (runp, struct pthread, list);
  959. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  960. continue;
  961. int *const gscope_flagp = &t->header.gscope_flag;
  962. /* We have to wait until this thread is done with the global
  963. scope. First tell the thread that we are waiting and
  964. possibly have to be woken. */
  965. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  966. THREAD_GSCOPE_FLAG_WAIT,
  967. THREAD_GSCOPE_FLAG_USED))
  968. continue;
  969. do
  970. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  971. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  972. }
  973. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  974. }