Fix Wundef warning for HAVE_STRFTIME
[glibc.git] / nptl / pthread_create.c
blob29971637337b579aee0fbd49bda07e50a06b88c6
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 lll_robust_dead (this->__lock, /* XYZ */ LLL_SHARED);
395 while (robust != (void *) &pd->robust_head);
397 #endif
399 /* Mark the memory of the stack as usable to the kernel. We free
400 everything except for the space used for the TCB itself. */
401 size_t pagesize_m1 = __getpagesize () - 1;
402 #ifdef _STACK_GROWS_DOWN
403 char *sp = CURRENT_STACK_FRAME;
404 size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
405 #else
406 # error "to do"
407 #endif
408 assert (freesize < pd->stackblock_size);
409 if (freesize > PTHREAD_STACK_MIN)
410 __madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
412 /* If the thread is detached free the TCB. */
413 if (IS_DETACHED (pd))
414 /* Free the TCB. */
415 __free_tcb (pd);
416 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
418 /* Some other thread might call any of the setXid functions and expect
419 us to reply. In this case wait until we did that. */
421 lll_futex_wait (&pd->setxid_futex, 0, LLL_PRIVATE);
422 while (pd->cancelhandling & SETXID_BITMASK);
424 /* Reset the value so that the stack can be reused. */
425 pd->setxid_futex = 0;
428 /* We cannot call '_exit' here. '_exit' will terminate the process.
430 The 'exit' implementation in the kernel will signal when the
431 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
432 flag. The 'tid' field in the TCB will be set to zero.
434 The exit code is zero since in case all threads exit by calling
435 'pthread_exit' the exit status must be 0 (zero). */
436 __exit_thread ();
438 /* NOTREACHED */
439 return 0;
444 __pthread_create_2_1 (newthread, attr, start_routine, arg)
445 pthread_t *newthread;
446 const pthread_attr_t *attr;
447 void *(*start_routine) (void *);
448 void *arg;
450 STACK_VARIABLES;
452 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
453 struct pthread_attr default_attr;
454 bool free_cpuset = false;
455 if (iattr == NULL)
457 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
458 default_attr = __default_pthread_attr;
459 size_t cpusetsize = default_attr.cpusetsize;
460 if (cpusetsize > 0)
462 cpu_set_t *cpuset;
463 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
464 cpuset = __alloca (cpusetsize);
465 else
467 cpuset = malloc (cpusetsize);
468 if (cpuset == NULL)
470 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
471 return ENOMEM;
473 free_cpuset = true;
475 memcpy (cpuset, default_attr.cpuset, cpusetsize);
476 default_attr.cpuset = cpuset;
478 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
479 iattr = &default_attr;
482 struct pthread *pd = NULL;
483 int err = ALLOCATE_STACK (iattr, &pd);
484 int retval = 0;
486 if (__glibc_unlikely (err != 0))
487 /* Something went wrong. Maybe a parameter of the attributes is
488 invalid or we could not allocate memory. Note we have to
489 translate error codes. */
491 retval = err == ENOMEM ? EAGAIN : err;
492 goto out;
496 /* Initialize the TCB. All initializations with zero should be
497 performed in 'get_cached_stack'. This way we avoid doing this if
498 the stack freshly allocated with 'mmap'. */
500 #if TLS_TCB_AT_TP
501 /* Reference to the TCB itself. */
502 pd->header.self = pd;
504 /* Self-reference for TLS. */
505 pd->header.tcb = pd;
506 #endif
508 /* Store the address of the start routine and the parameter. Since
509 we do not start the function directly the stillborn thread will
510 get the information from its thread descriptor. */
511 pd->start_routine = start_routine;
512 pd->arg = arg;
514 /* Copy the thread attribute flags. */
515 struct pthread *self = THREAD_SELF;
516 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
517 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
519 /* Initialize the field for the ID of the thread which is waiting
520 for us. This is a self-reference in case the thread is created
521 detached. */
522 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
524 /* The debug events are inherited from the parent. */
525 pd->eventbuf = self->eventbuf;
528 /* Copy the parent's scheduling parameters. The flags will say what
529 is valid and what is not. */
530 pd->schedpolicy = self->schedpolicy;
531 pd->schedparam = self->schedparam;
533 /* Copy the stack guard canary. */
534 #ifdef THREAD_COPY_STACK_GUARD
535 THREAD_COPY_STACK_GUARD (pd);
536 #endif
538 /* Copy the pointer guard value. */
539 #ifdef THREAD_COPY_POINTER_GUARD
540 THREAD_COPY_POINTER_GUARD (pd);
541 #endif
543 /* Determine scheduling parameters for the thread. */
544 if (__builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
545 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
547 INTERNAL_SYSCALL_DECL (scerr);
549 /* Use the scheduling parameters the user provided. */
550 if (iattr->flags & ATTR_FLAG_POLICY_SET)
551 pd->schedpolicy = iattr->schedpolicy;
552 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
554 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
555 pd->flags |= ATTR_FLAG_POLICY_SET;
558 if (iattr->flags & ATTR_FLAG_SCHED_SET)
559 memcpy (&pd->schedparam, &iattr->schedparam,
560 sizeof (struct sched_param));
561 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
563 INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
564 pd->flags |= ATTR_FLAG_SCHED_SET;
567 /* Check for valid priorities. */
568 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
569 iattr->schedpolicy);
570 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
571 iattr->schedpolicy);
572 if (pd->schedparam.sched_priority < minprio
573 || pd->schedparam.sched_priority > maxprio)
575 /* Perhaps a thread wants to change the IDs and if waiting
576 for this stillborn thread. */
577 if (__builtin_expect (atomic_exchange_acq (&pd->setxid_futex, 0)
578 == -2, 0))
579 lll_futex_wake (&pd->setxid_futex, 1, LLL_PRIVATE);
581 __deallocate_stack (pd);
583 retval = EINVAL;
584 goto out;
588 /* Pass the descriptor to the caller. */
589 *newthread = (pthread_t) pd;
591 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
593 /* Start the thread. */
594 retval = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
596 out:
597 if (__glibc_unlikely (free_cpuset))
598 free (default_attr.cpuset);
600 return retval;
602 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
605 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
607 __pthread_create_2_0 (newthread, attr, start_routine, arg)
608 pthread_t *newthread;
609 const pthread_attr_t *attr;
610 void *(*start_routine) (void *);
611 void *arg;
613 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
614 the old size and access to the new members might crash the program.
615 We convert the struct now. */
616 struct pthread_attr new_attr;
618 if (attr != NULL)
620 struct pthread_attr *iattr = (struct pthread_attr *) attr;
621 size_t ps = __getpagesize ();
623 /* Copy values from the user-provided attributes. */
624 new_attr.schedparam = iattr->schedparam;
625 new_attr.schedpolicy = iattr->schedpolicy;
626 new_attr.flags = iattr->flags;
628 /* Fill in default values for the fields not present in the old
629 implementation. */
630 new_attr.guardsize = ps;
631 new_attr.stackaddr = NULL;
632 new_attr.stacksize = 0;
633 new_attr.cpuset = NULL;
635 /* We will pass this value on to the real implementation. */
636 attr = (pthread_attr_t *) &new_attr;
639 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
641 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
642 GLIBC_2_0);
643 #endif
645 /* Information for libthread_db. */
647 #include "../nptl_db/db_info.c"
649 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
650 functions to be present as well. */
651 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
652 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_trylock)
653 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
655 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
656 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
658 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
659 PTHREAD_STATIC_FN_REQUIRE (pthread_key_delete)
660 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
661 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)