allocatestack.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. size_t cnt;
  674. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  675. if (curp->specific[cnt] != NULL)
  676. {
  677. memset (curp->specific[cnt], '\0',
  678. sizeof (curp->specific_1stblock));
  679. /* We have allocated the block which we do not
  680. free here so re-set the bit. */
  681. curp->specific_used = true;
  682. }
  683. }
  684. }
  685. }
  686. /* Reset the PIDs in any cached stacks. */
  687. list_for_each (runp, &stack_cache)
  688. {
  689. struct pthread *curp = list_entry (runp, struct pthread, list);
  690. curp->pid = self->pid;
  691. }
  692. /* Add the stack of all running threads to the cache. */
  693. list_splice (&stack_used, &stack_cache);
  694. /* Remove the entry for the current thread to from the cache list
  695. and add it to the list of running threads. Which of the two
  696. lists is decided by the user_stack flag. */
  697. stack_list_del (&self->list);
  698. /* Re-initialize the lists for all the threads. */
  699. INIT_LIST_HEAD (&stack_used);
  700. INIT_LIST_HEAD (&__stack_user);
  701. if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
  702. list_add (&self->list, &__stack_user);
  703. else
  704. list_add (&self->list, &stack_used);
  705. /* There is one thread running. */
  706. __nptl_nthreads = 1;
  707. in_flight_stack = 0;
  708. /* Initialize the lock. */
  709. stack_cache_lock = LLL_LOCK_INITIALIZER;
  710. }
  711. #if HP_TIMING_AVAIL
  712. # undef __find_thread_by_id
  713. /* Find a thread given the thread ID. */
  714. attribute_hidden
  715. struct pthread *
  716. __find_thread_by_id (pid_t tid)
  717. {
  718. struct pthread *result = NULL;
  719. lll_lock (stack_cache_lock, LLL_PRIVATE);
  720. /* Iterate over the list with system-allocated threads first. */
  721. list_t *runp;
  722. list_for_each (runp, &stack_used)
  723. {
  724. struct pthread *curp;
  725. curp = list_entry (runp, struct pthread, list);
  726. if (curp->tid == tid)
  727. {
  728. result = curp;
  729. goto out;
  730. }
  731. }
  732. /* Now the list with threads using user-allocated stacks. */
  733. list_for_each (runp, &__stack_user)
  734. {
  735. struct pthread *curp;
  736. curp = list_entry (runp, struct pthread, list);
  737. if (curp->tid == tid)
  738. {
  739. result = curp;
  740. goto out;
  741. }
  742. }
  743. out:
  744. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  745. return result;
  746. }
  747. #endif
  748. static void
  749. internal_function
  750. setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
  751. {
  752. int ch;
  753. /* Don't let the thread exit before the setxid handler runs. */
  754. t->setxid_futex = 0;
  755. do
  756. {
  757. ch = t->cancelhandling;
  758. /* If the thread is exiting right now, ignore it. */
  759. if ((ch & EXITING_BITMASK) != 0)
  760. return;
  761. }
  762. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  763. ch | SETXID_BITMASK, ch));
  764. }
  765. static void
  766. internal_function
  767. setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
  768. {
  769. int ch;
  770. do
  771. {
  772. ch = t->cancelhandling;
  773. if ((ch & SETXID_BITMASK) == 0)
  774. return;
  775. }
  776. while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
  777. ch & ~SETXID_BITMASK, ch));
  778. /* Release the futex just in case. */
  779. t->setxid_futex = 1;
  780. lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
  781. }
  782. static int
  783. internal_function
  784. setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
  785. {
  786. if ((t->cancelhandling & SETXID_BITMASK) == 0)
  787. return 0;
  788. int val;
  789. INTERNAL_SYSCALL_DECL (err);
  790. #if __ASSUME_TGKILL
  791. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  792. t->tid, SIGSETXID);
  793. #else
  794. # ifdef __NR_tgkill
  795. val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
  796. t->tid, SIGSETXID);
  797. if (INTERNAL_SYSCALL_ERROR_P (val, err)
  798. && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
  799. # endif
  800. val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
  801. #endif
  802. /* If this failed, it must have had not started yet or else exited. */
  803. if (!INTERNAL_SYSCALL_ERROR_P (val, err))
  804. {
  805. atomic_increment (&cmdp->cntr);
  806. return 1;
  807. }
  808. else
  809. return 0;
  810. }
  811. int
  812. attribute_hidden
  813. __nptl_setxid (struct xid_command *cmdp)
  814. {
  815. int signalled;
  816. int result;
  817. lll_lock (stack_cache_lock, LLL_PRIVATE);
  818. __xidcmd = cmdp;
  819. cmdp->cntr = 0;
  820. struct pthread *self = THREAD_SELF;
  821. /* Iterate over the list with system-allocated threads first. */
  822. list_t *runp;
  823. list_for_each (runp, &stack_used)
  824. {
  825. struct pthread *t = list_entry (runp, struct pthread, list);
  826. if (t == self)
  827. continue;
  828. setxid_mark_thread (cmdp, t);
  829. }
  830. /* Now the list with threads using user-allocated stacks. */
  831. list_for_each (runp, &__stack_user)
  832. {
  833. struct pthread *t = list_entry (runp, struct pthread, list);
  834. if (t == self)
  835. continue;
  836. setxid_mark_thread (cmdp, t);
  837. }
  838. /* Iterate until we don't succeed in signalling anyone. That means
  839. we have gotten all running threads, and their children will be
  840. automatically correct once started. */
  841. do
  842. {
  843. signalled = 0;
  844. list_for_each (runp, &stack_used)
  845. {
  846. struct pthread *t = list_entry (runp, struct pthread, list);
  847. if (t == self)
  848. continue;
  849. signalled += setxid_signal_thread (cmdp, t);
  850. }
  851. list_for_each (runp, &__stack_user)
  852. {
  853. struct pthread *t = list_entry (runp, struct pthread, list);
  854. if (t == self)
  855. continue;
  856. signalled += setxid_signal_thread (cmdp, t);
  857. }
  858. int cur = cmdp->cntr;
  859. while (cur != 0)
  860. {
  861. lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
  862. cur = cmdp->cntr;
  863. }
  864. }
  865. while (signalled != 0);
  866. /* Clean up flags, so that no thread blocks during exit waiting
  867. for a signal which will never come. */
  868. list_for_each (runp, &stack_used)
  869. {
  870. struct pthread *t = list_entry (runp, struct pthread, list);
  871. if (t == self)
  872. continue;
  873. setxid_unmark_thread (cmdp, t);
  874. }
  875. list_for_each (runp, &__stack_user)
  876. {
  877. struct pthread *t = list_entry (runp, struct pthread, list);
  878. if (t == self)
  879. continue;
  880. setxid_unmark_thread (cmdp, t);
  881. }
  882. /* This must be last, otherwise the current thread might not have
  883. permissions to send SIGSETXID syscall to the other threads. */
  884. INTERNAL_SYSCALL_DECL (err);
  885. result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
  886. cmdp->id[0], cmdp->id[1], cmdp->id[2]);
  887. if (INTERNAL_SYSCALL_ERROR_P (result, err))
  888. {
  889. __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
  890. result = -1;
  891. }
  892. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  893. return result;
  894. }
  895. static inline void __attribute__((always_inline))
  896. init_one_static_tls (struct pthread *curp, struct link_map *map)
  897. {
  898. dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
  899. # if defined(TLS_TCB_AT_TP)
  900. void *dest = (char *) curp - map->l_tls_offset;
  901. # elif defined(TLS_DTV_AT_TP)
  902. void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  903. # else
  904. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  905. # endif
  906. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  907. dtv[map->l_tls_modid].pointer.val = dest;
  908. dtv[map->l_tls_modid].pointer.is_static = true;
  909. /* Initialize the memory. */
  910. memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  911. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  912. }
  913. void
  914. attribute_hidden
  915. __pthread_init_static_tls (struct link_map *map)
  916. {
  917. lll_lock (stack_cache_lock, LLL_PRIVATE);
  918. /* Iterate over the list with system-allocated threads first. */
  919. list_t *runp;
  920. list_for_each (runp, &stack_used)
  921. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  922. /* Now the list with threads using user-allocated stacks. */
  923. list_for_each (runp, &__stack_user)
  924. init_one_static_tls (list_entry (runp, struct pthread, list), map);
  925. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  926. }
  927. void
  928. attribute_hidden
  929. __wait_lookup_done (void)
  930. {
  931. lll_lock (stack_cache_lock, LLL_PRIVATE);
  932. struct pthread *self = THREAD_SELF;
  933. /* Iterate over the list with system-allocated threads first. */
  934. list_t *runp;
  935. list_for_each (runp, &stack_used)
  936. {
  937. struct pthread *t = list_entry (runp, struct pthread, list);
  938. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  939. continue;
  940. int *const gscope_flagp = &t->header.gscope_flag;
  941. /* We have to wait until this thread is done with the global
  942. scope. First tell the thread that we are waiting and
  943. possibly have to be woken. */
  944. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  945. THREAD_GSCOPE_FLAG_WAIT,
  946. THREAD_GSCOPE_FLAG_USED))
  947. continue;
  948. do
  949. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  950. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  951. }
  952. /* Now the list with threads using user-allocated stacks. */
  953. list_for_each (runp, &__stack_user)
  954. {
  955. struct pthread *t = list_entry (runp, struct pthread, list);
  956. if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
  957. continue;
  958. int *const gscope_flagp = &t->header.gscope_flag;
  959. /* We have to wait until this thread is done with the global
  960. scope. First tell the thread that we are waiting and
  961. possibly have to be woken. */
  962. if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
  963. THREAD_GSCOPE_FLAG_WAIT,
  964. THREAD_GSCOPE_FLAG_USED))
  965. continue;
  966. do
  967. lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
  968. while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
  969. }
  970. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  971. }