1 /* Copyright (C) 2002, 2003 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
26 #include <sys/param.h>
27 #include <dl-sysdep.h>
32 #ifndef NEED_SEPARATE_REGISTER_STACK
34 /* Most architectures have exactly one stack pointer. Some have more. */
35 #define STACK_VARIABLES void *stackaddr
37 /* How to pass the values to the 'create_thread' function. */
38 #define STACK_VARIABLES_ARGS stackaddr
40 /* How to declare function which gets there parameters. */
41 #define STACK_VARIABLES_PARMS void *stackaddr
43 /* How to declare allocate_stack. */
44 #define ALLOCATE_STACK_PARMS void **stack
46 /* This is how the function is called. We do it this way to allow
47 other variants of the function to have more parameters. */
48 #define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
52 #define STACK_VARIABLES void *stackaddr; size_t stacksize
53 #define STACK_VARIABLES_ARGS stackaddr, stacksize
54 #define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
55 #define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
56 #define ALLOCATE_STACK(attr, pd) \
57 allocate_stack (attr, pd, &stackaddr, &stacksize)
62 /* Default alignment of stack. */
64 # define STACK_ALIGN __alignof__ (long double)
67 /* Default value for minimal stack size after allocating thread
68 descriptor and guard. */
69 #ifndef MINIMAL_REST_STACK
70 # define MINIMAL_REST_STACK 4096
74 /* Let the architecture add some flags to the mmap() call used to
76 #ifndef ARCH_MAP_FLAGS
77 # define ARCH_MAP_FLAGS 0
80 /* This yields the pointer that TLS support code calls the thread pointer. */
82 # define TLS_TPADJ(pd) (pd)
84 # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
87 /* Cache handling for not-yet free stacks. */
89 /* Maximum size in kB of cache. */
90 static size_t stack_cache_maxsize = 40 * 1024 * 1024; /* 40MiBi by default. */
91 static size_t stack_cache_actsize;
93 /* Mutex protecting this variable. */
94 static lll_lock_t stack_cache_lock = LLL_LOCK_INITIALIZER;
96 /* List of queued stack frames. */
97 static LIST_HEAD (stack_cache);
99 /* List of the stacks in use. */
100 static LIST_HEAD (stack_used);
102 /* List of the threads with user provided stacks in use. No need to
103 initialize this, since it's done in __pthread_initialize_minimal. */
104 list_t __stack_user __attribute__ ((nocommon));
105 hidden_data_def (__stack_user)
107 #if COLORING_INCREMENT != 0
108 /* Number of threads created. */
109 static unsigned int nptl_ncreated;
113 /* Check whether the stack is still used or not. */
114 #define FREE_P(descr) ((descr)->tid <= 0)
117 /* We create a double linked list of all cache entries. Double linked
118 because this allows removing entries from the end. */
121 /* Get a stack frame from the cache. We have to match by size since
122 some blocks might be too small or far too large. */
123 static struct pthread *
124 get_cached_stack (size_t *sizep, void **memp)
126 size_t size = *sizep;
127 struct pthread *result = NULL;
130 lll_lock (stack_cache_lock);
132 /* Search the cache for a matching entry. We search for the
133 smallest stack which has at least the required size. Note that
134 in normal situations the size of all allocated stacks is the
135 same. As the very least there are only a few different sizes.
136 Therefore this loop will exit early most of the time with an
138 list_for_each (entry, &stack_cache)
140 struct pthread *curr;
142 curr = list_entry (entry, struct pthread, list);
143 if (FREE_P (curr) && curr->stackblock_size >= size)
145 if (curr->stackblock_size == size)
152 || result->stackblock_size > curr->stackblock_size)
157 if (__builtin_expect (result == NULL, 0)
158 /* Make sure the size difference is not too excessive. In that
159 case we do not use the block. */
160 || __builtin_expect (result->stackblock_size > 4 * size, 0))
162 /* Release the lock. */
163 lll_unlock (stack_cache_lock);
168 /* Dequeue the entry. */
169 list_del (&result->list);
171 /* And add to the list of stacks in use. */
172 list_add (&result->list, &stack_used);
174 /* And decrease the cache size. */
175 stack_cache_actsize -= result->stackblock_size;
177 /* Release the lock early. */
178 lll_unlock (stack_cache_lock);
180 /* Report size and location of the stack to the caller. */
181 *sizep = result->stackblock_size;
182 *memp = result->stackblock;
184 /* Cancellation handling is back to the default. */
185 result->cancelhandling = 0;
186 result->cleanup = NULL;
188 /* No pending event. */
189 result->nextevent = NULL;
192 dtv_t *dtv = GET_DTV (TLS_TPADJ (result));
193 memset (dtv, '\0', (dtv[-1].counter + 1) * sizeof (dtv_t));
195 /* Re-initialize the TLS. */
196 _dl_allocate_tls_init (TLS_TPADJ (result));
202 /* Add a stack frame which is not used anymore to the stack. Must be
203 called with the cache lock held. */
205 __attribute ((always_inline))
206 queue_stack (struct pthread *stack)
208 /* We unconditionally add the stack to the list. The memory may
209 still be in use but it will not be reused until the kernel marks
210 the stack as not used anymore. */
211 list_add (&stack->list, &stack_cache);
213 stack_cache_actsize += stack->stackblock_size;
214 if (__builtin_expect (stack_cache_actsize > stack_cache_maxsize, 0))
216 /* We reduce the size of the cache. Remove the last entries
217 until the size is below the limit. */
221 /* Search from the end of the list. */
222 list_for_each_prev_safe (entry, prev, &stack_cache)
224 struct pthread *curr;
226 curr = list_entry (entry, struct pthread, list);
229 /* Unlink the block. */
232 /* Account for the freed memory. */
233 stack_cache_actsize -= curr->stackblock_size;
235 /* Free the memory associated with the ELF TLS. */
236 _dl_deallocate_tls (TLS_TPADJ (curr), false);
238 /* Remove this block. This should never fail. If it
239 does something is really wrong. */
240 if (munmap (curr->stackblock, curr->stackblock_size) != 0)
243 /* Maybe we have freed enough. */
244 if (stack_cache_actsize <= stack_cache_maxsize)
254 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
255 ALLOCATE_STACK_PARMS)
259 size_t pagesize_m1 = __getpagesize () - 1;
262 assert (attr != NULL);
263 assert (powerof2 (pagesize_m1 + 1));
264 assert (TCB_ALIGNMENT >= STACK_ALIGN);
266 /* Get the stack size from the attribute if it is set. Otherwise we
267 use the default we determined at start time. */
268 size = attr->stacksize ?: __default_stacksize;
270 /* Get memory for the stack. */
271 if (__builtin_expect (attr->flags & ATTR_FLAG_STACKADDR, 0))
275 /* If the user also specified the size of the stack make sure it
277 if (attr->stacksize != 0
278 && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
281 /* Adjust stack size for alignment of the TLS block. */
283 adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
284 & __static_tls_align_m1;
285 assert (size > adj + TLS_TCB_SIZE);
287 adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
288 & __static_tls_align_m1;
292 /* The user provided some memory. Let's hope it matches the
293 size... We do not allocate guard pages if the user provided
294 the stack. It is the user's responsibility to do this if it
297 pd = (struct pthread *) ((uintptr_t) attr->stackaddr
298 - TLS_TCB_SIZE - adj);
300 pd = (struct pthread *) (((uintptr_t) attr->stackaddr
301 - __static_tls_size - adj)
305 /* The user provided stack memory needs to be cleared. */
306 memset (pd, '\0', sizeof (struct pthread));
308 /* The first TSD block is included in the TCB. */
309 pd->specific[0] = pd->specific_1stblock;
311 #if defined __ASSUME_CLONE_STOPPED && LLL_LOCK_INITIALIZER != 0
312 /* Initialize the lock. */
313 pd->lock = LLL_LOCK_INITIALIZER;
316 /* Remember the stack-related values. */
317 pd->stackblock = (char *) attr->stackaddr - size;
318 pd->stackblock_size = size;
320 /* This is a user-provided stack. It will not be queued in the
321 stack cache nor will the memory (except the TLS memory) be freed. */
322 pd->user_stack = true;
324 /* This is at least the second thread. */
325 pd->header.multiple_threads = 1;
326 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
327 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
330 #ifdef NEED_DL_SYSINFO
331 /* Copy the sysinfo value from the parent. */
332 pd->header.sysinfo = THREAD_GETMEM (THREAD_SELF, header.sysinfo);
335 /* The process ID is also the same as that of the caller. */
336 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
338 /* Allocate the DTV for this thread. */
339 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
340 /* Something went wrong. */
344 /* Prepare to modify global data. */
345 lll_lock (stack_cache_lock);
347 /* And add to the list of stacks in use. */
348 list_add (&pd->list, &__stack_user);
350 lll_unlock (stack_cache_lock);
354 /* Allocate some anonymous memory. If possible use the cache. */
358 const int prot = (PROT_READ | PROT_WRITE
359 | ((GL(dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
361 #if COLORING_INCREMENT != 0
362 /* Add one more page for stack coloring. Don't do it for stacks
363 with 16 times pagesize or larger. This might just cause
364 unnecessary misalignment. */
365 if (size <= 16 * pagesize_m1)
366 size += pagesize_m1 + 1;
369 /* Adjust the stack size for alignment. */
370 size &= ~__static_tls_align_m1;
373 /* Make sure the size of the stack is enough for the guard and
374 eventually the thread descriptor. */
375 guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
376 if (__builtin_expect (size < (guardsize + __static_tls_size
377 + MINIMAL_REST_STACK + pagesize_m1 + 1),
379 /* The stack is too small (or the guard too large). */
382 /* Try to get a stack from the cache. */
384 pd = get_cached_stack (&size, &mem);
387 /* To avoid aliasing effects on a larger scale then pages we
388 adjust the allocated stack size if necessary. This way
389 allocations directly following each other will not have
390 aliasing problems. */
391 #if MULTI_PAGE_ALIASING != 0
392 if ((size % MULTI_PAGE_ALIASING) == 0)
393 size += pagesize_m1 + 1;
396 mem = mmap (NULL, size, prot,
397 MAP_PRIVATE | MAP_ANONYMOUS | ARCH_MAP_FLAGS, -1, 0);
399 if (__builtin_expect (mem == MAP_FAILED, 0))
401 #ifdef ARCH_RETRY_MMAP
402 mem = ARCH_RETRY_MMAP (size);
403 if (__builtin_expect (mem == MAP_FAILED, 0))
408 /* SIZE is guaranteed to be greater than zero.
409 So we can never get a null pointer back from mmap. */
410 assert (mem != NULL);
412 #if COLORING_INCREMENT != 0
413 /* Atomically increment NCREATED. */
414 unsigned int ncreated = (atomic_exchange_and_add (&nptl_ncreated, 1)
417 /* We chose the offset for coloring by incrementing it for
418 every new thread by a fixed amount. The offset used
419 module the page size. Even if coloring would be better
420 relative to higher alignment values it makes no sense to
421 do it since the mmap() interface does not allow us to
422 specify any alignment for the returned memory block. */
423 size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
425 /* Make sure the coloring offsets does not disturb the alignment
426 of the TCB and static TLS block. */
427 if (__builtin_expect ((coloring & __static_tls_align_m1) != 0, 0))
428 coloring = (((coloring + __static_tls_align_m1)
429 & ~(__static_tls_align_m1))
432 /* Unless specified we do not make any adjustments. */
436 /* Place the thread descriptor at the end of the stack. */
438 pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
440 pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
442 & ~__static_tls_align_m1)
446 /* Remember the stack-related values. */
447 pd->stackblock = mem;
448 pd->stackblock_size = size;
450 /* We allocated the first block thread-specific data array.
451 This address will not change for the lifetime of this
453 pd->specific[0] = pd->specific_1stblock;
455 #if defined __ASSUME_CLONE_STOPPED && LLL_LOCK_INITIALIZER != 0
456 /* Initialize the lock. */
457 pd->lock = LLL_LOCK_INITIALIZER;
460 /* This is at least the second thread. */
461 pd->header.multiple_threads = 1;
462 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
463 __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
466 #ifdef NEED_DL_SYSINFO
467 /* Copy the sysinfo value from the parent. */
468 pd->header.sysinfo = THREAD_GETMEM (THREAD_SELF, header.sysinfo);
471 /* The process ID is also the same as that of the caller. */
472 pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
474 /* Allocate the DTV for this thread. */
475 if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
477 /* Something went wrong. */
480 /* Free the stack memory we just allocated. */
481 (void) munmap (mem, size);
487 /* Prepare to modify global data. */
488 lll_lock (stack_cache_lock);
490 /* And add to the list of stacks in use. */
491 list_add (&pd->list, &stack_used);
493 lll_unlock (stack_cache_lock);
496 /* Note that all of the stack and the thread descriptor is
497 zeroed. This means we do not have to initialize fields
498 with initial value zero. This is specifically true for
499 the 'tid' field which is always set back to zero once the
500 stack is not used anymore and for the 'guardsize' field
501 which will be read next. */
504 /* Create or resize the guard area if necessary. */
505 if (__builtin_expect (guardsize > pd->guardsize, 0))
507 #ifdef NEED_SEPARATE_REGISTER_STACK
508 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
512 if (mprotect (guard, guardsize, PROT_NONE) != 0)
518 lll_lock (stack_cache_lock);
520 /* Remove the thread from the list. */
521 list_del (&pd->list);
523 lll_unlock (stack_cache_lock);
525 /* Get rid of the TLS block we allocated. */
526 _dl_deallocate_tls (TLS_TPADJ (pd), false);
528 /* Free the stack memory regardless of whether the size
529 of the cache is over the limit or not. If this piece
530 of memory caused problems we better do not use it
531 anymore. Uh, and we ignore possible errors. There
532 is nothing we could do. */
533 (void) munmap (mem, size);
538 pd->guardsize = guardsize;
540 else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
543 /* The old guard area is too large. */
545 #ifdef NEED_SEPARATE_REGISTER_STACK
546 char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
547 char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
550 && mprotect (oldguard, guard - oldguard, prot) != 0)
553 if (mprotect (guard + guardsize,
554 oldguard + pd->guardsize - guard - guardsize,
558 if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
563 pd->guardsize = guardsize;
567 #ifndef __ASSUME_CLONE_STOPPED
568 /* Initialize the lock. We have to do this unconditionally if the
569 CLONE_STOPPED flag is not available since then the stillborn
570 thread could be canceled while the lock is taken. */
571 pd->lock = LLL_LOCK_INITIALIZER;
574 /* We place the thread descriptor at the end of the stack. */
578 /* The stack begins before the TCB and the static TLS block. */
579 stacktop = ((char *) (pd + 1) - __static_tls_size);
581 stacktop = (char *) (pd - 1);
584 #ifdef NEED_SEPARATE_REGISTER_STACK
585 *stack = pd->stackblock;
586 *stacksize = stacktop - *stack;
597 __deallocate_stack (struct pthread *pd)
599 lll_lock (stack_cache_lock);
601 /* Remove the thread from the list of threads with user defined
603 list_del (&pd->list);
605 /* Not much to do. Just free the mmap()ed memory. Note that we do
606 not reset the 'used' flag in the 'tid' field. This is done by
607 the kernel. If no thread has been created yet this field is
609 if (__builtin_expect (! pd->user_stack, 1))
610 (void) queue_stack (pd);
612 /* Free the memory associated with the ELF TLS. */
613 _dl_deallocate_tls (TLS_TPADJ (pd), false);
615 lll_unlock (stack_cache_lock);
621 __make_stacks_executable (void)
623 #ifdef NEED_SEPARATE_REGISTER_STACK
624 const size_t pagemask = ~(__getpagesize () - 1);
627 lll_lock (stack_cache_lock);
631 list_for_each (runp, &stack_used)
633 struct pthread *const pd = list_entry (runp, struct pthread, list);
634 #ifdef NEED_SEPARATE_REGISTER_STACK
635 void *stack = (pd->stackblock
636 + (((((pd->stackblock_size - pd->guardsize) / 2)
637 & pagemask) + pd->guardsize) & pagemask));
638 size_t len = pd->stackblock + pd->stackblock_size - stack;
640 void *stack = pd->stackblock + pd->guardsize;
641 size_t len = pd->stackblock_size - pd->guardsize;
643 if (mprotect (stack, len, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
650 lll_unlock (stack_cache_lock);
652 _dl_make_stack_executable ();
658 /* In case of a fork() call the memory allocation in the child will be
659 the same but only one thread is running. All stacks except that of
660 the one running thread are not used anymore. We have to recycle
663 __reclaim_stacks (void)
665 struct pthread *self = (struct pthread *) THREAD_SELF;
667 /* No locking necessary. The caller is the only stack in use. */
669 /* Mark all stacks except the still running one as free. */
671 list_for_each (runp, &stack_used)
673 struct pthread *curp;
675 curp = list_entry (runp, struct pthread, list);
678 /* This marks the stack as free. */
681 /* The PID field must be initialized for the new process. */
682 curp->pid = self->pid;
684 /* Account for the size of the stack. */
685 stack_cache_actsize += curp->stackblock_size;
689 /* Add the stack of all running threads to the cache. */
690 list_splice (&stack_used, &stack_cache);
692 /* Remove the entry for the current thread to from the cache list
693 and add it to the list of running threads. Which of the two
694 lists is decided by the user_stack flag. */
695 list_del (&self->list);
697 /* Re-initialize the lists for all the threads. */
698 INIT_LIST_HEAD (&stack_used);
699 INIT_LIST_HEAD (&__stack_user);
701 if (__builtin_expect (THREAD_GETMEM (self, user_stack), 0))
702 list_add (&self->list, &__stack_user);
704 list_add (&self->list, &stack_used);
706 /* There is one thread running. */
709 /* Initialize the lock. */
710 stack_cache_lock = LLL_LOCK_INITIALIZER;
715 /* Find a thread given the thread ID. */
718 __find_thread_by_id (pid_t tid)
720 struct pthread *result = NULL;
722 lll_lock (stack_cache_lock);
724 /* Iterate over the list with system-allocated threads first. */
726 list_for_each (runp, &stack_used)
728 struct pthread *curp;
730 curp = list_entry (runp, struct pthread, list);
732 if (curp->tid == tid)
739 /* Now the list with threads using user-allocated stacks. */
740 list_for_each (runp, &__stack_user)
742 struct pthread *curp;
744 curp = list_entry (runp, struct pthread, list);
746 if (curp->tid == tid)
754 lll_unlock (stack_cache_lock);
760 static inline void __attribute__((always_inline))
761 init_one_static_tls (struct pthread *curp, struct link_map *map)
763 dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
765 void *dest = (char *) curp - map->l_tls_offset;
767 void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
769 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
772 /* Fill in the DTV slot so that a later LD/GD access will find it. */
773 dtv[map->l_tls_modid].pointer = dest;
775 /* Initialize the memory. */
776 memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
777 '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
782 __pthread_init_static_tls (struct link_map *map)
784 lll_lock (stack_cache_lock);
786 /* Iterate over the list with system-allocated threads first. */
788 list_for_each (runp, &stack_used)
789 init_one_static_tls (list_entry (runp, struct pthread, list), map);
791 /* Now the list with threads using user-allocated stacks. */
792 list_for_each (runp, &__stack_user)
793 init_one_static_tls (list_entry (runp, struct pthread, list), map);
795 lll_unlock (stack_cache_lock);