x86: Rename __glibc_reserved1 to feature_1 in tcbhead_t [BZ #22563]
[glibc.git] / nptl / pthread_create.c
blob5f5a007b7f048f7b2a9c4dad9f357ff39957379a
1 /* Copyright (C) 2002-2018 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>
33 #include <default-sched.h>
34 #include <futex-internal.h>
35 #include <tls-setup.h>
36 #include "libioP.h"
38 #include <shlib-compat.h>
40 #include <stap-probe.h>
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 /* CONCURRENCY NOTES:
61 Understanding who is the owner of the 'struct pthread' or 'PD'
62 (refers to the value of the 'struct pthread *pd' function argument)
63 is critically important in determining exactly which operations are
64 allowed and which are not and when, particularly when it comes to the
65 implementation of pthread_create, pthread_join, pthread_detach, and
66 other functions which all operate on PD.
68 The owner of PD is responsible for freeing the final resources
69 associated with PD, and may examine the memory underlying PD at any
70 point in time until it frees it back to the OS or to reuse by the
71 runtime.
73 The thread which calls pthread_create is called the creating thread.
74 The creating thread begins as the owner of PD.
76 During startup the new thread may examine PD in coordination with the
77 owner thread (which may be itself).
79 The four cases of ownership transfer are:
81 (1) Ownership of PD is released to the process (all threads may use it)
82 after the new thread starts in a joinable state
83 i.e. pthread_create returns a usable pthread_t.
85 (2) Ownership of PD is released to the new thread starting in a detached
86 state.
88 (3) Ownership of PD is dynamically released to a running thread via
89 pthread_detach.
91 (4) Ownership of PD is acquired by the thread which calls pthread_join.
93 Implementation notes:
95 The PD->stopped_start and thread_ran variables are used to determine
96 exactly which of the four ownership states we are in and therefore
97 what actions can be taken. For example after (2) we cannot read or
98 write from PD anymore since the thread may no longer exist and the
99 memory may be unmapped.
101 It is important to point out that PD->lock is being used both
102 similar to a one-shot semaphore and subsequently as a mutex. The
103 lock is taken in the parent to force the child to wait, and then the
104 child releases the lock. However, this semaphore-like effect is used
105 only for synchronizing the parent and child. After startup the lock
106 is used like a mutex to create a critical section during which a
107 single owner modifies the thread parameters.
109 The most complicated cases happen during thread startup:
111 (a) If the created thread is in a detached (PTHREAD_CREATE_DETACHED),
112 or joinable (default PTHREAD_CREATE_JOINABLE) state and
113 STOPPED_START is true, then the creating thread has ownership of
114 PD until the PD->lock is released by pthread_create. If any
115 errors occur we are in states (c), (d), or (e) below.
117 (b) If the created thread is in a detached state
118 (PTHREAD_CREATED_DETACHED), and STOPPED_START is false, then the
119 creating thread has ownership of PD until it invokes the OS
120 kernel's thread creation routine. If this routine returns
121 without error, then the created thread owns PD; otherwise, see
122 (c) and (e) below.
124 (c) If the detached thread setup failed and THREAD_RAN is true, then
125 the creating thread releases ownership to the new thread by
126 sending a cancellation signal. All threads set THREAD_RAN to
127 true as quickly as possible after returning from the OS kernel's
128 thread creation routine.
130 (d) If the joinable thread setup failed and THREAD_RAN is true, then
131 then the creating thread retains ownership of PD and must cleanup
132 state. Ownership cannot be released to the process via the
133 return of pthread_create since a non-zero result entails PD is
134 undefined and therefore cannot be joined to free the resources.
135 We privately call pthread_join on the thread to finish handling
136 the resource shutdown (Or at least we should, see bug 19511).
138 (e) If the thread creation failed and THREAD_RAN is false, then the
139 creating thread retains ownership of PD and must cleanup state.
140 No waiting for the new thread is required because it never
141 started.
143 The nptl_db interface:
145 The interface with nptl_db requires that we enqueue PD into a linked
146 list and then call a function which the debugger will trap. The PD
147 will then be dequeued and control returned to the thread. The caller
148 at the time must have ownership of PD and such ownership remains
149 after control returns to thread. The enqueued PD is removed from the
150 linked list by the nptl_db callback td_thr_event_getmsg. The debugger
151 must ensure that the thread does not resume execution, otherwise
152 ownership of PD may be lost and examining PD will not be possible.
154 Note that the GNU Debugger as of (December 10th 2015) commit
155 c2c2a31fdb228d41ce3db62b268efea04bd39c18 no longer uses
156 td_thr_event_getmsg and several other related nptl_db interfaces. The
157 principal reason for this is that nptl_db does not support non-stop
158 mode where other threads can run concurrently and modify runtime
159 structures currently in use by the debugger and the nptl_db
160 interface.
162 Axioms:
164 * The create_thread function can never set stopped_start to false.
165 * The created thread can read stopped_start but never write to it.
166 * The variable thread_ran is set some time after the OS thread
167 creation routine returns, how much time after the thread is created
168 is unspecified, but it should be as quickly as possible.
172 /* CREATE THREAD NOTES:
174 createthread.c defines the create_thread function, and two macros:
175 START_THREAD_DEFN and START_THREAD_SELF (see below).
177 create_thread must initialize PD->stopped_start. It should be true
178 if the STOPPED_START parameter is true, or if create_thread needs the
179 new thread to synchronize at startup for some other implementation
180 reason. If STOPPED_START will be true, then create_thread is obliged
181 to lock PD->lock before starting the thread. Then pthread_create
182 unlocks PD->lock which synchronizes-with START_THREAD_DEFN in the
183 child thread which does an acquire/release of PD->lock as the last
184 action before calling the user entry point. The goal of all of this
185 is to ensure that the required initial thread attributes are applied
186 (by the creating thread) before the new thread runs user code. Note
187 that the the functions pthread_getschedparam, pthread_setschedparam,
188 pthread_setschedprio, __pthread_tpp_change_priority, and
189 __pthread_current_priority reuse the same lock, PD->lock, for a
190 similar purpose e.g. synchronizing the setting of similar thread
191 attributes. These functions are never called before the thread is
192 created, so don't participate in startup syncronization, but given
193 that the lock is present already and in the unlocked state, reusing
194 it saves space.
196 The return value is zero for success or an errno code for failure.
197 If the return value is ENOMEM, that will be translated to EAGAIN,
198 so create_thread need not do that. On failure, *THREAD_RAN should
199 be set to true iff the thread actually started up and then got
200 canceled before calling user code (*PD->start_routine). */
201 static int create_thread (struct pthread *pd, const struct pthread_attr *attr,
202 bool *stopped_start, STACK_VARIABLES_PARMS,
203 bool *thread_ran);
205 #include <createthread.c>
208 struct pthread *
209 __find_in_stack_list (struct pthread *pd)
211 list_t *entry;
212 struct pthread *result = NULL;
214 lll_lock (stack_cache_lock, LLL_PRIVATE);
216 list_for_each (entry, &stack_used)
218 struct pthread *curp;
220 curp = list_entry (entry, struct pthread, list);
221 if (curp == pd)
223 result = curp;
224 break;
228 if (result == NULL)
229 list_for_each (entry, &__stack_user)
231 struct pthread *curp;
233 curp = list_entry (entry, struct pthread, list);
234 if (curp == pd)
236 result = curp;
237 break;
241 lll_unlock (stack_cache_lock, LLL_PRIVATE);
243 return result;
247 /* Deallocate POSIX thread-local-storage. */
248 void
249 attribute_hidden
250 __nptl_deallocate_tsd (void)
252 struct pthread *self = THREAD_SELF;
254 /* Maybe no data was ever allocated. This happens often so we have
255 a flag for this. */
256 if (THREAD_GETMEM (self, specific_used))
258 size_t round;
259 size_t cnt;
261 round = 0;
264 size_t idx;
266 /* So far no new nonzero data entry. */
267 THREAD_SETMEM (self, specific_used, false);
269 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
271 struct pthread_key_data *level2;
273 level2 = THREAD_GETMEM_NC (self, specific, cnt);
275 if (level2 != NULL)
277 size_t inner;
279 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
280 ++inner, ++idx)
282 void *data = level2[inner].data;
284 if (data != NULL)
286 /* Always clear the data. */
287 level2[inner].data = NULL;
289 /* Make sure the data corresponds to a valid
290 key. This test fails if the key was
291 deallocated and also if it was
292 re-allocated. It is the user's
293 responsibility to free the memory in this
294 case. */
295 if (level2[inner].seq
296 == __pthread_keys[idx].seq
297 /* It is not necessary to register a destructor
298 function. */
299 && __pthread_keys[idx].destr != NULL)
300 /* Call the user-provided destructor. */
301 __pthread_keys[idx].destr (data);
305 else
306 idx += PTHREAD_KEY_1STLEVEL_SIZE;
309 if (THREAD_GETMEM (self, specific_used) == 0)
310 /* No data has been modified. */
311 goto just_free;
313 /* We only repeat the process a fixed number of times. */
314 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
316 /* Just clear the memory of the first block for reuse. */
317 memset (&THREAD_SELF->specific_1stblock, '\0',
318 sizeof (self->specific_1stblock));
320 just_free:
321 /* Free the memory for the other blocks. */
322 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
324 struct pthread_key_data *level2;
326 level2 = THREAD_GETMEM_NC (self, specific, cnt);
327 if (level2 != NULL)
329 /* The first block is allocated as part of the thread
330 descriptor. */
331 free (level2);
332 THREAD_SETMEM_NC (self, specific, cnt, NULL);
336 THREAD_SETMEM (self, specific_used, false);
341 /* Deallocate a thread's stack after optionally making sure the thread
342 descriptor is still valid. */
343 void
344 __free_tcb (struct pthread *pd)
346 /* The thread is exiting now. */
347 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
348 TERMINATED_BIT) == 0, 1))
350 /* Remove the descriptor from the list. */
351 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
352 /* Something is really wrong. The descriptor for a still
353 running thread is gone. */
354 abort ();
356 /* Free TPP data. */
357 if (__glibc_unlikely (pd->tpp != NULL))
359 struct priority_protection_data *tpp = pd->tpp;
361 pd->tpp = NULL;
362 free (tpp);
365 /* Queue the stack memory block for reuse and exit the process. The
366 kernel will signal via writing to the address returned by
367 QUEUE-STACK when the stack is available. */
368 __deallocate_stack (pd);
373 /* Local function to start thread and handle cleanup.
374 createthread.c defines the macro START_THREAD_DEFN to the
375 declaration that its create_thread function will refer to, and
376 START_THREAD_SELF to the expression to optimally deliver the new
377 thread's THREAD_SELF value. */
378 START_THREAD_DEFN
380 struct pthread *pd = START_THREAD_SELF;
382 #if HP_TIMING_AVAIL
383 /* Remember the time when the thread was started. */
384 hp_timing_t now;
385 HP_TIMING_NOW (now);
386 THREAD_SETMEM (pd, cpuclock_offset, now);
387 #endif
389 /* Initialize resolver state pointer. */
390 __resp = &pd->res;
392 /* Initialize pointers to locale data. */
393 __ctype_init ();
395 /* Allow setxid from now onwards. */
396 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0) == -2))
397 futex_wake (&pd->setxid_futex, 1, FUTEX_PRIVATE);
399 #ifdef __NR_set_robust_list
400 # ifndef __ASSUME_SET_ROBUST_LIST
401 if (__set_robust_list_avail >= 0)
402 # endif
404 INTERNAL_SYSCALL_DECL (err);
405 /* This call should never fail because the initial call in init.c
406 succeeded. */
407 INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
408 sizeof (struct robust_list_head));
410 #endif
412 #ifdef SIGCANCEL
413 /* If the parent was running cancellation handlers while creating
414 the thread the new thread inherited the signal mask. Reset the
415 cancellation signal mask. */
416 if (__glibc_unlikely (pd->parent_cancelhandling & CANCELING_BITMASK))
418 INTERNAL_SYSCALL_DECL (err);
419 sigset_t mask;
420 __sigemptyset (&mask);
421 __sigaddset (&mask, SIGCANCEL);
422 (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &mask,
423 NULL, _NSIG / 8);
425 #endif
427 /* This is where the try/finally block should be created. For
428 compilers without that support we do use setjmp. */
429 struct pthread_unwind_buf unwind_buf;
431 int not_first_call;
432 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
434 /* No previous handlers. NB: This must be done after setjmp since the
435 private space in the unwind jump buffer may overlap space used by
436 setjmp to store extra architecture-specific information which is
437 never used by the cancellation-specific __libc_unwind_longjmp.
439 The private space is allowed to overlap because the unwinder never
440 has to return through any of the jumped-to call frames, and thus
441 only a minimum amount of saved data need be stored, and for example,
442 need not include the process signal mask information. This is all
443 an optimization to reduce stack usage when pushing cancellation
444 handlers. */
445 unwind_buf.priv.data.prev = NULL;
446 unwind_buf.priv.data.cleanup = NULL;
448 if (__glibc_likely (! not_first_call))
450 /* Store the new cleanup handler info. */
451 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
453 /* We are either in (a) or (b), and in either case we either own
454 PD already (2) or are about to own PD (1), and so our only
455 restriction would be that we can't free PD until we know we
456 have ownership (see CONCURRENCY NOTES above). */
457 if (__glibc_unlikely (pd->stopped_start))
459 int oldtype = CANCEL_ASYNC ();
461 /* Get the lock the parent locked to force synchronization. */
462 lll_lock (pd->lock, LLL_PRIVATE);
464 /* We have ownership of PD now. */
466 /* And give it up right away. */
467 lll_unlock (pd->lock, LLL_PRIVATE);
469 CANCEL_RESET (oldtype);
472 LIBC_PROBE (pthread_start, 3, (pthread_t) pd, pd->start_routine, pd->arg);
474 /* Run the code the user provided. */
475 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
478 /* Call destructors for the thread_local TLS variables. */
479 #ifndef SHARED
480 if (&__call_tls_dtors != NULL)
481 #endif
482 __call_tls_dtors ();
484 /* Run the destructor for the thread-local data. */
485 __nptl_deallocate_tsd ();
487 /* Clean up any state libc stored in thread-local variables. */
488 __libc_thread_freeres ();
490 /* If this is the last thread we terminate the process now. We
491 do not notify the debugger, it might just irritate it if there
492 is no thread left. */
493 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads)))
494 /* This was the last thread. */
495 exit (0);
497 /* Report the death of the thread if this is wanted. */
498 if (__glibc_unlikely (pd->report_events))
500 /* See whether TD_DEATH is in any of the mask. */
501 const int idx = __td_eventword (TD_DEATH);
502 const uint32_t mask = __td_eventmask (TD_DEATH);
504 if ((mask & (__nptl_threads_events.event_bits[idx]
505 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
507 /* Yep, we have to signal the death. Add the descriptor to
508 the list but only if it is not already on it. */
509 if (pd->nextevent == NULL)
511 pd->eventbuf.eventnum = TD_DEATH;
512 pd->eventbuf.eventdata = pd;
515 pd->nextevent = __nptl_last_event;
516 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
517 pd, pd->nextevent));
520 /* Now call the function which signals the event. See
521 CONCURRENCY NOTES for the nptl_db interface comments. */
522 __nptl_death_event ();
526 /* The thread is exiting now. Don't set this bit until after we've hit
527 the event-reporting breakpoint, so that td_thr_get_info on us while at
528 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
529 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
531 #ifndef __ASSUME_SET_ROBUST_LIST
532 /* If this thread has any robust mutexes locked, handle them now. */
533 # if __PTHREAD_MUTEX_HAVE_PREV
534 void *robust = pd->robust_head.list;
535 # else
536 __pthread_slist_t *robust = pd->robust_list.__next;
537 # endif
538 /* We let the kernel do the notification if it is able to do so.
539 If we have to do it here there for sure are no PI mutexes involved
540 since the kernel support for them is even more recent. */
541 if (__set_robust_list_avail < 0
542 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
546 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
547 ((char *) robust - offsetof (struct __pthread_mutex_s,
548 __list.__next));
549 robust = *((void **) robust);
551 # if __PTHREAD_MUTEX_HAVE_PREV
552 this->__list.__prev = NULL;
553 # endif
554 this->__list.__next = NULL;
556 atomic_or (&this->__lock, FUTEX_OWNER_DIED);
557 futex_wake ((unsigned int *) &this->__lock, 1,
558 /* XYZ */ FUTEX_SHARED);
560 while (robust != (void *) &pd->robust_head);
562 #endif
564 advise_stack_range (pd->stackblock, pd->stackblock_size, (uintptr_t) pd,
565 pd->guardsize);
567 /* If the thread is detached free the TCB. */
568 if (IS_DETACHED (pd))
569 /* Free the TCB. */
570 __free_tcb (pd);
571 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
573 /* Some other thread might call any of the setXid functions and expect
574 us to reply. In this case wait until we did that. */
576 /* XXX This differs from the typical futex_wait_simple pattern in that
577 the futex_wait condition (setxid_futex) is different from the
578 condition used in the surrounding loop (cancelhandling). We need
579 to check and document why this is correct. */
580 futex_wait_simple (&pd->setxid_futex, 0, FUTEX_PRIVATE);
581 while (pd->cancelhandling & SETXID_BITMASK);
583 /* Reset the value so that the stack can be reused. */
584 pd->setxid_futex = 0;
587 /* We cannot call '_exit' here. '_exit' will terminate the process.
589 The 'exit' implementation in the kernel will signal when the
590 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
591 flag. The 'tid' field in the TCB will be set to zero.
593 The exit code is zero since in case all threads exit by calling
594 'pthread_exit' the exit status must be 0 (zero). */
595 __exit_thread ();
597 /* NOTREACHED */
601 /* Return true iff obliged to report TD_CREATE events. */
602 static bool
603 report_thread_creation (struct pthread *pd)
605 if (__glibc_unlikely (THREAD_GETMEM (THREAD_SELF, report_events)))
607 /* The parent thread is supposed to report events.
608 Check whether the TD_CREATE event is needed, too. */
609 const size_t idx = __td_eventword (TD_CREATE);
610 const uint32_t mask = __td_eventmask (TD_CREATE);
612 return ((mask & (__nptl_threads_events.event_bits[idx]
613 | pd->eventbuf.eventmask.event_bits[idx])) != 0);
615 return false;
620 __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
621 void *(*start_routine) (void *), void *arg)
623 STACK_VARIABLES;
625 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
626 struct pthread_attr default_attr;
627 bool free_cpuset = false;
628 if (iattr == NULL)
630 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
631 default_attr = __default_pthread_attr;
632 size_t cpusetsize = default_attr.cpusetsize;
633 if (cpusetsize > 0)
635 cpu_set_t *cpuset;
636 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
637 cpuset = __alloca (cpusetsize);
638 else
640 cpuset = malloc (cpusetsize);
641 if (cpuset == NULL)
643 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
644 return ENOMEM;
646 free_cpuset = true;
648 memcpy (cpuset, default_attr.cpuset, cpusetsize);
649 default_attr.cpuset = cpuset;
651 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
652 iattr = &default_attr;
655 struct pthread *pd = NULL;
656 int err = ALLOCATE_STACK (iattr, &pd);
657 int retval = 0;
659 if (__glibc_unlikely (err != 0))
660 /* Something went wrong. Maybe a parameter of the attributes is
661 invalid or we could not allocate memory. Note we have to
662 translate error codes. */
664 retval = err == ENOMEM ? EAGAIN : err;
665 goto out;
669 /* Initialize the TCB. All initializations with zero should be
670 performed in 'get_cached_stack'. This way we avoid doing this if
671 the stack freshly allocated with 'mmap'. */
673 #if TLS_TCB_AT_TP
674 /* Reference to the TCB itself. */
675 pd->header.self = pd;
677 /* Self-reference for TLS. */
678 pd->header.tcb = pd;
679 #endif
681 /* Store the address of the start routine and the parameter. Since
682 we do not start the function directly the stillborn thread will
683 get the information from its thread descriptor. */
684 pd->start_routine = start_routine;
685 pd->arg = arg;
687 /* Copy the thread attribute flags. */
688 struct pthread *self = THREAD_SELF;
689 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
690 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
692 /* Initialize the field for the ID of the thread which is waiting
693 for us. This is a self-reference in case the thread is created
694 detached. */
695 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
697 /* The debug events are inherited from the parent. */
698 pd->eventbuf = self->eventbuf;
701 /* Copy the parent's scheduling parameters. The flags will say what
702 is valid and what is not. */
703 pd->schedpolicy = self->schedpolicy;
704 pd->schedparam = self->schedparam;
706 /* Copy the stack guard canary. */
707 #ifdef THREAD_COPY_STACK_GUARD
708 THREAD_COPY_STACK_GUARD (pd);
709 #endif
711 /* Copy the pointer guard value. */
712 #ifdef THREAD_COPY_POINTER_GUARD
713 THREAD_COPY_POINTER_GUARD (pd);
714 #endif
716 /* Setup tcbhead. */
717 tls_setup_tcbhead (pd);
719 /* Verify the sysinfo bits were copied in allocate_stack if needed. */
720 #ifdef NEED_DL_SYSINFO
721 CHECK_THREAD_SYSINFO (pd);
722 #endif
724 /* Inform start_thread (above) about cancellation state that might
725 translate into inherited signal state. */
726 pd->parent_cancelhandling = THREAD_GETMEM (THREAD_SELF, cancelhandling);
728 /* Determine scheduling parameters for the thread. */
729 if (__builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
730 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
732 /* Use the scheduling parameters the user provided. */
733 if (iattr->flags & ATTR_FLAG_POLICY_SET)
735 pd->schedpolicy = iattr->schedpolicy;
736 pd->flags |= ATTR_FLAG_POLICY_SET;
738 if (iattr->flags & ATTR_FLAG_SCHED_SET)
740 /* The values were validated in pthread_attr_setschedparam. */
741 pd->schedparam = iattr->schedparam;
742 pd->flags |= ATTR_FLAG_SCHED_SET;
745 if ((pd->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
746 != (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
747 collect_default_sched (pd);
750 if (__glibc_unlikely (__nptl_nthreads == 1))
751 _IO_enable_locks ();
753 /* Pass the descriptor to the caller. */
754 *newthread = (pthread_t) pd;
756 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
758 /* One more thread. We cannot have the thread do this itself, since it
759 might exist but not have been scheduled yet by the time we've returned
760 and need to check the value to behave correctly. We must do it before
761 creating the thread, in case it does get scheduled first and then
762 might mistakenly think it was the only thread. In the failure case,
763 we momentarily store a false value; this doesn't matter because there
764 is no kosher thing a signal handler interrupting us right here can do
765 that cares whether the thread count is correct. */
766 atomic_increment (&__nptl_nthreads);
768 /* Our local value of stopped_start and thread_ran can be accessed at
769 any time. The PD->stopped_start may only be accessed if we have
770 ownership of PD (see CONCURRENCY NOTES above). */
771 bool stopped_start = false; bool thread_ran = false;
773 /* Start the thread. */
774 if (__glibc_unlikely (report_thread_creation (pd)))
776 stopped_start = true;
778 /* We always create the thread stopped at startup so we can
779 notify the debugger. */
780 retval = create_thread (pd, iattr, &stopped_start,
781 STACK_VARIABLES_ARGS, &thread_ran);
782 if (retval == 0)
784 /* We retain ownership of PD until (a) (see CONCURRENCY NOTES
785 above). */
787 /* Assert stopped_start is true in both our local copy and the
788 PD copy. */
789 assert (stopped_start);
790 assert (pd->stopped_start);
792 /* Now fill in the information about the new thread in
793 the newly created thread's data structure. We cannot let
794 the new thread do this since we don't know whether it was
795 already scheduled when we send the event. */
796 pd->eventbuf.eventnum = TD_CREATE;
797 pd->eventbuf.eventdata = pd;
799 /* Enqueue the descriptor. */
801 pd->nextevent = __nptl_last_event;
802 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
803 pd, pd->nextevent)
804 != 0);
806 /* Now call the function which signals the event. See
807 CONCURRENCY NOTES for the nptl_db interface comments. */
808 __nptl_create_event ();
811 else
812 retval = create_thread (pd, iattr, &stopped_start,
813 STACK_VARIABLES_ARGS, &thread_ran);
815 if (__glibc_unlikely (retval != 0))
817 if (thread_ran)
818 /* State (c) or (d) and we may not have PD ownership (see
819 CONCURRENCY NOTES above). We can assert that STOPPED_START
820 must have been true because thread creation didn't fail, but
821 thread attribute setting did. */
822 /* See bug 19511 which explains why doing nothing here is a
823 resource leak for a joinable thread. */
824 assert (stopped_start);
825 else
827 /* State (e) and we have ownership of PD (see CONCURRENCY
828 NOTES above). */
830 /* Oops, we lied for a second. */
831 atomic_decrement (&__nptl_nthreads);
833 /* Perhaps a thread wants to change the IDs and is waiting for this
834 stillborn thread. */
835 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0)
836 == -2))
837 futex_wake (&pd->setxid_futex, 1, FUTEX_PRIVATE);
839 /* Free the resources. */
840 __deallocate_stack (pd);
843 /* We have to translate error codes. */
844 if (retval == ENOMEM)
845 retval = EAGAIN;
847 else
849 /* We don't know if we have PD ownership. Once we check the local
850 stopped_start we'll know if we're in state (a) or (b) (see
851 CONCURRENCY NOTES above). */
852 if (stopped_start)
853 /* State (a), we own PD. The thread blocked on this lock either
854 because we're doing TD_CREATE event reporting, or for some
855 other reason that create_thread chose. Now let it run
856 free. */
857 lll_unlock (pd->lock, LLL_PRIVATE);
859 /* We now have for sure more than one thread. The main thread might
860 not yet have the flag set. No need to set the global variable
861 again if this is what we use. */
862 THREAD_SETMEM (THREAD_SELF, header.multiple_threads, 1);
865 out:
866 if (__glibc_unlikely (free_cpuset))
867 free (default_attr.cpuset);
869 return retval;
871 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
874 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
876 __pthread_create_2_0 (pthread_t *newthread, const pthread_attr_t *attr,
877 void *(*start_routine) (void *), void *arg)
879 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
880 the old size and access to the new members might crash the program.
881 We convert the struct now. */
882 struct pthread_attr new_attr;
884 if (attr != NULL)
886 struct pthread_attr *iattr = (struct pthread_attr *) attr;
887 size_t ps = __getpagesize ();
889 /* Copy values from the user-provided attributes. */
890 new_attr.schedparam = iattr->schedparam;
891 new_attr.schedpolicy = iattr->schedpolicy;
892 new_attr.flags = iattr->flags;
894 /* Fill in default values for the fields not present in the old
895 implementation. */
896 new_attr.guardsize = ps;
897 new_attr.stackaddr = NULL;
898 new_attr.stacksize = 0;
899 new_attr.cpuset = NULL;
901 /* We will pass this value on to the real implementation. */
902 attr = (pthread_attr_t *) &new_attr;
905 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
907 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
908 GLIBC_2_0);
909 #endif
911 /* Information for libthread_db. */
913 #include "../nptl_db/db_info.c"
915 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
916 functions to be present as well. */
917 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_lock)
918 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_trylock)
919 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_unlock)
921 PTHREAD_STATIC_FN_REQUIRE (__pthread_once)
922 PTHREAD_STATIC_FN_REQUIRE (__pthread_cancel)
924 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_create)
925 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_delete)
926 PTHREAD_STATIC_FN_REQUIRE (__pthread_setspecific)
927 PTHREAD_STATIC_FN_REQUIRE (__pthread_getspecific)