Remove TLS configure tests.
[platform/upstream/linaro-glibc.git] / nptl / allocatestack.c
1 /* Copyright (C) 2002-2014 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
4
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.
9
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.
14
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/>.  */
18
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 <dl-sysdep.h>
28 #include <dl-tls.h>
29 #include <tls.h>
30 #include <list.h>
31 #include <lowlevellock.h>
32 #include <kernel-features.h>
33 #include <stack-aliasing.h>
34
35
36 #ifndef NEED_SEPARATE_REGISTER_STACK
37
38 /* Most architectures have exactly one stack pointer.  Some have more.  */
39 # define STACK_VARIABLES void *stackaddr = NULL
40
41 /* How to pass the values to the 'create_thread' function.  */
42 # define STACK_VARIABLES_ARGS stackaddr
43
44 /* How to declare function which gets there parameters.  */
45 # define STACK_VARIABLES_PARMS void *stackaddr
46
47 /* How to declare allocate_stack.  */
48 # define ALLOCATE_STACK_PARMS void **stack
49
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)
53
54 #else
55
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
59
60 /* How to pass the values to the 'create_thread' function.  */
61 # define STACK_VARIABLES_ARGS stackaddr, stacksize
62
63 /* How to declare function which gets there parameters.  */
64 # define STACK_VARIABLES_PARMS void *stackaddr, size_t stacksize
65
66 /* How to declare allocate_stack.  */
67 # define ALLOCATE_STACK_PARMS void **stack, size_t *stacksize
68
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)
73
74 #endif
75
76
77 /* Default alignment of stack.  */
78 #ifndef STACK_ALIGN
79 # define STACK_ALIGN __alignof__ (long double)
80 #endif
81
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
87
88
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
94
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
101
102 /* Cache handling for not-yet free stacks.  */
103
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;
107
108 /* Mutex protecting this variable.  */
109 static int stack_cache_lock = LLL_LOCK_INITIALIZER;
110
111 /* List of queued stack frames.  */
112 static LIST_HEAD (stack_cache);
113
114 /* List of the stacks in use.  */
115 static LIST_HEAD (stack_used);
116
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;
121
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)
126
127 #if COLORING_INCREMENT != 0
128 /* Number of threads created.  */
129 static unsigned int nptl_ncreated;
130 #endif
131
132
133 /* Check whether the stack is still used or not.  */
134 #define FREE_P(descr) ((descr)->tid <= 0)
135
136
137 static void
138 stack_list_del (list_t *elem)
139 {
140   in_flight_stack = (uintptr_t) elem;
141
142   atomic_write_barrier ();
143
144   list_del (elem);
145
146   atomic_write_barrier ();
147
148   in_flight_stack = 0;
149 }
150
151
152 static void
153 stack_list_add (list_t *elem, list_t *list)
154 {
155   in_flight_stack = (uintptr_t) elem | 1;
156
157   atomic_write_barrier ();
158
159   list_add (elem, list);
160
161   atomic_write_barrier ();
162
163   in_flight_stack = 0;
164 }
165
166
167 /* We create a double linked list of all cache entries.  Double linked
168    because this allows removing entries from the end.  */
169
170
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)
175 {
176   size_t size = *sizep;
177   struct pthread *result = NULL;
178   list_t *entry;
179
180   lll_lock (stack_cache_lock, LLL_PRIVATE);
181
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)
189     {
190       struct pthread *curr;
191
192       curr = list_entry (entry, struct pthread, list);
193       if (FREE_P (curr) && curr->stackblock_size >= size)
194         {
195           if (curr->stackblock_size == size)
196             {
197               result = curr;
198               break;
199             }
200
201           if (result == NULL
202               || result->stackblock_size > curr->stackblock_size)
203             result = curr;
204         }
205     }
206
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))
211     {
212       /* Release the lock.  */
213       lll_unlock (stack_cache_lock, LLL_PRIVATE);
214
215       return NULL;
216     }
217
218   /* Don't allow setxid until cloned.  */
219   result->setxid_futex = -1;
220
221   /* Dequeue the entry.  */
222   stack_list_del (&result->list);
223
224   /* And add to the list of stacks in use.  */
225   stack_list_add (&result->list, &stack_used);
226
227   /* And decrease the cache size.  */
228   stack_cache_actsize -= result->stackblock_size;
229
230   /* Release the lock early.  */
231   lll_unlock (stack_cache_lock, LLL_PRIVATE);
232
233   /* Report size and location of the stack to the caller.  */
234   *sizep = result->stackblock_size;
235   *memp = result->stackblock;
236
237   /* Cancellation handling is back to the default.  */
238   result->cancelhandling = 0;
239   result->cleanup = NULL;
240
241   /* No pending event.  */
242   result->nextevent = NULL;
243
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));
251
252   /* Re-initialize the TLS.  */
253   _dl_allocate_tls_init (TLS_TPADJ (result));
254
255   return result;
256 }
257
258
259 /* Free stacks until cache size is lower than LIMIT.  */
260 void
261 __free_stacks (size_t limit)
262 {
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;
267
268   /* Search from the end of the list.  */
269   list_for_each_prev_safe (entry, prev, &stack_cache)
270     {
271       struct pthread *curr;
272
273       curr = list_entry (entry, struct pthread, list);
274       if (FREE_P (curr))
275         {
276           /* Unlink the block.  */
277           stack_list_del (entry);
278
279           /* Account for the freed memory.  */
280           stack_cache_actsize -= curr->stackblock_size;
281
282           /* Free the memory associated with the ELF TLS.  */
283           _dl_deallocate_tls (TLS_TPADJ (curr), false);
284
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 ();
289
290           /* Maybe we have freed enough.  */
291           if (stack_cache_actsize <= limit)
292             break;
293         }
294     }
295 }
296
297
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)
303 {
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);
308
309   stack_cache_actsize += stack->stackblock_size;
310   if (__glibc_unlikely (stack_cache_actsize > stack_cache_maxsize))
311     __free_stacks (stack_cache_maxsize);
312 }
313
314
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
321                    )
322 {
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;
339
340   return 0;
341 }
342
343
344 /* Returns a usable stack for a new thread either by allocating a
345    new stack or reusing a cached stack of sufficient size.
346    ATTR must be non-NULL and point to a valid pthread_attr.
347    PDP must be non-NULL.  */
348 static int
349 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
350                 ALLOCATE_STACK_PARMS)
351 {
352   struct pthread *pd;
353   size_t size;
354   size_t pagesize_m1 = __getpagesize () - 1;
355   void *stacktop;
356
357   assert (powerof2 (pagesize_m1 + 1));
358   assert (TCB_ALIGNMENT >= STACK_ALIGN);
359
360   /* Get the stack size from the attribute if it is set.  Otherwise we
361      use the default we determined at start time.  */
362   if (attr->stacksize != 0)
363     size = attr->stacksize;
364   else
365     {
366       lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
367       size = __default_pthread_attr.stacksize;
368       lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
369     }
370
371   /* Get memory for the stack.  */
372   if (__glibc_unlikely (attr->flags & ATTR_FLAG_STACKADDR))
373     {
374       uintptr_t adj;
375
376       /* If the user also specified the size of the stack make sure it
377          is large enough.  */
378       if (attr->stacksize != 0
379           && attr->stacksize < (__static_tls_size + MINIMAL_REST_STACK))
380         return EINVAL;
381
382       /* Adjust stack size for alignment of the TLS block.  */
383 #if TLS_TCB_AT_TP
384       adj = ((uintptr_t) attr->stackaddr - TLS_TCB_SIZE)
385             & __static_tls_align_m1;
386       assert (size > adj + TLS_TCB_SIZE);
387 #elif TLS_DTV_AT_TP
388       adj = ((uintptr_t) attr->stackaddr - __static_tls_size)
389             & __static_tls_align_m1;
390       assert (size > adj);
391 #endif
392
393       /* The user provided some memory.  Let's hope it matches the
394          size...  We do not allocate guard pages if the user provided
395          the stack.  It is the user's responsibility to do this if it
396          is wanted.  */
397 #if TLS_TCB_AT_TP
398       pd = (struct pthread *) ((uintptr_t) attr->stackaddr
399                                - TLS_TCB_SIZE - adj);
400 #elif TLS_DTV_AT_TP
401       pd = (struct pthread *) (((uintptr_t) attr->stackaddr
402                                 - __static_tls_size - adj)
403                                - TLS_PRE_TCB_SIZE);
404 #endif
405
406       /* The user provided stack memory needs to be cleared.  */
407       memset (pd, '\0', sizeof (struct pthread));
408
409       /* The first TSD block is included in the TCB.  */
410       pd->specific[0] = pd->specific_1stblock;
411
412       /* Remember the stack-related values.  */
413       pd->stackblock = (char *) attr->stackaddr - size;
414       pd->stackblock_size = size;
415
416       /* This is a user-provided stack.  It will not be queued in the
417          stack cache nor will the memory (except the TLS memory) be freed.  */
418       pd->user_stack = true;
419
420       /* This is at least the second thread.  */
421       pd->header.multiple_threads = 1;
422 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
423       __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
424 #endif
425
426 #ifndef __ASSUME_PRIVATE_FUTEX
427       /* The thread must know when private futexes are supported.  */
428       pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
429                                                 header.private_futex);
430 #endif
431
432 #ifdef NEED_DL_SYSINFO
433       /* Copy the sysinfo value from the parent.  */
434       THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
435 #endif
436
437       /* The process ID is also the same as that of the caller.  */
438       pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
439
440       /* Don't allow setxid until cloned.  */
441       pd->setxid_futex = -1;
442
443       /* Allocate the DTV for this thread.  */
444       if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
445         {
446           /* Something went wrong.  */
447           assert (errno == ENOMEM);
448           return errno;
449         }
450
451
452       /* Prepare to modify global data.  */
453       lll_lock (stack_cache_lock, LLL_PRIVATE);
454
455       /* And add to the list of stacks in use.  */
456       list_add (&pd->list, &__stack_user);
457
458       lll_unlock (stack_cache_lock, LLL_PRIVATE);
459     }
460   else
461     {
462       /* Allocate some anonymous memory.  If possible use the cache.  */
463       size_t guardsize;
464       size_t reqsize;
465       void *mem;
466       const int prot = (PROT_READ | PROT_WRITE
467                         | ((GL(dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
468
469 #if COLORING_INCREMENT != 0
470       /* Add one more page for stack coloring.  Don't do it for stacks
471          with 16 times pagesize or larger.  This might just cause
472          unnecessary misalignment.  */
473       if (size <= 16 * pagesize_m1)
474         size += pagesize_m1 + 1;
475 #endif
476
477       /* Adjust the stack size for alignment.  */
478       size &= ~__static_tls_align_m1;
479       assert (size != 0);
480
481       /* Make sure the size of the stack is enough for the guard and
482          eventually the thread descriptor.  */
483       guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
484       if (__builtin_expect (size < ((guardsize + __static_tls_size
485                                      + MINIMAL_REST_STACK + pagesize_m1)
486                                     & ~pagesize_m1),
487                             0))
488         /* The stack is too small (or the guard too large).  */
489         return EINVAL;
490
491       /* Try to get a stack from the cache.  */
492       reqsize = size;
493       pd = get_cached_stack (&size, &mem);
494       if (pd == NULL)
495         {
496           /* To avoid aliasing effects on a larger scale than pages we
497              adjust the allocated stack size if necessary.  This way
498              allocations directly following each other will not have
499              aliasing problems.  */
500 #if MULTI_PAGE_ALIASING != 0
501           if ((size % MULTI_PAGE_ALIASING) == 0)
502             size += pagesize_m1 + 1;
503 #endif
504
505           mem = mmap (NULL, size, prot,
506                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
507
508           if (__glibc_unlikely (mem == MAP_FAILED))
509             return errno;
510
511           /* SIZE is guaranteed to be greater than zero.
512              So we can never get a null pointer back from mmap.  */
513           assert (mem != NULL);
514
515 #if COLORING_INCREMENT != 0
516           /* Atomically increment NCREATED.  */
517           unsigned int ncreated = atomic_increment_val (&nptl_ncreated);
518
519           /* We chose the offset for coloring by incrementing it for
520              every new thread by a fixed amount.  The offset used
521              module the page size.  Even if coloring would be better
522              relative to higher alignment values it makes no sense to
523              do it since the mmap() interface does not allow us to
524              specify any alignment for the returned memory block.  */
525           size_t coloring = (ncreated * COLORING_INCREMENT) & pagesize_m1;
526
527           /* Make sure the coloring offsets does not disturb the alignment
528              of the TCB and static TLS block.  */
529           if (__glibc_unlikely ((coloring & __static_tls_align_m1) != 0))
530             coloring = (((coloring + __static_tls_align_m1)
531                          & ~(__static_tls_align_m1))
532                         & ~pagesize_m1);
533 #else
534           /* Unless specified we do not make any adjustments.  */
535 # define coloring 0
536 #endif
537
538           /* Place the thread descriptor at the end of the stack.  */
539 #if TLS_TCB_AT_TP
540           pd = (struct pthread *) ((char *) mem + size - coloring) - 1;
541 #elif TLS_DTV_AT_TP
542           pd = (struct pthread *) ((((uintptr_t) mem + size - coloring
543                                     - __static_tls_size)
544                                     & ~__static_tls_align_m1)
545                                    - TLS_PRE_TCB_SIZE);
546 #endif
547
548           /* Remember the stack-related values.  */
549           pd->stackblock = mem;
550           pd->stackblock_size = size;
551
552           /* We allocated the first block thread-specific data array.
553              This address will not change for the lifetime of this
554              descriptor.  */
555           pd->specific[0] = pd->specific_1stblock;
556
557           /* This is at least the second thread.  */
558           pd->header.multiple_threads = 1;
559 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
560           __pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
561 #endif
562
563 #ifndef __ASSUME_PRIVATE_FUTEX
564           /* The thread must know when private futexes are supported.  */
565           pd->header.private_futex = THREAD_GETMEM (THREAD_SELF,
566                                                     header.private_futex);
567 #endif
568
569 #ifdef NEED_DL_SYSINFO
570           /* Copy the sysinfo value from the parent.  */
571           THREAD_SYSINFO(pd) = THREAD_SELF_SYSINFO;
572 #endif
573
574           /* Don't allow setxid until cloned.  */
575           pd->setxid_futex = -1;
576
577           /* The process ID is also the same as that of the caller.  */
578           pd->pid = THREAD_GETMEM (THREAD_SELF, pid);
579
580           /* Allocate the DTV for this thread.  */
581           if (_dl_allocate_tls (TLS_TPADJ (pd)) == NULL)
582             {
583               /* Something went wrong.  */
584               assert (errno == ENOMEM);
585
586               /* Free the stack memory we just allocated.  */
587               (void) munmap (mem, size);
588
589               return errno;
590             }
591
592
593           /* Prepare to modify global data.  */
594           lll_lock (stack_cache_lock, LLL_PRIVATE);
595
596           /* And add to the list of stacks in use.  */
597           stack_list_add (&pd->list, &stack_used);
598
599           lll_unlock (stack_cache_lock, LLL_PRIVATE);
600
601
602           /* There might have been a race.  Another thread might have
603              caused the stacks to get exec permission while this new
604              stack was prepared.  Detect if this was possible and
605              change the permission if necessary.  */
606           if (__builtin_expect ((GL(dl_stack_flags) & PF_X) != 0
607                                 && (prot & PROT_EXEC) == 0, 0))
608             {
609               int err = change_stack_perm (pd
610 #ifdef NEED_SEPARATE_REGISTER_STACK
611                                            , ~pagesize_m1
612 #endif
613                                            );
614               if (err != 0)
615                 {
616                   /* Free the stack memory we just allocated.  */
617                   (void) munmap (mem, size);
618
619                   return err;
620                 }
621             }
622
623
624           /* Note that all of the stack and the thread descriptor is
625              zeroed.  This means we do not have to initialize fields
626              with initial value zero.  This is specifically true for
627              the 'tid' field which is always set back to zero once the
628              stack is not used anymore and for the 'guardsize' field
629              which will be read next.  */
630         }
631
632       /* Create or resize the guard area if necessary.  */
633       if (__glibc_unlikely (guardsize > pd->guardsize))
634         {
635 #ifdef NEED_SEPARATE_REGISTER_STACK
636           char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
637 #elif _STACK_GROWS_DOWN
638           char *guard = mem;
639 # elif _STACK_GROWS_UP
640           char *guard = (char *) (((uintptr_t) pd - guardsize) & ~pagesize_m1);
641 #endif
642           if (mprotect (guard, guardsize, PROT_NONE) != 0)
643             {
644             mprot_error:
645               lll_lock (stack_cache_lock, LLL_PRIVATE);
646
647               /* Remove the thread from the list.  */
648               stack_list_del (&pd->list);
649
650               lll_unlock (stack_cache_lock, LLL_PRIVATE);
651
652               /* Get rid of the TLS block we allocated.  */
653               _dl_deallocate_tls (TLS_TPADJ (pd), false);
654
655               /* Free the stack memory regardless of whether the size
656                  of the cache is over the limit or not.  If this piece
657                  of memory caused problems we better do not use it
658                  anymore.  Uh, and we ignore possible errors.  There
659                  is nothing we could do.  */
660               (void) munmap (mem, size);
661
662               return errno;
663             }
664
665           pd->guardsize = guardsize;
666         }
667       else if (__builtin_expect (pd->guardsize - guardsize > size - reqsize,
668                                  0))
669         {
670           /* The old guard area is too large.  */
671
672 #ifdef NEED_SEPARATE_REGISTER_STACK
673           char *guard = mem + (((size - guardsize) / 2) & ~pagesize_m1);
674           char *oldguard = mem + (((size - pd->guardsize) / 2) & ~pagesize_m1);
675
676           if (oldguard < guard
677               && mprotect (oldguard, guard - oldguard, prot) != 0)
678             goto mprot_error;
679
680           if (mprotect (guard + guardsize,
681                         oldguard + pd->guardsize - guard - guardsize,
682                         prot) != 0)
683             goto mprot_error;
684 #elif _STACK_GROWS_DOWN
685           if (mprotect ((char *) mem + guardsize, pd->guardsize - guardsize,
686                         prot) != 0)
687             goto mprot_error;
688 #elif _STACK_GROWS_UP
689           if (mprotect ((char *) pd - pd->guardsize,
690                         pd->guardsize - guardsize, prot) != 0)
691             goto mprot_error;
692 #endif
693
694           pd->guardsize = guardsize;
695         }
696       /* The pthread_getattr_np() calls need to get passed the size
697          requested in the attribute, regardless of how large the
698          actually used guardsize is.  */
699       pd->reported_guardsize = guardsize;
700     }
701
702   /* Initialize the lock.  We have to do this unconditionally since the
703      stillborn thread could be canceled while the lock is taken.  */
704   pd->lock = LLL_LOCK_INITIALIZER;
705
706   /* The robust mutex lists also need to be initialized
707      unconditionally because the cleanup for the previous stack owner
708      might have happened in the kernel.  */
709   pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
710                                   - offsetof (pthread_mutex_t,
711                                               __data.__list.__next));
712   pd->robust_head.list_op_pending = NULL;
713 #ifdef __PTHREAD_MUTEX_HAVE_PREV
714   pd->robust_prev = &pd->robust_head;
715 #endif
716   pd->robust_head.list = &pd->robust_head;
717
718   /* We place the thread descriptor at the end of the stack.  */
719   *pdp = pd;
720
721 #if TLS_TCB_AT_TP
722   /* The stack begins before the TCB and the static TLS block.  */
723   stacktop = ((char *) (pd + 1) - __static_tls_size);
724 #elif TLS_DTV_AT_TP
725   stacktop = (char *) (pd - 1);
726 #endif
727
728 #ifdef NEED_SEPARATE_REGISTER_STACK
729   *stack = pd->stackblock;
730   *stacksize = stacktop - *stack;
731 #elif _STACK_GROWS_DOWN
732   *stack = stacktop;
733 #elif _STACK_GROWS_UP
734   *stack = pd->stackblock;
735   assert (*stack > 0);
736 #endif
737
738   return 0;
739 }
740
741
742 void
743 internal_function
744 __deallocate_stack (struct pthread *pd)
745 {
746   lll_lock (stack_cache_lock, LLL_PRIVATE);
747
748   /* Remove the thread from the list of threads with user defined
749      stacks.  */
750   stack_list_del (&pd->list);
751
752   /* Not much to do.  Just free the mmap()ed memory.  Note that we do
753      not reset the 'used' flag in the 'tid' field.  This is done by
754      the kernel.  If no thread has been created yet this field is
755      still zero.  */
756   if (__glibc_likely (! pd->user_stack))
757     (void) queue_stack (pd);
758   else
759     /* Free the memory associated with the ELF TLS.  */
760     _dl_deallocate_tls (TLS_TPADJ (pd), false);
761
762   lll_unlock (stack_cache_lock, LLL_PRIVATE);
763 }
764
765
766 int
767 internal_function
768 __make_stacks_executable (void **stack_endp)
769 {
770   /* First the main thread's stack.  */
771   int err = _dl_make_stack_executable (stack_endp);
772   if (err != 0)
773     return err;
774
775 #ifdef NEED_SEPARATE_REGISTER_STACK
776   const size_t pagemask = ~(__getpagesize () - 1);
777 #endif
778
779   lll_lock (stack_cache_lock, LLL_PRIVATE);
780
781   list_t *runp;
782   list_for_each (runp, &stack_used)
783     {
784       err = change_stack_perm (list_entry (runp, struct pthread, list)
785 #ifdef NEED_SEPARATE_REGISTER_STACK
786                                , pagemask
787 #endif
788                                );
789       if (err != 0)
790         break;
791     }
792
793   /* Also change the permission for the currently unused stacks.  This
794      might be wasted time but better spend it here than adding a check
795      in the fast path.  */
796   if (err == 0)
797     list_for_each (runp, &stack_cache)
798       {
799         err = change_stack_perm (list_entry (runp, struct pthread, list)
800 #ifdef NEED_SEPARATE_REGISTER_STACK
801                                  , pagemask
802 #endif
803                                  );
804         if (err != 0)
805           break;
806       }
807
808   lll_unlock (stack_cache_lock, LLL_PRIVATE);
809
810   return err;
811 }
812
813
814 /* In case of a fork() call the memory allocation in the child will be
815    the same but only one thread is running.  All stacks except that of
816    the one running thread are not used anymore.  We have to recycle
817    them.  */
818 void
819 __reclaim_stacks (void)
820 {
821   struct pthread *self = (struct pthread *) THREAD_SELF;
822
823   /* No locking necessary.  The caller is the only stack in use.  But
824      we have to be aware that we might have interrupted a list
825      operation.  */
826
827   if (in_flight_stack != 0)
828     {
829       bool add_p = in_flight_stack & 1;
830       list_t *elem = (list_t *) (in_flight_stack & ~(uintptr_t) 1);
831
832       if (add_p)
833         {
834           /* We always add at the beginning of the list.  So in this case we
835              only need to check the beginning of these lists to see if the
836              pointers at the head of the list are inconsistent.  */
837           list_t *l = NULL;
838
839           if (stack_used.next->prev != &stack_used)
840             l = &stack_used;
841           else if (stack_cache.next->prev != &stack_cache)
842             l = &stack_cache;
843
844           if (l != NULL)
845             {
846               assert (l->next->prev == elem);
847               elem->next = l->next;
848               elem->prev = l;
849               l->next = elem;
850             }
851         }
852       else
853         {
854           /* We can simply always replay the delete operation.  */
855           elem->next->prev = elem->prev;
856           elem->prev->next = elem->next;
857         }
858     }
859
860   /* Mark all stacks except the still running one as free.  */
861   list_t *runp;
862   list_for_each (runp, &stack_used)
863     {
864       struct pthread *curp = list_entry (runp, struct pthread, list);
865       if (curp != self)
866         {
867           /* This marks the stack as free.  */
868           curp->tid = 0;
869
870           /* The PID field must be initialized for the new process.  */
871           curp->pid = self->pid;
872
873           /* Account for the size of the stack.  */
874           stack_cache_actsize += curp->stackblock_size;
875
876           if (curp->specific_used)
877             {
878               /* Clear the thread-specific data.  */
879               memset (curp->specific_1stblock, '\0',
880                       sizeof (curp->specific_1stblock));
881
882               curp->specific_used = false;
883
884               for (size_t cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
885                 if (curp->specific[cnt] != NULL)
886                   {
887                     memset (curp->specific[cnt], '\0',
888                             sizeof (curp->specific_1stblock));
889
890                     /* We have allocated the block which we do not
891                        free here so re-set the bit.  */
892                     curp->specific_used = true;
893                   }
894             }
895         }
896     }
897
898   /* Reset the PIDs in any cached stacks.  */
899   list_for_each (runp, &stack_cache)
900     {
901       struct pthread *curp = list_entry (runp, struct pthread, list);
902       curp->pid = self->pid;
903     }
904
905   /* Add the stack of all running threads to the cache.  */
906   list_splice (&stack_used, &stack_cache);
907
908   /* Remove the entry for the current thread to from the cache list
909      and add it to the list of running threads.  Which of the two
910      lists is decided by the user_stack flag.  */
911   stack_list_del (&self->list);
912
913   /* Re-initialize the lists for all the threads.  */
914   INIT_LIST_HEAD (&stack_used);
915   INIT_LIST_HEAD (&__stack_user);
916
917   if (__glibc_unlikely (THREAD_GETMEM (self, user_stack)))
918     list_add (&self->list, &__stack_user);
919   else
920     list_add (&self->list, &stack_used);
921
922   /* There is one thread running.  */
923   __nptl_nthreads = 1;
924
925   in_flight_stack = 0;
926
927   /* Initialize locks.  */
928   stack_cache_lock = LLL_LOCK_INITIALIZER;
929   __default_pthread_attr_lock = LLL_LOCK_INITIALIZER;
930 }
931
932
933 #if HP_TIMING_AVAIL
934 # undef __find_thread_by_id
935 /* Find a thread given the thread ID.  */
936 attribute_hidden
937 struct pthread *
938 __find_thread_by_id (pid_t tid)
939 {
940   struct pthread *result = NULL;
941
942   lll_lock (stack_cache_lock, LLL_PRIVATE);
943
944   /* Iterate over the list with system-allocated threads first.  */
945   list_t *runp;
946   list_for_each (runp, &stack_used)
947     {
948       struct pthread *curp;
949
950       curp = list_entry (runp, struct pthread, list);
951
952       if (curp->tid == tid)
953         {
954           result = curp;
955           goto out;
956         }
957     }
958
959   /* Now the list with threads using user-allocated stacks.  */
960   list_for_each (runp, &__stack_user)
961     {
962       struct pthread *curp;
963
964       curp = list_entry (runp, struct pthread, list);
965
966       if (curp->tid == tid)
967         {
968           result = curp;
969           goto out;
970         }
971     }
972
973  out:
974   lll_unlock (stack_cache_lock, LLL_PRIVATE);
975
976   return result;
977 }
978 #endif
979
980
981 static void
982 internal_function
983 setxid_mark_thread (struct xid_command *cmdp, struct pthread *t)
984 {
985   int ch;
986
987   /* Wait until this thread is cloned.  */
988   if (t->setxid_futex == -1
989       && ! atomic_compare_and_exchange_bool_acq (&t->setxid_futex, -2, -1))
990     do
991       lll_futex_wait (&t->setxid_futex, -2, LLL_PRIVATE);
992     while (t->setxid_futex == -2);
993
994   /* Don't let the thread exit before the setxid handler runs.  */
995   t->setxid_futex = 0;
996
997   do
998     {
999       ch = t->cancelhandling;
1000
1001       /* If the thread is exiting right now, ignore it.  */
1002       if ((ch & EXITING_BITMASK) != 0)
1003         {
1004           /* Release the futex if there is no other setxid in
1005              progress.  */
1006           if ((ch & SETXID_BITMASK) == 0)
1007             {
1008               t->setxid_futex = 1;
1009               lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1010             }
1011           return;
1012         }
1013     }
1014   while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1015                                                ch | SETXID_BITMASK, ch));
1016 }
1017
1018
1019 static void
1020 internal_function
1021 setxid_unmark_thread (struct xid_command *cmdp, struct pthread *t)
1022 {
1023   int ch;
1024
1025   do
1026     {
1027       ch = t->cancelhandling;
1028       if ((ch & SETXID_BITMASK) == 0)
1029         return;
1030     }
1031   while (atomic_compare_and_exchange_bool_acq (&t->cancelhandling,
1032                                                ch & ~SETXID_BITMASK, ch));
1033
1034   /* Release the futex just in case.  */
1035   t->setxid_futex = 1;
1036   lll_futex_wake (&t->setxid_futex, 1, LLL_PRIVATE);
1037 }
1038
1039
1040 static int
1041 internal_function
1042 setxid_signal_thread (struct xid_command *cmdp, struct pthread *t)
1043 {
1044   if ((t->cancelhandling & SETXID_BITMASK) == 0)
1045     return 0;
1046
1047   int val;
1048   INTERNAL_SYSCALL_DECL (err);
1049   val = INTERNAL_SYSCALL (tgkill, err, 3, THREAD_GETMEM (THREAD_SELF, pid),
1050                           t->tid, SIGSETXID);
1051
1052   /* If this failed, it must have had not started yet or else exited.  */
1053   if (!INTERNAL_SYSCALL_ERROR_P (val, err))
1054     {
1055       atomic_increment (&cmdp->cntr);
1056       return 1;
1057     }
1058   else
1059     return 0;
1060 }
1061
1062 /* Check for consistency across set*id system call results.  The abort
1063    should not happen as long as all privileges changes happen through
1064    the glibc wrappers.  ERROR must be 0 (no error) or an errno
1065    code.  */
1066 void
1067 attribute_hidden
1068 __nptl_setxid_error (struct xid_command *cmdp, int error)
1069 {
1070   do
1071     {
1072       int olderror = cmdp->error;
1073       if (olderror == error)
1074         break;
1075       if (olderror != -1)
1076         /* Mismatch between current and previous results.  */
1077         abort ();
1078     }
1079   while (atomic_compare_and_exchange_bool_acq (&cmdp->error, error, -1));
1080 }
1081
1082 int
1083 attribute_hidden
1084 __nptl_setxid (struct xid_command *cmdp)
1085 {
1086   int signalled;
1087   int result;
1088   lll_lock (stack_cache_lock, LLL_PRIVATE);
1089
1090   __xidcmd = cmdp;
1091   cmdp->cntr = 0;
1092   cmdp->error = -1;
1093
1094   struct pthread *self = THREAD_SELF;
1095
1096   /* Iterate over the list with system-allocated threads first.  */
1097   list_t *runp;
1098   list_for_each (runp, &stack_used)
1099     {
1100       struct pthread *t = list_entry (runp, struct pthread, list);
1101       if (t == self)
1102         continue;
1103
1104       setxid_mark_thread (cmdp, t);
1105     }
1106
1107   /* Now the list with threads using user-allocated stacks.  */
1108   list_for_each (runp, &__stack_user)
1109     {
1110       struct pthread *t = list_entry (runp, struct pthread, list);
1111       if (t == self)
1112         continue;
1113
1114       setxid_mark_thread (cmdp, t);
1115     }
1116
1117   /* Iterate until we don't succeed in signalling anyone.  That means
1118      we have gotten all running threads, and their children will be
1119      automatically correct once started.  */
1120   do
1121     {
1122       signalled = 0;
1123
1124       list_for_each (runp, &stack_used)
1125         {
1126           struct pthread *t = list_entry (runp, struct pthread, list);
1127           if (t == self)
1128             continue;
1129
1130           signalled += setxid_signal_thread (cmdp, t);
1131         }
1132
1133       list_for_each (runp, &__stack_user)
1134         {
1135           struct pthread *t = list_entry (runp, struct pthread, list);
1136           if (t == self)
1137             continue;
1138
1139           signalled += setxid_signal_thread (cmdp, t);
1140         }
1141
1142       int cur = cmdp->cntr;
1143       while (cur != 0)
1144         {
1145           lll_futex_wait (&cmdp->cntr, cur, LLL_PRIVATE);
1146           cur = cmdp->cntr;
1147         }
1148     }
1149   while (signalled != 0);
1150
1151   /* Clean up flags, so that no thread blocks during exit waiting
1152      for a signal which will never come.  */
1153   list_for_each (runp, &stack_used)
1154     {
1155       struct pthread *t = list_entry (runp, struct pthread, list);
1156       if (t == self)
1157         continue;
1158
1159       setxid_unmark_thread (cmdp, t);
1160     }
1161
1162   list_for_each (runp, &__stack_user)
1163     {
1164       struct pthread *t = list_entry (runp, struct pthread, list);
1165       if (t == self)
1166         continue;
1167
1168       setxid_unmark_thread (cmdp, t);
1169     }
1170
1171   /* This must be last, otherwise the current thread might not have
1172      permissions to send SIGSETXID syscall to the other threads.  */
1173   INTERNAL_SYSCALL_DECL (err);
1174   result = INTERNAL_SYSCALL_NCS (cmdp->syscall_no, err, 3,
1175                                  cmdp->id[0], cmdp->id[1], cmdp->id[2]);
1176   int error = 0;
1177   if (__glibc_unlikely (INTERNAL_SYSCALL_ERROR_P (result, err)))
1178     {
1179       error = INTERNAL_SYSCALL_ERRNO (result, err);
1180       __set_errno (error);
1181       result = -1;
1182     }
1183   __nptl_setxid_error (cmdp, error);
1184
1185   lll_unlock (stack_cache_lock, LLL_PRIVATE);
1186   return result;
1187 }
1188
1189 static inline void __attribute__((always_inline))
1190 init_one_static_tls (struct pthread *curp, struct link_map *map)
1191 {
1192   dtv_t *dtv = GET_DTV (TLS_TPADJ (curp));
1193 # if TLS_TCB_AT_TP
1194   void *dest = (char *) curp - map->l_tls_offset;
1195 # elif TLS_DTV_AT_TP
1196   void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
1197 # else
1198 #  error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
1199 # endif
1200
1201   /* Fill in the DTV slot so that a later LD/GD access will find it.  */
1202   dtv[map->l_tls_modid].pointer.val = dest;
1203   dtv[map->l_tls_modid].pointer.is_static = true;
1204
1205   /* Initialize the memory.  */
1206   memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
1207           '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
1208 }
1209
1210 void
1211 attribute_hidden
1212 __pthread_init_static_tls (struct link_map *map)
1213 {
1214   lll_lock (stack_cache_lock, LLL_PRIVATE);
1215
1216   /* Iterate over the list with system-allocated threads first.  */
1217   list_t *runp;
1218   list_for_each (runp, &stack_used)
1219     init_one_static_tls (list_entry (runp, struct pthread, list), map);
1220
1221   /* Now the list with threads using user-allocated stacks.  */
1222   list_for_each (runp, &__stack_user)
1223     init_one_static_tls (list_entry (runp, struct pthread, list), map);
1224
1225   lll_unlock (stack_cache_lock, LLL_PRIVATE);
1226 }
1227
1228
1229 void
1230 attribute_hidden
1231 __wait_lookup_done (void)
1232 {
1233   lll_lock (stack_cache_lock, LLL_PRIVATE);
1234
1235   struct pthread *self = THREAD_SELF;
1236
1237   /* Iterate over the list with system-allocated threads first.  */
1238   list_t *runp;
1239   list_for_each (runp, &stack_used)
1240     {
1241       struct pthread *t = list_entry (runp, struct pthread, list);
1242       if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1243         continue;
1244
1245       int *const gscope_flagp = &t->header.gscope_flag;
1246
1247       /* We have to wait until this thread is done with the global
1248          scope.  First tell the thread that we are waiting and
1249          possibly have to be woken.  */
1250       if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1251                                                 THREAD_GSCOPE_FLAG_WAIT,
1252                                                 THREAD_GSCOPE_FLAG_USED))
1253         continue;
1254
1255       do
1256         lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1257       while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1258     }
1259
1260   /* Now the list with threads using user-allocated stacks.  */
1261   list_for_each (runp, &__stack_user)
1262     {
1263       struct pthread *t = list_entry (runp, struct pthread, list);
1264       if (t == self || t->header.gscope_flag == THREAD_GSCOPE_FLAG_UNUSED)
1265         continue;
1266
1267       int *const gscope_flagp = &t->header.gscope_flag;
1268
1269       /* We have to wait until this thread is done with the global
1270          scope.  First tell the thread that we are waiting and
1271          possibly have to be woken.  */
1272       if (atomic_compare_and_exchange_bool_acq (gscope_flagp,
1273                                                 THREAD_GSCOPE_FLAG_WAIT,
1274                                                 THREAD_GSCOPE_FLAG_USED))
1275         continue;
1276
1277       do
1278         lll_futex_wait (gscope_flagp, THREAD_GSCOPE_FLAG_WAIT, LLL_PRIVATE);
1279       while (*gscope_flagp == THREAD_GSCOPE_FLAG_WAIT);
1280     }
1281
1282   lll_unlock (stack_cache_lock, LLL_PRIVATE);
1283 }