[ARM] Optimise memchr for NEON-enabled processors
[glibc.git] / nptl / pthread_create.c
blob7a970ffc5bc6123bbad7d2e38e974ffd2bf859f9
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.
99 It is important to point out that PD->lock is being used both
100 similar to a one-shot semaphore and subsequently as a mutex. The
101 lock is taken in the parent to force the child to wait, and then the
102 child releases the lock. However, this semaphore-like effect is used
103 only for synchronizing the parent and child. After startup the lock
104 is used like a mutex to create a critical section during which a
105 single owner modifies the thread parameters.
107 The most complicated cases happen during thread startup:
109 (a) If the created thread is in a detached (PTHREAD_CREATE_DETACHED),
110 or joinable (default PTHREAD_CREATE_JOINABLE) state and
111 STOPPED_START is true, then the creating thread has ownership of
112 PD until the PD->lock is released by pthread_create. If any
113 errors occur we are in states (c), (d), or (e) below.
115 (b) If the created thread is in a detached state
116 (PTHREAD_CREATED_DETACHED), and STOPPED_START is false, then the
117 creating thread has ownership of PD until it invokes the OS
118 kernel's thread creation routine. If this routine returns
119 without error, then the created thread owns PD; otherwise, see
120 (c) and (e) below.
122 (c) If the detached thread setup failed and THREAD_RAN is true, then
123 the creating thread releases ownership to the new thread by
124 sending a cancellation signal. All threads set THREAD_RAN to
125 true as quickly as possible after returning from the OS kernel's
126 thread creation routine.
128 (d) If the joinable thread setup failed and THREAD_RAN is true, then
129 then the creating thread retains ownership of PD and must cleanup
130 state. Ownership cannot be released to the process via the
131 return of pthread_create since a non-zero result entails PD is
132 undefined and therefore cannot be joined to free the resources.
133 We privately call pthread_join on the thread to finish handling
134 the resource shutdown (Or at least we should, see bug 19511).
136 (e) If the thread creation failed and THREAD_RAN is false, then the
137 creating thread retains ownership of PD and must cleanup state.
138 No waiting for the new thread is required because it never
139 started.
141 The nptl_db interface:
143 The interface with nptl_db requires that we enqueue PD into a linked
144 list and then call a function which the debugger will trap. The PD
145 will then be dequeued and control returned to the thread. The caller
146 at the time must have ownership of PD and such ownership remains
147 after control returns to thread. The enqueued PD is removed from the
148 linked list by the nptl_db callback td_thr_event_getmsg. The debugger
149 must ensure that the thread does not resume execution, otherwise
150 ownership of PD may be lost and examining PD will not be possible.
152 Note that the GNU Debugger as of (December 10th 2015) commit
153 c2c2a31fdb228d41ce3db62b268efea04bd39c18 no longer uses
154 td_thr_event_getmsg and several other related nptl_db interfaces. The
155 principal reason for this is that nptl_db does not support non-stop
156 mode where other threads can run concurrently and modify runtime
157 structures currently in use by the debugger and the nptl_db
158 interface.
160 Axioms:
162 * The create_thread function can never set stopped_start to false.
163 * The created thread can read stopped_start but never write to it.
164 * The variable thread_ran is set some time after the OS thread
165 creation routine returns, how much time after the thread is created
166 is unspecified, but it should be as quickly as possible.
170 /* CREATE THREAD NOTES:
172 createthread.c defines the create_thread function, and two macros:
173 START_THREAD_DEFN and START_THREAD_SELF (see below).
175 create_thread must initialize PD->stopped_start. It should be true
176 if the STOPPED_START parameter is true, or if create_thread needs the
177 new thread to synchronize at startup for some other implementation
178 reason. If STOPPED_START will be true, then create_thread is obliged
179 to lock PD->lock before starting the thread. Then pthread_create
180 unlocks PD->lock which synchronizes-with START_THREAD_DEFN in the
181 child thread which does an acquire/release of PD->lock as the last
182 action before calling the user entry point. The goal of all of this
183 is to ensure that the required initial thread attributes are applied
184 (by the creating thread) before the new thread runs user code. Note
185 that the the functions pthread_getschedparam, pthread_setschedparam,
186 pthread_setschedprio, __pthread_tpp_change_priority, and
187 __pthread_current_priority reuse the same lock, PD->lock, for a
188 similar purpose e.g. synchronizing the setting of similar thread
189 attributes. These functions are never called before the thread is
190 created, so don't participate in startup syncronization, but given
191 that the lock is present already and in the unlocked state, reusing
192 it saves space.
194 The return value is zero for success or an errno code for failure.
195 If the return value is ENOMEM, that will be translated to EAGAIN,
196 so create_thread need not do that. On failure, *THREAD_RAN should
197 be set to true iff the thread actually started up and then got
198 canceled before calling user code (*PD->start_routine). */
199 static int create_thread (struct pthread *pd, const struct pthread_attr *attr,
200 bool *stopped_start, STACK_VARIABLES_PARMS,
201 bool *thread_ran);
203 #include <createthread.c>
206 struct pthread *
207 internal_function
208 __find_in_stack_list (struct pthread *pd)
210 list_t *entry;
211 struct pthread *result = NULL;
213 lll_lock (stack_cache_lock, LLL_PRIVATE);
215 list_for_each (entry, &stack_used)
217 struct pthread *curp;
219 curp = list_entry (entry, struct pthread, list);
220 if (curp == pd)
222 result = curp;
223 break;
227 if (result == NULL)
228 list_for_each (entry, &__stack_user)
230 struct pthread *curp;
232 curp = list_entry (entry, struct pthread, list);
233 if (curp == pd)
235 result = curp;
236 break;
240 lll_unlock (stack_cache_lock, LLL_PRIVATE);
242 return result;
246 /* Deallocate POSIX thread-local-storage. */
247 void
248 attribute_hidden
249 __nptl_deallocate_tsd (void)
251 struct pthread *self = THREAD_SELF;
253 /* Maybe no data was ever allocated. This happens often so we have
254 a flag for this. */
255 if (THREAD_GETMEM (self, specific_used))
257 size_t round;
258 size_t cnt;
260 round = 0;
263 size_t idx;
265 /* So far no new nonzero data entry. */
266 THREAD_SETMEM (self, specific_used, false);
268 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
270 struct pthread_key_data *level2;
272 level2 = THREAD_GETMEM_NC (self, specific, cnt);
274 if (level2 != NULL)
276 size_t inner;
278 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
279 ++inner, ++idx)
281 void *data = level2[inner].data;
283 if (data != NULL)
285 /* Always clear the data. */
286 level2[inner].data = NULL;
288 /* Make sure the data corresponds to a valid
289 key. This test fails if the key was
290 deallocated and also if it was
291 re-allocated. It is the user's
292 responsibility to free the memory in this
293 case. */
294 if (level2[inner].seq
295 == __pthread_keys[idx].seq
296 /* It is not necessary to register a destructor
297 function. */
298 && __pthread_keys[idx].destr != NULL)
299 /* Call the user-provided destructor. */
300 __pthread_keys[idx].destr (data);
304 else
305 idx += PTHREAD_KEY_1STLEVEL_SIZE;
308 if (THREAD_GETMEM (self, specific_used) == 0)
309 /* No data has been modified. */
310 goto just_free;
312 /* We only repeat the process a fixed number of times. */
313 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
315 /* Just clear the memory of the first block for reuse. */
316 memset (&THREAD_SELF->specific_1stblock, '\0',
317 sizeof (self->specific_1stblock));
319 just_free:
320 /* Free the memory for the other blocks. */
321 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
323 struct pthread_key_data *level2;
325 level2 = THREAD_GETMEM_NC (self, specific, cnt);
326 if (level2 != NULL)
328 /* The first block is allocated as part of the thread
329 descriptor. */
330 free (level2);
331 THREAD_SETMEM_NC (self, specific, cnt, NULL);
335 THREAD_SETMEM (self, specific_used, false);
340 /* Deallocate a thread's stack after optionally making sure the thread
341 descriptor is still valid. */
342 void
343 internal_function
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 /* No previous handlers. */
432 unwind_buf.priv.data.prev = NULL;
433 unwind_buf.priv.data.cleanup = NULL;
435 int not_first_call;
436 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
437 if (__glibc_likely (! not_first_call))
439 /* Store the new cleanup handler info. */
440 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
442 /* We are either in (a) or (b), and in either case we either own
443 PD already (2) or are about to own PD (1), and so our only
444 restriction would be that we can't free PD until we know we
445 have ownership (see CONCURRENCY NOTES above). */
446 if (__glibc_unlikely (pd->stopped_start))
448 int oldtype = CANCEL_ASYNC ();
450 /* Get the lock the parent locked to force synchronization. */
451 lll_lock (pd->lock, LLL_PRIVATE);
453 /* We have ownership of PD now. */
455 /* And give it up right away. */
456 lll_unlock (pd->lock, LLL_PRIVATE);
458 CANCEL_RESET (oldtype);
461 LIBC_PROBE (pthread_start, 3, (pthread_t) pd, pd->start_routine, pd->arg);
463 /* Run the code the user provided. */
464 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
467 /* Call destructors for the thread_local TLS variables. */
468 #ifndef SHARED
469 if (&__call_tls_dtors != NULL)
470 #endif
471 __call_tls_dtors ();
473 /* Run the destructor for the thread-local data. */
474 __nptl_deallocate_tsd ();
476 /* Clean up any state libc stored in thread-local variables. */
477 __libc_thread_freeres ();
479 /* If this is the last thread we terminate the process now. We
480 do not notify the debugger, it might just irritate it if there
481 is no thread left. */
482 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads)))
483 /* This was the last thread. */
484 exit (0);
486 /* Report the death of the thread if this is wanted. */
487 if (__glibc_unlikely (pd->report_events))
489 /* See whether TD_DEATH is in any of the mask. */
490 const int idx = __td_eventword (TD_DEATH);
491 const uint32_t mask = __td_eventmask (TD_DEATH);
493 if ((mask & (__nptl_threads_events.event_bits[idx]
494 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
496 /* Yep, we have to signal the death. Add the descriptor to
497 the list but only if it is not already on it. */
498 if (pd->nextevent == NULL)
500 pd->eventbuf.eventnum = TD_DEATH;
501 pd->eventbuf.eventdata = pd;
504 pd->nextevent = __nptl_last_event;
505 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
506 pd, pd->nextevent));
509 /* Now call the function which signals the event. See
510 CONCURRENCY NOTES for the nptl_db interface comments. */
511 __nptl_death_event ();
515 /* The thread is exiting now. Don't set this bit until after we've hit
516 the event-reporting breakpoint, so that td_thr_get_info on us while at
517 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
518 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
520 #ifndef __ASSUME_SET_ROBUST_LIST
521 /* If this thread has any robust mutexes locked, handle them now. */
522 # ifdef __PTHREAD_MUTEX_HAVE_PREV
523 void *robust = pd->robust_head.list;
524 # else
525 __pthread_slist_t *robust = pd->robust_list.__next;
526 # endif
527 /* We let the kernel do the notification if it is able to do so.
528 If we have to do it here there for sure are no PI mutexes involved
529 since the kernel support for them is even more recent. */
530 if (__set_robust_list_avail < 0
531 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
535 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
536 ((char *) robust - offsetof (struct __pthread_mutex_s,
537 __list.__next));
538 robust = *((void **) robust);
540 # ifdef __PTHREAD_MUTEX_HAVE_PREV
541 this->__list.__prev = NULL;
542 # endif
543 this->__list.__next = NULL;
545 atomic_or (&this->__lock, FUTEX_OWNER_DIED);
546 futex_wake ((unsigned int *) &this->__lock, 1,
547 /* XYZ */ FUTEX_SHARED);
549 while (robust != (void *) &pd->robust_head);
551 #endif
553 /* Mark the memory of the stack as usable to the kernel. We free
554 everything except for the space used for the TCB itself. */
555 size_t pagesize_m1 = __getpagesize () - 1;
556 #ifdef _STACK_GROWS_DOWN
557 char *sp = CURRENT_STACK_FRAME;
558 size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
559 assert (freesize < pd->stackblock_size);
560 if (freesize > PTHREAD_STACK_MIN)
561 __madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
562 #else
563 /* Page aligned start of memory to free (higher than or equal
564 to current sp plus the minimum stack size). */
565 void *freeblock = (void*)((size_t)(CURRENT_STACK_FRAME
566 + PTHREAD_STACK_MIN
567 + pagesize_m1)
568 & ~pagesize_m1);
569 char *free_end = (char *) (((uintptr_t) pd - pd->guardsize) & ~pagesize_m1);
570 /* Is there any space to free? */
571 if (free_end > (char *)freeblock)
573 size_t freesize = (size_t)(free_end - (char *)freeblock);
574 assert (freesize < pd->stackblock_size);
575 __madvise (freeblock, freesize, MADV_DONTNEED);
577 #endif
579 /* If the thread is detached free the TCB. */
580 if (IS_DETACHED (pd))
581 /* Free the TCB. */
582 __free_tcb (pd);
583 else if (__glibc_unlikely (pd->cancelhandling & SETXID_BITMASK))
585 /* Some other thread might call any of the setXid functions and expect
586 us to reply. In this case wait until we did that. */
588 /* XXX This differs from the typical futex_wait_simple pattern in that
589 the futex_wait condition (setxid_futex) is different from the
590 condition used in the surrounding loop (cancelhandling). We need
591 to check and document why this is correct. */
592 futex_wait_simple (&pd->setxid_futex, 0, FUTEX_PRIVATE);
593 while (pd->cancelhandling & SETXID_BITMASK);
595 /* Reset the value so that the stack can be reused. */
596 pd->setxid_futex = 0;
599 /* We cannot call '_exit' here. '_exit' will terminate the process.
601 The 'exit' implementation in the kernel will signal when the
602 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
603 flag. The 'tid' field in the TCB will be set to zero.
605 The exit code is zero since in case all threads exit by calling
606 'pthread_exit' the exit status must be 0 (zero). */
607 __exit_thread ();
609 /* NOTREACHED */
613 /* Return true iff obliged to report TD_CREATE events. */
614 static bool
615 report_thread_creation (struct pthread *pd)
617 if (__glibc_unlikely (THREAD_GETMEM (THREAD_SELF, report_events)))
619 /* The parent thread is supposed to report events.
620 Check whether the TD_CREATE event is needed, too. */
621 const size_t idx = __td_eventword (TD_CREATE);
622 const uint32_t mask = __td_eventmask (TD_CREATE);
624 return ((mask & (__nptl_threads_events.event_bits[idx]
625 | pd->eventbuf.eventmask.event_bits[idx])) != 0);
627 return false;
632 __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
633 void *(*start_routine) (void *), void *arg)
635 STACK_VARIABLES;
637 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
638 struct pthread_attr default_attr;
639 bool free_cpuset = false;
640 if (iattr == NULL)
642 lll_lock (__default_pthread_attr_lock, LLL_PRIVATE);
643 default_attr = __default_pthread_attr;
644 size_t cpusetsize = default_attr.cpusetsize;
645 if (cpusetsize > 0)
647 cpu_set_t *cpuset;
648 if (__glibc_likely (__libc_use_alloca (cpusetsize)))
649 cpuset = __alloca (cpusetsize);
650 else
652 cpuset = malloc (cpusetsize);
653 if (cpuset == NULL)
655 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
656 return ENOMEM;
658 free_cpuset = true;
660 memcpy (cpuset, default_attr.cpuset, cpusetsize);
661 default_attr.cpuset = cpuset;
663 lll_unlock (__default_pthread_attr_lock, LLL_PRIVATE);
664 iattr = &default_attr;
667 struct pthread *pd = NULL;
668 int err = ALLOCATE_STACK (iattr, &pd);
669 int retval = 0;
671 if (__glibc_unlikely (err != 0))
672 /* Something went wrong. Maybe a parameter of the attributes is
673 invalid or we could not allocate memory. Note we have to
674 translate error codes. */
676 retval = err == ENOMEM ? EAGAIN : err;
677 goto out;
681 /* Initialize the TCB. All initializations with zero should be
682 performed in 'get_cached_stack'. This way we avoid doing this if
683 the stack freshly allocated with 'mmap'. */
685 #if TLS_TCB_AT_TP
686 /* Reference to the TCB itself. */
687 pd->header.self = pd;
689 /* Self-reference for TLS. */
690 pd->header.tcb = pd;
691 #endif
693 /* Store the address of the start routine and the parameter. Since
694 we do not start the function directly the stillborn thread will
695 get the information from its thread descriptor. */
696 pd->start_routine = start_routine;
697 pd->arg = arg;
699 /* Copy the thread attribute flags. */
700 struct pthread *self = THREAD_SELF;
701 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
702 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
704 /* Initialize the field for the ID of the thread which is waiting
705 for us. This is a self-reference in case the thread is created
706 detached. */
707 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
709 /* The debug events are inherited from the parent. */
710 pd->eventbuf = self->eventbuf;
713 /* Copy the parent's scheduling parameters. The flags will say what
714 is valid and what is not. */
715 pd->schedpolicy = self->schedpolicy;
716 pd->schedparam = self->schedparam;
718 /* Copy the stack guard canary. */
719 #ifdef THREAD_COPY_STACK_GUARD
720 THREAD_COPY_STACK_GUARD (pd);
721 #endif
723 /* Copy the pointer guard value. */
724 #ifdef THREAD_COPY_POINTER_GUARD
725 THREAD_COPY_POINTER_GUARD (pd);
726 #endif
728 /* Verify the sysinfo bits were copied in allocate_stack if needed. */
729 #ifdef NEED_DL_SYSINFO
730 CHECK_THREAD_SYSINFO (pd);
731 #endif
733 /* Inform start_thread (above) about cancellation state that might
734 translate into inherited signal state. */
735 pd->parent_cancelhandling = THREAD_GETMEM (THREAD_SELF, cancelhandling);
737 /* Determine scheduling parameters for the thread. */
738 if (__builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
739 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
741 /* Use the scheduling parameters the user provided. */
742 if (iattr->flags & ATTR_FLAG_POLICY_SET)
744 pd->schedpolicy = iattr->schedpolicy;
745 pd->flags |= ATTR_FLAG_POLICY_SET;
747 if (iattr->flags & ATTR_FLAG_SCHED_SET)
749 /* The values were validated in pthread_attr_setschedparam. */
750 pd->schedparam = iattr->schedparam;
751 pd->flags |= ATTR_FLAG_SCHED_SET;
754 if ((pd->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
755 != (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
756 collect_default_sched (pd);
759 /* Pass the descriptor to the caller. */
760 *newthread = (pthread_t) pd;
762 LIBC_PROBE (pthread_create, 4, newthread, attr, start_routine, arg);
764 /* One more thread. We cannot have the thread do this itself, since it
765 might exist but not have been scheduled yet by the time we've returned
766 and need to check the value to behave correctly. We must do it before
767 creating the thread, in case it does get scheduled first and then
768 might mistakenly think it was the only thread. In the failure case,
769 we momentarily store a false value; this doesn't matter because there
770 is no kosher thing a signal handler interrupting us right here can do
771 that cares whether the thread count is correct. */
772 atomic_increment (&__nptl_nthreads);
774 /* Our local value of stopped_start and thread_ran can be accessed at
775 any time. The PD->stopped_start may only be accessed if we have
776 ownership of PD (see CONCURRENCY NOTES above). */
777 bool stopped_start = false; bool thread_ran = false;
779 /* Start the thread. */
780 if (__glibc_unlikely (report_thread_creation (pd)))
782 stopped_start = true;
784 /* We always create the thread stopped at startup so we can
785 notify the debugger. */
786 retval = create_thread (pd, iattr, &stopped_start,
787 STACK_VARIABLES_ARGS, &thread_ran);
788 if (retval == 0)
790 /* We retain ownership of PD until (a) (see CONCURRENCY NOTES
791 above). */
793 /* Assert stopped_start is true in both our local copy and the
794 PD copy. */
795 assert (stopped_start);
796 assert (pd->stopped_start);
798 /* Now fill in the information about the new thread in
799 the newly created thread's data structure. We cannot let
800 the new thread do this since we don't know whether it was
801 already scheduled when we send the event. */
802 pd->eventbuf.eventnum = TD_CREATE;
803 pd->eventbuf.eventdata = pd;
805 /* Enqueue the descriptor. */
807 pd->nextevent = __nptl_last_event;
808 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
809 pd, pd->nextevent)
810 != 0);
812 /* Now call the function which signals the event. See
813 CONCURRENCY NOTES for the nptl_db interface comments. */
814 __nptl_create_event ();
817 else
818 retval = create_thread (pd, iattr, &stopped_start,
819 STACK_VARIABLES_ARGS, &thread_ran);
821 if (__glibc_unlikely (retval != 0))
823 if (thread_ran)
824 /* State (c) or (d) and we may not have PD ownership (see
825 CONCURRENCY NOTES above). We can assert that STOPPED_START
826 must have been true because thread creation didn't fail, but
827 thread attribute setting did. */
828 /* See bug 19511 which explains why doing nothing here is a
829 resource leak for a joinable thread. */
830 assert (stopped_start);
831 else
833 /* State (e) and we have ownership of PD (see CONCURRENCY
834 NOTES above). */
836 /* Oops, we lied for a second. */
837 atomic_decrement (&__nptl_nthreads);
839 /* Perhaps a thread wants to change the IDs and is waiting for this
840 stillborn thread. */
841 if (__glibc_unlikely (atomic_exchange_acq (&pd->setxid_futex, 0)
842 == -2))
843 futex_wake (&pd->setxid_futex, 1, FUTEX_PRIVATE);
845 /* Free the resources. */
846 __deallocate_stack (pd);
849 /* We have to translate error codes. */
850 if (retval == ENOMEM)
851 retval = EAGAIN;
853 else
855 /* We don't know if we have PD ownership. Once we check the local
856 stopped_start we'll know if we're in state (a) or (b) (see
857 CONCURRENCY NOTES above). */
858 if (stopped_start)
859 /* State (a), we own PD. The thread blocked on this lock either
860 because we're doing TD_CREATE event reporting, or for some
861 other reason that create_thread chose. Now let it run
862 free. */
863 lll_unlock (pd->lock, LLL_PRIVATE);
865 /* We now have for sure more than one thread. The main thread might
866 not yet have the flag set. No need to set the global variable
867 again if this is what we use. */
868 THREAD_SETMEM (THREAD_SELF, header.multiple_threads, 1);
871 out:
872 if (__glibc_unlikely (free_cpuset))
873 free (default_attr.cpuset);
875 return retval;
877 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
880 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
882 __pthread_create_2_0 (pthread_t *newthread, const pthread_attr_t *attr,
883 void *(*start_routine) (void *), void *arg)
885 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
886 the old size and access to the new members might crash the program.
887 We convert the struct now. */
888 struct pthread_attr new_attr;
890 if (attr != NULL)
892 struct pthread_attr *iattr = (struct pthread_attr *) attr;
893 size_t ps = __getpagesize ();
895 /* Copy values from the user-provided attributes. */
896 new_attr.schedparam = iattr->schedparam;
897 new_attr.schedpolicy = iattr->schedpolicy;
898 new_attr.flags = iattr->flags;
900 /* Fill in default values for the fields not present in the old
901 implementation. */
902 new_attr.guardsize = ps;
903 new_attr.stackaddr = NULL;
904 new_attr.stacksize = 0;
905 new_attr.cpuset = NULL;
907 /* We will pass this value on to the real implementation. */
908 attr = (pthread_attr_t *) &new_attr;
911 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
913 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
914 GLIBC_2_0);
915 #endif
917 /* Information for libthread_db. */
919 #include "../nptl_db/db_info.c"
921 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
922 functions to be present as well. */
923 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_lock)
924 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_trylock)
925 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_unlock)
927 PTHREAD_STATIC_FN_REQUIRE (__pthread_once)
928 PTHREAD_STATIC_FN_REQUIRE (__pthread_cancel)
930 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_create)
931 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_delete)
932 PTHREAD_STATIC_FN_REQUIRE (__pthread_setspecific)
933 PTHREAD_STATIC_FN_REQUIRE (__pthread_getspecific)