Support C11 __STDC_SOURCE__ and _ISOC11_SOURCE
[glibc.git] / nptl / allocatestack.c
blobb1b17ceba7eae4fda0ec970dc56e32e42746f39c
1 /* Copyright (C) 2002-2007, 2009, 2010, 2011 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, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 #include <assert.h>
21 #include <errno.h>
22 #include <signal.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/mman.h>
27 #include <sys/param.h>
28 #include <dl-sysdep.h>
29 #include <dl-tls.h>
30 #include <tls.h>
31 #include <list.h>
32 #include <lowlevellock.h>
33 #include <kernel-features.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 (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
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 static int
345 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
346 ALLOCATE_STACK_PARMS)
348 struct pthread *pd;
349 size_t size;
350 size_t pagesize_m1 = __getpagesize () - 1;
351 void *stacktop;
353 assert (attr != NULL);
354 assert (powerof2 (pagesize_m1 + 1));
355 assert (TCB_ALIGNMENT >= STACK_ALIGN);
357 /* Get the stack size from the attribute if it is set. Otherwise we
358 use the default we determined at start time. */
359 size = attr->stacksize ?: __default_stacksize;
361 /* Get memory for the stack. */
362 if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
364 uintptr_t adj;
366 /* If the user also specified the size of the stack make sure it
367 is large enough. */
368 if (attr->stacksize != 0
369 && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
370 return EINVAL;
372 /* Adjust stack size for alignment of the TLS block. */
373 #if TLS_TCB_AT_TP
374 adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
375 & __static_tls_align_m1;
376 assert (size > adj + TLS_TCB_SIZE);
377 #elif TLS_DTV_AT_TP
378 adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
379 & __static_tls_align_m1;
380 assert (size > adj);
381 #endif
383 /* The user provided some memory. Let's hope it matches the
384 size... We do not allocate guard pages if the user provided
385 the stack. It is the user's responsibility to do this if it
386 is wanted. */
387 #if TLS_TCB_AT_TP
388 pd = (struct pthread *) ((uintptr_t) attr->stackaddr
389 - TLS_TCB_SIZE - adj);
390 #elif TLS_DTV_AT_TP
391 pd = (struct pthread *) (((uintptr_t) attr->stackaddr
392 - __static_tls_size - adj)
393 - TLS_PRE_TCB_SIZE);
394 #endif
396 /* The user provided stack memory needs to be cleared. */
397 memset (pd, '\0', sizeof (struct pthread));
399 /* The first TSD block is included in the TCB. */
400 pd->specific[0] = pd->specific_1stblock;
402 /* Remember the stack-related values. */
403 pd->stackblock = (char *) attr->stackaddr - size;
404 pd->stackblock_size = size;
406 /* This is a user-provided stack. It will not be queued in the
407 stack cache nor will the memory (except the TLS memory) be freed. */
408 pd->user_stack = true;
410 /* This is at least the second thread. */
411 pd->header.multiple_threads = 1;
412 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
413 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
414 #endif
416 #ifndef __ASSUME_PRIVATE_FUTEX
417 /* The thread must know when private futexes are supported. */
418 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
419 header.private_futex);
420 #endif
422 #ifdef NEED_DL_SYSINFO
423 /* Copy the sysinfo value from the parent. */
424 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
425 #endif
427 /* The process ID is also the same as that of the caller. */
428 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
430 /* Don't allow setxid until cloned. */
431 pd->setxid_futex = -1;
433 /* Allocate the DTV for this thread. */
434 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
436 /* Something went wrong. */
437 assert (errno == ENOMEM);
438 return errno;
442 /* Prepare to modify global data. */
443 lll_lock (stack_cache_lock, LLL_PRIVATE);
445 /* And add to the list of stacks in use. */
446 list_add (&pd->list, &__stack_user);
448 lll_unlock (stack_cache_lock, LLL_PRIVATE);
450 else
452 /* Allocate some anonymous memory. If possible use the cache. */
453 size_t guardsize;
454 size_t reqsize;
455 void *mem;
456 const int prot = (PROT_READ | PROT_WRITE
457 | ((GL(dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
459 #if COLORING_INCREMENT != 0
460 /* Add one more page for stack coloring. Don't do it for stacks
461 with 16 times pagesize or larger. This might just cause
462 unnecessary misalignment. */
463 if (size <= 16 * pagesize_m1)
464 size += pagesize_m1 + 1;
465 #endif
467 /* Adjust the stack size for alignment. */
468 size &= ~__static_tls_align_m1;
469 assert (size != 0);
471 /* Make sure the size of the stack is enough for the guard and
472 eventually the thread descriptor. */
473 guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
474 if (__builtin_expect (size < ((guardsize + __static_tls_size
475 + MINIMAL_REST_STACK + pagesize_m1)
476 & ~pagesize_m1),
478 /* The stack is too small (or the guard too large). */
479 return EINVAL;
481 /* Try to get a stack from the cache. */
482 reqsize = size;
483 pd = get_cached_stack (&size, &mem);
484 if (pd == NULL)
486 /* To avoid aliasing effects on a larger scale than pages we
487 adjust the allocated stack size if necessary. This way
488 allocations directly following each other will not have
489 aliasing problems. */
490 #if MULTI_PAGE_ALIASING != 0
491 if ((size % MULTI_PAGE_ALIASING) == 0)
492 size += pagesize_m1 + 1;
493 #endif
495 mem = mmap (NULL, size, prot,
496 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
498 if (__builtin_expect (mem == MAP_FAILED, 0))
499 return errno;
501 /* SIZE is guaranteed to be greater than zero.
502 So we can never get a null pointer back from mmap. */
503 assert (mem != NULL);
505 #if COLORING_INCREMENT != 0
506 /* Atomically increment NCREATED. */
507 unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
509 /* We chose the offset for coloring by incrementing it for
510 every new thread by a fixed amount. The offset used
511 module the page size. Even if coloring would be better
512 relative to higher alignment values it makes no sense to
513 do it since the mmap() interface does not allow us to
514 specify any alignment for the returned memory block. */
515 size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
517 /* Make sure the coloring offsets does not disturb the alignment
518 of the TCB and static TLS block. */
519 if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
520 coloring = (((coloring + __static_tls_align_m1)
521 & ~(__static_tls_align_m1))
522 & ~pagesize_m1);
523 #else
524 /* Unless specified we do not make any adjustments. */
525 # define coloring 0
526 #endif
528 /* Place the thread descriptor at the end of the stack. */
529 #if TLS_TCB_AT_TP
530 pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
531 #elif TLS_DTV_AT_TP
532 pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
533 - __static_tls_size)
534 & ~__static_tls_align_m1)
535 - TLS_PRE_TCB_SIZE);
536 #endif
538 /* Remember the stack-related values. */
539 pd->stackblock = mem;
540 pd->stackblock_size = size;
542 /* We allocated the first block thread-specific data array.
543 This address will not change for the lifetime of this
544 descriptor. */
545 pd->specific[0] = pd->specific_1stblock;
547 /* This is at least the second thread. */
548 pd->header.multiple_threads = 1;
549 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
550 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
551 #endif
553 #ifndef __ASSUME_PRIVATE_FUTEX
554 /* The thread must know when private futexes are supported. */
555 pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
556 header.private_futex);
557 #endif
559 #ifdef NEED_DL_SYSINFO
560 /* Copy the sysinfo value from the parent. */
561 THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
562 #endif
564 /* Don't allow setxid until cloned. */
565 pd->setxid_futex = -1;
567 /* The process ID is also the same as that of the caller. */
568 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
570 /* Allocate the DTV for this thread. */
571 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
573 /* Something went wrong. */
574 assert (errno == ENOMEM);
576 /* Free the stack memory we just allocated. */
577 (void) munmap (mem, size);
579 return errno;
583 /* Prepare to modify global data. */
584 lll_lock (stack_cache_lock, LLL_PRIVATE);
586 /* And add to the list of stacks in use. */
587 stack_list_add (&pd->list, &stack_used);
589 lll_unlock (stack_cache_lock, LLL_PRIVATE);
592 /* There might have been a race. Another thread might have
593 caused the stacks to get exec permission while this new
594 stack was prepared. Detect if this was possible and
595 change the permission if necessary. */
596 if (__builtin_expect ((GL(dl_stack_flags) & PF_X) != 0
597 && (prot & PROT_EXEC) == 0, 0))
599 int err = change_stack_perm (pd
600 #ifdef NEED_SEPARATE_REGISTER_STACK
601 , ~pagesize_m1
602 #endif
604 if (err != 0)
606 /* Free the stack memory we just allocated. */
607 (void) munmap (mem, size);
609 return err;
614 /* Note that all of the stack and the thread descriptor is
615 zeroed. This means we do not have to initialize fields
616 with initial value zero. This is specifically true for
617 the 'tid' field which is always set back to zero once the
618 stack is not used anymore and for the 'guardsize' field
619 which will be read next. */
622 /* Create or resize the guard area if necessary. */
623 if (__builtin_expect (guardsize > pd->guardsize, 0))
625 #ifdef NEED_SEPARATE_REGISTER_STACK
626 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
627 #elif _STACK_GROWS_DOWN
628 char *guard = mem;
629 # elif _STACK_GROWS_UP
630 char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
631 #endif
632 if (mprotect (guard, guardsize, PROT_NONE) != 0)
634 mprot_error:
635 lll_lock (stack_cache_lock, LLL_PRIVATE);
637 /* Remove the thread from the list. */
638 stack_list_del (&pd->list);
640 lll_unlock (stack_cache_lock, LLL_PRIVATE);
642 /* Get rid of the TLS block we allocated. */
643 _dl_deallocate_tls (TLS_TPADJ (pd), false);
645 /* Free the stack memory regardless of whether the size
646 of the cache is over the limit or not. If this piece
647 of memory caused problems we better do not use it
648 anymore. Uh, and we ignore possible errors. There
649 is nothing we could do. */
650 (void) munmap (mem, size);
652 return errno;
655 pd->guardsize = guardsize;
657 else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
660 /* The old guard area is too large. */
662 #ifdef NEED_SEPARATE_REGISTER_STACK
663 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
664 char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
666 if (oldguard < guard
667 && mprotect (oldguard, guard - oldguard, prot) != 0)
668 goto mprot_error;
670 if (mprotect (guard + guardsize,
671 oldguard + pd->guardsize - guard - guardsize,
672 prot) != 0)
673 goto mprot_error;
674 #elif _STACK_GROWS_DOWN
675 if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
676 prot) != 0)
677 goto mprot_error;
678 #elif _STACK_GROWS_UP
679 if (mprotect ((char *) pd - pd->guardsize,
680 pd->guardsize - guardsize, prot) != 0)
681 goto mprot_error;
682 #endif
684 pd->guardsize = guardsize;
686 /* The pthread_getattr_np() calls need to get passed the size
687 requested in the attribute, regardless of how large the
688 actually used guardsize is. */
689 pd->reported_guardsize = guardsize;
692 /* Initialize the lock. We have to do this unconditionally since the
693 stillborn thread could be canceled while the lock is taken. */
694 pd->lock = LLL_LOCK_INITIALIZER;
696 /* The robust mutex lists also need to be initialized
697 unconditionally because the cleanup for the previous stack owner
698 might have happened in the kernel. */
699 pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
700 - offsetof (pthread_mutex_t,
701 __data.__list.__next));
702 pd->robust_head.list_op_pending = NULL;
703 #ifdef __PTHREAD_MUTEX_HAVE_PREV
704 pd->robust_prev = &pd->robust_head;
705 #endif
706 pd->robust_head.list = &pd->robust_head;
708 /* We place the thread descriptor at the end of the stack. */
709 *pdp = pd;
711 #if TLS_TCB_AT_TP
712 /* The stack begins before the TCB and the static TLS block. */
713 stacktop = ((char *) (pd + 1) - __static_tls_size);
714 #elif TLS_DTV_AT_TP
715 stacktop = (char *) (pd - 1);
716 #endif
718 #ifdef NEED_SEPARATE_REGISTER_STACK
719 *stack = pd->stackblock;
720 *stacksize = stacktop - *stack;
721 #elif _STACK_GROWS_DOWN
722 *stack = stacktop;
723 #elif _STACK_GROWS_UP
724 *stack = pd->stackblock;
725 assert (*stack > 0);
726 #endif
728 return 0;
732 void
733 internal_function
734 __deallocate_stack (struct pthread *pd)
736 lll_lock (stack_cache_lock, LLL_PRIVATE);
738 /* Remove the thread from the list of threads with user defined
739 stacks. */
740 stack_list_del (&pd->list);
742 /* Not much to do. Just free the mmap()ed memory. Note that we do
743 not reset the 'used' flag in the 'tid' field. This is done by
744 the kernel. If no thread has been created yet this field is
745 still zero. */
746 if (__builtin_expect (! pd->user_stack, 1))
747 (void) queue_stack (pd);
748 else
749 /* Free the memory associated with the ELF TLS. */
750 _dl_deallocate_tls (TLS_TPADJ (pd), false);
752 lll_unlock (stack_cache_lock, LLL_PRIVATE);
757 internal_function
758 __make_stacks_executable (void **stack_endp)
760 /* First the main thread's stack. */
761 int err = _dl_make_stack_executable (stack_endp);
762 if (err != 0)
763 return err;
765 #ifdef NEED_SEPARATE_REGISTER_STACK
766 const size_t pagemask = ~(__getpagesize () - 1);
767 #endif
769 lll_lock (stack_cache_lock, LLL_PRIVATE);
771 list_t *runp;
772 list_for_each (runp, &stack_used)
774 err = change_stack_perm (list_entry (runp, struct pthread, list)
775 #ifdef NEED_SEPARATE_REGISTER_STACK
776 , pagemask
777 #endif
779 if (err != 0)
780 break;
783 /* Also change the permission for the currently unused stacks. This
784 might be wasted time but better spend it here than adding a check
785 in the fast path. */
786 if (err == 0)
787 list_for_each (runp, &stack_cache)
789 err = change_stack_perm (list_entry (runp, struct pthread, list)
790 #ifdef NEED_SEPARATE_REGISTER_STACK
791 , pagemask
792 #endif
794 if (err != 0)
795 break;
798 lll_unlock (stack_cache_lock, LLL_PRIVATE);
800 return err;
804 /* In case of a fork() call the memory allocation in the child will be
805 the same but only one thread is running. All stacks except that of
806 the one running thread are not used anymore. We have to recycle
807 them. */
808 void
809 __reclaim_stacks (void)
811 struct pthread *self = (struct pthread *) THREAD_SELF;
813 /* No locking necessary. The caller is the only stack in use. But
814 we have to be aware that we might have interrupted a list
815 operation. */
817 if (in_flight_stack != 0)
819 bool add_p = in_flight_stack & 1;
820 list_t *elem = (list_t *) (in_flight_stack & ~(uintptr_t) 1);
822 if (add_p)
824 /* We always add at the beginning of the list. So in this
825 case we only need to check the beginning of these lists. */
826 int check_list (list_t *l)
828 if (l->next->prev != l)
830 assert (l->next->prev == elem);
832 elem->next = l->next;
833 elem->prev = l;
834 l->next = elem;
836 return 1;
839 return 0;
842 if (check_list (&stack_used) == 0)
843 (void) check_list (&stack_cache);
845 else
847 /* We can simply always replay the delete operation. */
848 elem->next->prev = elem->prev;
849 elem->prev->next = elem->next;
853 /* Mark all stacks except the still running one as free. */
854 list_t *runp;
855 list_for_each (runp, &stack_used)
857 struct pthread *curp = list_entry (runp, struct pthread, list);
858 if (curp != self)
860 /* This marks the stack as free. */
861 curp->tid = 0;
863 /* The PID field must be initialized for the new process. */
864 curp->pid = self->pid;
866 /* Account for the size of the stack. */
867 stack_cache_actsize += curp->stackblock_size;
869 if (curp->specific_used)
871 /* Clear the thread-specific data. */
872 memset (curp->specific_1stblock, '\0',
873 sizeof (curp->specific_1stblock));
875 curp->specific_used = false;
877 for (size_t cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
878 if (curp->specific[cnt] != NULL)
880 memset (curp->specific[cnt], '\0',
881 sizeof (curp->specific_1stblock));
883 /* We have allocated the block which we do not
884 free here so re-set the bit. */
885 curp->specific_used = true;
891 /* Reset the PIDs in any cached stacks. */
892 list_for_each (runp, &stack_cache)
894 struct pthread *curp = list_entry (runp, struct pthread, list);
895 curp->pid = self->pid;
898 /* Add the stack of all running threads to the cache. */
899 list_splice (&stack_used, &stack_cache);
901 /* Remove the entry for the current thread to from the cache list
902 and add it to the list of running threads. Which of the two
903 lists is decided by the user_stack flag. */
904 stack_list_del (&self->list);
906 /* Re-initialize the lists for all the threads. */
907 INIT_LIST_HEAD (&stack_used);
908 INIT_LIST_HEAD (&__stack_user);
910 if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
911 list_add (&self->list, &__stack_user);
912 else
913 list_add (&self->list, &stack_used);
915 /* There is one thread running. */
916 __nptl_nthreads = 1;
918 in_flight_stack = 0;
920 /* Initialize the lock. */
921 stack_cache_lock = LLL_LOCK_INITIALIZER;
925 #if HP_TIMING_AVAIL
926 # undef __find_thread_by_id
927 /* Find a thread given the thread ID. */
928 attribute_hidden
929 struct pthread *
930 __find_thread_by_id (pid_t tid)
932 struct pthread *result = NULL;
934 lll_lock (stack_cache_lock, LLL_PRIVATE);
936 /* Iterate over the list with system-allocated threads first. */
937 list_t *runp;
938 list_for_each (runp, &stack_used)
940 struct pthread *curp;
942 curp = list_entry (runp, struct pthread, list);
944 if (curp->tid == tid)
946 result = curp;
947 goto out;
951 /* Now the list with threads using user-allocated stacks. */
952 list_for_each (runp, &__stack_user)
954 struct pthread *curp;
956 curp = list_entry (runp, struct pthread, list);
958 if (curp->tid == tid)
960 result = curp;
961 goto out;
965 out:
966 lll_unlock (stack_cache_lock, LLL_PRIVATE);
968 return result;
970 #endif
973 static void
974 internal_function
975 setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
977 int ch;
979 /* Wait until this thread is cloned. */
980 if (t->setxid_futex == -1
981 && ! atomic_compare_and_exchange_bool_acq (&t->setxid_futex, -2, -1))
983 lll_futex_wait (&t->setxid_futex, -2, LLL_PRIVATE);
984 while (t->setxid_futex == -2);
986 /* Don't let the thread exit before the setxid handler runs. */
987 t->setxid_futex = 0;
991 ch = t->cancelhandling;
993 /* If the thread is exiting right now, ignore it. */
994 if ((ch & EXITING_BITMASK) != 0)
996 /* Release the futex if there is no other setxid in
997 progress. */
998 if ((ch & SETXID_BITMASK) == 0)
1000 t->setxid_futex = 1;
1001 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1003 return;
1006 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1007 ch | SETXID_BITMASK, ch));
1011 static void
1012 internal_function
1013 setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
1015 int ch;
1019 ch = t->cancelhandling;
1020 if ((ch & SETXID_BITMASK) == 0)
1021 return;
1023 while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1024 ch & ~SETXID_BITMASK, ch));
1026 /* Release the futex just in case. */
1027 t->setxid_futex = 1;
1028 lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1032 static int
1033 internal_function
1034 setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
1036 if ((t->cancelhandling & SETXID_BITMASK) == 0)
1037 return 0;
1039 int val;
1040 INTERNAL_SYSCALL_DECL (err);
1041 #if __ASSUME_TGKILL
1042 val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
1043 t->tid, SIGSETXID);
1044 #else
1045 # ifdef __NR_tgkill
1046 val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
1047 t->tid, SIGSETXID);
1048 if (INTERNAL_SYSCALL_ERROR_P (val, err)
1049 && INTERNAL_SYSCALL_ERRNO (val, err) == ENOSYS)
1050 # endif
1051 val = INTERNAL_SYSCALL (tkill, err, 2, t->tid, SIGSETXID);
1052 #endif
1054 /* If this failed, it must have had not started yet or else exited. */
1055 if (!INTERNAL_SYSCALL_ERROR_P (val, err))
1057 atomic_increment (&cmdp->cntr);
1058 return 1;
1060 else
1061 return 0;
1066 attribute_hidden
1067 __nptl_setxid (struct xid_command *cmdp)
1069 int signalled;
1070 int result;
1071 lll_lock (stack_cache_lock, LLL_PRIVATE);
1073 __xidcmd = cmdp;
1074 cmdp->cntr = 0;
1076 struct pthread *self = THREAD_SELF;
1078 /* Iterate over the list with system-allocated threads first. */
1079 list_t *runp;
1080 list_for_each (runp, &stack_used)
1082 struct pthread *t = list_entry (runp, struct pthread, list);
1083 if (t == self)
1084 continue;
1086 setxid_mark_thread (cmdp, t);
1089 /* Now the list with threads using user-allocated stacks. */
1090 list_for_each (runp, &__stack_user)
1092 struct pthread *t = list_entry (runp, struct pthread, list);
1093 if (t == self)
1094 continue;
1096 setxid_mark_thread (cmdp, t);
1099 /* Iterate until we don't succeed in signalling anyone. That means
1100 we have gotten all running threads, and their children will be
1101 automatically correct once started. */
1104 signalled = 0;
1106 list_for_each (runp, &stack_used)
1108 struct pthread *t = list_entry (runp, struct pthread, list);
1109 if (t == self)
1110 continue;
1112 signalled += setxid_signal_thread (cmdp, t);
1115 list_for_each (runp, &__stack_user)
1117 struct pthread *t = list_entry (runp, struct pthread, list);
1118 if (t == self)
1119 continue;
1121 signalled += setxid_signal_thread (cmdp, t);
1124 int cur = cmdp->cntr;
1125 while (cur != 0)
1127 lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
1128 cur = cmdp->cntr;
1131 while (signalled != 0);
1133 /* Clean up flags, so that no thread blocks during exit waiting
1134 for a signal which will never come. */
1135 list_for_each (runp, &stack_used)
1137 struct pthread *t = list_entry (runp, struct pthread, list);
1138 if (t == self)
1139 continue;
1141 setxid_unmark_thread (cmdp, t);
1144 list_for_each (runp, &__stack_user)
1146 struct pthread *t = list_entry (runp, struct pthread, list);
1147 if (t == self)
1148 continue;
1150 setxid_unmark_thread (cmdp, t);
1153 /* This must be last, otherwise the current thread might not have
1154 permissions to send SIGSETXID syscall to the other threads. */
1155 INTERNAL_SYSCALL_DECL (err);
1156 result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
1157 cmdp->id[0], cmdp->id[1], cmdp->id[2]);
1158 if (INTERNAL_SYSCALL_ERROR_P (result, err))
1160 __set_errno (INTERNAL_SYSCALL_ERRNO (result, err));
1161 result = -1;
1164 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1165 return result;
1168 static inline void __attribute__((always_inline))
1169 init_one_static_tls (struct pthread *curp, struct link_map *map)
1171 dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
1172 # if TLS_TCB_AT_TP
1173 void *dest = (char *) curp - map->l_tls_offset;
1174 # elif TLS_DTV_AT_TP
1175 void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
1176 # else
1177 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1178 # endif
1180 /* Fill in the DTV slot so that a later LD/GD access will find it. */
1181 dtv[map->l_tls_modid].pointer.val = dest;
1182 dtv[map->l_tls_modid].pointer.is_static = true;
1184 /* Initialize the memory. */
1185 memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
1186 '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
1189 void
1190 attribute_hidden
1191 __pthread_init_static_tls (struct link_map *map)
1193 lll_lock (stack_cache_lock, LLL_PRIVATE);
1195 /* Iterate over the list with system-allocated threads first. */
1196 list_t *runp;
1197 list_for_each (runp, &stack_used)
1198 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1200 /* Now the list with threads using user-allocated stacks. */
1201 list_for_each (runp, &__stack_user)
1202 init_one_static_tls (list_entry (runp, struct pthread, list), map);
1204 lll_unlock (stack_cache_lock, LLL_PRIVATE);
1208 void
1209 attribute_hidden
1210 __wait_lookup_done (void)
1212 lll_lock (stack_cache_lock, LLL_PRIVATE);
1214 struct pthread *self = THREAD_SELF;
1216 /* Iterate over the list with system-allocated threads first. */
1217 list_t *runp;
1218 list_for_each (runp, &stack_used)
1220 struct pthread *t = list_entry (runp, struct pthread, list);
1221 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1222 continue;
1224 int *const gscope_flagp = &t->header.gscope_flag;
1226 /* We have to wait until this thread is done with the global
1227 scope. First tell the thread that we are waiting and
1228 possibly have to be woken. */
1229 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1230 THREAD_GSCOPE_FLAG_WAIT,
1231 THREAD_GSCOPE_FLAG_USED))
1232 continue;
1235 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1236 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1239 /* Now the list with threads using user-allocated stacks. */
1240 list_for_each (runp, &__stack_user)
1242 struct pthread *t = list_entry (runp, struct pthread, list);
1243 if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1244 continue;
1246 int *const gscope_flagp = &t->header.gscope_flag;
1248 /* We have to wait until this thread is done with the global
1249 scope. First tell the thread that we are waiting and
1250 possibly have to be woken. */
1251 if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1252 THREAD_GSCOPE_FLAG_WAIT,
1253 THREAD_GSCOPE_FLAG_USED))
1254 continue;
1257 lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1258 while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1261 lll_unlock (stack_cache_lock, LLL_PRIVATE);