S390: Move utf8-utf32-z9.c to multiarch folder and use s390_libc_ifunc_expr macro.
[glibc.git] / nptl / pthread_create.c
blobd0d74149d327241c85b3a3929ba2587a2065499a
1 /* Copyright (C) 2002-2017 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>
36 #include <shlib-compat.h>
38 #include <stap-probe.h>
41 /* Nozero if debugging mode is enabled. */
42 int __pthread_debug;
44 /* Globally enabled events. */
45 static td_thr_events_t __nptl_threads_events __attribute_used__;
47 /* Pointer to descriptor with the last event. */
48 static struct pthread *__nptl_last_event __attribute_used__;
50 /* Number of threads running. */
51 unsigned int __nptl_nthreads = 1;
54 /* Code to allocate and deallocate a stack. */
55 #include "allocatestack.c"
57 /* CONCURRENCY NOTES:
59 Understanding who is the owner of the 'struct pthread' or 'PD'
60 (refers to the value of the 'struct pthread *pd' function argument)
61 is critically important in determining exactly which operations are
62 allowed and which are not and when, particularly when it comes to the
63 implementation of pthread_create, pthread_join, pthread_detach, and
64 other functions which all operate on PD.
66 The owner of PD is responsible for freeing the final resources
67 associated with PD, and may examine the memory underlying PD at any
68 point in time until it frees it back to the OS or to reuse by the
69 runtime.
71 The thread which calls pthread_create is called the creating thread.
72 The creating thread begins as the owner of PD.
74 During startup the new thread may examine PD in coordination with the
75 owner thread (which may be itself).
77 The four cases of ownership transfer are:
79 (1) Ownership of PD is released to the process (all threads may use it)
80 after the new thread starts in a joinable state
81 i.e. pthread_create returns a usable pthread_t.
83 (2) Ownership of PD is released to the new thread starting in a detached
84 state.
86 (3) Ownership of PD is dynamically released to a running thread via
87 pthread_detach.
89 (4) Ownership of PD is acquired by the thread which calls pthread_join.
91 Implementation notes:
93 The PD->stopped_start and thread_ran variables are used to determine
94 exactly which of the four ownership states we are in and therefore
95 what actions can be taken. For example after (2) we cannot read or
96 write from PD anymore since the thread may no longer exist and the
97 memory may be unmapped. The most complicated cases happen during
98 thread startup:
100 (a) If the created thread is in a detached (PTHREAD_CREATE_DETACHED),
101 or joinable (default PTHREAD_CREATE_JOINABLE) state and
102 STOPPED_START is true, then the creating thread has ownership of
103 PD until the PD->lock is released by pthread_create. If any
104 errors occur we are in states (c), (d), or (e) below.
106 (b) If the created thread is in a detached state
107 (PTHREAD_CREATED_DETACHED), and STOPPED_START is false, then the
108 creating thread has ownership of PD until it invokes the OS
109 kernel's thread creation routine. If this routine returns
110 without error, then the created thread owns PD; otherwise, see
111 (c) and (e) below.
113 (c) If the detached thread setup failed and THREAD_RAN is true, then
114 the creating thread releases ownership to the new thread by
115 sending a cancellation signal. All threads set THREAD_RAN to
116 true as quickly as possible after returning from the OS kernel's
117 thread creation routine.
119 (d) If the joinable thread setup failed and THREAD_RAN is true, then
120 then the creating thread retains ownership of PD and must cleanup
121 state. Ownership cannot be released to the process via the
122 return of pthread_create since a non-zero result entails PD is
123 undefined and therefore cannot be joined to free the resources.
124 We privately call pthread_join on the thread to finish handling
125 the resource shutdown (Or at least we should, see bug 19511).
127 (e) If the thread creation failed and THREAD_RAN is false, then the
128 creating thread retains ownership of PD and must cleanup state.
129 No waiting for the new thread is required because it never
130 started.
132 The nptl_db interface:
134 The interface with nptl_db requires that we enqueue PD into a linked
135 list and then call a function which the debugger will trap. The PD
136 will then be dequeued and control returned to the thread. The caller
137 at the time must have ownership of PD and such ownership remains
138 after control returns to thread. The enqueued PD is removed from the
139 linked list by the nptl_db callback td_thr_event_getmsg. The debugger
140 must ensure that the thread does not resume execution, otherwise
141 ownership of PD may be lost and examining PD will not be possible.
143 Note that the GNU Debugger as of (December 10th 2015) commit
144 c2c2a31fdb228d41ce3db62b268efea04bd39c18 no longer uses
145 td_thr_event_getmsg and several other related nptl_db interfaces. The
146 principal reason for this is that nptl_db does not support non-stop
147 mode where other threads can run concurrently and modify runtime
148 structures currently in use by the debugger and the nptl_db
149 interface.
151 Axioms:
153 * The create_thread function can never set stopped_start to false.
154 * The created thread can read stopped_start but never write to it.
155 * The variable thread_ran is set some time after the OS thread
156 creation routine returns, how much time after the thread is created
157 is unspecified, but it should be as quickly as possible.
161 /* CREATE THREAD NOTES:
163 createthread.c defines the create_thread function, and two macros:
164 START_THREAD_DEFN and START_THREAD_SELF (see below).
166 create_thread must initialize PD->stopped_start. It should be true
167 if the STOPPED_START parameter is true, or if create_thread needs the
168 new thread to synchronize at startup for some other implementation
169 reason. If STOPPED_START will be true, then create_thread is obliged
170 to lock PD->lock before starting the thread. Then pthread_create
171 unlocks PD->lock which synchronizes-with START_THREAD_DEFN in the
172 child thread which does an acquire/release of PD->lock as the last
173 action before calling the user entry point. The goal of all of this
174 is to ensure that the required initial thread attributes are applied
175 (by the creating thread) before the new thread runs user code. Note
176 that the the functions pthread_getschedparam, pthread_setschedparam,
177 pthread_setschedprio, __pthread_tpp_change_priority, and
178 __pthread_current_priority reuse the same lock, PD->lock, for a
179 similar purpose e.g. synchronizing the setting of similar thread
180 attributes. These functions are never called before the thread is
181 created, so don't participate in startup syncronization, but given
182 that the lock is present already and in the unlocked state, reusing
183 it saves space.
185 The return value is zero for success or an errno code for failure.
186 If the return value is ENOMEM, that will be translated to EAGAIN,
187 so create_thread need not do that. On failure, *THREAD_RAN should
188 be set to true iff the thread actually started up and then got
189 canceled before calling user code (*PD->start_routine). */
190 static int create_thread (struct pthread *pd, const struct pthread_attr *attr,
191 bool *stopped_start, STACK_VARIABLES_PARMS,
192 bool *thread_ran);
194 #include <createthread.c>
197 struct pthread *
198 internal_function
199 __find_in_stack_list (struct pthread *pd)
201 list_t *entry;
202 struct pthread *result = NULL;
204 lll_lock (stack_cache_lock, LLL_PRIVATE);
206 list_for_each (entry, &stack_used)
208 struct pthread *curp;
210 curp = list_entry (entry, struct pthread, list);
211 if (curp == pd)
213 result = curp;
214 break;
218 if (result == NULL)
219 list_for_each (entry, &__stack_user)
221 struct pthread *curp;
223 curp = list_entry (entry, struct pthread, list);
224 if (curp == pd)
226 result = curp;
227 break;
231 lll_unlock (stack_cache_lock, LLL_PRIVATE);
233 return result;
237 /* Deallocate POSIX thread-local-storage. */
238 void
239 attribute_hidden
240 __nptl_deallocate_tsd (void)
242 struct pthread *self = THREAD_SELF;
244 /* Maybe no data was ever allocated. This happens often so we have
245 a flag for this. */
246 if (THREAD_GETMEM (self, specific_used))
248 size_t round;
249 size_t cnt;
251 round = 0;
254 size_t idx;
256 /* So far no new nonzero data entry. */
257 THREAD_SETMEM (self, specific_used, false);
259 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
261 struct pthread_key_data *level2;
263 level2 = THREAD_GETMEM_NC (self, specific, cnt);
265 if (level2 != NULL)
267 size_t inner;
269 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
270 ++inner, ++idx)
272 void *data = level2[inner].data;
274 if (data != NULL)
276 /* Always clear the data. */
277 level2[inner].data = NULL;
279 /* Make sure the data corresponds to a valid
280 key. This test fails if the key was
281 deallocated and also if it was
282 re-allocated. It is the user's
283 responsibility to free the memory in this
284 case. */
285 if (level2[inner].seq
286 == __pthread_keys[idx].seq
287 /* It is not necessary to register a destructor
288 function. */
289 && __pthread_keys[idx].destr != NULL)
290 /* Call the user-provided destructor. */
291 __pthread_keys[idx].destr (data);
295 else
296 idx += PTHREAD_KEY_1STLEVEL_SIZE;
299 if (THREAD_GETMEM (self, specific_used) == 0)
300 /* No data has been modified. */
301 goto just_free;
303 /* We only repeat the process a fixed number of times. */
304 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
306 /* Just clear the memory of the first block for reuse. */
307 memset (&THREAD_SELF->specific_1stblock, '\0',
308 sizeof (self->specific_1stblock));
310 just_free:
311 /* Free the memory for the other blocks. */
312 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
314 struct pthread_key_data *level2;
316 level2 = THREAD_GETMEM_NC (self, specific, cnt);
317 if (level2 != NULL)
319 /* The first block is allocated as part of the thread
320 descriptor. */
321 free (level2);
322 THREAD_SETMEM_NC (self, specific, cnt, NULL);
326 THREAD_SETMEM (self, specific_used, false);
331 /* Deallocate a thread's stack after optionally making sure the thread
332 descriptor is still valid. */
333 void
334 internal_function
335 __free_tcb (struct pthread *pd)
337 /* The thread is exiting now. */
338 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
339 TERMINATED_BIT) == 0, 1))
341 /* Remove the descriptor from the list. */
342 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
343 /* Something is really wrong. The descriptor for a still
344 running thread is gone. */
345 abort ();
347 /* Free TPP data. */
348 if (__glibc_unlikely (pd->tpp != NULL))
350 struct priority_protection_data *tpp = pd->tpp;
352 pd->tpp = NULL;
353 free (tpp);
356 /* Queue the stack memory block for reuse and exit the process. The
357 kernel will signal via writing to the address returned by
358 QUEUE-STACK when the stack is available. */
359 __deallocate_stack (pd);
364 /* Local function to start thread and handle cleanup.
365 createthread.c defines the macro START_THREAD_DEFN to the
366 declaration that its create_thread function will refer to, and
367 START_THREAD_SELF to the expression to optimally deliver the new
368 thread's THREAD_SELF value. */
369 START_THREAD_DEFN
371 struct pthread *pd = START_THREAD_SELF;
373 #if HP_TIMING_AVAIL
374 /* Remember the time when the thread was started. */
375 hp_timing_t now;
376 HP_TIMING_NOW (now);
377 THREAD_SETMEM (pd, cpuclock_offset, now);
378 #endif
380 /* Initialize resolver state pointer. */
381 __resp = &pd->res;
383 /* Initialize pointers to locale data. */
384 __ctype_init ();
386 /* Allow setxid from now onwards. */
387 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0) == -2))
388 futex_wake (&pd->setxid_futex, 1, FUTEX_PRIVATE);
390 #ifdef __NR_set_robust_list
391 # ifndef __ASSUME_SET_ROBUST_LIST
392 if (__set_robust_list_avail >= 0)
393 # endif
395 INTERNAL_SYSCALL_DECL (err);
396 /* This call should never fail because the initial call in init.c
397 succeeded. */
398 INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
399 sizeof (struct robust_list_head));
401 #endif
403 #ifdef SIGCANCEL
404 /* If the parent was running cancellation handlers while creating
405 the thread the new thread inherited the signal mask. Reset the
406 cancellation signal mask. */
407 if (__glibc_unlikely (pd->parent_cancelhandling & CANCELING_BITMASK))
409 INTERNAL_SYSCALL_DECL (err);
410 sigset_t mask;
411 __sigemptyset (&mask);
412 __sigaddset (&mask, SIGCANCEL);
413 (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &mask,
414 NULL, _NSIG / 8);
416 #endif
418 /* This is where the try/finally block should be created. For
419 compilers without that support we do use setjmp. */
420 struct pthread_unwind_buf unwind_buf;
422 /* No previous handlers. */
423 unwind_buf.priv.data.prev = NULL;
424 unwind_buf.priv.data.cleanup = NULL;
426 int not_first_call;
427 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
428 if (__glibc_likely (! not_first_call))
430 /* Store the new cleanup handler info. */
431 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
433 /* We are either in (a) or (b), and in either case we either own
434 PD already (2) or are about to own PD (1), and so our only
435 restriction would be that we can't free PD until we know we
436 have ownership (see CONCURRENCY NOTES above). */
437 if (__glibc_unlikely (pd->stopped_start))
439 int oldtype = CANCEL_ASYNC ();
441 /* Get the lock the parent locked to force synchronization. */
442 lll_lock (pd->lock, LLL_PRIVATE);
444 /* We have ownership of PD now. */
446 /* And give it up right away. */
447 lll_unlock (pd->lock, LLL_PRIVATE);
449 CANCEL_RESET (oldtype);
452 LIBC_PROBE (pthread_start, 3, (pthread_t) pd, pd->start_routine, pd->arg);
454 /* Run the code the user provided. */
455 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
458 /* Call destructors for the thread_local TLS variables. */
459 #ifndef SHARED
460 if (&__call_tls_dtors != NULL)
461 #endif
462 __call_tls_dtors ();
464 /* Run the destructor for the thread-local data. */
465 __nptl_deallocate_tsd ();
467 /* Clean up any state libc stored in thread-local variables. */
468 __libc_thread_freeres ();
470 /* If this is the last thread we terminate the process now. We
471 do not notify the debugger, it might just irritate it if there
472 is no thread left. */
473 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads)))
474 /* This was the last thread. */
475 exit (0);
477 /* Report the death of the thread if this is wanted. */
478 if (__glibc_unlikely (pd->report_events))
480 /* See whether TD_DEATH is in any of the mask. */
481 const int idx = __td_eventword (TD_DEATH);
482 const uint32_t mask = __td_eventmask (TD_DEATH);
484 if ((mask & (__nptl_threads_events.event_bits[idx]
485 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
487 /* Yep, we have to signal the death. Add the descriptor to
488 the list but only if it is not already on it. */
489 if (pd->nextevent == NULL)
491 pd->eventbuf.eventnum = TD_DEATH;
492 pd->eventbuf.eventdata = pd;
495 pd->nextevent = __nptl_last_event;
496 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
497 pd, pd->nextevent));
500 /* Now call the function which signals the event. See
501 CONCURRENCY NOTES for the nptl_db interface comments. */
502 __nptl_death_event ();
506 /* The thread is exiting now. Don't set this bit until after we've hit
507 the event-reporting breakpoint, so that td_thr_get_info on us while at
508 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
509 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
511 #ifndef __ASSUME_SET_ROBUST_LIST
512 /* If this thread has any robust mutexes locked, handle them now. */
513 # ifdef __PTHREAD_MUTEX_HAVE_PREV
514 void *robust = pd->robust_head.list;
515 # else
516 __pthread_slist_t *robust = pd->robust_list.__next;
517 # endif
518 /* We let the kernel do the notification if it is able to do so.
519 If we have to do it here there for sure are no PI mutexes involved
520 since the kernel support for them is even more recent. */
521 if (__set_robust_list_avail < 0
522 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
526 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
527 ((char *) robust - offsetof (struct __pthread_mutex_s,
528 __list.__next));
529 robust = *((void **) robust);
531 # ifdef __PTHREAD_MUTEX_HAVE_PREV
532 this->__list.__prev = NULL;
533 # endif
534 this->__list.__next = NULL;
536 atomic_or (&this->__lock, FUTEX_OWNER_DIED);
537 futex_wake ((unsigned int *) &this->__lock, 1,
538 /* XYZ */ FUTEX_SHARED);
540 while (robust != (void *) &pd->robust_head);
542 #endif
544 /* Mark the memory of the stack as usable to the kernel. We free
545 everything except for the space used for the TCB itself. */
546 size_t pagesize_m1 = __getpagesize () - 1;
547 #ifdef _STACK_GROWS_DOWN
548 char *sp = CURRENT_STACK_FRAME;
549 size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
550 assert (freesize < pd->stackblock_size);
551 if (freesize > PTHREAD_STACK_MIN)
552 __madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
553 #else
554 /* Page aligned start of memory to free (higher than or equal
555 to current sp plus the minimum stack size). */
556 void *freeblock = (void*)((size_t)(CURRENT_STACK_FRAME
557 + PTHREAD_STACK_MIN
558 + pagesize_m1)
559 & ~pagesize_m1);
560 char *free_end = (char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1);
561 /* Is there any space to free? */
562 if (free_end > (char *)freeblock)
564 size_t freesize = (size_t)(free_end - (char *)freeblock);
565 assert (freesize < pd->stackblock_size);
566 __madvise (freeblock, freesize, MADV_DONTNEED);
568 #endif
570 /* If the thread is detached free the TCB. */
571 if (IS_DETACHED (pd))
572 /* Free the TCB. */
573 __free_tcb (pd);
574 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
576 /* Some other thread might call any of the setXid functions and expect
577 us to reply. In this case wait until we did that. */
579 /* XXX This differs from the typical futex_wait_simple pattern in that
580 the futex_wait condition (setxid_futex) is different from the
581 condition used in the surrounding loop (cancelhandling). We need
582 to check and document why this is correct. */
583 futex_wait_simple (&pd->setxid_futex, 0, FUTEX_PRIVATE);
584 while (pd->cancelhandling & SETXID_BITMASK);
586 /* Reset the value so that the stack can be reused. */
587 pd->setxid_futex = 0;
590 /* We cannot call '_exit' here. '_exit' will terminate the process.
592 The 'exit' implementation in the kernel will signal when the
593 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
594 flag. The 'tid' field in the TCB will be set to zero.
596 The exit code is zero since in case all threads exit by calling
597 'pthread_exit' the exit status must be 0 (zero). */
598 __exit_thread ();
600 /* NOTREACHED */
604 /* Return true iff obliged to report TD_CREATE events. */
605 static bool
606 report_thread_creation (struct pthread *pd)
608 if (__glibc_unlikely (THREAD_GETMEM (THREAD_SELF, report_events)))
610 /* The parent thread is supposed to report events.
611 Check whether the TD_CREATE event is needed, too. */
612 const size_t idx = __td_eventword (TD_CREATE);
613 const uint32_t mask = __td_eventmask (TD_CREATE);
615 return ((mask & (__nptl_threads_events.event_bits[idx]
616 | pd->eventbuf.eventmask.event_bits[idx])) != 0);
618 return false;
623 __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
624 void *(*start_routine) (void *), void *arg)
626 STACK_VARIABLES;
628 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
629 struct pthread_attr default_attr;
630 bool free_cpuset = false;
631 if (iattr == NULL)
633 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
634 default_attr = __default_pthread_attr;
635 size_t cpusetsize = default_attr.cpusetsize;
636 if (cpusetsize > 0)
638 cpu_set_t *cpuset;
639 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
640 cpuset = __alloca (cpusetsize);
641 else
643 cpuset = malloc (cpusetsize);
644 if (cpuset == NULL)
646 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
647 return ENOMEM;
649 free_cpuset = true;
651 memcpy (cpuset, default_attr.cpuset, cpusetsize);
652 default_attr.cpuset = cpuset;
654 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
655 iattr = &default_attr;
658 struct pthread *pd = NULL;
659 int err = ALLOCATE_STACK (iattr, &pd);
660 int retval = 0;
662 if (__glibc_unlikely (err != 0))
663 /* Something went wrong. Maybe a parameter of the attributes is
664 invalid or we could not allocate memory. Note we have to
665 translate error codes. */
667 retval = err == ENOMEM ? EAGAIN : err;
668 goto out;
672 /* Initialize the TCB. All initializations with zero should be
673 performed in 'get_cached_stack'. This way we avoid doing this if
674 the stack freshly allocated with 'mmap'. */
676 #if TLS_TCB_AT_TP
677 /* Reference to the TCB itself. */
678 pd->header.self = pd;
680 /* Self-reference for TLS. */
681 pd->header.tcb = pd;
682 #endif
684 /* Store the address of the start routine and the parameter. Since
685 we do not start the function directly the stillborn thread will
686 get the information from its thread descriptor. */
687 pd->start_routine = start_routine;
688 pd->arg = arg;
690 /* Copy the thread attribute flags. */
691 struct pthread *self = THREAD_SELF;
692 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
693 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
695 /* Initialize the field for the ID of the thread which is waiting
696 for us. This is a self-reference in case the thread is created
697 detached. */
698 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
700 /* The debug events are inherited from the parent. */
701 pd->eventbuf = self->eventbuf;
704 /* Copy the parent's scheduling parameters. The flags will say what
705 is valid and what is not. */
706 pd->schedpolicy = self->schedpolicy;
707 pd->schedparam = self->schedparam;
709 /* Copy the stack guard canary. */
710 #ifdef THREAD_COPY_STACK_GUARD
711 THREAD_COPY_STACK_GUARD (pd);
712 #endif
714 /* Copy the pointer guard value. */
715 #ifdef THREAD_COPY_POINTER_GUARD
716 THREAD_COPY_POINTER_GUARD (pd);
717 #endif
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 /* Pass the descriptor to the caller. */
751 *newthread = (pthread_t) pd;
753 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
755 /* One more thread. We cannot have the thread do this itself, since it
756 might exist but not have been scheduled yet by the time we've returned
757 and need to check the value to behave correctly. We must do it before
758 creating the thread, in case it does get scheduled first and then
759 might mistakenly think it was the only thread. In the failure case,
760 we momentarily store a false value; this doesn't matter because there
761 is no kosher thing a signal handler interrupting us right here can do
762 that cares whether the thread count is correct. */
763 atomic_increment (&__nptl_nthreads);
765 /* Our local value of stopped_start and thread_ran can be accessed at
766 any time. The PD->stopped_start may only be accessed if we have
767 ownership of PD (see CONCURRENCY NOTES above). */
768 bool stopped_start = false; bool thread_ran = false;
770 /* Start the thread. */
771 if (__glibc_unlikely (report_thread_creation (pd)))
773 stopped_start = true;
775 /* We always create the thread stopped at startup so we can
776 notify the debugger. */
777 retval = create_thread (pd, iattr, &stopped_start,
778 STACK_VARIABLES_ARGS, &thread_ran);
779 if (retval == 0)
781 /* We retain ownership of PD until (a) (see CONCURRENCY NOTES
782 above). */
784 /* Assert stopped_start is true in both our local copy and the
785 PD copy. */
786 assert (stopped_start);
787 assert (pd->stopped_start);
789 /* Now fill in the information about the new thread in
790 the newly created thread's data structure. We cannot let
791 the new thread do this since we don't know whether it was
792 already scheduled when we send the event. */
793 pd->eventbuf.eventnum = TD_CREATE;
794 pd->eventbuf.eventdata = pd;
796 /* Enqueue the descriptor. */
798 pd->nextevent = __nptl_last_event;
799 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
800 pd, pd->nextevent)
801 != 0);
803 /* Now call the function which signals the event. See
804 CONCURRENCY NOTES for the nptl_db interface comments. */
805 __nptl_create_event ();
808 else
809 retval = create_thread (pd, iattr, &stopped_start,
810 STACK_VARIABLES_ARGS, &thread_ran);
812 if (__glibc_unlikely (retval != 0))
814 if (thread_ran)
815 /* State (c) or (d) and we may not have PD ownership (see
816 CONCURRENCY NOTES above). We can assert that STOPPED_START
817 must have been true because thread creation didn't fail, but
818 thread attribute setting did. */
819 /* See bug 19511 which explains why doing nothing here is a
820 resource leak for a joinable thread. */
821 assert (stopped_start);
822 else
824 /* State (e) and we have ownership of PD (see CONCURRENCY
825 NOTES above). */
827 /* Oops, we lied for a second. */
828 atomic_decrement (&__nptl_nthreads);
830 /* Perhaps a thread wants to change the IDs and is waiting for this
831 stillborn thread. */
832 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0)
833 == -2))
834 futex_wake (&pd->setxid_futex, 1, FUTEX_PRIVATE);
836 /* Free the resources. */
837 __deallocate_stack (pd);
840 /* We have to translate error codes. */
841 if (retval == ENOMEM)
842 retval = EAGAIN;
844 else
846 /* We don't know if we have PD ownership. Once we check the local
847 stopped_start we'll know if we're in state (a) or (b) (see
848 CONCURRENCY NOTES above). */
849 if (stopped_start)
850 /* State (a), we own PD. The thread blocked on this lock either
851 because we're doing TD_CREATE event reporting, or for some
852 other reason that create_thread chose. Now let it run
853 free. */
854 lll_unlock (pd->lock, LLL_PRIVATE);
856 /* We now have for sure more than one thread. The main thread might
857 not yet have the flag set. No need to set the global variable
858 again if this is what we use. */
859 THREAD_SETMEM (THREAD_SELF, header.multiple_threads, 1);
862 out:
863 if (__glibc_unlikely (free_cpuset))
864 free (default_attr.cpuset);
866 return retval;
868 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
871 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
873 __pthread_create_2_0 (pthread_t *newthread, const pthread_attr_t *attr,
874 void *(*start_routine) (void *), void *arg)
876 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
877 the old size and access to the new members might crash the program.
878 We convert the struct now. */
879 struct pthread_attr new_attr;
881 if (attr != NULL)
883 struct pthread_attr *iattr = (struct pthread_attr *) attr;
884 size_t ps = __getpagesize ();
886 /* Copy values from the user-provided attributes. */
887 new_attr.schedparam = iattr->schedparam;
888 new_attr.schedpolicy = iattr->schedpolicy;
889 new_attr.flags = iattr->flags;
891 /* Fill in default values for the fields not present in the old
892 implementation. */
893 new_attr.guardsize = ps;
894 new_attr.stackaddr = NULL;
895 new_attr.stacksize = 0;
896 new_attr.cpuset = NULL;
898 /* We will pass this value on to the real implementation. */
899 attr = (pthread_attr_t *) &new_attr;
902 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
904 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
905 GLIBC_2_0);
906 #endif
908 /* Information for libthread_db. */
910 #include "../nptl_db/db_info.c"
912 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
913 functions to be present as well. */
914 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
915 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_trylock)
916 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
918 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
919 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
921 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
922 PTHREAD_STATIC_FN_REQUIRE (pthread_key_delete)
923 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
924 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)