NPTL: Clean up gratuitous Linuxism in libpthread.so entry point.
[glibc.git] / nptl / pthread_create.c
blob0055634cd3706fffa60e9181845368f9c6aa3b4c
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 #ifdef SIGCANCEL
267 /* If the parent was running cancellation handlers while creating
268 the thread the new thread inherited the signal mask. Reset the
269 cancellation signal mask. */
270 if (__glibc_unlikely (pd->parent_cancelhandling & CANCELING_BITMASK))
272 INTERNAL_SYSCALL_DECL (err);
273 sigset_t mask;
274 __sigemptyset (&mask);
275 __sigaddset (&mask, SIGCANCEL);
276 (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &mask,
277 NULL, _NSIG / 8);
279 #endif
281 /* This is where the try/finally block should be created. For
282 compilers without that support we do use setjmp. */
283 struct pthread_unwind_buf unwind_buf;
285 /* No previous handlers. */
286 unwind_buf.priv.data.prev = NULL;
287 unwind_buf.priv.data.cleanup = NULL;
289 int not_first_call;
290 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
291 if (__glibc_likely (! not_first_call))
293 /* Store the new cleanup handler info. */
294 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
296 if (__glibc_unlikely (pd->stopped_start))
298 int oldtype = CANCEL_ASYNC ();
300 /* Get the lock the parent locked to force synchronization. */
301 lll_lock (pd->lock, LLL_PRIVATE);
302 /* And give it up right away. */
303 lll_unlock (pd->lock, LLL_PRIVATE);
305 CANCEL_RESET (oldtype);
308 LIBC_PROBE (pthread_start, 3, (pthread_t) pd, pd->start_routine, pd->arg);
310 /* Run the code the user provided. */
311 #ifdef CALL_THREAD_FCT
312 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
313 #else
314 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
315 #endif
318 /* Call destructors for the thread_local TLS variables. */
319 #ifndef SHARED
320 if (&__call_tls_dtors != NULL)
321 #endif
322 __call_tls_dtors ();
324 /* Run the destructor for the thread-local data. */
325 __nptl_deallocate_tsd ();
327 /* Clean up any state libc stored in thread-local variables. */
328 __libc_thread_freeres ();
330 /* If this is the last thread we terminate the process now. We
331 do not notify the debugger, it might just irritate it if there
332 is no thread left. */
333 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads)))
334 /* This was the last thread. */
335 exit (0);
337 /* Report the death of the thread if this is wanted. */
338 if (__glibc_unlikely (pd->report_events))
340 /* See whether TD_DEATH is in any of the mask. */
341 const int idx = __td_eventword (TD_DEATH);
342 const uint32_t mask = __td_eventmask (TD_DEATH);
344 if ((mask & (__nptl_threads_events.event_bits[idx]
345 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
347 /* Yep, we have to signal the death. Add the descriptor to
348 the list but only if it is not already on it. */
349 if (pd->nextevent == NULL)
351 pd->eventbuf.eventnum = TD_DEATH;
352 pd->eventbuf.eventdata = pd;
355 pd->nextevent = __nptl_last_event;
356 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
357 pd, pd->nextevent));
360 /* Now call the function to signal the event. */
361 __nptl_death_event ();
365 /* The thread is exiting now. Don't set this bit until after we've hit
366 the event-reporting breakpoint, so that td_thr_get_info on us while at
367 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
368 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
370 #ifndef __ASSUME_SET_ROBUST_LIST
371 /* If this thread has any robust mutexes locked, handle them now. */
372 # ifdef __PTHREAD_MUTEX_HAVE_PREV
373 void *robust = pd->robust_head.list;
374 # else
375 __pthread_slist_t *robust = pd->robust_list.__next;
376 # endif
377 /* We let the kernel do the notification if it is able to do so.
378 If we have to do it here there for sure are no PI mutexes involved
379 since the kernel support for them is even more recent. */
380 if (__set_robust_list_avail < 0
381 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
385 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
386 ((char *) robust - offsetof (struct __pthread_mutex_s,
387 __list.__next));
388 robust = *((void **) robust);
390 # ifdef __PTHREAD_MUTEX_HAVE_PREV
391 this->__list.__prev = NULL;
392 # endif
393 this->__list.__next = NULL;
395 atomic_or (&this->__lock, FUTEX_OWNER_DIED);
396 lll_futex_wake (this->__lock, 1, /* XYZ */ LLL_SHARED);
398 while (robust != (void *) &pd->robust_head);
400 #endif
402 /* Mark the memory of the stack as usable to the kernel. We free
403 everything except for the space used for the TCB itself. */
404 size_t pagesize_m1 = __getpagesize () - 1;
405 #ifdef _STACK_GROWS_DOWN
406 char *sp = CURRENT_STACK_FRAME;
407 size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
408 #else
409 # error "to do"
410 #endif
411 assert (freesize < pd->stackblock_size);
412 if (freesize > PTHREAD_STACK_MIN)
413 __madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
415 /* If the thread is detached free the TCB. */
416 if (IS_DETACHED (pd))
417 /* Free the TCB. */
418 __free_tcb (pd);
419 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
421 /* Some other thread might call any of the setXid functions and expect
422 us to reply. In this case wait until we did that. */
424 lll_futex_wait (&pd->setxid_futex, 0, LLL_PRIVATE);
425 while (pd->cancelhandling & SETXID_BITMASK);
427 /* Reset the value so that the stack can be reused. */
428 pd->setxid_futex = 0;
431 /* We cannot call '_exit' here. '_exit' will terminate the process.
433 The 'exit' implementation in the kernel will signal when the
434 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
435 flag. The 'tid' field in the TCB will be set to zero.
437 The exit code is zero since in case all threads exit by calling
438 'pthread_exit' the exit status must be 0 (zero). */
439 __exit_thread ();
441 /* NOTREACHED */
442 return 0;
447 __pthread_create_2_1 (newthread, attr, start_routine, arg)
448 pthread_t *newthread;
449 const pthread_attr_t *attr;
450 void *(*start_routine) (void *);
451 void *arg;
453 STACK_VARIABLES;
455 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
456 struct pthread_attr default_attr;
457 bool free_cpuset = false;
458 if (iattr == NULL)
460 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
461 default_attr = __default_pthread_attr;
462 size_t cpusetsize = default_attr.cpusetsize;
463 if (cpusetsize > 0)
465 cpu_set_t *cpuset;
466 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
467 cpuset = __alloca (cpusetsize);
468 else
470 cpuset = malloc (cpusetsize);
471 if (cpuset == NULL)
473 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
474 return ENOMEM;
476 free_cpuset = true;
478 memcpy (cpuset, default_attr.cpuset, cpusetsize);
479 default_attr.cpuset = cpuset;
481 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
482 iattr = &default_attr;
485 struct pthread *pd = NULL;
486 int err = ALLOCATE_STACK (iattr, &pd);
487 int retval = 0;
489 if (__glibc_unlikely (err != 0))
490 /* Something went wrong. Maybe a parameter of the attributes is
491 invalid or we could not allocate memory. Note we have to
492 translate error codes. */
494 retval = err == ENOMEM ? EAGAIN : err;
495 goto out;
499 /* Initialize the TCB. All initializations with zero should be
500 performed in 'get_cached_stack'. This way we avoid doing this if
501 the stack freshly allocated with 'mmap'. */
503 #if TLS_TCB_AT_TP
504 /* Reference to the TCB itself. */
505 pd->header.self = pd;
507 /* Self-reference for TLS. */
508 pd->header.tcb = pd;
509 #endif
511 /* Store the address of the start routine and the parameter. Since
512 we do not start the function directly the stillborn thread will
513 get the information from its thread descriptor. */
514 pd->start_routine = start_routine;
515 pd->arg = arg;
517 /* Copy the thread attribute flags. */
518 struct pthread *self = THREAD_SELF;
519 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
520 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
522 /* Initialize the field for the ID of the thread which is waiting
523 for us. This is a self-reference in case the thread is created
524 detached. */
525 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
527 /* The debug events are inherited from the parent. */
528 pd->eventbuf = self->eventbuf;
531 /* Copy the parent's scheduling parameters. The flags will say what
532 is valid and what is not. */
533 pd->schedpolicy = self->schedpolicy;
534 pd->schedparam = self->schedparam;
536 /* Copy the stack guard canary. */
537 #ifdef THREAD_COPY_STACK_GUARD
538 THREAD_COPY_STACK_GUARD (pd);
539 #endif
541 /* Copy the pointer guard value. */
542 #ifdef THREAD_COPY_POINTER_GUARD
543 THREAD_COPY_POINTER_GUARD (pd);
544 #endif
546 /* Determine scheduling parameters for the thread. */
547 if (__builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
548 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
550 INTERNAL_SYSCALL_DECL (scerr);
552 /* Use the scheduling parameters the user provided. */
553 if (iattr->flags & ATTR_FLAG_POLICY_SET)
554 pd->schedpolicy = iattr->schedpolicy;
555 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
557 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
558 pd->flags |= ATTR_FLAG_POLICY_SET;
561 if (iattr->flags & ATTR_FLAG_SCHED_SET)
562 memcpy (&pd->schedparam, &iattr->schedparam,
563 sizeof (struct sched_param));
564 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
566 INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
567 pd->flags |= ATTR_FLAG_SCHED_SET;
570 /* Check for valid priorities. */
571 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
572 iattr->schedpolicy);
573 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
574 iattr->schedpolicy);
575 if (pd->schedparam.sched_priority < minprio
576 || pd->schedparam.sched_priority > maxprio)
578 /* Perhaps a thread wants to change the IDs and if waiting
579 for this stillborn thread. */
580 if (__builtin_expect (atomic_exchange_acq (&pd->setxid_futex, 0)
581 == -2, 0))
582 lll_futex_wake (&pd->setxid_futex, 1, LLL_PRIVATE);
584 __deallocate_stack (pd);
586 retval = EINVAL;
587 goto out;
591 /* Pass the descriptor to the caller. */
592 *newthread = (pthread_t) pd;
594 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
596 /* Start the thread. */
597 retval = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
599 out:
600 if (__glibc_unlikely (free_cpuset))
601 free (default_attr.cpuset);
603 return retval;
605 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
608 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
610 __pthread_create_2_0 (newthread, attr, start_routine, arg)
611 pthread_t *newthread;
612 const pthread_attr_t *attr;
613 void *(*start_routine) (void *);
614 void *arg;
616 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
617 the old size and access to the new members might crash the program.
618 We convert the struct now. */
619 struct pthread_attr new_attr;
621 if (attr != NULL)
623 struct pthread_attr *iattr = (struct pthread_attr *) attr;
624 size_t ps = __getpagesize ();
626 /* Copy values from the user-provided attributes. */
627 new_attr.schedparam = iattr->schedparam;
628 new_attr.schedpolicy = iattr->schedpolicy;
629 new_attr.flags = iattr->flags;
631 /* Fill in default values for the fields not present in the old
632 implementation. */
633 new_attr.guardsize = ps;
634 new_attr.stackaddr = NULL;
635 new_attr.stacksize = 0;
636 new_attr.cpuset = NULL;
638 /* We will pass this value on to the real implementation. */
639 attr = (pthread_attr_t *) &new_attr;
642 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
644 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
645 GLIBC_2_0);
646 #endif
648 /* Information for libthread_db. */
650 #include "../nptl_db/db_info.c"
652 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
653 functions to be present as well. */
654 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
655 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_trylock)
656 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
658 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
659 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
661 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
662 PTHREAD_STATIC_FN_REQUIRE (pthread_key_delete)
663 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
664 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)