1 /* Copyright (C) 2002-2007, 2009, 2010 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
27 #include <sys/param.h>
28 #include <dl-sysdep.h>
30 #include <lowlevellock.h>
31 #include <kernel-features.h>
34 #ifndef NEED_SEPARATE_REGISTER_STACK
36 /* Most architectures have exactly one stack pointer. Some have more. */
37 # define STACK_VARIABLES void *stackaddr = NULL
39 /* How to pass the values to the 'create_thread' function. */
40 # define STACK_VARIABLES_ARGS stackaddr
42 /* How to declare function which gets there parameters. */
43 # define STACK_VARIABLES_PARMS void *stackaddr
45 /* How to declare allocate_stack. */
46 # define ALLOCATE_STACK_PARMS void **stack
48 /* This is how the function is called. We do it this way to allow
49 other variants of the function to have more parameters. */
50 # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)
54 /* We need two stacks. The kernel will place them but we have to tell
55 the kernel about the size of the reserved address space. */
56 # define STACK_VARIABLES void *stackaddr = NULL; size_t stacksize = 0
58 /* How to pass the values to the 'create_thread' function. */
59 # define STACK_VARIABLES_ARGS stackaddr, stacksize
61 /* How to declare function which gets there parameters. */
62 # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
64 /* How to declare allocate_stack. */
65 # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
67 /* This is how the function is called. We do it this way to allow
68 other variants of the function to have more parameters. */
69 # define ALLOCATE_STACK(attr, pd) \
70 allocate_stack (attr, pd, &stackaddr, &stacksize)
75 /* Default alignment of stack. */
77 # define STACK_ALIGN __alignof__ (long double)
80 /* Default value for minimal stack size after allocating thread
81 descriptor and guard. */
82 #ifndef MINIMAL_REST_STACK
83 # define MINIMAL_REST_STACK 4096
87 /* Newer kernels have the MAP_STACK flag to indicate a mapping is used for
88 a stack. Use it when possible. */
93 /* This yields the pointer that TLS support code calls the thread pointer. */
95 # define TLS_TPADJ(pd) (pd)
97 # define TLS_TPADJ(pd) ((struct pthread *)((char *) (pd) + TLS_PRE_TCB_SIZE))
100 /* Cache handling for not-yet free stacks. */
102 /* Maximum size in kB of cache. */
103 static size_t stack_cache_maxsize
= 40 * 1024 * 1024; /* 40MiBi by default. */
104 static size_t stack_cache_actsize
;
106 /* Mutex protecting this variable. */
107 static int stack_cache_lock
= LLL_LOCK_INITIALIZER
;
109 /* List of queued stack frames. */
110 static LIST_HEAD (stack_cache
);
112 /* List of the stacks in use. */
113 static LIST_HEAD (stack_used
);
115 /* We need to record what list operations we are going to do so that,
116 in case of an asynchronous interruption due to a fork() call, we
117 can correct for the work. */
118 static uintptr_t in_flight_stack
;
120 /* List of the threads with user provided stacks in use. No need to
121 initialize this, since it's done in __pthread_initialize_minimal. */
122 list_t __stack_user
__attribute__ ((nocommon
));
123 hidden_data_def (__stack_user
)
125 #if COLORING_INCREMENT != 0
126 /* Number of threads created. */
127 static unsigned int nptl_ncreated
;
131 /* Check whether the stack is still used or not. */
132 #define FREE_P(descr) ((descr)->tid <= 0)
136 stack_list_del (list_t
*elem
)
138 in_flight_stack
= (uintptr_t) elem
;
140 atomic_write_barrier ();
144 atomic_write_barrier ();
151 stack_list_add (list_t
*elem
, list_t
*list
)
153 in_flight_stack
= (uintptr_t) elem
| 1;
155 atomic_write_barrier ();
157 list_add (elem
, list
);
159 atomic_write_barrier ();
165 /* We create a double linked list of all cache entries. Double linked
166 because this allows removing entries from the end. */
169 /* Get a stack frame from the cache. We have to match by size since
170 some blocks might be too small or far too large. */
171 static struct pthread
*
172 get_cached_stack (size_t *sizep
, void **memp
)
174 size_t size
= *sizep
;
175 struct pthread
*result
= NULL
;
178 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
180 /* Search the cache for a matching entry. We search for the
181 smallest stack which has at least the required size. Note that
182 in normal situations the size of all allocated stacks is the
183 same. As the very least there are only a few different sizes.
184 Therefore this loop will exit early most of the time with an
186 list_for_each (entry
, &stack_cache
)
188 struct pthread
*curr
;
190 curr
= list_entry (entry
, struct pthread
, list
);
191 if (FREE_P (curr
) && curr
->stackblock_size
>= size
)
193 if (curr
->stackblock_size
== size
)
200 || result
->stackblock_size
> curr
->stackblock_size
)
205 if (__builtin_expect (result
== NULL
, 0)
206 /* Make sure the size difference is not too excessive. In that
207 case we do not use the block. */
208 || __builtin_expect (result
->stackblock_size
> 4 * size
, 0))
210 /* Release the lock. */
211 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
216 /* Don't allow setxid until cloned. */
217 result
->setxid_futex
= -1;
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
;
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
));
253 /* Free stacks until cache size is lower than LIMIT. */
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. */
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
);
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)
284 /* Maybe we have freed enough. */
285 if (stack_cache_actsize
<= limit
)
292 /* Add a stack frame which is not used anymore to the stack. Must be
293 called with the cache lock held. */
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
);
311 change_stack_perm (struct pthread
*pd
312 #ifdef NEED_SEPARATE_REGISTER_STACK
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 _STACK_GROWS_DOWN
323 void *stack
= pd
->stackblock
+ pd
->guardsize
;
324 size_t len
= pd
->stackblock_size
- pd
->guardsize
;
325 #elif _STACK_GROWS_UP
326 void *stack
= pd
->stackblock
;
327 size_t len
= (uintptr_t) pd
- pd
->guardsize
- (uintptr_t) pd
->stackblock
;
329 # error "Define either _STACK_GROWS_DOWN or _STACK_GROWS_UP"
331 if (mprotect (stack
, len
, PROT_READ
| PROT_WRITE
| PROT_EXEC
) != 0)
339 allocate_stack (const struct pthread_attr
*attr
, struct pthread
**pdp
,
340 ALLOCATE_STACK_PARMS
)
344 size_t pagesize_m1
= __getpagesize () - 1;
347 assert (attr
!= NULL
);
348 assert (powerof2 (pagesize_m1
+ 1));
349 assert (TCB_ALIGNMENT
>= STACK_ALIGN
);
351 /* Get the stack size from the attribute if it is set. Otherwise we
352 use the default we determined at start time. */
353 size
= attr
->stacksize
?: __default_stacksize
;
355 /* Get memory for the stack. */
356 if (__builtin_expect (attr
->flags
& ATTR_FLAG_STACKADDR
, 0))
360 /* If the user also specified the size of the stack make sure it
362 if (attr
->stacksize
!= 0
363 && attr
->stacksize
< (__static_tls_size
+ MINIMAL_REST_STACK
))
366 /* Adjust stack size for alignment of the TLS block. */
368 adj
= ((uintptr_t) attr
->stackaddr
- TLS_TCB_SIZE
)
369 & __static_tls_align_m1
;
370 assert (size
> adj
+ TLS_TCB_SIZE
);
372 adj
= ((uintptr_t) attr
->stackaddr
- __static_tls_size
)
373 & __static_tls_align_m1
;
377 /* The user provided some memory. Let's hope it matches the
378 size... We do not allocate guard pages if the user provided
379 the stack. It is the user's responsibility to do this if it
382 pd
= (struct pthread
*) ((uintptr_t) attr
->stackaddr
383 - TLS_TCB_SIZE
- adj
);
385 pd
= (struct pthread
*) (((uintptr_t) attr
->stackaddr
386 - __static_tls_size
- adj
)
390 /* The user provided stack memory needs to be cleared. */
391 memset (pd
, '\0', sizeof (struct pthread
));
393 /* The first TSD block is included in the TCB. */
394 pd
->specific
[0] = pd
->specific_1stblock
;
396 /* Remember the stack-related values. */
397 pd
->stackblock
= (char *) attr
->stackaddr
- size
;
398 pd
->stackblock_size
= size
;
400 /* This is a user-provided stack. It will not be queued in the
401 stack cache nor will the memory (except the TLS memory) be freed. */
402 pd
->user_stack
= true;
404 /* This is at least the second thread. */
405 pd
->header
.multiple_threads
= 1;
406 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
407 __pthread_multiple_threads
= *__libc_multiple_threads_ptr
= 1;
410 #ifndef __ASSUME_PRIVATE_FUTEX
411 /* The thread must know when private futexes are supported. */
412 pd
->header
.private_futex
= THREAD_GETMEM (THREAD_SELF
,
413 header
.private_futex
);
416 #ifdef NEED_DL_SYSINFO
417 /* Copy the sysinfo value from the parent. */
418 THREAD_SYSINFO(pd
) = THREAD_SELF_SYSINFO
;
421 /* The process ID is also the same as that of the caller. */
422 pd
->pid
= THREAD_GETMEM (THREAD_SELF
, pid
);
424 /* Don't allow setxid until cloned. */
425 pd
->setxid_futex
= -1;
427 /* Allocate the DTV for this thread. */
428 if (_dl_allocate_tls (TLS_TPADJ (pd
)) == NULL
)
430 /* Something went wrong. */
431 assert (errno
== ENOMEM
);
436 /* Prepare to modify global data. */
437 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
439 /* And add to the list of stacks in use. */
440 list_add (&pd
->list
, &__stack_user
);
442 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
446 /* Allocate some anonymous memory. If possible use the cache. */
450 const int prot
= (PROT_READ
| PROT_WRITE
451 | ((GL(dl_stack_flags
) & PF_X
) ? PROT_EXEC
: 0));
453 #if COLORING_INCREMENT != 0
454 /* Add one more page for stack coloring. Don't do it for stacks
455 with 16 times pagesize or larger. This might just cause
456 unnecessary misalignment. */
457 if (size
<= 16 * pagesize_m1
)
458 size
+= pagesize_m1
+ 1;
461 /* Adjust the stack size for alignment. */
462 size
&= ~__static_tls_align_m1
;
465 /* Make sure the size of the stack is enough for the guard and
466 eventually the thread descriptor. */
467 guardsize
= (attr
->guardsize
+ pagesize_m1
) & ~pagesize_m1
;
468 if (__builtin_expect (size
< ((guardsize
+ __static_tls_size
469 + MINIMAL_REST_STACK
+ pagesize_m1
)
472 /* The stack is too small (or the guard too large). */
475 /* Try to get a stack from the cache. */
477 pd
= get_cached_stack (&size
, &mem
);
480 /* To avoid aliasing effects on a larger scale than pages we
481 adjust the allocated stack size if necessary. This way
482 allocations directly following each other will not have
483 aliasing problems. */
484 #if MULTI_PAGE_ALIASING != 0
485 if ((size
% MULTI_PAGE_ALIASING
) == 0)
486 size
+= pagesize_m1
+ 1;
489 mem
= mmap (NULL
, size
, prot
,
490 MAP_PRIVATE
| MAP_ANONYMOUS
| MAP_STACK
, -1, 0);
492 if (__builtin_expect (mem
== MAP_FAILED
, 0))
495 __set_errno (EAGAIN
);
500 /* SIZE is guaranteed to be greater than zero.
501 So we can never get a null pointer back from mmap. */
502 assert (mem
!= NULL
);
504 #if COLORING_INCREMENT != 0
505 /* Atomically increment NCREATED. */
506 unsigned int ncreated
= atomic_increment_val (&nptl_ncreated
);
508 /* We chose the offset for coloring by incrementing it for
509 every new thread by a fixed amount. The offset used
510 module the page size. Even if coloring would be better
511 relative to higher alignment values it makes no sense to
512 do it since the mmap() interface does not allow us to
513 specify any alignment for the returned memory block. */
514 size_t coloring
= (ncreated
* COLORING_INCREMENT
) & pagesize_m1
;
516 /* Make sure the coloring offsets does not disturb the alignment
517 of the TCB and static TLS block. */
518 if (__builtin_expect ((coloring
& __static_tls_align_m1
) != 0, 0))
519 coloring
= (((coloring
+ __static_tls_align_m1
)
520 & ~(__static_tls_align_m1
))
523 /* Unless specified we do not make any adjustments. */
527 /* Place the thread descriptor at the end of the stack. */
529 pd
= (struct pthread
*) ((char *) mem
+ size
- coloring
) - 1;
531 pd
= (struct pthread
*) ((((uintptr_t) mem
+ size
- coloring
533 & ~__static_tls_align_m1
)
537 /* Remember the stack-related values. */
538 pd
->stackblock
= mem
;
539 pd
->stackblock_size
= size
;
541 /* We allocated the first block thread-specific data array.
542 This address will not change for the lifetime of this
544 pd
->specific
[0] = pd
->specific_1stblock
;
546 /* This is at least the second thread. */
547 pd
->header
.multiple_threads
= 1;
548 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
549 __pthread_multiple_threads
= *__libc_multiple_threads_ptr
= 1;
552 #ifndef __ASSUME_PRIVATE_FUTEX
553 /* The thread must know when private futexes are supported. */
554 pd
->header
.private_futex
= THREAD_GETMEM (THREAD_SELF
,
555 header
.private_futex
);
558 #ifdef NEED_DL_SYSINFO
559 /* Copy the sysinfo value from the parent. */
560 THREAD_SYSINFO(pd
) = THREAD_SELF_SYSINFO
;
563 /* Don't allow setxid until cloned. */
564 pd
->setxid_futex
= -1;
566 /* The process ID is also the same as that of the caller. */
567 pd
->pid
= THREAD_GETMEM (THREAD_SELF
, pid
);
569 /* Allocate the DTV for this thread. */
570 if (_dl_allocate_tls (TLS_TPADJ (pd
)) == NULL
)
572 /* Something went wrong. */
573 assert (errno
== ENOMEM
);
575 /* Free the stack memory we just allocated. */
576 (void) munmap (mem
, size
);
582 /* Prepare to modify global data. */
583 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
585 /* And add to the list of stacks in use. */
586 stack_list_add (&pd
->list
, &stack_used
);
588 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
591 /* There might have been a race. Another thread might have
592 caused the stacks to get exec permission while this new
593 stack was prepared. Detect if this was possible and
594 change the permission if necessary. */
595 if (__builtin_expect ((GL(dl_stack_flags
) & PF_X
) != 0
596 && (prot
& PROT_EXEC
) == 0, 0))
598 int err
= change_stack_perm (pd
599 #ifdef NEED_SEPARATE_REGISTER_STACK
605 /* Free the stack memory we just allocated. */
606 (void) munmap (mem
, size
);
613 /* Note that all of the stack and the thread descriptor is
614 zeroed. This means we do not have to initialize fields
615 with initial value zero. This is specifically true for
616 the 'tid' field which is always set back to zero once the
617 stack is not used anymore and for the 'guardsize' field
618 which will be read next. */
621 /* Create or resize the guard area if necessary. */
622 if (__builtin_expect (guardsize
> pd
->guardsize
, 0))
624 #ifdef NEED_SEPARATE_REGISTER_STACK
625 char *guard
= mem
+ (((size
- guardsize
) / 2) & ~pagesize_m1
);
626 #elif _STACK_GROWS_DOWN
628 # elif _STACK_GROWS_UP
629 char *guard
= (char *) (((uintptr_t) pd
- guardsize
) & ~pagesize_m1
);
631 if (mprotect (guard
, guardsize
, PROT_NONE
) != 0)
637 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
639 /* Remove the thread from the list. */
640 stack_list_del (&pd
->list
);
642 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
644 /* Get rid of the TLS block we allocated. */
645 _dl_deallocate_tls (TLS_TPADJ (pd
), false);
647 /* Free the stack memory regardless of whether the size
648 of the cache is over the limit or not. If this piece
649 of memory caused problems we better do not use it
650 anymore. Uh, and we ignore possible errors. There
651 is nothing we could do. */
652 (void) munmap (mem
, size
);
657 pd
->guardsize
= guardsize
;
659 else if (__builtin_expect (pd
->guardsize
- guardsize
> size
- reqsize
,
662 /* The old guard area is too large. */
664 #ifdef NEED_SEPARATE_REGISTER_STACK
665 char *guard
= mem
+ (((size
- guardsize
) / 2) & ~pagesize_m1
);
666 char *oldguard
= mem
+ (((size
- pd
->guardsize
) / 2) & ~pagesize_m1
);
669 && mprotect (oldguard
, guard
- oldguard
, prot
) != 0)
672 if (mprotect (guard
+ guardsize
,
673 oldguard
+ pd
->guardsize
- guard
- guardsize
,
676 #elif _STACK_GROWS_DOWN
677 if (mprotect ((char *) mem
+ guardsize
, pd
->guardsize
- guardsize
,
680 #elif _STACK_GROWS_UP
681 if (mprotect ((char *) pd
- pd
->guardsize
,
682 pd
->guardsize
- guardsize
, prot
) != 0)
686 pd
->guardsize
= guardsize
;
688 /* The pthread_getattr_np() calls need to get passed the size
689 requested in the attribute, regardless of how large the
690 actually used guardsize is. */
691 pd
->reported_guardsize
= guardsize
;
694 /* Initialize the lock. We have to do this unconditionally since the
695 stillborn thread could be canceled while the lock is taken. */
696 pd
->lock
= LLL_LOCK_INITIALIZER
;
698 /* The robust mutex lists also need to be initialized
699 unconditionally because the cleanup for the previous stack owner
700 might have happened in the kernel. */
701 pd
->robust_head
.futex_offset
= (offsetof (pthread_mutex_t
, __data
.__lock
)
702 - offsetof (pthread_mutex_t
,
703 __data
.__list
.__next
));
704 pd
->robust_head
.list_op_pending
= NULL
;
705 #ifdef __PTHREAD_MUTEX_HAVE_PREV
706 pd
->robust_prev
= &pd
->robust_head
;
708 pd
->robust_head
.list
= &pd
->robust_head
;
710 /* We place the thread descriptor at the end of the stack. */
714 /* The stack begins before the TCB and the static TLS block. */
715 stacktop
= ((char *) (pd
+ 1) - __static_tls_size
);
717 stacktop
= (char *) (pd
- 1);
720 #ifdef NEED_SEPARATE_REGISTER_STACK
721 *stack
= pd
->stackblock
;
722 *stacksize
= stacktop
- *stack
;
723 #elif _STACK_GROWS_DOWN
725 #elif _STACK_GROWS_UP
726 *stack
= pd
->stackblock
;
736 __deallocate_stack (struct pthread
*pd
)
738 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
740 /* Remove the thread from the list of threads with user defined
742 stack_list_del (&pd
->list
);
744 /* Not much to do. Just free the mmap()ed memory. Note that we do
745 not reset the 'used' flag in the 'tid' field. This is done by
746 the kernel. If no thread has been created yet this field is
748 if (__builtin_expect (! pd
->user_stack
, 1))
749 (void) queue_stack (pd
);
751 /* Free the memory associated with the ELF TLS. */
752 _dl_deallocate_tls (TLS_TPADJ (pd
), false);
754 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
760 __make_stacks_executable (void **stack_endp
)
762 /* First the main thread's stack. */
763 int err
= _dl_make_stack_executable (stack_endp
);
767 #ifdef NEED_SEPARATE_REGISTER_STACK
768 const size_t pagemask
= ~(__getpagesize () - 1);
771 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
774 list_for_each (runp
, &stack_used
)
776 err
= change_stack_perm (list_entry (runp
, struct pthread
, list
)
777 #ifdef NEED_SEPARATE_REGISTER_STACK
785 /* Also change the permission for the currently unused stacks. This
786 might be wasted time but better spend it here than adding a check
789 list_for_each (runp
, &stack_cache
)
791 err
= change_stack_perm (list_entry (runp
, struct pthread
, list
)
792 #ifdef NEED_SEPARATE_REGISTER_STACK
800 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
806 /* In case of a fork() call the memory allocation in the child will be
807 the same but only one thread is running. All stacks except that of
808 the one running thread are not used anymore. We have to recycle
811 __reclaim_stacks (void)
813 struct pthread
*self
= (struct pthread
*) THREAD_SELF
;
815 /* No locking necessary. The caller is the only stack in use. But
816 we have to be aware that we might have interrupted a list
819 if (in_flight_stack
!= 0)
821 bool add_p
= in_flight_stack
& 1;
822 list_t
*elem
= (list_t
*) (in_flight_stack
& ~UINTMAX_C (1));
826 /* We always add at the beginning of the list. So in this
827 case we only need to check the beginning of these lists. */
828 int check_list (list_t
*l
)
830 if (l
->next
->prev
!= l
)
832 assert (l
->next
->prev
== elem
);
834 elem
->next
= l
->next
;
844 if (check_list (&stack_used
) == 0)
845 (void) check_list (&stack_cache
);
849 /* We can simply always replay the delete operation. */
850 elem
->next
->prev
= elem
->prev
;
851 elem
->prev
->next
= elem
->next
;
855 /* Mark all stacks except the still running one as free. */
857 list_for_each (runp
, &stack_used
)
859 struct pthread
*curp
= list_entry (runp
, struct pthread
, list
);
862 /* This marks the stack as free. */
865 /* The PID field must be initialized for the new process. */
866 curp
->pid
= self
->pid
;
868 /* Account for the size of the stack. */
869 stack_cache_actsize
+= curp
->stackblock_size
;
871 if (curp
->specific_used
)
873 /* Clear the thread-specific data. */
874 memset (curp
->specific_1stblock
, '\0',
875 sizeof (curp
->specific_1stblock
));
877 curp
->specific_used
= false;
879 for (size_t cnt
= 1; cnt
< PTHREAD_KEY_1STLEVEL_SIZE
; ++cnt
)
880 if (curp
->specific
[cnt
] != NULL
)
882 memset (curp
->specific
[cnt
], '\0',
883 sizeof (curp
->specific_1stblock
));
885 /* We have allocated the block which we do not
886 free here so re-set the bit. */
887 curp
->specific_used
= true;
893 /* Reset the PIDs in any cached stacks. */
894 list_for_each (runp
, &stack_cache
)
896 struct pthread
*curp
= list_entry (runp
, struct pthread
, list
);
897 curp
->pid
= self
->pid
;
900 /* Add the stack of all running threads to the cache. */
901 list_splice (&stack_used
, &stack_cache
);
903 /* Remove the entry for the current thread to from the cache list
904 and add it to the list of running threads. Which of the two
905 lists is decided by the user_stack flag. */
906 stack_list_del (&self
->list
);
908 /* Re-initialize the lists for all the threads. */
909 INIT_LIST_HEAD (&stack_used
);
910 INIT_LIST_HEAD (&__stack_user
);
912 if (__builtin_expect (THREAD_GETMEM (self
, user_stack
), 0))
913 list_add (&self
->list
, &__stack_user
);
915 list_add (&self
->list
, &stack_used
);
917 /* There is one thread running. */
922 /* Initialize the lock. */
923 stack_cache_lock
= LLL_LOCK_INITIALIZER
;
928 # undef __find_thread_by_id
929 /* Find a thread given the thread ID. */
932 __find_thread_by_id (pid_t tid
)
934 struct pthread
*result
= NULL
;
936 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
938 /* Iterate over the list with system-allocated threads first. */
940 list_for_each (runp
, &stack_used
)
942 struct pthread
*curp
;
944 curp
= list_entry (runp
, struct pthread
, list
);
946 if (curp
->tid
== tid
)
953 /* Now the list with threads using user-allocated stacks. */
954 list_for_each (runp
, &__stack_user
)
956 struct pthread
*curp
;
958 curp
= list_entry (runp
, struct pthread
, list
);
960 if (curp
->tid
== tid
)
968 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
977 setxid_mark_thread (struct xid_command
*cmdp
, struct pthread
*t
)
981 /* Wait until this thread is cloned. */
982 if (t
->setxid_futex
== -1
983 && ! atomic_compare_and_exchange_bool_acq (&t
->setxid_futex
, -2, -1))
985 lll_futex_wait (&t
->setxid_futex
, -2, LLL_PRIVATE
);
986 while (t
->setxid_futex
== -2);
988 /* Don't let the thread exit before the setxid handler runs. */
993 ch
= t
->cancelhandling
;
995 /* If the thread is exiting right now, ignore it. */
996 if ((ch
& EXITING_BITMASK
) != 0)
999 while (atomic_compare_and_exchange_bool_acq (&t
->cancelhandling
,
1000 ch
| SETXID_BITMASK
, ch
));
1006 setxid_unmark_thread (struct xid_command
*cmdp
, struct pthread
*t
)
1012 ch
= t
->cancelhandling
;
1013 if ((ch
& SETXID_BITMASK
) == 0)
1016 while (atomic_compare_and_exchange_bool_acq (&t
->cancelhandling
,
1017 ch
& ~SETXID_BITMASK
, ch
));
1019 /* Release the futex just in case. */
1020 t
->setxid_futex
= 1;
1021 lll_futex_wake (&t
->setxid_futex
, 1, LLL_PRIVATE
);
1027 setxid_signal_thread (struct xid_command
*cmdp
, struct pthread
*t
)
1029 if ((t
->cancelhandling
& SETXID_BITMASK
) == 0)
1033 INTERNAL_SYSCALL_DECL (err
);
1035 val
= INTERNAL_SYSCALL (tgkill
, err
, 3, THREAD_GETMEM (THREAD_SELF
, pid
),
1039 val
= INTERNAL_SYSCALL (tgkill
, err
, 3, THREAD_GETMEM (THREAD_SELF
, pid
),
1041 if (INTERNAL_SYSCALL_ERROR_P (val
, err
)
1042 && INTERNAL_SYSCALL_ERRNO (val
, err
) == ENOSYS
)
1044 val
= INTERNAL_SYSCALL (tkill
, err
, 2, t
->tid
, SIGSETXID
);
1047 /* If this failed, it must have had not started yet or else exited. */
1048 if (!INTERNAL_SYSCALL_ERROR_P (val
, err
))
1050 atomic_increment (&cmdp
->cntr
);
1060 __nptl_setxid (struct xid_command
*cmdp
)
1064 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
1069 struct pthread
*self
= THREAD_SELF
;
1071 /* Iterate over the list with system-allocated threads first. */
1073 list_for_each (runp
, &stack_used
)
1075 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1079 setxid_mark_thread (cmdp
, t
);
1082 /* Now the list with threads using user-allocated stacks. */
1083 list_for_each (runp
, &__stack_user
)
1085 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1089 setxid_mark_thread (cmdp
, t
);
1092 /* Iterate until we don't succeed in signalling anyone. That means
1093 we have gotten all running threads, and their children will be
1094 automatically correct once started. */
1099 list_for_each (runp
, &stack_used
)
1101 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1105 signalled
+= setxid_signal_thread (cmdp
, t
);
1108 list_for_each (runp
, &__stack_user
)
1110 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1114 signalled
+= setxid_signal_thread (cmdp
, t
);
1117 int cur
= cmdp
->cntr
;
1120 lll_futex_wait (&cmdp
->cntr
, cur
, LLL_PRIVATE
);
1124 while (signalled
!= 0);
1126 /* Clean up flags, so that no thread blocks during exit waiting
1127 for a signal which will never come. */
1128 list_for_each (runp
, &stack_used
)
1130 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1134 setxid_unmark_thread (cmdp
, t
);
1137 list_for_each (runp
, &__stack_user
)
1139 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1143 setxid_unmark_thread (cmdp
, t
);
1146 /* This must be last, otherwise the current thread might not have
1147 permissions to send SIGSETXID syscall to the other threads. */
1148 INTERNAL_SYSCALL_DECL (err
);
1149 result
= INTERNAL_SYSCALL_NCS (cmdp
->syscall_no
, err
, 3,
1150 cmdp
->id
[0], cmdp
->id
[1], cmdp
->id
[2]);
1151 if (INTERNAL_SYSCALL_ERROR_P (result
, err
))
1153 __set_errno (INTERNAL_SYSCALL_ERRNO (result
, err
));
1157 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
1161 static inline void __attribute__((always_inline
))
1162 init_one_static_tls (struct pthread
*curp
, struct link_map
*map
)
1164 dtv_t
*dtv
= GET_DTV (TLS_TPADJ (curp
));
1166 void *dest
= (char *) curp
- map
->l_tls_offset
;
1167 # elif TLS_DTV_AT_TP
1168 void *dest
= (char *) curp
+ map
->l_tls_offset
+ TLS_PRE_TCB_SIZE
;
1170 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1173 /* Fill in the DTV slot so that a later LD/GD access will find it. */
1174 dtv
[map
->l_tls_modid
].pointer
.val
= dest
;
1175 dtv
[map
->l_tls_modid
].pointer
.is_static
= true;
1177 /* Initialize the memory. */
1178 memset (__mempcpy (dest
, map
->l_tls_initimage
, map
->l_tls_initimage_size
),
1179 '\0', map
->l_tls_blocksize
- map
->l_tls_initimage_size
);
1184 __pthread_init_static_tls (struct link_map
*map
)
1186 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
1188 /* Iterate over the list with system-allocated threads first. */
1190 list_for_each (runp
, &stack_used
)
1191 init_one_static_tls (list_entry (runp
, struct pthread
, list
), map
);
1193 /* Now the list with threads using user-allocated stacks. */
1194 list_for_each (runp
, &__stack_user
)
1195 init_one_static_tls (list_entry (runp
, struct pthread
, list
), map
);
1197 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
1203 __wait_lookup_done (void)
1205 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
1207 struct pthread
*self
= THREAD_SELF
;
1209 /* Iterate over the list with system-allocated threads first. */
1211 list_for_each (runp
, &stack_used
)
1213 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1214 if (t
== self
|| t
->header
.gscope_flag
== THREAD_GSCOPE_FLAG_UNUSED
)
1217 int *const gscope_flagp
= &t
->header
.gscope_flag
;
1219 /* We have to wait until this thread is done with the global
1220 scope. First tell the thread that we are waiting and
1221 possibly have to be woken. */
1222 if (atomic_compare_and_exchange_bool_acq (gscope_flagp
,
1223 THREAD_GSCOPE_FLAG_WAIT
,
1224 THREAD_GSCOPE_FLAG_USED
))
1228 lll_futex_wait (gscope_flagp
, THREAD_GSCOPE_FLAG_WAIT
, LLL_PRIVATE
);
1229 while (*gscope_flagp
== THREAD_GSCOPE_FLAG_WAIT
);
1232 /* Now the list with threads using user-allocated stacks. */
1233 list_for_each (runp
, &__stack_user
)
1235 struct pthread
*t
= list_entry (runp
, struct pthread
, list
);
1236 if (t
== self
|| t
->header
.gscope_flag
== THREAD_GSCOPE_FLAG_UNUSED
)
1239 int *const gscope_flagp
= &t
->header
.gscope_flag
;
1241 /* We have to wait until this thread is done with the global
1242 scope. First tell the thread that we are waiting and
1243 possibly have to be woken. */
1244 if (atomic_compare_and_exchange_bool_acq (gscope_flagp
,
1245 THREAD_GSCOPE_FLAG_WAIT
,
1246 THREAD_GSCOPE_FLAG_USED
))
1250 lll_futex_wait (gscope_flagp
, THREAD_GSCOPE_FLAG_WAIT
, LLL_PRIVATE
);
1251 while (*gscope_flagp
== THREAD_GSCOPE_FLAG_WAIT
);
1254 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);