Remove shlib-versions entries redundant with DEFAULT entries.
[glibc.git] / nptl / pthread_create.c
blobb9af01076794cb3daf5e737466bff94b79c32ffc
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.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 #include <ctype.h>
20 #include <errno.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdint.h>
25 #include "pthreadP.h"
26 #include <hp-timing.h>
27 #include <ldsodefs.h>
28 #include <atomic.h>
29 #include <libc-internal.h>
30 #include <resolv.h>
31 #include <kernel-features.h>
32 #include <exit-thread.h>
34 #include <shlib-compat.h>
36 #include <stap-probe.h>
39 /* Local function to start thread and handle cleanup. */
40 static int start_thread (void *arg);
43 /* Nozero if debugging mode is enabled. */
44 int __pthread_debug;
46 /* Globally enabled events. */
47 static td_thr_events_t __nptl_threads_events __attribute_used__;
49 /* Pointer to descriptor with the last event. */
50 static struct pthread *__nptl_last_event __attribute_used__;
52 /* Number of threads running. */
53 unsigned int __nptl_nthreads = 1;
56 /* Code to allocate and deallocate a stack. */
57 #include "allocatestack.c"
59 /* Code to create the thread. */
60 #include <createthread.c>
63 struct pthread *
64 internal_function
65 __find_in_stack_list (pd)
66 struct pthread *pd;
68 list_t *entry;
69 struct pthread *result = NULL;
71 lll_lock (stack_cache_lock, LLL_PRIVATE);
73 list_for_each (entry, &stack_used)
75 struct pthread *curp;
77 curp = list_entry (entry, struct pthread, list);
78 if (curp == pd)
80 result = curp;
81 break;
85 if (result == NULL)
86 list_for_each (entry, &__stack_user)
88 struct pthread *curp;
90 curp = list_entry (entry, struct pthread, list);
91 if (curp == pd)
93 result = curp;
94 break;
98 lll_unlock (stack_cache_lock, LLL_PRIVATE);
100 return result;
104 /* Deallocate POSIX thread-local-storage. */
105 void
106 attribute_hidden
107 __nptl_deallocate_tsd (void)
109 struct pthread *self = THREAD_SELF;
111 /* Maybe no data was ever allocated. This happens often so we have
112 a flag for this. */
113 if (THREAD_GETMEM (self, specific_used))
115 size_t round;
116 size_t cnt;
118 round = 0;
121 size_t idx;
123 /* So far no new nonzero data entry. */
124 THREAD_SETMEM (self, specific_used, false);
126 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
128 struct pthread_key_data *level2;
130 level2 = THREAD_GETMEM_NC (self, specific, cnt);
132 if (level2 != NULL)
134 size_t inner;
136 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
137 ++inner, ++idx)
139 void *data = level2[inner].data;
141 if (data != NULL)
143 /* Always clear the data. */
144 level2[inner].data = NULL;
146 /* Make sure the data corresponds to a valid
147 key. This test fails if the key was
148 deallocated and also if it was
149 re-allocated. It is the user's
150 responsibility to free the memory in this
151 case. */
152 if (level2[inner].seq
153 == __pthread_keys[idx].seq
154 /* It is not necessary to register a destructor
155 function. */
156 && __pthread_keys[idx].destr != NULL)
157 /* Call the user-provided destructor. */
158 __pthread_keys[idx].destr (data);
162 else
163 idx += PTHREAD_KEY_1STLEVEL_SIZE;
166 if (THREAD_GETMEM (self, specific_used) == 0)
167 /* No data has been modified. */
168 goto just_free;
170 /* We only repeat the process a fixed number of times. */
171 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
173 /* Just clear the memory of the first block for reuse. */
174 memset (&THREAD_SELF->specific_1stblock, '\0',
175 sizeof (self->specific_1stblock));
177 just_free:
178 /* Free the memory for the other blocks. */
179 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
181 struct pthread_key_data *level2;
183 level2 = THREAD_GETMEM_NC (self, specific, cnt);
184 if (level2 != NULL)
186 /* The first block is allocated as part of the thread
187 descriptor. */
188 free (level2);
189 THREAD_SETMEM_NC (self, specific, cnt, NULL);
193 THREAD_SETMEM (self, specific_used, false);
198 /* Deallocate a thread's stack after optionally making sure the thread
199 descriptor is still valid. */
200 void
201 internal_function
202 __free_tcb (struct pthread *pd)
204 /* The thread is exiting now. */
205 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
206 TERMINATED_BIT) == 0, 1))
208 /* Remove the descriptor from the list. */
209 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
210 /* Something is really wrong. The descriptor for a still
211 running thread is gone. */
212 abort ();
214 /* Free TPP data. */
215 if (__glibc_unlikely (pd->tpp != NULL))
217 struct priority_protection_data *tpp = pd->tpp;
219 pd->tpp = NULL;
220 free (tpp);
223 /* Queue the stack memory block for reuse and exit the process. The
224 kernel will signal via writing to the address returned by
225 QUEUE-STACK when the stack is available. */
226 __deallocate_stack (pd);
231 static int
232 start_thread (void *arg)
234 struct pthread *pd = (struct pthread *) arg;
236 #if HP_TIMING_AVAIL
237 /* Remember the time when the thread was started. */
238 hp_timing_t now;
239 HP_TIMING_NOW (now);
240 THREAD_SETMEM (pd, cpuclock_offset, now);
241 #endif
243 /* Initialize resolver state pointer. */
244 __resp = &pd->res;
246 /* Initialize pointers to locale data. */
247 __ctype_init ();
249 /* Allow setxid from now onwards. */
250 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0) == -2))
251 lll_futex_wake (&pd->setxid_futex, 1, LLL_PRIVATE);
253 #ifdef __NR_set_robust_list
254 # ifndef __ASSUME_SET_ROBUST_LIST
255 if (__set_robust_list_avail >= 0)
256 # endif
258 INTERNAL_SYSCALL_DECL (err);
259 /* This call should never fail because the initial call in init.c
260 succeeded. */
261 INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
262 sizeof (struct robust_list_head));
264 #endif
266 /* If the parent was running cancellation handlers while creating
267 the thread the new thread inherited the signal mask. Reset the
268 cancellation signal mask. */
269 if (__glibc_unlikely (pd->parent_cancelhandling & CANCELING_BITMASK))
271 INTERNAL_SYSCALL_DECL (err);
272 sigset_t mask;
273 __sigemptyset (&mask);
274 __sigaddset (&mask, SIGCANCEL);
275 (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &mask,
276 NULL, _NSIG / 8);
279 /* This is where the try/finally block should be created. For
280 compilers without that support we do use setjmp. */
281 struct pthread_unwind_buf unwind_buf;
283 /* No previous handlers. */
284 unwind_buf.priv.data.prev = NULL;
285 unwind_buf.priv.data.cleanup = NULL;
287 int not_first_call;
288 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
289 if (__glibc_likely (! not_first_call))
291 /* Store the new cleanup handler info. */
292 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
294 if (__glibc_unlikely (pd->stopped_start))
296 int oldtype = CANCEL_ASYNC ();
298 /* Get the lock the parent locked to force synchronization. */
299 lll_lock (pd->lock, LLL_PRIVATE);
300 /* And give it up right away. */
301 lll_unlock (pd->lock, LLL_PRIVATE);
303 CANCEL_RESET (oldtype);
306 LIBC_PROBE (pthread_start, 3, (pthread_t) pd, pd->start_routine, pd->arg);
308 /* Run the code the user provided. */
309 #ifdef CALL_THREAD_FCT
310 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
311 #else
312 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
313 #endif
316 /* Call destructors for the thread_local TLS variables. */
317 #ifndef SHARED
318 if (&__call_tls_dtors != NULL)
319 #endif
320 __call_tls_dtors ();
322 /* Run the destructor for the thread-local data. */
323 __nptl_deallocate_tsd ();
325 /* Clean up any state libc stored in thread-local variables. */
326 __libc_thread_freeres ();
328 /* If this is the last thread we terminate the process now. We
329 do not notify the debugger, it might just irritate it if there
330 is no thread left. */
331 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads)))
332 /* This was the last thread. */
333 exit (0);
335 /* Report the death of the thread if this is wanted. */
336 if (__glibc_unlikely (pd->report_events))
338 /* See whether TD_DEATH is in any of the mask. */
339 const int idx = __td_eventword (TD_DEATH);
340 const uint32_t mask = __td_eventmask (TD_DEATH);
342 if ((mask & (__nptl_threads_events.event_bits[idx]
343 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
345 /* Yep, we have to signal the death. Add the descriptor to
346 the list but only if it is not already on it. */
347 if (pd->nextevent == NULL)
349 pd->eventbuf.eventnum = TD_DEATH;
350 pd->eventbuf.eventdata = pd;
353 pd->nextevent = __nptl_last_event;
354 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
355 pd, pd->nextevent));
358 /* Now call the function to signal the event. */
359 __nptl_death_event ();
363 /* The thread is exiting now. Don't set this bit until after we've hit
364 the event-reporting breakpoint, so that td_thr_get_info on us while at
365 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
366 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
368 #ifndef __ASSUME_SET_ROBUST_LIST
369 /* If this thread has any robust mutexes locked, handle them now. */
370 # ifdef __PTHREAD_MUTEX_HAVE_PREV
371 void *robust = pd->robust_head.list;
372 # else
373 __pthread_slist_t *robust = pd->robust_list.__next;
374 # endif
375 /* We let the kernel do the notification if it is able to do so.
376 If we have to do it here there for sure are no PI mutexes involved
377 since the kernel support for them is even more recent. */
378 if (__set_robust_list_avail < 0
379 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
383 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
384 ((char *) robust - offsetof (struct __pthread_mutex_s,
385 __list.__next));
386 robust = *((void **) robust);
388 # ifdef __PTHREAD_MUTEX_HAVE_PREV
389 this->__list.__prev = NULL;
390 # endif
391 this->__list.__next = NULL;
393 atomic_or (&this->__lock, FUTEX_OWNER_DIED);
394 lll_futex_wake (this->__lock, 1, /* XYZ */ LLL_SHARED);
396 while (robust != (void *) &pd->robust_head);
398 #endif
400 /* Mark the memory of the stack as usable to the kernel. We free
401 everything except for the space used for the TCB itself. */
402 size_t pagesize_m1 = __getpagesize () - 1;
403 #ifdef _STACK_GROWS_DOWN
404 char *sp = CURRENT_STACK_FRAME;
405 size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
406 #else
407 # error "to do"
408 #endif
409 assert (freesize < pd->stackblock_size);
410 if (freesize > PTHREAD_STACK_MIN)
411 __madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
413 /* If the thread is detached free the TCB. */
414 if (IS_DETACHED (pd))
415 /* Free the TCB. */
416 __free_tcb (pd);
417 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
419 /* Some other thread might call any of the setXid functions and expect
420 us to reply. In this case wait until we did that. */
422 lll_futex_wait (&pd->setxid_futex, 0, LLL_PRIVATE);
423 while (pd->cancelhandling & SETXID_BITMASK);
425 /* Reset the value so that the stack can be reused. */
426 pd->setxid_futex = 0;
429 /* We cannot call '_exit' here. '_exit' will terminate the process.
431 The 'exit' implementation in the kernel will signal when the
432 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
433 flag. The 'tid' field in the TCB will be set to zero.
435 The exit code is zero since in case all threads exit by calling
436 'pthread_exit' the exit status must be 0 (zero). */
437 __exit_thread ();
439 /* NOTREACHED */
440 return 0;
445 __pthread_create_2_1 (newthread, attr, start_routine, arg)
446 pthread_t *newthread;
447 const pthread_attr_t *attr;
448 void *(*start_routine) (void *);
449 void *arg;
451 STACK_VARIABLES;
453 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
454 struct pthread_attr default_attr;
455 bool free_cpuset = false;
456 if (iattr == NULL)
458 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
459 default_attr = __default_pthread_attr;
460 size_t cpusetsize = default_attr.cpusetsize;
461 if (cpusetsize > 0)
463 cpu_set_t *cpuset;
464 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
465 cpuset = __alloca (cpusetsize);
466 else
468 cpuset = malloc (cpusetsize);
469 if (cpuset == NULL)
471 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
472 return ENOMEM;
474 free_cpuset = true;
476 memcpy (cpuset, default_attr.cpuset, cpusetsize);
477 default_attr.cpuset = cpuset;
479 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
480 iattr = &default_attr;
483 struct pthread *pd = NULL;
484 int err = ALLOCATE_STACK (iattr, &pd);
485 int retval = 0;
487 if (__glibc_unlikely (err != 0))
488 /* Something went wrong. Maybe a parameter of the attributes is
489 invalid or we could not allocate memory. Note we have to
490 translate error codes. */
492 retval = err == ENOMEM ? EAGAIN : err;
493 goto out;
497 /* Initialize the TCB. All initializations with zero should be
498 performed in 'get_cached_stack'. This way we avoid doing this if
499 the stack freshly allocated with 'mmap'. */
501 #if TLS_TCB_AT_TP
502 /* Reference to the TCB itself. */
503 pd->header.self = pd;
505 /* Self-reference for TLS. */
506 pd->header.tcb = pd;
507 #endif
509 /* Store the address of the start routine and the parameter. Since
510 we do not start the function directly the stillborn thread will
511 get the information from its thread descriptor. */
512 pd->start_routine = start_routine;
513 pd->arg = arg;
515 /* Copy the thread attribute flags. */
516 struct pthread *self = THREAD_SELF;
517 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
518 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
520 /* Initialize the field for the ID of the thread which is waiting
521 for us. This is a self-reference in case the thread is created
522 detached. */
523 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
525 /* The debug events are inherited from the parent. */
526 pd->eventbuf = self->eventbuf;
529 /* Copy the parent's scheduling parameters. The flags will say what
530 is valid and what is not. */
531 pd->schedpolicy = self->schedpolicy;
532 pd->schedparam = self->schedparam;
534 /* Copy the stack guard canary. */
535 #ifdef THREAD_COPY_STACK_GUARD
536 THREAD_COPY_STACK_GUARD (pd);
537 #endif
539 /* Copy the pointer guard value. */
540 #ifdef THREAD_COPY_POINTER_GUARD
541 THREAD_COPY_POINTER_GUARD (pd);
542 #endif
544 /* Determine scheduling parameters for the thread. */
545 if (__builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
546 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
548 INTERNAL_SYSCALL_DECL (scerr);
550 /* Use the scheduling parameters the user provided. */
551 if (iattr->flags & ATTR_FLAG_POLICY_SET)
552 pd->schedpolicy = iattr->schedpolicy;
553 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
555 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
556 pd->flags |= ATTR_FLAG_POLICY_SET;
559 if (iattr->flags & ATTR_FLAG_SCHED_SET)
560 memcpy (&pd->schedparam, &iattr->schedparam,
561 sizeof (struct sched_param));
562 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
564 INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
565 pd->flags |= ATTR_FLAG_SCHED_SET;
568 /* Check for valid priorities. */
569 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
570 iattr->schedpolicy);
571 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
572 iattr->schedpolicy);
573 if (pd->schedparam.sched_priority < minprio
574 || pd->schedparam.sched_priority > maxprio)
576 /* Perhaps a thread wants to change the IDs and if waiting
577 for this stillborn thread. */
578 if (__builtin_expect (atomic_exchange_acq (&pd->setxid_futex, 0)
579 == -2, 0))
580 lll_futex_wake (&pd->setxid_futex, 1, LLL_PRIVATE);
582 __deallocate_stack (pd);
584 retval = EINVAL;
585 goto out;
589 /* Pass the descriptor to the caller. */
590 *newthread = (pthread_t) pd;
592 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
594 /* Start the thread. */
595 retval = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
597 out:
598 if (__glibc_unlikely (free_cpuset))
599 free (default_attr.cpuset);
601 return retval;
603 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
606 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
608 __pthread_create_2_0 (newthread, attr, start_routine, arg)
609 pthread_t *newthread;
610 const pthread_attr_t *attr;
611 void *(*start_routine) (void *);
612 void *arg;
614 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
615 the old size and access to the new members might crash the program.
616 We convert the struct now. */
617 struct pthread_attr new_attr;
619 if (attr != NULL)
621 struct pthread_attr *iattr = (struct pthread_attr *) attr;
622 size_t ps = __getpagesize ();
624 /* Copy values from the user-provided attributes. */
625 new_attr.schedparam = iattr->schedparam;
626 new_attr.schedpolicy = iattr->schedpolicy;
627 new_attr.flags = iattr->flags;
629 /* Fill in default values for the fields not present in the old
630 implementation. */
631 new_attr.guardsize = ps;
632 new_attr.stackaddr = NULL;
633 new_attr.stacksize = 0;
634 new_attr.cpuset = NULL;
636 /* We will pass this value on to the real implementation. */
637 attr = (pthread_attr_t *) &new_attr;
640 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
642 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
643 GLIBC_2_0);
644 #endif
646 /* Information for libthread_db. */
648 #include "../nptl_db/db_info.c"
650 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
651 functions to be present as well. */
652 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
653 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_trylock)
654 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
656 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
657 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
659 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
660 PTHREAD_STATIC_FN_REQUIRE (pthread_key_delete)
661 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
662 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)