Fix shm_open posix compliance error code
[uclibc-ng.git] / libpthread / nptl / allocatestack.c
blob137979542b394e0bb56b0f4e8d0654a14058b8b4
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.
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 <tls.h>
28 #include <lowlevellock.h>
29 #include <link.h>
30 #include <bits/kernel-features.h>
33 #ifndef NEED_SEPARATE_REGISTER_STACK
35 /* Most architectures have exactly one stack pointer. Some have more. */
36 # define STACK_VARIABLES void *stackaddr = NULL
38 /* How to pass the values to the 'create_thread' function. */
39 # define STACK_VARIABLES_ARGS stackaddr
41 /* How to declare function which gets there parameters. */
42 # define STACK_VARIABLES_PARMS void *stackaddr
44 /* How to declare allocate_stack. */
45 # define ALLOCATE_STACK_PARMS void **stack
47 /* This is how the function is called. We do it this way to allow
48 other variants of the function to have more parameters. */
49 # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
51 #else
53 /* We need two stacks. The kernel will place them but we have to tell
54 the kernel about the size of the reserved address space. */
55 # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
57 /* How to pass the values to the 'create_thread' function. */
58 # define STACK_VARIABLES_ARGS stackaddr, stacksize
60 /* How to declare function which gets there parameters. */
61 # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
63 /* How to declare allocate_stack. */
64 # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
66 /* This is how the function is called. We do it this way to allow
67 other variants of the function to have more parameters. */
68 # define ALLOCATE_STACK(attr, pd) \
69 allocate_stack (attr, pd, &stackaddr, &stacksize)
71 #endif
74 /* Default alignment of stack. */
75 #ifndef STACK_ALIGN
76 # define STACK_ALIGN __alignof__ (long double)
77 #endif
79 /* Default value for minimal stack size after allocating thread
80 descriptor and guard. */
81 #ifndef MINIMAL_REST_STACK
82 # define MINIMAL_REST_STACK 4096
83 #endif
86 /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
87 a stack. Use it when possible. */
88 #ifndef MAP_STACK
89 # define MAP_STACK 0
90 #endif
92 /* This yields the pointer that TLS support code calls the thread pointer. */
93 #if defined(TLS_TCB_AT_TP)
94 # define TLS_TPADJ(pd) (pd)
95 #elif defined(TLS_DTV_AT_TP)
96 # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
97 #endif
99 /* Cache handling for not-yet free stacks. */
102 Maximum size in kB of cache. GNU libc default is 40MiB
103 embedded systems don't have enough ram for big dirty stack caches,
104 reduce it to 16MiB. 4 does not work, f.e. tst-kill4 segfaults.
106 static size_t stack_cache_maxsize = 16 * 1024 * 1024;
107 static size_t stack_cache_actsize;
109 /* Mutex protecting this variable. */
110 static int stack_cache_lock = LLL_LOCK_INITIALIZER;
112 /* List of queued stack frames. */
113 static LIST_HEAD (stack_cache);
115 /* List of the stacks in use. */
116 static LIST_HEAD (stack_used);
118 /* We need to record what list operations we are going to do so that,
119 in case of an asynchronous interruption due to a fork() call, we
120 can correct for the work. */
121 static uintptr_t in_flight_stack;
123 /* List of the threads with user provided stacks in use. No need to
124 initialize this, since it's done in __pthread_initialize_minimal. */
125 list_t __stack_user __attribute__ ((nocommon));
126 hidden_data_def (__stack_user)
128 #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
129 /* Number of threads created. */
130 static unsigned int nptl_ncreated;
131 #endif
134 /* Check whether the stack is still used or not. */
135 #define FREE_P(descr) ((descr)->tid <= 0)
138 static void
139 stack_list_del (list_t *elem)
141 in_flight_stack = (uintptr_t) elem;
143 atomic_write_barrier ();
145 list_del (elem);
147 atomic_write_barrier ();
149 in_flight_stack = 0;
153 static void
154 stack_list_add (list_t *elem, list_t *list)
156 in_flight_stack = (uintptr_t) elem | 1;
158 atomic_write_barrier ();
160 list_add (elem, list);
162 atomic_write_barrier ();
164 in_flight_stack = 0;
168 /* We create a double linked list of all cache entries. Double linked
169 because this allows removing entries from the end. */
172 /* Get a stack frame from the cache. We have to match by size since
173 some blocks might be too small or far too large. */
174 static struct pthread *
175 get_cached_stack (size_t *sizep, void **memp)
177 size_t size = *sizep;
178 struct pthread *result = NULL;
179 list_t *entry;
181 lll_lock (stack_cache_lock, LLL_PRIVATE);
183 /* Search the cache for a matching entry. We search for the
184 smallest stack which has at least the required size. Note that
185 in normal situations the size of all allocated stacks is the
186 same. As the very least there are only a few different sizes.
187 Therefore this loop will exit early most of the time with an
188 exact match. */
189 list_for_each (entry, &stack_cache)
191 struct pthread *curr;
193 curr = list_entry (entry, struct pthread, list);
194 if (FREE_P (curr) && curr->stackblock_size >= size)
196 if (curr->stackblock_size == size)
198 result = curr;
199 break;
202 if (result == NULL
203 || result->stackblock_size > curr->stackblock_size)
204 result = curr;
208 if (__builtin_expect (result == NULL, 0)
209 /* Make sure the size difference is not too excessive. In that
210 case we do not use the block. */
211 || __builtin_expect (result->stackblock_size > 4 * size, 0))
213 /* Release the lock. */
214 lll_unlock (stack_cache_lock, LLL_PRIVATE);
216 return NULL;
219 /* Dequeue the entry. */
220 stack_list_del (&result->list);
222 /* And add to the list of stacks in use. */
223 stack_list_add (&result->list, &stack_used);
225 /* And decrease the cache size. */
226 stack_cache_actsize -= result->stackblock_size;
228 /* Release the lock early. */
229 lll_unlock (stack_cache_lock, LLL_PRIVATE);
231 /* Report size and location of the stack to the caller. */
232 *sizep = result->stackblock_size;
233 *memp = result->stackblock;
235 /* Cancellation handling is back to the default. */
236 result->cancelhandling = 0;
237 result->cleanup = NULL;
239 /* No pending event. */
240 result->nextevent = NULL;
242 /* Clear the DTV. */
243 dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
244 memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
246 /* Re-initialize the TLS. */
247 _dl_allocate_tls_init (TLS_TPADJ (result));
249 return result;
253 /* Free stacks until cache size is lower than LIMIT. */
254 void
255 __free_stacks (size_t limit)
257 /* We reduce the size of the cache. Remove the last entries until
258 the size is below the limit. */
259 list_t *entry;
260 list_t *prev;
262 /* Search from the end of the list. */
263 list_for_each_prev_safe (entry, prev, &stack_cache)
265 struct pthread *curr;
267 curr = list_entry (entry, struct pthread, list);
268 if (FREE_P (curr))
270 /* Unlink the block. */
271 stack_list_del (entry);
273 /* Account for the freed memory. */
274 stack_cache_actsize -= curr->stackblock_size;
276 /* Free the memory associated with the ELF TLS. */
277 _dl_deallocate_tls (TLS_TPADJ (curr), false);
279 /* Remove this block. This should never fail. If it does
280 something is really wrong. */
281 if (munmap (curr->stackblock, curr->stackblock_size) != 0)
282 abort ();
284 /* Maybe we have freed enough. */
285 if (stack_cache_actsize <= limit)
286 break;
292 /* Add a stack frame which is not used anymore to the stack. Must be
293 called with the cache lock held. */
294 static inline void
295 __attribute ((always_inline))
296 queue_stack (struct pthread *stack)
298 /* We unconditionally add the stack to the list. The memory may
299 still be in use but it will not be reused until the kernel marks
300 the stack as not used anymore. */
301 stack_list_add (&stack->list, &stack_cache);
303 stack_cache_actsize += stack->stackblock_size;
304 if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
305 __free_stacks (stack_cache_maxsize);
309 static int
310 internal_function
311 change_stack_perm (struct pthread *pd
312 #ifdef NEED_SEPARATE_REGISTER_STACK
313 , size_t pagemask
314 #endif
317 #ifdef NEED_SEPARATE_REGISTER_STACK
318 void *stack = (pd->stackblock
319 + (((((pd->stackblock_size - pd->guardsize) / 2)
320 & pagemask) + pd->guardsize) & pagemask));
321 size_t len = pd->stackblock + pd->stackblock_size - stack;
322 #elif defined _STACK_GROWS_DOWN
323 void *stack = pd->stackblock + pd->guardsize;
324 size_t len = pd->stackblock_size - pd->guardsize;
325 #elif defined _STACK_GROWS_UP
326 void *stack = pd->stackblock;
327 size_t len = (uintptr_t) pd - pd->guardsize - (uintptr_t) pd->stackblock;
328 #else
329 # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
330 #endif
331 #ifdef __ARCH_USE_MMU__
332 if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
333 return errno;
334 #endif
336 return 0;
340 static int
341 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
342 ALLOCATE_STACK_PARMS)
344 struct pthread *pd;
345 size_t size;
346 size_t pagesize_m1 = __getpagesize () - 1;
347 void *stacktop;
349 assert (attr != NULL);
350 assert (powerof2 (pagesize_m1 + 1));
351 assert (TCB_ALIGNMENT >= STACK_ALIGN);
353 /* Get the stack size from the attribute if it is set. Otherwise we
354 use the default we determined at start time. */
355 size = attr->stacksize ?: __default_stacksize;
357 /* Get memory for the stack. */
358 if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
360 uintptr_t adj;
362 /* If the user also specified the size of the stack make sure it
363 is large enough. */
364 if (attr->stacksize != 0
365 && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
366 return EINVAL;
368 /* Adjust stack size for alignment of the TLS block. */
369 #if defined(TLS_TCB_AT_TP)
370 adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
371 & __static_tls_align_m1;
372 assert (size > adj + TLS_TCB_SIZE);
373 #elif defined(TLS_DTV_AT_TP)
374 adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
375 & __static_tls_align_m1;
376 assert (size > adj);
377 #endif
379 /* The user provided some memory. Let's hope it matches the
380 size... We do not allocate guard pages if the user provided
381 the stack. It is the user's responsibility to do this if it
382 is wanted. */
383 #if defined(TLS_TCB_AT_TP)
384 pd = (struct pthread *) ((uintptr_t) attr->stackaddr
385 - TLS_TCB_SIZE - adj);
386 #elif defined(TLS_DTV_AT_TP)
387 pd = (struct pthread *) (((uintptr_t) attr->stackaddr
388 - __static_tls_size - adj)
389 - TLS_PRE_TCB_SIZE);
390 #endif
392 /* The user provided stack memory needs to be cleared. */
393 memset (pd, '\0', sizeof (struct pthread));
395 /* The first TSD block is included in the TCB. */
396 pd->specific[0] = pd->specific_1stblock;
398 /* Remember the stack-related values. */
399 pd->stackblock = (char *) attr->stackaddr - size;
400 pd->stackblock_size = size;
402 /* This is a user-provided stack. It will not be queued in the
403 stack cache nor will the memory (except the TLS memory) be freed. */
404 pd->user_stack = true;
406 /* This is at least the second thread. */
407 pd->header.multiple_threads = 1;
408 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
409 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
410 #endif
412 #ifndef __ASSUME_PRIVATE_FUTEX
413 /* The thread must know when private futexes are supported. */
414 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
415 header.private_futex);
416 #endif
418 #ifdef NEED_DL_SYSINFO
419 /* Copy the sysinfo value from the parent. */
420 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
421 #endif
423 /* Allocate the DTV for this thread. */
424 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
426 /* Something went wrong. */
427 assert (errno == ENOMEM);
428 return EAGAIN;
432 /* Prepare to modify global data. */
433 lll_lock (stack_cache_lock, LLL_PRIVATE);
435 /* And add to the list of stacks in use. */
436 list_add (&pd->list, &__stack_user);
438 lll_unlock (stack_cache_lock, LLL_PRIVATE);
440 else
442 /* Allocate some anonymous memory. If possible use the cache. */
443 size_t guardsize;
444 size_t reqsize;
445 void *mem = 0;
446 const int prot = (PROT_READ | PROT_WRITE);
448 #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
449 /* Add one more page for stack coloring. Don't do it for stacks
450 with 16 times pagesize or larger. This might just cause
451 unnecessary misalignment. */
452 if (size <= 16 * pagesize_m1)
453 size += pagesize_m1 + 1;
454 #endif
456 /* Adjust the stack size for alignment. */
457 size &= ~__static_tls_align_m1;
458 assert (size != 0);
460 /* Make sure the size of the stack is enough for the guard and
461 eventually the thread descriptor. */
462 guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
463 if (__builtin_expect (size < ((guardsize + __static_tls_size
464 + MINIMAL_REST_STACK + pagesize_m1)
465 & ~pagesize_m1),
467 /* The stack is too small (or the guard too large). */
468 return EINVAL;
470 /* Try to get a stack from the cache. */
471 reqsize = size;
472 pd = get_cached_stack (&size, &mem);
473 if (pd == NULL)
475 /* To avoid aliasing effects on a larger scale than pages we
476 adjust the allocated stack size if necessary. This way
477 allocations directly following each other will not have
478 aliasing problems. */
479 #if defined MULTI_PAGE_ALIASING && MULTI_PAGE_ALIASING != 0
480 if ((size % MULTI_PAGE_ALIASING) == 0)
481 size += pagesize_m1 + 1;
482 #endif
484 mem = mmap (NULL, size, prot,
485 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
487 if (__builtin_expect (mem == MAP_FAILED, 0))
489 if (errno == ENOMEM)
490 __set_errno (EAGAIN);
492 return errno;
495 /* SIZE is guaranteed to be greater than zero.
496 So we can never get a null pointer back from mmap. */
497 assert (mem != NULL);
499 #if defined COLORING_INCREMENT && COLORING_INCREMENT != 0
500 /* Atomically increment NCREATED. */
501 unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
503 /* We chose the offset for coloring by incrementing it for
504 every new thread by a fixed amount. The offset used
505 module the page size. Even if coloring would be better
506 relative to higher alignment values it makes no sense to
507 do it since the mmap() interface does not allow us to
508 specify any alignment for the returned memory block. */
509 size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
511 /* Make sure the coloring offsets does not disturb the alignment
512 of the TCB and static TLS block. */
513 if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
514 coloring = (((coloring + __static_tls_align_m1)
515 & ~(__static_tls_align_m1))
516 & ~pagesize_m1);
517 #else
518 /* Unless specified we do not make any adjustments. */
519 # define coloring 0
520 #endif
522 /* Place the thread descriptor at the end of the stack. */
523 #if defined(TLS_TCB_AT_TP)
524 pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
525 #elif defined(TLS_DTV_AT_TP)
526 pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
527 - __static_tls_size)
528 & ~__static_tls_align_m1)
529 - TLS_PRE_TCB_SIZE);
530 #endif
532 /* Remember the stack-related values. */
533 pd->stackblock = mem;
534 pd->stackblock_size = size;
536 /* We allocated the first block thread-specific data array.
537 This address will not change for the lifetime of this
538 descriptor. */
539 pd->specific[0] = pd->specific_1stblock;
541 /* This is at least the second thread. */
542 pd->header.multiple_threads = 1;
543 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
544 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
545 #endif
547 #ifndef __ASSUME_PRIVATE_FUTEX
548 /* The thread must know when private futexes are supported. */
549 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
550 header.private_futex);
551 #endif
553 #ifdef NEED_DL_SYSINFO
554 /* Copy the sysinfo value from the parent. */
555 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
556 #endif
558 /* Allocate the DTV for this thread. */
559 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
561 /* Something went wrong. */
562 assert (errno == ENOMEM);
564 /* Free the stack memory we just allocated. */
565 (void) munmap (mem, size);
567 return EAGAIN;
571 /* Prepare to modify global data. */
572 lll_lock (stack_cache_lock, LLL_PRIVATE);
574 /* And add to the list of stacks in use. */
575 stack_list_add (&pd->list, &stack_used);
577 lll_unlock (stack_cache_lock, LLL_PRIVATE);
580 /* Note that all of the stack and the thread descriptor is
581 zeroed. This means we do not have to initialize fields
582 with initial value zero. This is specifically true for
583 the 'tid' field which is always set back to zero once the
584 stack is not used anymore and for the 'guardsize' field
585 which will be read next. */
588 /* Create or resize the guard area if necessary. */
589 if (__builtin_expect (guardsize > pd->guardsize, 0))
591 #ifdef NEED_SEPARATE_REGISTER_STACK
592 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
593 #elif defined _STACK_GROWS_DOWN
594 char *guard = mem;
595 #elif defined _STACK_GROWS_UP
596 char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
597 #endif
598 #ifdef __ARCH_USE_MMU__
599 if (mprotect (guard, guardsize, PROT_NONE) != 0)
601 int err;
602 mprot_error:
603 err = errno;
605 lll_lock (stack_cache_lock, LLL_PRIVATE);
607 /* Remove the thread from the list. */
608 stack_list_del (&pd->list);
610 lll_unlock (stack_cache_lock, LLL_PRIVATE);
612 /* Get rid of the TLS block we allocated. */
613 _dl_deallocate_tls (TLS_TPADJ (pd), false);
615 /* Free the stack memory regardless of whether the size
616 of the cache is over the limit or not. If this piece
617 of memory caused problems we better do not use it
618 anymore. Uh, and we ignore possible errors. There
619 is nothing we could do. */
620 (void) munmap (mem, size);
622 return err;
624 #endif
626 pd->guardsize = guardsize;
628 else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
631 /* The old guard area is too large. */
633 #ifdef NEED_SEPARATE_REGISTER_STACK
634 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
635 char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
637 #ifdef __ARCH_USE_MMU__
638 if (oldguard < guard
639 && mprotect (oldguard, guard - oldguard, prot) != 0)
640 goto mprot_error;
642 if (mprotect (guard + guardsize,
643 oldguard + pd->guardsize - guard - guardsize,
644 prot) != 0)
645 goto mprot_error;
646 #elif defined _STACK_GROWS_DOWN
647 if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
648 prot) != 0)
649 goto mprot_error;
650 #elif defined _STACK_GROWS_UP
651 if (mprotect ((char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1),
652 pd->guardsize - guardsize, prot) != 0)
653 goto mprot_error;
654 #endif
655 #endif
657 pd->guardsize = guardsize;
659 /* The pthread_getattr_np() calls need to get passed the size
660 requested in the attribute, regardless of how large the
661 actually used guardsize is. */
662 pd->reported_guardsize = guardsize;
665 /* Initialize the lock. We have to do this unconditionally since the
666 stillborn thread could be canceled while the lock is taken. */
667 pd->lock = LLL_LOCK_INITIALIZER;
669 /* The robust mutex lists also need to be initialized
670 unconditionally because the cleanup for the previous stack owner
671 might have happened in the kernel. */
672 pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
673 - offsetof (pthread_mutex_t,
674 __data.__list.__next));
675 pd->robust_head.list_op_pending = NULL;
676 #ifdef __PTHREAD_MUTEX_HAVE_PREV
677 pd->robust_prev = &pd->robust_head;
678 #endif
679 pd->robust_head.list = &pd->robust_head;
681 /* We place the thread descriptor at the end of the stack. */
682 *pdp = pd;
684 #if defined(TLS_TCB_AT_TP)
685 /* The stack begins before the TCB and the static TLS block. */
686 stacktop = ((char *) (pd + 1) - __static_tls_size);
687 #elif defined(TLS_DTV_AT_TP)
688 stacktop = (char *) (pd - 1);
689 #endif
691 #ifdef NEED_SEPARATE_REGISTER_STACK
692 *stack = pd->stackblock;
693 *stacksize = stacktop - *stack;
694 #elif defined _STACK_GROWS_DOWN
695 *stack = stacktop;
696 #elif defined _STACK_GROWS_UP
697 *stack = pd->stackblock;
698 assert (*stack > 0);
699 #endif
701 return 0;
705 void
706 internal_function
707 __deallocate_stack (struct pthread *pd)
709 lll_lock (stack_cache_lock, LLL_PRIVATE);
711 /* Remove the thread from the list of threads with user defined
712 stacks. */
713 stack_list_del (&pd->list);
715 /* Not much to do. Just free the mmap()ed memory. Note that we do
716 not reset the 'used' flag in the 'tid' field. This is done by
717 the kernel. If no thread has been created yet this field is
718 still zero. */
719 if (__builtin_expect (! pd->user_stack, 1))
720 (void) queue_stack (pd);
721 else
722 /* Free the memory associated with the ELF TLS. */
723 _dl_deallocate_tls (TLS_TPADJ (pd), false);
725 lll_unlock (stack_cache_lock, LLL_PRIVATE);
730 internal_function
731 __make_stacks_executable (void **stack_endp)
733 /* First the main thread's stack. */
734 int err = EPERM;
735 if (err != 0)
736 return err;
738 #ifdef NEED_SEPARATE_REGISTER_STACK
739 const size_t pagemask = ~(__getpagesize () - 1);
740 #endif
742 lll_lock (stack_cache_lock, LLL_PRIVATE);
744 list_t *runp;
745 list_for_each (runp, &stack_used)
747 err = change_stack_perm (list_entry (runp, struct pthread, list)
748 #ifdef NEED_SEPARATE_REGISTER_STACK
749 , pagemask
750 #endif
752 if (err != 0)
753 break;
756 /* Also change the permission for the currently unused stacks. This
757 might be wasted time but better spend it here than adding a check
758 in the fast path. */
759 if (err == 0)
760 list_for_each (runp, &stack_cache)
762 err = change_stack_perm (list_entry (runp, struct pthread, list)
763 #ifdef NEED_SEPARATE_REGISTER_STACK
764 , pagemask
765 #endif
767 if (err != 0)
768 break;
771 lll_unlock (stack_cache_lock, LLL_PRIVATE);
773 return err;
777 /* In case of a fork() call the memory allocation in the child will be
778 the same but only one thread is running. All stacks except that of
779 the one running thread are not used anymore. We have to recycle
780 them. */
781 void
782 __reclaim_stacks (void)
784 struct pthread *self = (struct pthread *) THREAD_SELF;
786 /* No locking necessary. The caller is the only stack in use. But
787 we have to be aware that we might have interrupted a list
788 operation. */
790 if (in_flight_stack != 0)
792 bool add_p = in_flight_stack & 1;
793 list_t *elem = (list_t *)(uintptr_t)(in_flight_stack & ~UINTMAX_C (1));
795 if (add_p)
797 /* We always add at the beginning of the list. So in this
798 case we only need to check the beginning of these lists. */
799 int check_list (list_t *l)
801 if (l->next->prev != l)
803 assert (l->next->prev == elem);
805 elem->next = l->next;
806 elem->prev = l;
807 l->next = elem;
809 return 1;
812 return 0;
815 if (check_list (&stack_used) == 0)
816 (void) check_list (&stack_cache);
818 else
820 /* We can simply always replay the delete operation. */
821 elem->next->prev = elem->prev;
822 elem->prev->next = elem->next;
826 /* Mark all stacks except the still running one as free. */
827 list_t *runp;
828 list_for_each (runp, &stack_used)
830 struct pthread *curp = list_entry (runp, struct pthread, list);
831 if (curp != self)
833 /* This marks the stack as free. */
834 curp->tid = 0;
836 /* Account for the size of the stack. */
837 stack_cache_actsize += curp->stackblock_size;
839 if (curp->specific_used)
841 /* Clear the thread-specific data. */
842 memset (curp->specific_1stblock, '\0',
843 sizeof (curp->specific_1stblock));
845 curp->specific_used = false;
847 size_t cnt;
848 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
849 if (curp->specific[cnt] != NULL)
851 memset (curp->specific[cnt], '\0',
852 sizeof (curp->specific_1stblock));
854 /* We have allocated the block which we do not
855 free here so re-set the bit. */
856 curp->specific_used = true;
862 /* Add the stack of all running threads to the cache. */
863 list_splice (&stack_used, &stack_cache);
865 /* Remove the entry for the current thread to from the cache list
866 and add it to the list of running threads. Which of the two
867 lists is decided by the user_stack flag. */
868 stack_list_del (&self->list);
870 /* Re-initialize the lists for all the threads. */
871 INIT_LIST_HEAD (&stack_used);
872 INIT_LIST_HEAD (&__stack_user);
874 if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
875 list_add (&self->list, &__stack_user);
876 else
877 list_add (&self->list, &stack_used);
879 /* There is one thread running. */
880 __nptl_nthreads = 1;
882 in_flight_stack = 0;
884 /* Initialize the lock. */
885 stack_cache_lock = LLL_LOCK_INITIALIZER;
889 static void
890 internal_function
891 setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
893 int ch;
895 /* Don't let the thread exit before the setxid handler runs. */
896 t->setxid_futex = 0;
900 ch = t->cancelhandling;
902 /* If the thread is exiting right now, ignore it. */
903 if ((ch & EXITING_BITMASK) != 0)
904 return;
906 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
907 ch | SETXID_BITMASK, ch));
911 static void
912 internal_function
913 setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
915 int ch;
919 ch = t->cancelhandling;
920 if ((ch & SETXID_BITMASK) == 0)
921 return;
923 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
924 ch & ~SETXID_BITMASK, ch));
926 /* Release the futex just in case. */
927 t->setxid_futex = 1;
928 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
932 static int
933 internal_function
934 setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
936 if ((t->cancelhandling & SETXID_BITMASK) == 0)
937 return 0;
939 int val;
940 pid_t pid = getpid ();
941 INTERNAL_SYSCALL_DECL (err);
942 val = INTERNAL_SYSCALL (tgkill, err, 3, pid, t->tid, SIGSETXID);
944 /* If this failed, it must have had not started yet or else exited. */
945 if (!INTERNAL_SYSCALL_ERROR_P (val, err))
947 atomic_increment (&cmdp->cntr);
948 return 1;
950 else
951 return 0;
956 attribute_hidden
957 __nptl_setxid (struct xid_command *cmdp)
959 int signalled;
960 int result;
961 lll_lock (stack_cache_lock, LLL_PRIVATE);
963 __xidcmd = cmdp;
964 cmdp->cntr = 0;
966 struct pthread *self = THREAD_SELF;
968 /* Iterate over the list with system-allocated threads first. */
969 list_t *runp;
970 list_for_each (runp, &stack_used)
972 struct pthread *t = list_entry (runp, struct pthread, list);
973 if (t == self)
974 continue;
976 setxid_mark_thread (cmdp, t);
979 /* Now the list with threads using user-allocated stacks. */
980 list_for_each (runp, &__stack_user)
982 struct pthread *t = list_entry (runp, struct pthread, list);
983 if (t == self)
984 continue;
986 setxid_mark_thread (cmdp, t);
989 /* Iterate until we don't succeed in signalling anyone. That means
990 we have gotten all running threads, and their children will be
991 automatically correct once started. */
994 signalled = 0;
996 list_for_each (runp, &stack_used)
998 struct pthread *t = list_entry (runp, struct pthread, list);
999 if (t == self)
1000 continue;
1002 signalled += setxid_signal_thread (cmdp, t);
1005 list_for_each (runp, &__stack_user)
1007 struct pthread *t = list_entry (runp, struct pthread, list);
1008 if (t == self)
1009 continue;
1011 signalled += setxid_signal_thread (cmdp, t);
1014 int cur = cmdp->cntr;
1015 while (cur != 0)
1017 lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
1018 cur = cmdp->cntr;
1021 while (signalled != 0);
1023 /* Clean up flags, so that no thread blocks during exit waiting
1024 for a signal which will never come. */
1025 list_for_each (runp, &stack_used)
1027 struct pthread *t = list_entry (runp, struct pthread, list);
1028 if (t == self)
1029 continue;
1031 setxid_unmark_thread (cmdp, t);
1034 list_for_each (runp, &__stack_user)
1036 struct pthread *t = list_entry (runp, struct pthread, list);
1037 if (t == self)
1038 continue;
1040 setxid_unmark_thread (cmdp, t);
1043 /* This must be last, otherwise the current thread might not have
1044 permissions to send SIGSETXID syscall to the other threads. */
1045 INTERNAL_SYSCALL_DECL (err);
1046 result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
1047 cmdp->id[0], cmdp->id[1], cmdp->id[2]);
1048 if (INTERNAL_SYSCALL_ERROR_P (result, err))
1050 __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
1051 result = -1;
1054 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1055 return result;
1058 static inline void __attribute__((always_inline))
1059 init_one_static_tls (struct pthread *curp, struct link_map *map)
1061 dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
1062 # if defined(TLS_TCB_AT_TP)
1063 void *dest = (char *) curp - map->l_tls_offset;
1064 # elif defined(TLS_DTV_AT_TP)
1065 void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
1066 # else
1067 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1068 # endif
1070 /* Fill in the DTV slot so that a later LD/GD access will find it. */
1071 dtv[map->l_tls_modid].pointer.val = dest;
1072 dtv[map->l_tls_modid].pointer.is_static = true;
1074 /* Initialize the memory. */
1075 memset (mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
1076 '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
1079 void
1080 attribute_hidden
1081 __pthread_init_static_tls (struct link_map *map)
1083 lll_lock (stack_cache_lock, LLL_PRIVATE);
1085 /* Iterate over the list with system-allocated threads first. */
1086 list_t *runp;
1087 list_for_each (runp, &stack_used)
1088 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1090 /* Now the list with threads using user-allocated stacks. */
1091 list_for_each (runp, &__stack_user)
1092 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1094 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1098 void
1099 attribute_hidden
1100 __wait_lookup_done (void)
1102 lll_lock (stack_cache_lock, LLL_PRIVATE);
1104 struct pthread *self = THREAD_SELF;
1106 /* Iterate over the list with system-allocated threads first. */
1107 list_t *runp;
1108 list_for_each (runp, &stack_used)
1110 struct pthread *t = list_entry (runp, struct pthread, list);
1111 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1112 continue;
1114 int *const gscope_flagp = &t->header.gscope_flag;
1116 /* We have to wait until this thread is done with the global
1117 scope. First tell the thread that we are waiting and
1118 possibly have to be woken. */
1119 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1120 THREAD_GSCOPE_FLAG_WAIT,
1121 THREAD_GSCOPE_FLAG_USED))
1122 continue;
1125 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1126 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1129 /* Now the list with threads using user-allocated stacks. */
1130 list_for_each (runp, &__stack_user)
1132 struct pthread *t = list_entry (runp, struct pthread, list);
1133 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1134 continue;
1136 int *const gscope_flagp = &t->header.gscope_flag;
1138 /* We have to wait until this thread is done with the global
1139 scope. First tell the thread that we are waiting and
1140 possibly have to be woken. */
1141 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1142 THREAD_GSCOPE_FLAG_WAIT,
1143 THREAD_GSCOPE_FLAG_USED))
1144 continue;
1147 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1148 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1151 lll_unlock (stack_cache_lock, LLL_PRIVATE);