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/>. */
26 #include <sys/param.h>
27 #include <dl-sysdep.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)
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)
77 /* Default alignment of stack. */
79 # define STACK_ALIGN __alignof__ (long double)
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
89 /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
90 a stack. Use it when possible. */
95 /* This yields the pointer that TLS support code calls the thread pointer. */
97 # define TLS_TPADJ(pd) (pd)
99 # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
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;
133 /* Check whether the stack is still used or not. */
134 #define FREE_P(descr) ((descr)->tid <= 0)
138 stack_list_del (list_t *elem)
140 in_flight_stack = (uintptr_t) elem;
142 atomic_write_barrier ();
146 atomic_write_barrier ();
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 ();
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;
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
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)
202 || result->stackblock_size > curr->stackblock_size)
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);
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;
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));
259 /* Free stacks until cache size is lower than LIMIT. */
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. */
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);
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)
290 /* Maybe we have freed enough. */
291 if (stack_cache_actsize <= limit)
298 /* Add a stack frame which is not used anymore to the stack. Must be
299 called with the cache lock held. */
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);
317 change_stack_perm (struct pthread *pd
318 #ifdef NEED_SEPARATE_REGISTER_STACK
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;
335 # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
337 if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 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. */
349 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
350 ALLOCATE_STACK_PARMS)
354 size_t pagesize_m1 = __getpagesize () - 1;
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;
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))
376 /* If the user also specified the size of the stack make sure it
378 if (attr->stacksize != 0
379 && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
382 /* Adjust stack size for alignment of the TLS block. */
384 adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
385 & __static_tls_align_m1;
386 assert (size > adj + TLS_TCB_SIZE);
388 adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
389 & __static_tls_align_m1;
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
398 pd = (struct pthread *) ((uintptr_t) attr->stackaddr
399 - TLS_TCB_SIZE - adj);
401 pd = (struct pthread *) (((uintptr_t) attr->stackaddr
402 - __static_tls_size - adj)
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;
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);
432 #ifdef NEED_DL_SYSINFO
433 /* Copy the sysinfo value from the parent. */
434 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
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);
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);
462 /* Allocate some anonymous memory. If possible use the cache. */
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;
477 /* Adjust the stack size for alignment. */
478 size &= ~__static_tls_align_m1;
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)
488 /* The stack is too small (or the guard too large). */
491 /* Try to get a stack from the cache. */
493 pd = get_cached_stack (&size, &mem);
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;
505 mem = mmap (NULL, size, prot,
506 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
508 if (__glibc_unlikely (mem == MAP_FAILED))
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))
534 /* Unless specified we do not make any adjustments. */
538 /* Place the thread descriptor at the end of the stack. */
540 pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
542 pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
544 & ~__static_tls_align_m1)
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
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;
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);
569 #ifdef NEED_DL_SYSINFO
570 /* Copy the sysinfo value from the parent. */
571 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
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);
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
616 /* Free the stack memory we just allocated. */
617 (void) munmap (mem, size);
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
639 # elif _STACK_GROWS_UP
640 char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
642 if (mprotect (guard, guardsize, PROT_NONE) != 0)
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);
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);
677 && mprotect (oldguard, guard - oldguard, prot) != 0)
680 if (mprotect (guard + guardsize,
681 oldguard + pd->guardsize - guard - guardsize,
684 #elif _STACK_GROWS_DOWN
685 if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
688 #elif _STACK_GROWS_UP
689 if (mprotect ((char *) pd - pd->guardsize,
690 pd->guardsize - guardsize, prot) != 0)
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;
716 pd->robust_head.list = &pd->robust_head;
718 /* We place the thread descriptor at the end of the stack. */
722 /* The stack begins before the TCB and the static TLS block. */
723 stacktop = ((char *) (pd + 1) - __static_tls_size);
725 stacktop = (char *) (pd - 1);
728 #ifdef NEED_SEPARATE_REGISTER_STACK
729 *stack = pd->stackblock;
730 *stacksize = stacktop - *stack;
731 #elif _STACK_GROWS_DOWN
733 #elif _STACK_GROWS_UP
734 *stack = pd->stackblock;
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
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
756 if (__glibc_likely (! pd->user_stack))
757 (void) queue_stack (pd);
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);
768 __make_stacks_executable (void **stack_endp)
770 /* First the main thread's stack. */
771 int err = _dl_make_stack_executable (stack_endp);
775 #ifdef NEED_SEPARATE_REGISTER_STACK
776 const size_t pagemask = ~(__getpagesize () - 1);
779 lll_lock (stack_cache_lock, LLL_PRIVATE);
782 list_for_each (runp, &stack_used)
784 err = change_stack_perm (list_entry (runp, struct pthread, list)
785 #ifdef NEED_SEPARATE_REGISTER_STACK
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
797 list_for_each (runp, &stack_cache)
799 err = change_stack_perm (list_entry (runp, struct pthread, list)
800 #ifdef NEED_SEPARATE_REGISTER_STACK
808 lll_unlock (stack_cache_lock, LLL_PRIVATE);
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
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
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);
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. */
839 if (stack_used.next->prev != &stack_used)
841 else if (stack_cache.next->prev != &stack_cache)
846 assert (l->next->prev == elem);
847 elem->next = l->next;
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. */
862 list_for_each (runp, &stack_used)
864 struct pthread *curp = list_entry (runp, struct pthread, list);
867 /* This marks the stack as free. */
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);
920 list_add (&self->list, &stack_used);
922 /* There is one thread running. */
927 /* Initialize locks. */
928 stack_cache_lock = LLL_LOCK_INITIALIZER;
929 __default_pthread_attr_lock = LLL_LOCK_INITIALIZER;
934 # undef __find_thread_by_id
935 /* Find a thread given the thread ID. */
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. */
946 list_for_each (runp, &stack_used)
948 struct pthread *curp;
950 curp = list_entry (runp, struct pthread, list);
952 if (curp->tid == tid)
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)
974 lll_unlock (stack_cache_lock, LLL_PRIVATE);
983 setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
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. */
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
1006 if ((ch & SETXID_BITMASK) == 0)
1008 t->setxid_futex = 1;
1009 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1014 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1015 ch | SETXID_BITMASK, ch));
1021 setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
1027 ch = t->cancelhandling;
1028 if ((ch & SETXID_BITMASK) == 0)
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);
1042 setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
1044 if ((t->cancelhandling & SETXID_BITMASK) == 0)
1048 INTERNAL_SYSCALL_DECL (err);
1049 val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
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);
1062 /* Check for consistency across set*id system call results. The abort
1063 should not happen as long as all privileges changes happen through
1064 the glibc wrappers. ERROR must be 0 (no error) or an errno
1068 __nptl_setxid_error (struct xid_command *cmdp, int error)
1072 int olderror = cmdp->error;
1073 if (olderror == error)
1076 /* Mismatch between current and previous results. */
1079 while (atomic_compare_and_exchange_bool_acq (&cmdp->error, error, -1));
1084 __nptl_setxid (struct xid_command *cmdp)
1088 lll_lock (stack_cache_lock, LLL_PRIVATE);
1094 struct pthread *self = THREAD_SELF;
1096 /* Iterate over the list with system-allocated threads first. */
1098 list_for_each (runp, &stack_used)
1100 struct pthread *t = list_entry (runp, struct pthread, list);
1104 setxid_mark_thread (cmdp, t);
1107 /* Now the list with threads using user-allocated stacks. */
1108 list_for_each (runp, &__stack_user)
1110 struct pthread *t = list_entry (runp, struct pthread, list);
1114 setxid_mark_thread (cmdp, t);
1117 /* Iterate until we don't succeed in signalling anyone. That means
1118 we have gotten all running threads, and their children will be
1119 automatically correct once started. */
1124 list_for_each (runp, &stack_used)
1126 struct pthread *t = list_entry (runp, struct pthread, list);
1130 signalled += setxid_signal_thread (cmdp, t);
1133 list_for_each (runp, &__stack_user)
1135 struct pthread *t = list_entry (runp, struct pthread, list);
1139 signalled += setxid_signal_thread (cmdp, t);
1142 int cur = cmdp->cntr;
1145 lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
1149 while (signalled != 0);
1151 /* Clean up flags, so that no thread blocks during exit waiting
1152 for a signal which will never come. */
1153 list_for_each (runp, &stack_used)
1155 struct pthread *t = list_entry (runp, struct pthread, list);
1159 setxid_unmark_thread (cmdp, t);
1162 list_for_each (runp, &__stack_user)
1164 struct pthread *t = list_entry (runp, struct pthread, list);
1168 setxid_unmark_thread (cmdp, t);
1171 /* This must be last, otherwise the current thread might not have
1172 permissions to send SIGSETXID syscall to the other threads. */
1173 INTERNAL_SYSCALL_DECL (err);
1174 result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
1175 cmdp->id[0], cmdp->id[1], cmdp->id[2]);
1177 if (__glibc_unlikely (INTERNAL_SYSCALL_ERROR_P (result, err)))
1179 error = INTERNAL_SYSCALL_ERRNO (result, err);
1180 __set_errno (error);
1183 __nptl_setxid_error (cmdp, error);
1185 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1189 static inline void __attribute__((always_inline))
1190 init_one_static_tls (struct pthread *curp, struct link_map *map)
1192 dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
1194 void *dest = (char *) curp - map->l_tls_offset;
1195 # elif TLS_DTV_AT_TP
1196 void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
1198 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1201 /* Fill in the DTV slot so that a later LD/GD access will find it. */
1202 dtv[map->l_tls_modid].pointer.val = dest;
1203 dtv[map->l_tls_modid].pointer.is_static = true;
1205 /* Initialize the memory. */
1206 memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
1207 '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
1212 __pthread_init_static_tls (struct link_map *map)
1214 lll_lock (stack_cache_lock, LLL_PRIVATE);
1216 /* Iterate over the list with system-allocated threads first. */
1218 list_for_each (runp, &stack_used)
1219 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1221 /* Now the list with threads using user-allocated stacks. */
1222 list_for_each (runp, &__stack_user)
1223 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1225 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1231 __wait_lookup_done (void)
1233 lll_lock (stack_cache_lock, LLL_PRIVATE);
1235 struct pthread *self = THREAD_SELF;
1237 /* Iterate over the list with system-allocated threads first. */
1239 list_for_each (runp, &stack_used)
1241 struct pthread *t = list_entry (runp, struct pthread, list);
1242 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1245 int *const gscope_flagp = &t->header.gscope_flag;
1247 /* We have to wait until this thread is done with the global
1248 scope. First tell the thread that we are waiting and
1249 possibly have to be woken. */
1250 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1251 THREAD_GSCOPE_FLAG_WAIT,
1252 THREAD_GSCOPE_FLAG_USED))
1256 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1257 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1260 /* Now the list with threads using user-allocated stacks. */
1261 list_for_each (runp, &__stack_user)
1263 struct pthread *t = list_entry (runp, struct pthread, list);
1264 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1267 int *const gscope_flagp = &t->header.gscope_flag;
1269 /* We have to wait until this thread is done with the global
1270 scope. First tell the thread that we are waiting and
1271 possibly have to be woken. */
1272 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1273 THREAD_GSCOPE_FLAG_WAIT,
1274 THREAD_GSCOPE_FLAG_USED))
1278 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1279 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1282 lll_unlock (stack_cache_lock, LLL_PRIVATE);