Fix Wundef warning for __STDC_VERSION__
[glibc.git] / nptl / allocatestack.c
blob9095ef430d97474115fa25a3427ddd2e62616a0f
1 /* Copyright (C) 2002-2014 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 #include <assert.h>
20 #include <errno.h>
21 #include <signal.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <sys/mman.h>
26 #include <sys/param.h>
27 #include <dl-sysdep.h>
28 #include <dl-tls.h>
29 #include <tls.h>
30 #include <list.h>
31 #include <lowlevellock.h>
32 #include <kernel-features.h>
33 #include <stack-aliasing.h>
36 #ifndef NEED_SEPARATE_REGISTER_STACK
38 /* Most architectures have exactly one stack pointer. Some have more. */
39 # define STACK_VARIABLES void *stackaddr = NULL
41 /* How to pass the values to the 'create_thread' function. */
42 # define STACK_VARIABLES_ARGS stackaddr
44 /* How to declare function which gets there parameters. */
45 # define STACK_VARIABLES_PARMS void *stackaddr
47 /* How to declare allocate_stack. */
48 # define ALLOCATE_STACK_PARMS void **stack
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) allocate_stack (attr, pd, &stackaddr)
54 #else
56 /* We need two stacks. The kernel will place them but we have to tell
57 the kernel about the size of the reserved address space. */
58 # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
60 /* How to pass the values to the 'create_thread' function. */
61 # define STACK_VARIABLES_ARGS stackaddr, stacksize
63 /* How to declare function which gets there parameters. */
64 # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
66 /* How to declare allocate_stack. */
67 # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
69 /* This is how the function is called. We do it this way to allow
70 other variants of the function to have more parameters. */
71 # define ALLOCATE_STACK(attr, pd) \
72 allocate_stack (attr, pd, &stackaddr, &stacksize)
74 #endif
77 /* Default alignment of stack. */
78 #ifndef STACK_ALIGN
79 # define STACK_ALIGN __alignof__ (long double)
80 #endif
82 /* Default value for minimal stack size after allocating thread
83 descriptor and guard. */
84 #ifndef MINIMAL_REST_STACK
85 # define MINIMAL_REST_STACK 4096
86 #endif
89 /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
90 a stack. Use it when possible. */
91 #ifndef MAP_STACK
92 # define MAP_STACK 0
93 #endif
95 /* This yields the pointer that TLS support code calls the thread pointer. */
96 #if TLS_TCB_AT_TP
97 # define TLS_TPADJ(pd) (pd)
98 #elif TLS_DTV_AT_TP
99 # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
100 #endif
102 /* Cache handling for not-yet free stacks. */
104 /* Maximum size in kB of cache. */
105 static size_t stack_cache_maxsize = 40 * 1024 * 1024; /* 40MiBi by default. */
106 static size_t stack_cache_actsize;
108 /* Mutex protecting this variable. */
109 static int stack_cache_lock = LLL_LOCK_INITIALIZER;
111 /* List of queued stack frames. */
112 static LIST_HEAD (stack_cache);
114 /* List of the stacks in use. */
115 static LIST_HEAD (stack_used);
117 /* We need to record what list operations we are going to do so that,
118 in case of an asynchronous interruption due to a fork() call, we
119 can correct for the work. */
120 static uintptr_t in_flight_stack;
122 /* List of the threads with user provided stacks in use. No need to
123 initialize this, since it's done in __pthread_initialize_minimal. */
124 list_t __stack_user __attribute__ ((nocommon));
125 hidden_data_def (__stack_user)
127 #if COLORING_INCREMENT != 0
128 /* Number of threads created. */
129 static unsigned int nptl_ncreated;
130 #endif
133 /* Check whether the stack is still used or not. */
134 #define FREE_P(descr) ((descr)->tid <= 0)
137 static void
138 stack_list_del (list_t *elem)
140 in_flight_stack = (uintptr_t) elem;
142 atomic_write_barrier ();
144 list_del (elem);
146 atomic_write_barrier ();
148 in_flight_stack = 0;
152 static void
153 stack_list_add (list_t *elem, list_t *list)
155 in_flight_stack = (uintptr_t) elem | 1;
157 atomic_write_barrier ();
159 list_add (elem, list);
161 atomic_write_barrier ();
163 in_flight_stack = 0;
167 /* We create a double linked list of all cache entries. Double linked
168 because this allows removing entries from the end. */
171 /* Get a stack frame from the cache. We have to match by size since
172 some blocks might be too small or far too large. */
173 static struct pthread *
174 get_cached_stack (size_t *sizep, void **memp)
176 size_t size = *sizep;
177 struct pthread *result = NULL;
178 list_t *entry;
180 lll_lock (stack_cache_lock, LLL_PRIVATE);
182 /* Search the cache for a matching entry. We search for the
183 smallest stack which has at least the required size. Note that
184 in normal situations the size of all allocated stacks is the
185 same. As the very least there are only a few different sizes.
186 Therefore this loop will exit early most of the time with an
187 exact match. */
188 list_for_each (entry, &stack_cache)
190 struct pthread *curr;
192 curr = list_entry (entry, struct pthread, list);
193 if (FREE_P (curr) && curr->stackblock_size >= size)
195 if (curr->stackblock_size == size)
197 result = curr;
198 break;
201 if (result == NULL
202 || result->stackblock_size > curr->stackblock_size)
203 result = curr;
207 if (__builtin_expect (result == NULL, 0)
208 /* Make sure the size difference is not too excessive. In that
209 case we do not use the block. */
210 || __builtin_expect (result->stackblock_size > 4 * size, 0))
212 /* Release the lock. */
213 lll_unlock (stack_cache_lock, LLL_PRIVATE);
215 return NULL;
218 /* Don't allow setxid until cloned. */
219 result->setxid_futex = -1;
221 /* Dequeue the entry. */
222 stack_list_del (&result->list);
224 /* And add to the list of stacks in use. */
225 stack_list_add (&result->list, &stack_used);
227 /* And decrease the cache size. */
228 stack_cache_actsize -= result->stackblock_size;
230 /* Release the lock early. */
231 lll_unlock (stack_cache_lock, LLL_PRIVATE);
233 /* Report size and location of the stack to the caller. */
234 *sizep = result->stackblock_size;
235 *memp = result->stackblock;
237 /* Cancellation handling is back to the default. */
238 result->cancelhandling = 0;
239 result->cleanup = NULL;
241 /* No pending event. */
242 result->nextevent = NULL;
244 /* Clear the DTV. */
245 dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
246 for (size_t cnt = 0; cnt < dtv[-1].counter; ++cnt)
247 if (! dtv[1 + cnt].pointer.is_static
248 && dtv[1 + cnt].pointer.val != TLS_DTV_UNALLOCATED)
249 free (dtv[1 + cnt].pointer.val);
250 memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
252 /* Re-initialize the TLS. */
253 _dl_allocate_tls_init (TLS_TPADJ (result));
255 return result;
259 /* Free stacks until cache size is lower than LIMIT. */
260 void
261 __free_stacks (size_t limit)
263 /* We reduce the size of the cache. Remove the last entries until
264 the size is below the limit. */
265 list_t *entry;
266 list_t *prev;
268 /* Search from the end of the list. */
269 list_for_each_prev_safe (entry, prev, &stack_cache)
271 struct pthread *curr;
273 curr = list_entry (entry, struct pthread, list);
274 if (FREE_P (curr))
276 /* Unlink the block. */
277 stack_list_del (entry);
279 /* Account for the freed memory. */
280 stack_cache_actsize -= curr->stackblock_size;
282 /* Free the memory associated with the ELF TLS. */
283 _dl_deallocate_tls (TLS_TPADJ (curr), false);
285 /* Remove this block. This should never fail. If it does
286 something is really wrong. */
287 if (munmap (curr->stackblock, curr->stackblock_size) != 0)
288 abort ();
290 /* Maybe we have freed enough. */
291 if (stack_cache_actsize <= limit)
292 break;
298 /* Add a stack frame which is not used anymore to the stack. Must be
299 called with the cache lock held. */
300 static inline void
301 __attribute ((always_inline))
302 queue_stack (struct pthread *stack)
304 /* We unconditionally add the stack to the list. The memory may
305 still be in use but it will not be reused until the kernel marks
306 the stack as not used anymore. */
307 stack_list_add (&stack->list, &stack_cache);
309 stack_cache_actsize += stack->stackblock_size;
310 if (__glibc_unlikely (stack_cache_actsize > stack_cache_maxsize))
311 __free_stacks (stack_cache_maxsize);
315 static int
316 internal_function
317 change_stack_perm (struct pthread *pd
318 #ifdef NEED_SEPARATE_REGISTER_STACK
319 , size_t pagemask
320 #endif
323 #ifdef NEED_SEPARATE_REGISTER_STACK
324 void *stack = (pd->stackblock
325 + (((((pd->stackblock_size - pd->guardsize) / 2)
326 & pagemask) + pd->guardsize) & pagemask));
327 size_t len = pd->stackblock + pd->stackblock_size - stack;
328 #elif _STACK_GROWS_DOWN
329 void *stack = pd->stackblock + pd->guardsize;
330 size_t len = pd->stackblock_size - pd->guardsize;
331 #elif _STACK_GROWS_UP
332 void *stack = pd->stackblock;
333 size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
334 #else
335 # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
336 #endif
337 if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
338 return errno;
340 return 0;
344 /* Returns a usable stack for a new thread either by allocating a
345 new stack or reusing a cached stack of sufficient size.
346 ATTR must be non-NULL and point to a valid pthread_attr.
347 PDP must be non-NULL. */
348 static int
349 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
350 ALLOCATE_STACK_PARMS)
352 struct pthread *pd;
353 size_t size;
354 size_t pagesize_m1 = __getpagesize () - 1;
355 void *stacktop;
357 assert (powerof2 (pagesize_m1 + 1));
358 assert (TCB_ALIGNMENT >= STACK_ALIGN);
360 /* Get the stack size from the attribute if it is set. Otherwise we
361 use the default we determined at start time. */
362 if (attr->stacksize != 0)
363 size = attr->stacksize;
364 else
366 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
367 size = __default_pthread_attr.stacksize;
368 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
371 /* Get memory for the stack. */
372 if (__glibc_unlikely (attr->flags & ATTR_FLAG_STACKADDR))
374 uintptr_t adj;
376 /* If the user also specified the size of the stack make sure it
377 is large enough. */
378 if (attr->stacksize != 0
379 && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
380 return EINVAL;
382 /* Adjust stack size for alignment of the TLS block. */
383 #if TLS_TCB_AT_TP
384 adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
385 & __static_tls_align_m1;
386 assert (size > adj + TLS_TCB_SIZE);
387 #elif TLS_DTV_AT_TP
388 adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
389 & __static_tls_align_m1;
390 assert (size > adj);
391 #endif
393 /* The user provided some memory. Let's hope it matches the
394 size... We do not allocate guard pages if the user provided
395 the stack. It is the user's responsibility to do this if it
396 is wanted. */
397 #if TLS_TCB_AT_TP
398 pd = (struct pthread *) ((uintptr_t) attr->stackaddr
399 - TLS_TCB_SIZE - adj);
400 #elif TLS_DTV_AT_TP
401 pd = (struct pthread *) (((uintptr_t) attr->stackaddr
402 - __static_tls_size - adj)
403 - TLS_PRE_TCB_SIZE);
404 #endif
406 /* The user provided stack memory needs to be cleared. */
407 memset (pd, '\0', sizeof (struct pthread));
409 /* The first TSD block is included in the TCB. */
410 pd->specific[0] = pd->specific_1stblock;
412 /* Remember the stack-related values. */
413 pd->stackblock = (char *) attr->stackaddr - size;
414 pd->stackblock_size = size;
416 /* This is a user-provided stack. It will not be queued in the
417 stack cache nor will the memory (except the TLS memory) be freed. */
418 pd->user_stack = true;
420 /* This is at least the second thread. */
421 pd->header.multiple_threads = 1;
422 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
423 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
424 #endif
426 #ifndef __ASSUME_PRIVATE_FUTEX
427 /* The thread must know when private futexes are supported. */
428 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
429 header.private_futex);
430 #endif
432 #ifdef NEED_DL_SYSINFO
433 /* Copy the sysinfo value from the parent. */
434 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
435 #endif
437 /* The process ID is also the same as that of the caller. */
438 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
440 /* Don't allow setxid until cloned. */
441 pd->setxid_futex = -1;
443 /* Allocate the DTV for this thread. */
444 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
446 /* Something went wrong. */
447 assert (errno == ENOMEM);
448 return errno;
452 /* Prepare to modify global data. */
453 lll_lock (stack_cache_lock, LLL_PRIVATE);
455 /* And add to the list of stacks in use. */
456 list_add (&pd->list, &__stack_user);
458 lll_unlock (stack_cache_lock, LLL_PRIVATE);
460 else
462 /* Allocate some anonymous memory. If possible use the cache. */
463 size_t guardsize;
464 size_t reqsize;
465 void *mem;
466 const int prot = (PROT_READ | PROT_WRITE
467 | ((GL(dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
469 #if COLORING_INCREMENT != 0
470 /* Add one more page for stack coloring. Don't do it for stacks
471 with 16 times pagesize or larger. This might just cause
472 unnecessary misalignment. */
473 if (size <= 16 * pagesize_m1)
474 size += pagesize_m1 + 1;
475 #endif
477 /* Adjust the stack size for alignment. */
478 size &= ~__static_tls_align_m1;
479 assert (size != 0);
481 /* Make sure the size of the stack is enough for the guard and
482 eventually the thread descriptor. */
483 guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
484 if (__builtin_expect (size < ((guardsize + __static_tls_size
485 + MINIMAL_REST_STACK + pagesize_m1)
486 & ~pagesize_m1),
488 /* The stack is too small (or the guard too large). */
489 return EINVAL;
491 /* Try to get a stack from the cache. */
492 reqsize = size;
493 pd = get_cached_stack (&size, &mem);
494 if (pd == NULL)
496 /* To avoid aliasing effects on a larger scale than pages we
497 adjust the allocated stack size if necessary. This way
498 allocations directly following each other will not have
499 aliasing problems. */
500 #if MULTI_PAGE_ALIASING != 0
501 if ((size % MULTI_PAGE_ALIASING) == 0)
502 size += pagesize_m1 + 1;
503 #endif
505 mem = mmap (NULL, size, prot,
506 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
508 if (__glibc_unlikely (mem == MAP_FAILED))
509 return errno;
511 /* SIZE is guaranteed to be greater than zero.
512 So we can never get a null pointer back from mmap. */
513 assert (mem != NULL);
515 #if COLORING_INCREMENT != 0
516 /* Atomically increment NCREATED. */
517 unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
519 /* We chose the offset for coloring by incrementing it for
520 every new thread by a fixed amount. The offset used
521 module the page size. Even if coloring would be better
522 relative to higher alignment values it makes no sense to
523 do it since the mmap() interface does not allow us to
524 specify any alignment for the returned memory block. */
525 size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
527 /* Make sure the coloring offsets does not disturb the alignment
528 of the TCB and static TLS block. */
529 if (__glibc_unlikely ((coloring & __static_tls_align_m1) != 0))
530 coloring = (((coloring + __static_tls_align_m1)
531 & ~(__static_tls_align_m1))
532 & ~pagesize_m1);
533 #else
534 /* Unless specified we do not make any adjustments. */
535 # define coloring 0
536 #endif
538 /* Place the thread descriptor at the end of the stack. */
539 #if TLS_TCB_AT_TP
540 pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
541 #elif TLS_DTV_AT_TP
542 pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
543 - __static_tls_size)
544 & ~__static_tls_align_m1)
545 - TLS_PRE_TCB_SIZE);
546 #endif
548 /* Remember the stack-related values. */
549 pd->stackblock = mem;
550 pd->stackblock_size = size;
552 /* We allocated the first block thread-specific data array.
553 This address will not change for the lifetime of this
554 descriptor. */
555 pd->specific[0] = pd->specific_1stblock;
557 /* This is at least the second thread. */
558 pd->header.multiple_threads = 1;
559 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
560 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
561 #endif
563 #ifndef __ASSUME_PRIVATE_FUTEX
564 /* The thread must know when private futexes are supported. */
565 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
566 header.private_futex);
567 #endif
569 #ifdef NEED_DL_SYSINFO
570 /* Copy the sysinfo value from the parent. */
571 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
572 #endif
574 /* Don't allow setxid until cloned. */
575 pd->setxid_futex = -1;
577 /* The process ID is also the same as that of the caller. */
578 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
580 /* Allocate the DTV for this thread. */
581 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
583 /* Something went wrong. */
584 assert (errno == ENOMEM);
586 /* Free the stack memory we just allocated. */
587 (void) munmap (mem, size);
589 return errno;
593 /* Prepare to modify global data. */
594 lll_lock (stack_cache_lock, LLL_PRIVATE);
596 /* And add to the list of stacks in use. */
597 stack_list_add (&pd->list, &stack_used);
599 lll_unlock (stack_cache_lock, LLL_PRIVATE);
602 /* There might have been a race. Another thread might have
603 caused the stacks to get exec permission while this new
604 stack was prepared. Detect if this was possible and
605 change the permission if necessary. */
606 if (__builtin_expect ((GL(dl_stack_flags) & PF_X) != 0
607 && (prot & PROT_EXEC) == 0, 0))
609 int err = change_stack_perm (pd
610 #ifdef NEED_SEPARATE_REGISTER_STACK
611 , ~pagesize_m1
612 #endif
614 if (err != 0)
616 /* Free the stack memory we just allocated. */
617 (void) munmap (mem, size);
619 return err;
624 /* Note that all of the stack and the thread descriptor is
625 zeroed. This means we do not have to initialize fields
626 with initial value zero. This is specifically true for
627 the 'tid' field which is always set back to zero once the
628 stack is not used anymore and for the 'guardsize' field
629 which will be read next. */
632 /* Create or resize the guard area if necessary. */
633 if (__glibc_unlikely (guardsize > pd->guardsize))
635 #ifdef NEED_SEPARATE_REGISTER_STACK
636 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
637 #elif _STACK_GROWS_DOWN
638 char *guard = mem;
639 # elif _STACK_GROWS_UP
640 char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
641 #endif
642 if (mprotect (guard, guardsize, PROT_NONE) != 0)
644 mprot_error:
645 lll_lock (stack_cache_lock, LLL_PRIVATE);
647 /* Remove the thread from the list. */
648 stack_list_del (&pd->list);
650 lll_unlock (stack_cache_lock, LLL_PRIVATE);
652 /* Get rid of the TLS block we allocated. */
653 _dl_deallocate_tls (TLS_TPADJ (pd), false);
655 /* Free the stack memory regardless of whether the size
656 of the cache is over the limit or not. If this piece
657 of memory caused problems we better do not use it
658 anymore. Uh, and we ignore possible errors. There
659 is nothing we could do. */
660 (void) munmap (mem, size);
662 return errno;
665 pd->guardsize = guardsize;
667 else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
670 /* The old guard area is too large. */
672 #ifdef NEED_SEPARATE_REGISTER_STACK
673 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
674 char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
676 if (oldguard < guard
677 && mprotect (oldguard, guard - oldguard, prot) != 0)
678 goto mprot_error;
680 if (mprotect (guard + guardsize,
681 oldguard + pd->guardsize - guard - guardsize,
682 prot) != 0)
683 goto mprot_error;
684 #elif _STACK_GROWS_DOWN
685 if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
686 prot) != 0)
687 goto mprot_error;
688 #elif _STACK_GROWS_UP
689 if (mprotect ((char *) pd - pd->guardsize,
690 pd->guardsize - guardsize, prot) != 0)
691 goto mprot_error;
692 #endif
694 pd->guardsize = guardsize;
696 /* The pthread_getattr_np() calls need to get passed the size
697 requested in the attribute, regardless of how large the
698 actually used guardsize is. */
699 pd->reported_guardsize = guardsize;
702 /* Initialize the lock. We have to do this unconditionally since the
703 stillborn thread could be canceled while the lock is taken. */
704 pd->lock = LLL_LOCK_INITIALIZER;
706 /* The robust mutex lists also need to be initialized
707 unconditionally because the cleanup for the previous stack owner
708 might have happened in the kernel. */
709 pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
710 - offsetof (pthread_mutex_t,
711 __data.__list.__next));
712 pd->robust_head.list_op_pending = NULL;
713 #ifdef __PTHREAD_MUTEX_HAVE_PREV
714 pd->robust_prev = &pd->robust_head;
715 #endif
716 pd->robust_head.list = &pd->robust_head;
718 /* We place the thread descriptor at the end of the stack. */
719 *pdp = pd;
721 #if TLS_TCB_AT_TP
722 /* The stack begins before the TCB and the static TLS block. */
723 stacktop = ((char *) (pd + 1) - __static_tls_size);
724 #elif TLS_DTV_AT_TP
725 stacktop = (char *) (pd - 1);
726 #endif
728 #ifdef NEED_SEPARATE_REGISTER_STACK
729 *stack = pd->stackblock;
730 *stacksize = stacktop - *stack;
731 #elif _STACK_GROWS_DOWN
732 *stack = stacktop;
733 #elif _STACK_GROWS_UP
734 *stack = pd->stackblock;
735 assert (*stack > 0);
736 #endif
738 return 0;
742 void
743 internal_function
744 __deallocate_stack (struct pthread *pd)
746 lll_lock (stack_cache_lock, LLL_PRIVATE);
748 /* Remove the thread from the list of threads with user defined
749 stacks. */
750 stack_list_del (&pd->list);
752 /* Not much to do. Just free the mmap()ed memory. Note that we do
753 not reset the 'used' flag in the 'tid' field. This is done by
754 the kernel. If no thread has been created yet this field is
755 still zero. */
756 if (__glibc_likely (! pd->user_stack))
757 (void) queue_stack (pd);
758 else
759 /* Free the memory associated with the ELF TLS. */
760 _dl_deallocate_tls (TLS_TPADJ (pd), false);
762 lll_unlock (stack_cache_lock, LLL_PRIVATE);
767 internal_function
768 __make_stacks_executable (void **stack_endp)
770 /* First the main thread's stack. */
771 int err = _dl_make_stack_executable (stack_endp);
772 if (err != 0)
773 return err;
775 #ifdef NEED_SEPARATE_REGISTER_STACK
776 const size_t pagemask = ~(__getpagesize () - 1);
777 #endif
779 lll_lock (stack_cache_lock, LLL_PRIVATE);
781 list_t *runp;
782 list_for_each (runp, &stack_used)
784 err = change_stack_perm (list_entry (runp, struct pthread, list)
785 #ifdef NEED_SEPARATE_REGISTER_STACK
786 , pagemask
787 #endif
789 if (err != 0)
790 break;
793 /* Also change the permission for the currently unused stacks. This
794 might be wasted time but better spend it here than adding a check
795 in the fast path. */
796 if (err == 0)
797 list_for_each (runp, &stack_cache)
799 err = change_stack_perm (list_entry (runp, struct pthread, list)
800 #ifdef NEED_SEPARATE_REGISTER_STACK
801 , pagemask
802 #endif
804 if (err != 0)
805 break;
808 lll_unlock (stack_cache_lock, LLL_PRIVATE);
810 return err;
814 /* In case of a fork() call the memory allocation in the child will be
815 the same but only one thread is running. All stacks except that of
816 the one running thread are not used anymore. We have to recycle
817 them. */
818 void
819 __reclaim_stacks (void)
821 struct pthread *self = (struct pthread *) THREAD_SELF;
823 /* No locking necessary. The caller is the only stack in use. But
824 we have to be aware that we might have interrupted a list
825 operation. */
827 if (in_flight_stack != 0)
829 bool add_p = in_flight_stack & 1;
830 list_t *elem = (list_t *) (in_flight_stack & ~(uintptr_t) 1);
832 if (add_p)
834 /* We always add at the beginning of the list. So in this case we
835 only need to check the beginning of these lists to see if the
836 pointers at the head of the list are inconsistent. */
837 list_t *l = NULL;
839 if (stack_used.next->prev != &stack_used)
840 l = &stack_used;
841 else if (stack_cache.next->prev != &stack_cache)
842 l = &stack_cache;
844 if (l != NULL)
846 assert (l->next->prev == elem);
847 elem->next = l->next;
848 elem->prev = l;
849 l->next = elem;
852 else
854 /* We can simply always replay the delete operation. */
855 elem->next->prev = elem->prev;
856 elem->prev->next = elem->next;
860 /* Mark all stacks except the still running one as free. */
861 list_t *runp;
862 list_for_each (runp, &stack_used)
864 struct pthread *curp = list_entry (runp, struct pthread, list);
865 if (curp != self)
867 /* This marks the stack as free. */
868 curp->tid = 0;
870 /* The PID field must be initialized for the new process. */
871 curp->pid = self->pid;
873 /* Account for the size of the stack. */
874 stack_cache_actsize += curp->stackblock_size;
876 if (curp->specific_used)
878 /* Clear the thread-specific data. */
879 memset (curp->specific_1stblock, '\0',
880 sizeof (curp->specific_1stblock));
882 curp->specific_used = false;
884 for (size_t cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
885 if (curp->specific[cnt] != NULL)
887 memset (curp->specific[cnt], '\0',
888 sizeof (curp->specific_1stblock));
890 /* We have allocated the block which we do not
891 free here so re-set the bit. */
892 curp->specific_used = true;
898 /* Reset the PIDs in any cached stacks. */
899 list_for_each (runp, &stack_cache)
901 struct pthread *curp = list_entry (runp, struct pthread, list);
902 curp->pid = self->pid;
905 /* Add the stack of all running threads to the cache. */
906 list_splice (&stack_used, &stack_cache);
908 /* Remove the entry for the current thread to from the cache list
909 and add it to the list of running threads. Which of the two
910 lists is decided by the user_stack flag. */
911 stack_list_del (&self->list);
913 /* Re-initialize the lists for all the threads. */
914 INIT_LIST_HEAD (&stack_used);
915 INIT_LIST_HEAD (&__stack_user);
917 if (__glibc_unlikely (THREAD_GETMEM (self, user_stack)))
918 list_add (&self->list, &__stack_user);
919 else
920 list_add (&self->list, &stack_used);
922 /* There is one thread running. */
923 __nptl_nthreads = 1;
925 in_flight_stack = 0;
927 /* Initialize locks. */
928 stack_cache_lock = LLL_LOCK_INITIALIZER;
929 __default_pthread_attr_lock = LLL_LOCK_INITIALIZER;
933 #if HP_TIMING_AVAIL
934 # undef __find_thread_by_id
935 /* Find a thread given the thread ID. */
936 attribute_hidden
937 struct pthread *
938 __find_thread_by_id (pid_t tid)
940 struct pthread *result = NULL;
942 lll_lock (stack_cache_lock, LLL_PRIVATE);
944 /* Iterate over the list with system-allocated threads first. */
945 list_t *runp;
946 list_for_each (runp, &stack_used)
948 struct pthread *curp;
950 curp = list_entry (runp, struct pthread, list);
952 if (curp->tid == tid)
954 result = curp;
955 goto out;
959 /* Now the list with threads using user-allocated stacks. */
960 list_for_each (runp, &__stack_user)
962 struct pthread *curp;
964 curp = list_entry (runp, struct pthread, list);
966 if (curp->tid == tid)
968 result = curp;
969 goto out;
973 out:
974 lll_unlock (stack_cache_lock, LLL_PRIVATE);
976 return result;
978 #endif
981 static void
982 internal_function
983 setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
985 int ch;
987 /* Wait until this thread is cloned. */
988 if (t->setxid_futex == -1
989 && ! atomic_compare_and_exchange_bool_acq (&t->setxid_futex, -2, -1))
991 lll_futex_wait (&t->setxid_futex, -2, LLL_PRIVATE);
992 while (t->setxid_futex == -2);
994 /* Don't let the thread exit before the setxid handler runs. */
995 t->setxid_futex = 0;
999 ch = t->cancelhandling;
1001 /* If the thread is exiting right now, ignore it. */
1002 if ((ch & EXITING_BITMASK) != 0)
1004 /* Release the futex if there is no other setxid in
1005 progress. */
1006 if ((ch & SETXID_BITMASK) == 0)
1008 t->setxid_futex = 1;
1009 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1011 return;
1014 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1015 ch | SETXID_BITMASK, ch));
1019 static void
1020 internal_function
1021 setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
1023 int ch;
1027 ch = t->cancelhandling;
1028 if ((ch & SETXID_BITMASK) == 0)
1029 return;
1031 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1032 ch & ~SETXID_BITMASK, ch));
1034 /* Release the futex just in case. */
1035 t->setxid_futex = 1;
1036 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1040 static int
1041 internal_function
1042 setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
1044 if ((t->cancelhandling & SETXID_BITMASK) == 0)
1045 return 0;
1047 int val;
1048 INTERNAL_SYSCALL_DECL (err);
1049 val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
1050 t->tid, SIGSETXID);
1052 /* If this failed, it must have had not started yet or else exited. */
1053 if (!INTERNAL_SYSCALL_ERROR_P (val, err))
1055 atomic_increment (&cmdp->cntr);
1056 return 1;
1058 else
1059 return 0;
1064 attribute_hidden
1065 __nptl_setxid (struct xid_command *cmdp)
1067 int signalled;
1068 int result;
1069 lll_lock (stack_cache_lock, LLL_PRIVATE);
1071 __xidcmd = cmdp;
1072 cmdp->cntr = 0;
1074 struct pthread *self = THREAD_SELF;
1076 /* Iterate over the list with system-allocated threads first. */
1077 list_t *runp;
1078 list_for_each (runp, &stack_used)
1080 struct pthread *t = list_entry (runp, struct pthread, list);
1081 if (t == self)
1082 continue;
1084 setxid_mark_thread (cmdp, t);
1087 /* Now the list with threads using user-allocated stacks. */
1088 list_for_each (runp, &__stack_user)
1090 struct pthread *t = list_entry (runp, struct pthread, list);
1091 if (t == self)
1092 continue;
1094 setxid_mark_thread (cmdp, t);
1097 /* Iterate until we don't succeed in signalling anyone. That means
1098 we have gotten all running threads, and their children will be
1099 automatically correct once started. */
1102 signalled = 0;
1104 list_for_each (runp, &stack_used)
1106 struct pthread *t = list_entry (runp, struct pthread, list);
1107 if (t == self)
1108 continue;
1110 signalled += setxid_signal_thread (cmdp, t);
1113 list_for_each (runp, &__stack_user)
1115 struct pthread *t = list_entry (runp, struct pthread, list);
1116 if (t == self)
1117 continue;
1119 signalled += setxid_signal_thread (cmdp, t);
1122 int cur = cmdp->cntr;
1123 while (cur != 0)
1125 lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
1126 cur = cmdp->cntr;
1129 while (signalled != 0);
1131 /* Clean up flags, so that no thread blocks during exit waiting
1132 for a signal which will never come. */
1133 list_for_each (runp, &stack_used)
1135 struct pthread *t = list_entry (runp, struct pthread, list);
1136 if (t == self)
1137 continue;
1139 setxid_unmark_thread (cmdp, t);
1142 list_for_each (runp, &__stack_user)
1144 struct pthread *t = list_entry (runp, struct pthread, list);
1145 if (t == self)
1146 continue;
1148 setxid_unmark_thread (cmdp, t);
1151 /* This must be last, otherwise the current thread might not have
1152 permissions to send SIGSETXID syscall to the other threads. */
1153 INTERNAL_SYSCALL_DECL (err);
1154 result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
1155 cmdp->id[0], cmdp->id[1], cmdp->id[2]);
1156 if (INTERNAL_SYSCALL_ERROR_P (result, err))
1158 __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
1159 result = -1;
1162 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1163 return result;
1166 static inline void __attribute__((always_inline))
1167 init_one_static_tls (struct pthread *curp, struct link_map *map)
1169 dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
1170 # if TLS_TCB_AT_TP
1171 void *dest = (char *) curp - map->l_tls_offset;
1172 # elif TLS_DTV_AT_TP
1173 void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
1174 # else
1175 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1176 # endif
1178 /* Fill in the DTV slot so that a later LD/GD access will find it. */
1179 dtv[map->l_tls_modid].pointer.val = dest;
1180 dtv[map->l_tls_modid].pointer.is_static = true;
1182 /* Initialize the memory. */
1183 memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
1184 '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
1187 void
1188 attribute_hidden
1189 __pthread_init_static_tls (struct link_map *map)
1191 lll_lock (stack_cache_lock, LLL_PRIVATE);
1193 /* Iterate over the list with system-allocated threads first. */
1194 list_t *runp;
1195 list_for_each (runp, &stack_used)
1196 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1198 /* Now the list with threads using user-allocated stacks. */
1199 list_for_each (runp, &__stack_user)
1200 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1202 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1206 void
1207 attribute_hidden
1208 __wait_lookup_done (void)
1210 lll_lock (stack_cache_lock, LLL_PRIVATE);
1212 struct pthread *self = THREAD_SELF;
1214 /* Iterate over the list with system-allocated threads first. */
1215 list_t *runp;
1216 list_for_each (runp, &stack_used)
1218 struct pthread *t = list_entry (runp, struct pthread, list);
1219 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1220 continue;
1222 int *const gscope_flagp = &t->header.gscope_flag;
1224 /* We have to wait until this thread is done with the global
1225 scope. First tell the thread that we are waiting and
1226 possibly have to be woken. */
1227 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1228 THREAD_GSCOPE_FLAG_WAIT,
1229 THREAD_GSCOPE_FLAG_USED))
1230 continue;
1233 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1234 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1237 /* Now the list with threads using user-allocated stacks. */
1238 list_for_each (runp, &__stack_user)
1240 struct pthread *t = list_entry (runp, struct pthread, list);
1241 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1242 continue;
1244 int *const gscope_flagp = &t->header.gscope_flag;
1246 /* We have to wait until this thread is done with the global
1247 scope. First tell the thread that we are waiting and
1248 possibly have to be woken. */
1249 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1250 THREAD_GSCOPE_FLAG_WAIT,
1251 THREAD_GSCOPE_FLAG_USED))
1252 continue;
1255 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1256 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1259 lll_unlock (stack_cache_lock, LLL_PRIVATE);