xref: /netbsd-src/lib/libpthread/pthread.c (revision 095b25e7dd8f3fc22724d05bfa59fd72a9eaafc5)
1*095b25e7Sdrochner /*	$NetBSD: pthread.c,v 1.89 2007/11/14 19:28:23 drochner Exp $	*/
2c62a74e6Sthorpej 
3c62a74e6Sthorpej /*-
41296e850Sad  * Copyright (c) 2001, 2002, 2003, 2006, 2007 The NetBSD Foundation, Inc.
5c62a74e6Sthorpej  * All rights reserved.
6c62a74e6Sthorpej  *
7c62a74e6Sthorpej  * This code is derived from software contributed to The NetBSD Foundation
81ac6a89bSad  * by Nathan J. Williams and Andrew Doran.
9c62a74e6Sthorpej  *
10c62a74e6Sthorpej  * Redistribution and use in source and binary forms, with or without
11c62a74e6Sthorpej  * modification, are permitted provided that the following conditions
12c62a74e6Sthorpej  * are met:
13c62a74e6Sthorpej  * 1. Redistributions of source code must retain the above copyright
14c62a74e6Sthorpej  *    notice, this list of conditions and the following disclaimer.
15c62a74e6Sthorpej  * 2. Redistributions in binary form must reproduce the above copyright
16c62a74e6Sthorpej  *    notice, this list of conditions and the following disclaimer in the
17c62a74e6Sthorpej  *    documentation and/or other materials provided with the distribution.
18c62a74e6Sthorpej  * 3. All advertising materials mentioning features or use of this software
19c62a74e6Sthorpej  *    must display the following acknowledgement:
20c62a74e6Sthorpej  *        This product includes software developed by the NetBSD
21c62a74e6Sthorpej  *        Foundation, Inc. and its contributors.
22c62a74e6Sthorpej  * 4. Neither the name of The NetBSD Foundation nor the names of its
23c62a74e6Sthorpej  *    contributors may be used to endorse or promote products derived
24c62a74e6Sthorpej  *    from this software without specific prior written permission.
25c62a74e6Sthorpej  *
26c62a74e6Sthorpej  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27c62a74e6Sthorpej  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28c62a74e6Sthorpej  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29c62a74e6Sthorpej  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30c62a74e6Sthorpej  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31c62a74e6Sthorpej  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32c62a74e6Sthorpej  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33c62a74e6Sthorpej  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34c62a74e6Sthorpej  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35c62a74e6Sthorpej  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36c62a74e6Sthorpej  * POSSIBILITY OF SUCH DAMAGE.
37c62a74e6Sthorpej  */
38c62a74e6Sthorpej 
39f043c0fbSlukem #include <sys/cdefs.h>
40*095b25e7Sdrochner __RCSID("$NetBSD: pthread.c,v 1.89 2007/11/14 19:28:23 drochner Exp $");
419e287199Sad 
429e287199Sad #define	__EXPOSE_STACK	1
439e287199Sad 
449e287199Sad #include <sys/param.h>
459e287199Sad #include <sys/mman.h>
469e287199Sad #include <sys/sysctl.h>
4766ac2ffaSad #include <sys/lwpctl.h>
48f043c0fbSlukem 
49c62a74e6Sthorpej #include <err.h>
50c62a74e6Sthorpej #include <errno.h>
51c62a74e6Sthorpej #include <lwp.h>
52c62a74e6Sthorpej #include <signal.h>
538bcff70bSnathanw #include <stdio.h>
54c62a74e6Sthorpej #include <stdlib.h>
55c62a74e6Sthorpej #include <string.h>
560172694eSnathanw #include <syslog.h>
57c62a74e6Sthorpej #include <ucontext.h>
588bcff70bSnathanw #include <unistd.h>
59c62a74e6Sthorpej #include <sched.h>
609e287199Sad 
61c62a74e6Sthorpej #include "pthread.h"
62c62a74e6Sthorpej #include "pthread_int.h"
63c62a74e6Sthorpej 
649583eeb2Sad pthread_rwlock_t pthread__alltree_lock = PTHREAD_RWLOCK_INITIALIZER;
659583eeb2Sad RB_HEAD(__pthread__alltree, __pthread_st) pthread__alltree;
669583eeb2Sad 
679583eeb2Sad #ifndef lint
689583eeb2Sad static int	pthread__cmp(struct __pthread_st *, struct __pthread_st *);
699583eeb2Sad RB_PROTOTYPE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp)
709583eeb2Sad #endif
719583eeb2Sad 
7266ac2ffaSad static void	pthread__create_tramp(pthread_t, void *(*)(void *), void *);
7350fa8db4Sad static void	pthread__initthread(pthread_t);
74b8833ff5Sad static void	pthread__scrubthread(pthread_t, char *, int);
759e287199Sad static int	pthread__stackid_setup(void *, size_t, pthread_t *);
769e287199Sad static int	pthread__stackalloc(pthread_t *);
779e287199Sad static void	pthread__initmain(pthread_t *);
7866ac2ffaSad static void	pthread__fork_callback(void);
79c62a74e6Sthorpej 
8015e9cec1Sad void	pthread__init(void);
8115e9cec1Sad 
82c62a74e6Sthorpej int pthread__started;
83f4fd6b79Sad pthread_mutex_t pthread__deadqueue_lock = PTHREAD_MUTEX_INITIALIZER;
8450fa8db4Sad pthread_queue_t pthread__deadqueue;
85f1b2c1c4Sad pthread_queue_t pthread__allqueue;
86c62a74e6Sthorpej 
87c62a74e6Sthorpej static pthread_attr_t pthread_default_attr;
8866ac2ffaSad static lwpctl_t pthread__dummy_lwpctl = { .lc_curcpu = LWPCTL_CPU_NONE };
8966ac2ffaSad static pthread_t pthread__first;
90c62a74e6Sthorpej 
910172694eSnathanw enum {
920172694eSnathanw 	DIAGASSERT_ABORT =	1<<0,
930172694eSnathanw 	DIAGASSERT_STDERR =	1<<1,
940172694eSnathanw 	DIAGASSERT_SYSLOG =	1<<2
950172694eSnathanw };
96df277271Snathanw 
970172694eSnathanw static int pthread__diagassert = DIAGASSERT_ABORT | DIAGASSERT_STDERR;
98df277271Snathanw 
99c94f5a91Sad int pthread__concurrency;
100c94f5a91Sad int pthread__nspins;
101ded26025Sad int pthread__unpark_max = PTHREAD__UNPARK_MAX;
1021d42dbd2Sad int pthread__osrev;
103f2f10664Scl 
1049e287199Sad /*
1059e287199Sad  * We have to initialize the pthread_stack* variables here because
1069e287199Sad  * mutexes are used before pthread_init() and thus pthread__initmain()
1079e287199Sad  * are called.  Since mutexes only save the stack pointer and not a
1089e287199Sad  * pointer to the thread data, it is safe to change the mapping from
1099e287199Sad  * stack pointer to thread data afterwards.
1109e287199Sad  */
1119e287199Sad #define	_STACKSIZE_LG 18
1129e287199Sad int	pthread__stacksize_lg = _STACKSIZE_LG;
1139e287199Sad size_t	pthread__stacksize = 1 << _STACKSIZE_LG;
1149e287199Sad vaddr_t	pthread__stackmask = (1 << _STACKSIZE_LG) - 1;
1159583eeb2Sad vaddr_t pthread__threadmask = (vaddr_t)~((1 << _STACKSIZE_LG) - 1);
1169e287199Sad #undef	_STACKSIZE_LG
1179e287199Sad 
118f782e995Sdrochner int _sys___sigprocmask14(int, const sigset_t *, sigset_t *);
119f782e995Sdrochner 
120c62a74e6Sthorpej __strong_alias(__libc_thr_self,pthread_self)
1217dc01dbfSthorpej __strong_alias(__libc_thr_create,pthread_create)
1227dc01dbfSthorpej __strong_alias(__libc_thr_exit,pthread_exit)
123c62a74e6Sthorpej __strong_alias(__libc_thr_errno,pthread__errno)
1249e5c8705Snathanw __strong_alias(__libc_thr_setcancelstate,pthread_setcancelstate)
125*095b25e7Sdrochner __strong_alias(__libc_thr_equal,pthread_equal)
12615e9cec1Sad __strong_alias(__libc_thr_init,pthread__init)
127c62a74e6Sthorpej 
128c62a74e6Sthorpej /*
129c62a74e6Sthorpej  * Static library kludge.  Place a reference to a symbol any library
130c62a74e6Sthorpej  * file which does not already have a reference here.
131c62a74e6Sthorpej  */
132c62a74e6Sthorpej extern int pthread__cancel_stub_binder;
133c62a74e6Sthorpej 
134c62a74e6Sthorpej void *pthread__static_lib_binder[] = {
135c62a74e6Sthorpej 	&pthread__cancel_stub_binder,
136c62a74e6Sthorpej 	pthread_cond_init,
137c62a74e6Sthorpej 	pthread_mutex_init,
138c62a74e6Sthorpej 	pthread_rwlock_init,
139c62a74e6Sthorpej 	pthread_barrier_init,
140c62a74e6Sthorpej 	pthread_key_create,
141bd9a18b7Snathanw 	pthread_setspecific,
142c62a74e6Sthorpej };
143c62a74e6Sthorpej 
144c62a74e6Sthorpej /*
145c62a74e6Sthorpej  * This needs to be started by the library loading code, before main()
146c62a74e6Sthorpej  * gets to run, for various things that use the state of the initial thread
147c62a74e6Sthorpej  * to work properly (thread-specific data is an application-visible example;
148c62a74e6Sthorpej  * spinlock counts for mutexes is an internal example).
149c62a74e6Sthorpej  */
150c62a74e6Sthorpej void
15115e9cec1Sad pthread__init(void)
152c62a74e6Sthorpej {
153c62a74e6Sthorpej 	pthread_t first;
1540172694eSnathanw 	char *p;
155b8833ff5Sad 	int i, mib[2];
156f2f10664Scl 	size_t len;
157c62a74e6Sthorpej 	extern int __isthreaded;
158c62a74e6Sthorpej 
159f2f10664Scl 	mib[0] = CTL_HW;
160f2f10664Scl 	mib[1] = HW_NCPU;
161f2f10664Scl 
162b8833ff5Sad 	len = sizeof(pthread__concurrency);
163b8833ff5Sad 	if (sysctl(mib, 2, &pthread__concurrency, &len, NULL, 0) == -1)
164792cc0e1Sad 		err(1, "sysctl(hw.ncpu");
165f2f10664Scl 
166c3f8e2eeSad 	mib[0] = CTL_KERN;
167c3f8e2eeSad 	mib[1] = KERN_OSREV;
168c3f8e2eeSad 
169c3f8e2eeSad 	len = sizeof(pthread__osrev);
170c3f8e2eeSad 	if (sysctl(mib, 2, &pthread__osrev, &len, NULL, 0) == -1)
171c3f8e2eeSad 		err(1, "sysctl(hw.osrevision");
172c3f8e2eeSad 
173c62a74e6Sthorpej 	/* Initialize locks first; they're needed elsewhere. */
174b8833ff5Sad 	pthread__lockprim_init();
175f2f10664Scl 
176b8833ff5Sad 	/* Fetch parameters. */
1773247035dSad 	i = (int)_lwp_unpark_all(NULL, 0, NULL);
1783247035dSad 	if (i == -1)
1793247035dSad 		err(1, "_lwp_unpark_all");
180ded26025Sad 	if (i < pthread__unpark_max)
181ded26025Sad 		pthread__unpark_max = i;
182c62a74e6Sthorpej 
183c62a74e6Sthorpej 	/* Basic data structure setup */
184c62a74e6Sthorpej 	pthread_attr_init(&pthread_default_attr);
185f1b2c1c4Sad 	PTQ_INIT(&pthread__allqueue);
186c62a74e6Sthorpej 	PTQ_INIT(&pthread__deadqueue);
1879583eeb2Sad 	RB_INIT(&pthread__alltree);
1889e287199Sad 
189c62a74e6Sthorpej 	/* Create the thread structure corresponding to main() */
190c62a74e6Sthorpej 	pthread__initmain(&first);
19150fa8db4Sad 	pthread__initthread(first);
192b8833ff5Sad 	pthread__scrubthread(first, NULL, 0);
1931ac6a89bSad 
1941ac6a89bSad 	first->pt_lid = _lwp_self();
195f1b2c1c4Sad 	PTQ_INSERT_HEAD(&pthread__allqueue, first, pt_allq);
1969583eeb2Sad 	RB_INSERT(__pthread__alltree, &pthread__alltree, first);
197c62a74e6Sthorpej 
19866ac2ffaSad 	/*
19966ac2ffaSad 	 * Don't need lwpctl if running on a uniprocessor.
20066ac2ffaSad 	 * Just use the dummy block.
20166ac2ffaSad 	 */
20266ac2ffaSad 	if (pthread__concurrency > 1)
20366ac2ffaSad 		(void)_lwp_ctl(LWPCTL_FEATURE_CURCPU, &first->pt_lwpctl);
20466ac2ffaSad 
205c62a74e6Sthorpej 	/* Start subsystems */
206c62a74e6Sthorpej 	PTHREAD_MD_INIT
207b8833ff5Sad 	pthread__debug_init();
208c62a74e6Sthorpej 
20915e9cec1Sad 	for (p = pthread__getenv("PTHREAD_DIAGASSERT"); p && *p; p++) {
2100172694eSnathanw 		switch (*p) {
2110172694eSnathanw 		case 'a':
2120172694eSnathanw 			pthread__diagassert |= DIAGASSERT_ABORT;
2130172694eSnathanw 			break;
2140172694eSnathanw 		case 'A':
2150172694eSnathanw 			pthread__diagassert &= ~DIAGASSERT_ABORT;
2160172694eSnathanw 			break;
2170172694eSnathanw 		case 'e':
2180172694eSnathanw 			pthread__diagassert |= DIAGASSERT_STDERR;
2190172694eSnathanw 			break;
2200172694eSnathanw 		case 'E':
2210172694eSnathanw 			pthread__diagassert &= ~DIAGASSERT_STDERR;
2220172694eSnathanw 			break;
2230172694eSnathanw 		case 'l':
2240172694eSnathanw 			pthread__diagassert |= DIAGASSERT_SYSLOG;
2250172694eSnathanw 			break;
2260172694eSnathanw 		case 'L':
2270172694eSnathanw 			pthread__diagassert &= ~DIAGASSERT_SYSLOG;
2280172694eSnathanw 			break;
229df277271Snathanw 		}
2300172694eSnathanw 	}
2310172694eSnathanw 
232c62a74e6Sthorpej 	/* Tell libc that we're here and it should role-play accordingly. */
23366ac2ffaSad 	pthread__first = first;
23466ac2ffaSad 	pthread_atfork(NULL, NULL, pthread__fork_callback);
235c62a74e6Sthorpej 	__isthreaded = 1;
236c62a74e6Sthorpej }
237c62a74e6Sthorpej 
2382a4cef11Snathanw static void
23966ac2ffaSad pthread__fork_callback(void)
24066ac2ffaSad {
24166ac2ffaSad 
24266ac2ffaSad 	/* lwpctl state is not copied across fork. */
24366ac2ffaSad 	if (pthread__concurrency > 1) {
24466ac2ffaSad 		(void)_lwp_ctl(LWPCTL_FEATURE_CURCPU,
24566ac2ffaSad 		    &pthread__first->pt_lwpctl);
24666ac2ffaSad 	}
24766ac2ffaSad }
24866ac2ffaSad 
24966ac2ffaSad static void
2502a4cef11Snathanw pthread__child_callback(void)
2512a4cef11Snathanw {
25266ac2ffaSad 
2532a4cef11Snathanw 	/*
2542a4cef11Snathanw 	 * Clean up data structures that a forked child process might
2552a4cef11Snathanw 	 * trip over. Note that if threads have been created (causing
2562a4cef11Snathanw 	 * this handler to be registered) the standards say that the
2572a4cef11Snathanw 	 * child will trigger undefined behavior if it makes any
2582a4cef11Snathanw 	 * pthread_* calls (or any other calls that aren't
2592a4cef11Snathanw 	 * async-signal-safe), so we don't really have to clean up
2602a4cef11Snathanw 	 * much. Anything that permits some pthread_* calls to work is
2612a4cef11Snathanw 	 * merely being polite.
2622a4cef11Snathanw 	 */
2632a4cef11Snathanw 	pthread__started = 0;
2642a4cef11Snathanw }
265c62a74e6Sthorpej 
2660e675542Schs static void
267c62a74e6Sthorpej pthread__start(void)
268c62a74e6Sthorpej {
269c62a74e6Sthorpej 
270ff14fbf2Snathanw 	/*
271ff14fbf2Snathanw 	 * Per-process timers are cleared by fork(); despite the
272ff14fbf2Snathanw 	 * various restrictions on fork() and threads, it's legal to
273ff14fbf2Snathanw 	 * fork() before creating any threads.
274ff14fbf2Snathanw 	 */
2752a4cef11Snathanw 	pthread_atfork(NULL, NULL, pthread__child_callback);
276c62a74e6Sthorpej }
277c62a74e6Sthorpej 
278c62a74e6Sthorpej 
279c62a74e6Sthorpej /* General-purpose thread data structure sanitization. */
28050fa8db4Sad /* ARGSUSED */
28150fa8db4Sad static void
28250fa8db4Sad pthread__initthread(pthread_t t)
283c62a74e6Sthorpej {
284c62a74e6Sthorpej 
28515e9cec1Sad 	t->pt_self = t;
286c62a74e6Sthorpej 	t->pt_magic = PT_MAGIC;
287c3f8e2eeSad 	t->pt_willpark = 0;
288c3f8e2eeSad 	t->pt_unpark = 0;
289c3f8e2eeSad 	t->pt_sleeponq = 0;
2908ccc6e06Sad 	t->pt_nwaiters = 0;
291c3f8e2eeSad 	t->pt_sleepobj = NULL;
292c3f8e2eeSad 	t->pt_signalled = 0;
293b8833ff5Sad 	t->pt_havespecific = 0;
2948ccc6e06Sad 	t->pt_early = NULL;
29566ac2ffaSad 	t->pt_lwpctl = &pthread__dummy_lwpctl;
29666ac2ffaSad 	t->pt_blocking = 0;
2971ac6a89bSad 
29815e9cec1Sad 	memcpy(&t->pt_lockops, pthread__lock_ops, sizeof(t->pt_lockops));
299f4fd6b79Sad 	pthread_mutex_init(&t->pt_lock, NULL);
300c62a74e6Sthorpej 	PTQ_INIT(&t->pt_cleanup_stack);
3017bf06aa7Sad 	PTQ_INIT(&t->pt_joiners);
302c62a74e6Sthorpej 	memset(&t->pt_specific, 0, sizeof(int) * PTHREAD_KEYS_MAX);
303c62a74e6Sthorpej }
304c62a74e6Sthorpej 
305b8833ff5Sad static void
306b8833ff5Sad pthread__scrubthread(pthread_t t, char *name, int flags)
307b8833ff5Sad {
308b8833ff5Sad 
309b8833ff5Sad 	t->pt_state = PT_STATE_RUNNING;
310b8833ff5Sad 	t->pt_exitval = NULL;
311b8833ff5Sad 	t->pt_flags = flags;
312b8833ff5Sad 	t->pt_cancel = 0;
313b8833ff5Sad 	t->pt_errno = 0;
314b8833ff5Sad 	t->pt_name = name;
315b8833ff5Sad 	t->pt_lid = 0;
316b8833ff5Sad }
317b8833ff5Sad 
318c62a74e6Sthorpej 
319c62a74e6Sthorpej int
320c62a74e6Sthorpej pthread_create(pthread_t *thread, const pthread_attr_t *attr,
321c62a74e6Sthorpej 	    void *(*startfunc)(void *), void *arg)
322c62a74e6Sthorpej {
323d9adedd7Sad 	pthread_t newthread;
324c62a74e6Sthorpej 	pthread_attr_t nattr;
325b33971b9Sthorpej 	struct pthread_attr_private *p;
3263ca3d0b1Schristos 	char * volatile name;
327ed964af1Sad 	unsigned long flag;
328ed964af1Sad 	int ret;
329c62a74e6Sthorpej 
330c62a74e6Sthorpej 	PTHREADD_ADD(PTHREADD_CREATE);
331c62a74e6Sthorpej 
332c62a74e6Sthorpej 	/*
333c62a74e6Sthorpej 	 * It's okay to check this without a lock because there can
334c62a74e6Sthorpej 	 * only be one thread before it becomes true.
335c62a74e6Sthorpej 	 */
336c62a74e6Sthorpej 	if (pthread__started == 0) {
337c62a74e6Sthorpej 		pthread__start();
338c62a74e6Sthorpej 		pthread__started = 1;
339c62a74e6Sthorpej 	}
340c62a74e6Sthorpej 
341c62a74e6Sthorpej 	if (attr == NULL)
342c62a74e6Sthorpej 		nattr = pthread_default_attr;
343e81f9f17Sdrochner 	else if (attr->pta_magic == PT_ATTR_MAGIC)
344c62a74e6Sthorpej 		nattr = *attr;
345c62a74e6Sthorpej 	else
346c62a74e6Sthorpej 		return EINVAL;
347c62a74e6Sthorpej 
348b33971b9Sthorpej 	/* Fetch misc. attributes from the attr structure. */
349508a50acSnathanw 	name = NULL;
350508a50acSnathanw 	if ((p = nattr.pta_private) != NULL)
351508a50acSnathanw 		if (p->ptap_name[0] != '\0')
352b33971b9Sthorpej 			if ((name = strdup(p->ptap_name)) == NULL)
353b33971b9Sthorpej 				return ENOMEM;
354c62a74e6Sthorpej 
355a014cf23Sad 	newthread = NULL;
356c62a74e6Sthorpej 
357b8833ff5Sad 	/*
358b8833ff5Sad 	 * Try to reclaim a dead thread.
359b8833ff5Sad 	 */
360a014cf23Sad 	if (!PTQ_EMPTY(&pthread__deadqueue)) {
361f4fd6b79Sad 		pthread_mutex_lock(&pthread__deadqueue_lock);
362c62a74e6Sthorpej 		newthread = PTQ_FIRST(&pthread__deadqueue);
3634cdc2ed8Syamt 		if (newthread != NULL) {
364b8833ff5Sad 			PTQ_REMOVE(&pthread__deadqueue, newthread, pt_deadq);
365f4fd6b79Sad 			pthread_mutex_unlock(&pthread__deadqueue_lock);
366a014cf23Sad 			if ((newthread->pt_flags & PT_FLAG_DETACHED) != 0) {
367a014cf23Sad 				/* Still running? */
36866ac2ffaSad 				if (newthread->pt_lwpctl->lc_curcpu !=
36966ac2ffaSad 				    LWPCTL_CPU_EXITED &&
37066ac2ffaSad 				    (_lwp_kill(newthread->pt_lid, 0) == 0 ||
37166ac2ffaSad 				    errno != ESRCH)) {
372f4fd6b79Sad 					pthread_mutex_lock(
373b8833ff5Sad 					    &pthread__deadqueue_lock);
37450fa8db4Sad 					PTQ_INSERT_TAIL(&pthread__deadqueue,
375b8833ff5Sad 					    newthread, pt_deadq);
376f4fd6b79Sad 					pthread_mutex_unlock(
377b8833ff5Sad 					    &pthread__deadqueue_lock);
3784cdc2ed8Syamt 					newthread = NULL;
37950fa8db4Sad 				}
3804cdc2ed8Syamt 			}
381a014cf23Sad 		} else
382f4fd6b79Sad 			pthread_mutex_unlock(&pthread__deadqueue_lock);
383a014cf23Sad 	}
384a014cf23Sad 
385b8833ff5Sad 	/*
386b8833ff5Sad 	 * If necessary set up a stack, allocate space for a pthread_st,
387b8833ff5Sad 	 * and initialize it.
388b8833ff5Sad 	 */
3894cdc2ed8Syamt 	if (newthread == NULL) {
390c62a74e6Sthorpej 		ret = pthread__stackalloc(&newthread);
391b7559f85Schristos 		if (ret != 0) {
392b7559f85Schristos 			if (name)
393b7559f85Schristos 				free(name);
394c62a74e6Sthorpej 			return ret;
395c62a74e6Sthorpej 		}
396b33971b9Sthorpej 
397b8833ff5Sad 		/* This is used only when creating the thread. */
398ed964af1Sad 		_INITCONTEXT_U(&newthread->pt_uc);
399877f8985Snathanw #ifdef PTHREAD_MACHINE_HAS_ID_REGISTER
400ed964af1Sad 		pthread__uc_id(&newthread->pt_uc) = newthread;
401877f8985Snathanw #endif
402ed964af1Sad 		newthread->pt_uc.uc_stack = newthread->pt_stack;
403ed964af1Sad 		newthread->pt_uc.uc_link = NULL;
404b8833ff5Sad 
405b8833ff5Sad 		/* Add to list of all threads. */
4069583eeb2Sad 		pthread_rwlock_wrlock(&pthread__alltree_lock);
407f1b2c1c4Sad 		PTQ_INSERT_TAIL(&pthread__allqueue, newthread, pt_allq);
4089583eeb2Sad 		RB_INSERT(__pthread__alltree, &pthread__alltree, newthread);
4099583eeb2Sad 		pthread_rwlock_unlock(&pthread__alltree_lock);
410b8833ff5Sad 
411b8833ff5Sad 		/* Will be reset by the thread upon exit. */
412b8833ff5Sad 		pthread__initthread(newthread);
413ed964af1Sad 	}
414ed964af1Sad 
415b8833ff5Sad 	/*
416b8833ff5Sad 	 * Create the new LWP.
417b8833ff5Sad 	 */
418b8833ff5Sad 	pthread__scrubthread(newthread, name, nattr.pta_flags);
41966ac2ffaSad 	makecontext(&newthread->pt_uc, pthread__create_tramp, 3,
42066ac2ffaSad 	    newthread, startfunc, arg);
421c62a74e6Sthorpej 
422ded26025Sad 	flag = 0;
423ded26025Sad 	if ((newthread->pt_flags & PT_FLAG_SUSPENDED) != 0)
424ded26025Sad 		flag |= LWP_SUSPENDED;
425ded26025Sad 	if ((newthread->pt_flags & PT_FLAG_DETACHED) != 0)
426ded26025Sad 		flag |= LWP_DETACHED;
427ed964af1Sad 	ret = _lwp_create(&newthread->pt_uc, flag, &newthread->pt_lid);
4281ac6a89bSad 	if (ret != 0) {
4291ac6a89bSad 		free(name);
430b8833ff5Sad 		newthread->pt_state = PT_STATE_DEAD;
431f4fd6b79Sad 		pthread_mutex_lock(&pthread__deadqueue_lock);
432b8833ff5Sad 		PTQ_INSERT_HEAD(&pthread__deadqueue, newthread, pt_deadq);
433f4fd6b79Sad 		pthread_mutex_unlock(&pthread__deadqueue_lock);
4341ac6a89bSad 		return ret;
4351ac6a89bSad 	}
4361ac6a89bSad 
437c62a74e6Sthorpej 	*thread = newthread;
438c62a74e6Sthorpej 
439c62a74e6Sthorpej 	return 0;
440c62a74e6Sthorpej }
441c62a74e6Sthorpej 
442c62a74e6Sthorpej 
443c62a74e6Sthorpej static void
44466ac2ffaSad pthread__create_tramp(pthread_t self, void *(*start)(void *), void *arg)
445c62a74e6Sthorpej {
446c62a74e6Sthorpej 	void *retval;
447c62a74e6Sthorpej 
44866ac2ffaSad #ifdef PTHREAD__HAVE_THREADREG
44966ac2ffaSad 	/* Set up identity register. */
45066ac2ffaSad 	pthread__threadreg_set(self);
45166ac2ffaSad #endif
45266ac2ffaSad 
45350fa8db4Sad 	/*
45450fa8db4Sad 	 * Throw away some stack in a feeble attempt to reduce cache
45550fa8db4Sad 	 * thrash.  May help for SMT processors.  XXX We should not
45650fa8db4Sad 	 * be allocating stacks on fixed 2MB boundaries.  Needs a
457f63239c2Sad 	 * thread register or decent thread local storage.  Note
458f63239c2Sad 	 * that pt_lid may not be set by this point, but we don't
459f63239c2Sad 	 * care.
46050fa8db4Sad 	 */
461f63239c2Sad 	(void)alloca(((unsigned)self->pt_lid & 7) << 8);
462f63239c2Sad 
463f63239c2Sad 	if (self->pt_name != NULL) {
464f63239c2Sad 		pthread_mutex_lock(&self->pt_lock);
465f63239c2Sad 		if (self->pt_name != NULL)
46666ac2ffaSad 			(void)_lwp_setname(0, self->pt_name);
467f63239c2Sad 		pthread_mutex_unlock(&self->pt_lock);
468f63239c2Sad 	}
46950fa8db4Sad 
47066ac2ffaSad 	/*
47166ac2ffaSad 	 * Don't need lwpctl if running on a uniprocessor.
47266ac2ffaSad 	 * Just use the dummy block.
47366ac2ffaSad 	 */
47466ac2ffaSad 	if (pthread__concurrency > 1)
47566ac2ffaSad 		(void)_lwp_ctl(LWPCTL_FEATURE_CURCPU, &self->pt_lwpctl);
47666ac2ffaSad 
47794a458ceSchs 	retval = (*start)(arg);
478c62a74e6Sthorpej 
479c62a74e6Sthorpej 	pthread_exit(retval);
480c62a74e6Sthorpej 
481143f5a27Schristos 	/*NOTREACHED*/
482143f5a27Schristos 	pthread__abort();
483c62a74e6Sthorpej }
484c62a74e6Sthorpej 
48538b1c6f4Schristos int
48638b1c6f4Schristos pthread_suspend_np(pthread_t thread)
48738b1c6f4Schristos {
488ba70e96aSchs 	pthread_t self;
489ba70e96aSchs 
490ba70e96aSchs 	self = pthread__self();
49138b1c6f4Schristos 	if (self == thread) {
49238b1c6f4Schristos 		return EDEADLK;
49338b1c6f4Schristos 	}
494ba70e96aSchs #ifdef ERRORCHECK
495d9adedd7Sad 	if (pthread__find(thread) != 0)
496ba70e96aSchs 		return ESRCH;
497ba70e96aSchs #endif
49840724da2Sad 	if (_lwp_suspend(thread->pt_lid) == 0)
49940724da2Sad 		return 0;
50040724da2Sad 	return errno;
50138b1c6f4Schristos }
50238b1c6f4Schristos 
50338b1c6f4Schristos int
50438b1c6f4Schristos pthread_resume_np(pthread_t thread)
50538b1c6f4Schristos {
50638b1c6f4Schristos 
507ba70e96aSchs #ifdef ERRORCHECK
508d9adedd7Sad 	if (pthread__find(thread) != 0)
509ba70e96aSchs 		return ESRCH;
510ba70e96aSchs #endif
51140724da2Sad 	if (_lwp_continue(thread->pt_lid) == 0)
51240724da2Sad 		return 0;
51340724da2Sad 	return errno;
51438b1c6f4Schristos }
51538b1c6f4Schristos 
516c62a74e6Sthorpej void
517c62a74e6Sthorpej pthread_exit(void *retval)
518c62a74e6Sthorpej {
51996b5a26dSnathanw 	pthread_t self;
520c62a74e6Sthorpej 	struct pt_clean_t *cleanup;
521b33971b9Sthorpej 	char *name;
522c62a74e6Sthorpej 
523c62a74e6Sthorpej 	self = pthread__self();
524c62a74e6Sthorpej 
525c62a74e6Sthorpej 	/* Disable cancellability. */
526f4fd6b79Sad 	pthread_mutex_lock(&self->pt_lock);
527c62a74e6Sthorpej 	self->pt_flags |= PT_FLAG_CS_DISABLED;
52866fcc1ceSnathanw 	self->pt_cancel = 0;
529f4fd6b79Sad 	pthread_mutex_unlock(&self->pt_lock);
530c62a74e6Sthorpej 
531c62a74e6Sthorpej 	/* Call any cancellation cleanup handlers */
532c62a74e6Sthorpej 	while (!PTQ_EMPTY(&self->pt_cleanup_stack)) {
533c62a74e6Sthorpej 		cleanup = PTQ_FIRST(&self->pt_cleanup_stack);
534c62a74e6Sthorpej 		PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next);
535c62a74e6Sthorpej 		(*cleanup->ptc_cleanup)(cleanup->ptc_arg);
536c62a74e6Sthorpej 	}
537c62a74e6Sthorpej 
538c62a74e6Sthorpej 	/* Perform cleanup of thread-specific data */
539c62a74e6Sthorpej 	pthread__destroy_tsd(self);
540c62a74e6Sthorpej 
541c62a74e6Sthorpej 	self->pt_exitval = retval;
542c62a74e6Sthorpej 
543f4fd6b79Sad 	pthread_mutex_lock(&self->pt_lock);
5446b2b9c62Syamt 	if (self->pt_flags & PT_FLAG_DETACHED) {
5456b2b9c62Syamt 		self->pt_state = PT_STATE_DEAD;
546b33971b9Sthorpej 		name = self->pt_name;
547b33971b9Sthorpej 		self->pt_name = NULL;
548f4fd6b79Sad 		pthread_mutex_lock(&pthread__deadqueue_lock);
549b8833ff5Sad 		PTQ_INSERT_TAIL(&pthread__deadqueue, self, pt_deadq);
550f4fd6b79Sad 		pthread_mutex_unlock(&pthread__deadqueue_lock);
551f4fd6b79Sad 		pthread_mutex_unlock(&self->pt_lock);
552b33971b9Sthorpej 		if (name != NULL)
553b33971b9Sthorpej 			free(name);
5541ac6a89bSad 		_lwp_exit();
555c62a74e6Sthorpej 	} else {
5566b2b9c62Syamt 		self->pt_state = PT_STATE_ZOMBIE;
557f4fd6b79Sad 		pthread_mutex_unlock(&self->pt_lock);
558b33971b9Sthorpej 		/* Note: name will be freed by the joiner. */
5591ac6a89bSad 		_lwp_exit();
560c62a74e6Sthorpej 	}
561c62a74e6Sthorpej 
562143f5a27Schristos 	/*NOTREACHED*/
563143f5a27Schristos 	pthread__abort();
564c62a74e6Sthorpej 	exit(1);
565c62a74e6Sthorpej }
566c62a74e6Sthorpej 
567c62a74e6Sthorpej 
568c62a74e6Sthorpej int
569c62a74e6Sthorpej pthread_join(pthread_t thread, void **valptr)
570c62a74e6Sthorpej {
571c62a74e6Sthorpej 	pthread_t self;
572b33971b9Sthorpej 	char *name;
573c62a74e6Sthorpej 
574c62a74e6Sthorpej 	self = pthread__self();
575c62a74e6Sthorpej 
576d9adedd7Sad 	if (pthread__find(thread) != 0)
577c62a74e6Sthorpej 		return ESRCH;
578c62a74e6Sthorpej 
579c62a74e6Sthorpej 	if (thread->pt_magic != PT_MAGIC)
580c62a74e6Sthorpej 		return EINVAL;
581c62a74e6Sthorpej 
582c62a74e6Sthorpej 	if (thread == self)
583c62a74e6Sthorpej 		return EDEADLK;
584c62a74e6Sthorpej 
585ded26025Sad 	/*
586ded26025Sad 	 * IEEE Std 1003.1, 2004 Edition:
587ded26025Sad 	 *
588c94f5a91Sad 	 * "The pthread_join() function shall not return an
589c94f5a91Sad 	 * error code of [EINTR]."
590ded26025Sad 	 */
591c94f5a91Sad 	while (_lwp_wait(thread->pt_lid, NULL) != 0) {
592c94f5a91Sad 		if (errno != EINTR)
593ded26025Sad 			return errno;
594c94f5a91Sad 	}
595c94f5a91Sad 
596c94f5a91Sad 	/*
597c94f5a91Sad 	 * No need to lock - nothing else should (legally) be
598c94f5a91Sad 	 * interested in the thread's state at this point.
599c94f5a91Sad 	 *
600c94f5a91Sad 	 * _lwp_wait() provides a barrier, so the user level
601c94f5a91Sad 	 * thread state will be visible to us at this point.
602c94f5a91Sad 	 */
603c94f5a91Sad 	if (thread->pt_state != PT_STATE_ZOMBIE) {
604c94f5a91Sad 		pthread__errorfunc(__FILE__, __LINE__, __func__,
605c94f5a91Sad 		    "not a zombie");
606c94f5a91Sad 	}
6071ac6a89bSad 	if (valptr != NULL)
608ded26025Sad 		*valptr = thread->pt_exitval;
6091ac6a89bSad 	name = thread->pt_name;
6101ac6a89bSad 	thread->pt_name = NULL;
6111ac6a89bSad 	thread->pt_state = PT_STATE_DEAD;
612f4fd6b79Sad 	pthread_mutex_lock(&pthread__deadqueue_lock);
613b8833ff5Sad 	PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_deadq);
614f4fd6b79Sad 	pthread_mutex_unlock(&pthread__deadqueue_lock);
61550fa8db4Sad 	if (name != NULL)
61650fa8db4Sad 		free(name);
617c94f5a91Sad 	return 0;
618c62a74e6Sthorpej }
619c62a74e6Sthorpej 
620c62a74e6Sthorpej 
621c62a74e6Sthorpej int
622c62a74e6Sthorpej pthread_equal(pthread_t t1, pthread_t t2)
623c62a74e6Sthorpej {
624c62a74e6Sthorpej 
625c62a74e6Sthorpej 	/* Nothing special here. */
626c62a74e6Sthorpej 	return (t1 == t2);
627c62a74e6Sthorpej }
628c62a74e6Sthorpej 
629c62a74e6Sthorpej 
630c62a74e6Sthorpej int
631c62a74e6Sthorpej pthread_detach(pthread_t thread)
632c62a74e6Sthorpej {
633f4fd6b79Sad 	int rv;
634c62a74e6Sthorpej 
635d9adedd7Sad 	if (pthread__find(thread) != 0)
636c62a74e6Sthorpej 		return ESRCH;
637c62a74e6Sthorpej 
638c62a74e6Sthorpej 	if (thread->pt_magic != PT_MAGIC)
639c62a74e6Sthorpej 		return EINVAL;
640c62a74e6Sthorpej 
641f4fd6b79Sad 	pthread_mutex_lock(&thread->pt_lock);
6421296e850Sad 	thread->pt_flags |= PT_FLAG_DETACHED;
643f4fd6b79Sad 	rv = _lwp_detach(thread->pt_lid);
644f4fd6b79Sad 	pthread_mutex_unlock(&thread->pt_lock);
645de213816Sad 
646f4fd6b79Sad 	if (rv == 0)
64740724da2Sad 		return 0;
64840724da2Sad 	return errno;
649c62a74e6Sthorpej }
650c62a74e6Sthorpej 
651c62a74e6Sthorpej 
652c62a74e6Sthorpej int
653b33971b9Sthorpej pthread_getname_np(pthread_t thread, char *name, size_t len)
654c62a74e6Sthorpej {
655c62a74e6Sthorpej 
656d9adedd7Sad 	if (pthread__find(thread) != 0)
657b33971b9Sthorpej 		return ESRCH;
658b33971b9Sthorpej 
659b33971b9Sthorpej 	if (thread->pt_magic != PT_MAGIC)
660b33971b9Sthorpej 		return EINVAL;
661b33971b9Sthorpej 
662f4fd6b79Sad 	pthread_mutex_lock(&thread->pt_lock);
663b33971b9Sthorpej 	if (thread->pt_name == NULL)
664b33971b9Sthorpej 		name[0] = '\0';
665b33971b9Sthorpej 	else
666b33971b9Sthorpej 		strlcpy(name, thread->pt_name, len);
667f4fd6b79Sad 	pthread_mutex_unlock(&thread->pt_lock);
668c62a74e6Sthorpej 
669c62a74e6Sthorpej 	return 0;
670c62a74e6Sthorpej }
671c62a74e6Sthorpej 
672c62a74e6Sthorpej 
673c62a74e6Sthorpej int
674b33971b9Sthorpej pthread_setname_np(pthread_t thread, const char *name, void *arg)
675b33971b9Sthorpej {
676b33971b9Sthorpej 	char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP];
677b33971b9Sthorpej 	int namelen;
678b33971b9Sthorpej 
679d9adedd7Sad 	if (pthread__find(thread) != 0)
680b33971b9Sthorpej 		return ESRCH;
681b33971b9Sthorpej 
682b33971b9Sthorpej 	if (thread->pt_magic != PT_MAGIC)
683b33971b9Sthorpej 		return EINVAL;
684b33971b9Sthorpej 
685b33971b9Sthorpej 	namelen = snprintf(newname, sizeof(newname), name, arg);
686b33971b9Sthorpej 	if (namelen >= PTHREAD_MAX_NAMELEN_NP)
687b33971b9Sthorpej 		return EINVAL;
688b33971b9Sthorpej 
689b33971b9Sthorpej 	cp = strdup(newname);
690b33971b9Sthorpej 	if (cp == NULL)
691b33971b9Sthorpej 		return ENOMEM;
692b33971b9Sthorpej 
693f4fd6b79Sad 	pthread_mutex_lock(&thread->pt_lock);
694b33971b9Sthorpej 	oldname = thread->pt_name;
695b33971b9Sthorpej 	thread->pt_name = cp;
696f63239c2Sad 	(void)_lwp_setname(thread->pt_lid, cp);
697f4fd6b79Sad 	pthread_mutex_unlock(&thread->pt_lock);
698b33971b9Sthorpej 
699b33971b9Sthorpej 	if (oldname != NULL)
700b33971b9Sthorpej 		free(oldname);
701b33971b9Sthorpej 
702b33971b9Sthorpej 	return 0;
703b33971b9Sthorpej }
704b33971b9Sthorpej 
705b33971b9Sthorpej 
706b33971b9Sthorpej 
707c62a74e6Sthorpej /*
708c62a74e6Sthorpej  * XXX There should be a way for applications to use the efficent
709c62a74e6Sthorpej  *  inline version, but there are opacity/namespace issues.
710c62a74e6Sthorpej  */
711c62a74e6Sthorpej pthread_t
712c62a74e6Sthorpej pthread_self(void)
713c62a74e6Sthorpej {
714c62a74e6Sthorpej 
715c62a74e6Sthorpej 	return pthread__self();
716c62a74e6Sthorpej }
717c62a74e6Sthorpej 
718c62a74e6Sthorpej 
719c62a74e6Sthorpej int
720c62a74e6Sthorpej pthread_cancel(pthread_t thread)
721c62a74e6Sthorpej {
722c62a74e6Sthorpej 
723d9adedd7Sad 	if (pthread__find(thread) != 0)
724ba70e96aSchs 		return ESRCH;
725f4fd6b79Sad 	pthread_mutex_lock(&thread->pt_lock);
7261ac6a89bSad 	thread->pt_flags |= PT_FLAG_CS_PENDING;
7271ac6a89bSad 	if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) {
7281ac6a89bSad 		thread->pt_cancel = 1;
729f4fd6b79Sad 		pthread_mutex_unlock(&thread->pt_lock);
7301ac6a89bSad 		_lwp_wakeup(thread->pt_lid);
7311ac6a89bSad 	} else
732f4fd6b79Sad 		pthread_mutex_unlock(&thread->pt_lock);
733c62a74e6Sthorpej 
734c62a74e6Sthorpej 	return 0;
735c62a74e6Sthorpej }
736c62a74e6Sthorpej 
737c62a74e6Sthorpej 
738c62a74e6Sthorpej int
739c62a74e6Sthorpej pthread_setcancelstate(int state, int *oldstate)
740c62a74e6Sthorpej {
741c62a74e6Sthorpej 	pthread_t self;
7420878df5dSnathanw 	int retval;
743c62a74e6Sthorpej 
744c62a74e6Sthorpej 	self = pthread__self();
7450878df5dSnathanw 	retval = 0;
746c62a74e6Sthorpej 
747f4fd6b79Sad 	pthread_mutex_lock(&self->pt_lock);
74850fa8db4Sad 
749c62a74e6Sthorpej 	if (oldstate != NULL) {
7500878df5dSnathanw 		if (self->pt_flags & PT_FLAG_CS_DISABLED)
751c62a74e6Sthorpej 			*oldstate = PTHREAD_CANCEL_DISABLE;
752c62a74e6Sthorpej 		else
753c62a74e6Sthorpej 			*oldstate = PTHREAD_CANCEL_ENABLE;
754c62a74e6Sthorpej 	}
755c62a74e6Sthorpej 
7560878df5dSnathanw 	if (state == PTHREAD_CANCEL_DISABLE) {
7570878df5dSnathanw 		self->pt_flags |= PT_FLAG_CS_DISABLED;
7580878df5dSnathanw 		if (self->pt_cancel) {
7590878df5dSnathanw 			self->pt_flags |= PT_FLAG_CS_PENDING;
7600878df5dSnathanw 			self->pt_cancel = 0;
7610878df5dSnathanw 		}
7620878df5dSnathanw 	} else if (state == PTHREAD_CANCEL_ENABLE) {
7630878df5dSnathanw 		self->pt_flags &= ~PT_FLAG_CS_DISABLED;
764c62a74e6Sthorpej 		/*
765c62a74e6Sthorpej 		 * If a cancellation was requested while cancellation
766c62a74e6Sthorpej 		 * was disabled, note that fact for future
767c62a74e6Sthorpej 		 * cancellation tests.
768c62a74e6Sthorpej 		 */
7690878df5dSnathanw 		if (self->pt_flags & PT_FLAG_CS_PENDING) {
770c62a74e6Sthorpej 			self->pt_cancel = 1;
771c62a74e6Sthorpej 			/* This is not a deferred cancellation point. */
7720878df5dSnathanw 			if (self->pt_flags & PT_FLAG_CS_ASYNC) {
773f4fd6b79Sad 				pthread_mutex_unlock(&self->pt_lock);
774c62a74e6Sthorpej 				pthread_exit(PTHREAD_CANCELED);
775c62a74e6Sthorpej 			}
7760878df5dSnathanw 		}
777c62a74e6Sthorpej 	} else
7780878df5dSnathanw 		retval = EINVAL;
779c62a74e6Sthorpej 
780f4fd6b79Sad 	pthread_mutex_unlock(&self->pt_lock);
78150fa8db4Sad 
7820878df5dSnathanw 	return retval;
783c62a74e6Sthorpej }
784c62a74e6Sthorpej 
785c62a74e6Sthorpej 
786c62a74e6Sthorpej int
787c62a74e6Sthorpej pthread_setcanceltype(int type, int *oldtype)
788c62a74e6Sthorpej {
789c62a74e6Sthorpej 	pthread_t self;
7900878df5dSnathanw 	int retval;
791c62a74e6Sthorpej 
792c62a74e6Sthorpej 	self = pthread__self();
7930878df5dSnathanw 	retval = 0;
7940878df5dSnathanw 
795f4fd6b79Sad 	pthread_mutex_lock(&self->pt_lock);
796c62a74e6Sthorpej 
797c62a74e6Sthorpej 	if (oldtype != NULL) {
7980878df5dSnathanw 		if (self->pt_flags & PT_FLAG_CS_ASYNC)
799c62a74e6Sthorpej 			*oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
800c62a74e6Sthorpej 		else
801c62a74e6Sthorpej 			*oldtype = PTHREAD_CANCEL_DEFERRED;
802c62a74e6Sthorpej 	}
803c62a74e6Sthorpej 
804c62a74e6Sthorpej 	if (type == PTHREAD_CANCEL_ASYNCHRONOUS) {
8050878df5dSnathanw 		self->pt_flags |= PT_FLAG_CS_ASYNC;
8060878df5dSnathanw 		if (self->pt_cancel) {
807f4fd6b79Sad 			pthread_mutex_unlock(&self->pt_lock);
808c62a74e6Sthorpej 			pthread_exit(PTHREAD_CANCELED);
8090878df5dSnathanw 		}
810c62a74e6Sthorpej 	} else if (type == PTHREAD_CANCEL_DEFERRED)
8110878df5dSnathanw 		self->pt_flags &= ~PT_FLAG_CS_ASYNC;
812c62a74e6Sthorpej 	else
8130878df5dSnathanw 		retval = EINVAL;
814c62a74e6Sthorpej 
815f4fd6b79Sad 	pthread_mutex_unlock(&self->pt_lock);
81650fa8db4Sad 
8170878df5dSnathanw 	return retval;
818c62a74e6Sthorpej }
819c62a74e6Sthorpej 
820c62a74e6Sthorpej 
821c62a74e6Sthorpej void
822c62a74e6Sthorpej pthread_testcancel()
823c62a74e6Sthorpej {
824c62a74e6Sthorpej 	pthread_t self;
825c62a74e6Sthorpej 
826c62a74e6Sthorpej 	self = pthread__self();
827c62a74e6Sthorpej 	if (self->pt_cancel)
828c62a74e6Sthorpej 		pthread_exit(PTHREAD_CANCELED);
829c62a74e6Sthorpej }
830c62a74e6Sthorpej 
831c62a74e6Sthorpej 
832c62a74e6Sthorpej /*
833c62a74e6Sthorpej  * POSIX requires that certain functions return an error rather than
834c62a74e6Sthorpej  * invoking undefined behavior even when handed completely bogus
835c62a74e6Sthorpej  * pthread_t values, e.g. stack garbage or (pthread_t)666. This
836c62a74e6Sthorpej  * utility routine searches the list of threads for the pthread_t
837c62a74e6Sthorpej  * value without dereferencing it.
838c62a74e6Sthorpej  */
839c62a74e6Sthorpej int
840d9adedd7Sad pthread__find(pthread_t id)
841c62a74e6Sthorpej {
842c62a74e6Sthorpej 	pthread_t target;
843c62a74e6Sthorpej 
8449583eeb2Sad 	pthread_rwlock_rdlock(&pthread__alltree_lock);
8459583eeb2Sad 	/* LINTED */
8469583eeb2Sad 	target = RB_FIND(__pthread__alltree, &pthread__alltree, id);
8479583eeb2Sad 	pthread_rwlock_unlock(&pthread__alltree_lock);
848c62a74e6Sthorpej 
849b8833ff5Sad 	if (target == NULL || target->pt_state == PT_STATE_DEAD)
850c62a74e6Sthorpej 		return ESRCH;
851c62a74e6Sthorpej 
852c62a74e6Sthorpej 	return 0;
853c62a74e6Sthorpej }
854c62a74e6Sthorpej 
855c62a74e6Sthorpej 
856c62a74e6Sthorpej void
857c62a74e6Sthorpej pthread__testcancel(pthread_t self)
858c62a74e6Sthorpej {
859c62a74e6Sthorpej 
860c62a74e6Sthorpej 	if (self->pt_cancel)
861c62a74e6Sthorpej 		pthread_exit(PTHREAD_CANCELED);
862c62a74e6Sthorpej }
863c62a74e6Sthorpej 
864c62a74e6Sthorpej 
865c62a74e6Sthorpej void
866c62a74e6Sthorpej pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store)
867c62a74e6Sthorpej {
868c62a74e6Sthorpej 	pthread_t self;
869c62a74e6Sthorpej 	struct pt_clean_t *entry;
870c62a74e6Sthorpej 
871c62a74e6Sthorpej 	self = pthread__self();
872c62a74e6Sthorpej 	entry = store;
873c62a74e6Sthorpej 	entry->ptc_cleanup = cleanup;
874c62a74e6Sthorpej 	entry->ptc_arg = arg;
875c62a74e6Sthorpej 	PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next);
876c62a74e6Sthorpej }
877c62a74e6Sthorpej 
878c62a74e6Sthorpej 
879c62a74e6Sthorpej void
880c62a74e6Sthorpej pthread__cleanup_pop(int ex, void *store)
881c62a74e6Sthorpej {
882c62a74e6Sthorpej 	pthread_t self;
883c62a74e6Sthorpej 	struct pt_clean_t *entry;
884c62a74e6Sthorpej 
885c62a74e6Sthorpej 	self = pthread__self();
886c62a74e6Sthorpej 	entry = store;
887c62a74e6Sthorpej 
888c62a74e6Sthorpej 	PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next);
889c62a74e6Sthorpej 	if (ex)
890c62a74e6Sthorpej 		(*entry->ptc_cleanup)(entry->ptc_arg);
891c62a74e6Sthorpej }
892c62a74e6Sthorpej 
893c62a74e6Sthorpej 
894c62a74e6Sthorpej int *
895c62a74e6Sthorpej pthread__errno(void)
896c62a74e6Sthorpej {
897c62a74e6Sthorpej 	pthread_t self;
898c62a74e6Sthorpej 
899c62a74e6Sthorpej 	self = pthread__self();
900c62a74e6Sthorpej 
901c62a74e6Sthorpej 	return &(self->pt_errno);
902c62a74e6Sthorpej }
9038bcff70bSnathanw 
9040c967901Snathanw ssize_t	_sys_write(int, const void *, size_t);
9050c967901Snathanw 
9068bcff70bSnathanw void
9070e6c93b9Sdrochner pthread__assertfunc(const char *file, int line, const char *function,
9080e6c93b9Sdrochner 		    const char *expr)
9098bcff70bSnathanw {
9108bcff70bSnathanw 	char buf[1024];
9118bcff70bSnathanw 	int len;
9128bcff70bSnathanw 
9138bcff70bSnathanw 	/*
9148bcff70bSnathanw 	 * snprintf should not acquire any locks, or we could
9158bcff70bSnathanw 	 * end up deadlocked if the assert caller held locks.
9168bcff70bSnathanw 	 */
9178bcff70bSnathanw 	len = snprintf(buf, 1024,
9188bcff70bSnathanw 	    "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
9198bcff70bSnathanw 	    expr, file, line,
9208bcff70bSnathanw 	    function ? ", function \"" : "",
9218bcff70bSnathanw 	    function ? function : "",
9228bcff70bSnathanw 	    function ? "\"" : "");
9238bcff70bSnathanw 
9240c967901Snathanw 	_sys_write(STDERR_FILENO, buf, (size_t)len);
9258bcff70bSnathanw 	(void)kill(getpid(), SIGABRT);
9268bcff70bSnathanw 
9278bcff70bSnathanw 	_exit(1);
9288bcff70bSnathanw }
929df277271Snathanw 
930df277271Snathanw 
931df277271Snathanw void
9320e6c93b9Sdrochner pthread__errorfunc(const char *file, int line, const char *function,
9330e6c93b9Sdrochner 		   const char *msg)
934df277271Snathanw {
935df277271Snathanw 	char buf[1024];
9360172694eSnathanw 	size_t len;
937df277271Snathanw 
9380172694eSnathanw 	if (pthread__diagassert == 0)
939df277271Snathanw 		return;
940df277271Snathanw 
941df277271Snathanw 	/*
942df277271Snathanw 	 * snprintf should not acquire any locks, or we could
943df277271Snathanw 	 * end up deadlocked if the assert caller held locks.
944df277271Snathanw 	 */
945df277271Snathanw 	len = snprintf(buf, 1024,
9460172694eSnathanw 	    "%s: Error detected by libpthread: %s.\n"
9470172694eSnathanw 	    "Detected by file \"%s\", line %d%s%s%s.\n"
9480172694eSnathanw 	    "See pthread(3) for information.\n",
9490172694eSnathanw 	    getprogname(), msg, file, line,
950df277271Snathanw 	    function ? ", function \"" : "",
951df277271Snathanw 	    function ? function : "",
9520172694eSnathanw 	    function ? "\"" : "");
953df277271Snathanw 
9540172694eSnathanw 	if (pthread__diagassert & DIAGASSERT_STDERR)
9550c967901Snathanw 		_sys_write(STDERR_FILENO, buf, len);
9560172694eSnathanw 
9570172694eSnathanw 	if (pthread__diagassert & DIAGASSERT_SYSLOG)
9580172694eSnathanw 		syslog(LOG_DEBUG | LOG_USER, "%s", buf);
9590172694eSnathanw 
9600172694eSnathanw 	if (pthread__diagassert & DIAGASSERT_ABORT) {
961df277271Snathanw 		(void)kill(getpid(), SIGABRT);
962df277271Snathanw 		_exit(1);
963df277271Snathanw 	}
964df277271Snathanw }
9651ac6a89bSad 
966fe9718acSad /*
967ded26025Sad  * Thread park/unpark operations.  The kernel operations are
968ded26025Sad  * modelled after a brief description from "Multithreading in
969ded26025Sad  * the Solaris Operating Environment":
970fe9718acSad  *
971fe9718acSad  * http://www.sun.com/software/whitepapers/solaris9/multithread.pdf
972fe9718acSad  */
973fe9718acSad 
9741ac6a89bSad #define	OOPS(msg)			\
975858097f9Schristos     pthread__errorfunc(__FILE__, __LINE__, __func__, msg)
9761ac6a89bSad 
9771ac6a89bSad int
9781ac6a89bSad pthread__park(pthread_t self, pthread_spin_t *lock,
97950fa8db4Sad 	      pthread_queue_t *queue, const struct timespec *abstime,
98050fa8db4Sad 	      int cancelpt, const void *hint)
9811ac6a89bSad {
982c3f8e2eeSad 	int rv, error;
9838ccc6e06Sad 	void *obj;
9841ac6a89bSad 
985c3f8e2eeSad 	/* Clear the willpark flag, since we're about to block. */
986c3f8e2eeSad 	self->pt_willpark = 0;
987c3f8e2eeSad 
988c3f8e2eeSad 	/*
98966ac2ffaSad 	 * For non-interlocked release of mutexes we need a store
99066ac2ffaSad 	 * barrier before incrementing pt_blocking away from zero.
99166ac2ffaSad 	 * This is provided by the caller (it will release an
99266ac2ffaSad 	 * interlock, or do an explicit barrier).
99366ac2ffaSad 	 */
99466ac2ffaSad 	self->pt_blocking++;
99566ac2ffaSad 
99666ac2ffaSad 	/*
997c3f8e2eeSad 	 * Kernels before 4.99.27 can't park and unpark in one step,
998c3f8e2eeSad 	 * so take care of it now if on an old kernel.
999c3f8e2eeSad 	 *
1000c3f8e2eeSad 	 * XXX Remove this check before NetBSD 5.0 is released.
1001c3f8e2eeSad 	 * It's for compatibility with recent -current only.
1002c3f8e2eeSad 	 */
1003c3f8e2eeSad 	if (__predict_false(pthread__osrev < 499002700) &&
1004c3f8e2eeSad 	    self->pt_unpark != 0) {
1005c3f8e2eeSad 		_lwp_unpark(self->pt_unpark, self->pt_unparkhint);
1006c3f8e2eeSad 		self->pt_unpark = 0;
1007c3f8e2eeSad 	}
1008c3f8e2eeSad 
1009ded26025Sad 	/*
1010ded26025Sad 	 * Wait until we are awoken by a pending unpark operation,
1011ded26025Sad 	 * a signal, an unpark posted after we have gone asleep,
1012ded26025Sad 	 * or an expired timeout.
101350fa8db4Sad 	 *
101450fa8db4Sad 	 * It is fine to test the value of both pt_sleepobj and
101550fa8db4Sad 	 * pt_sleeponq without holding any locks, because:
101650fa8db4Sad 	 *
101750fa8db4Sad 	 * o Only the blocking thread (this thread) ever sets them
101850fa8db4Sad 	 *   to a non-NULL value.
101950fa8db4Sad 	 *
102050fa8db4Sad 	 * o Other threads may set them NULL, but if they do so they
102150fa8db4Sad 	 *   must also make this thread return from _lwp_park.
102250fa8db4Sad 	 *
102350fa8db4Sad 	 * o _lwp_park, _lwp_unpark and _lwp_unpark_all are system
102450fa8db4Sad 	 *   calls and all make use of spinlocks in the kernel.  So
102550fa8db4Sad 	 *   these system calls act as full memory barriers, and will
102650fa8db4Sad 	 *   ensure that the calling CPU's store buffers are drained.
102750fa8db4Sad 	 *   In combination with the spinlock release before unpark,
102850fa8db4Sad 	 *   this means that modification of pt_sleepobj/onq by another
102950fa8db4Sad 	 *   thread will become globally visible before that thread
103050fa8db4Sad 	 *   schedules an unpark operation on this thread.
1031c3f8e2eeSad 	 *
1032c3f8e2eeSad 	 * Note: the test in the while() statement dodges the park op if
1033c3f8e2eeSad 	 * we have already been awoken, unless there is another thread to
1034c3f8e2eeSad 	 * awaken.  This saves a syscall - if we were already awakened,
1035c3f8e2eeSad 	 * the next call to _lwp_park() would need to return early in order
1036c3f8e2eeSad 	 * to eat the previous wakeup.
1037ded26025Sad 	 */
1038ded26025Sad 	rv = 0;
1039c3f8e2eeSad 	while ((self->pt_sleepobj != NULL || self->pt_unpark != 0) && rv == 0) {
1040c3f8e2eeSad 		/*
1041c3f8e2eeSad 		 * If we deferred unparking a thread, arrange to
1042c3f8e2eeSad 		 * have _lwp_park() restart it before blocking.
1043c3f8e2eeSad 		 */
1044c3f8e2eeSad 		error = _lwp_park(abstime, self->pt_unpark, hint,
1045c3f8e2eeSad 		    self->pt_unparkhint);
1046c3f8e2eeSad 		self->pt_unpark = 0;
1047c3f8e2eeSad 		if (error != 0) {
1048ded26025Sad 			switch (rv = errno) {
10491ac6a89bSad 			case EINTR:
10501ac6a89bSad 			case EALREADY:
1051ded26025Sad 				rv = 0;
1052ded26025Sad 				break;
1053ded26025Sad 			case ETIMEDOUT:
10541ac6a89bSad 				break;
10551ac6a89bSad 			default:
10561ac6a89bSad 				OOPS("_lwp_park failed");
10571ac6a89bSad 				break;
10581ac6a89bSad 			}
1059ded26025Sad 		}
10600c61b6a6Sad 		/* Check for cancellation. */
1061d9adedd7Sad 		if (cancelpt && self->pt_cancel)
10620c61b6a6Sad 			rv = EINTR;
106350fa8db4Sad 	}
10641ac6a89bSad 
1065ded26025Sad 	/*
1066ded26025Sad 	 * If we have been awoken early but are still on the queue,
106750fa8db4Sad 	 * then remove ourself.  Again, it's safe to do the test
106850fa8db4Sad 	 * without holding any locks.
1069ded26025Sad 	 */
10708ccc6e06Sad 	if (__predict_false(self->pt_sleeponq)) {
107115e9cec1Sad 		pthread__spinlock(self, lock);
107250fa8db4Sad 		if (self->pt_sleeponq) {
10731ac6a89bSad 			PTQ_REMOVE(queue, self, pt_sleep);
10748ccc6e06Sad 			obj = self->pt_sleepobj;
10751ac6a89bSad 			self->pt_sleepobj = NULL;
1076ded26025Sad 			self->pt_sleeponq = 0;
10778ccc6e06Sad 			if (obj != NULL && self->pt_early != NULL)
10788ccc6e06Sad 				(*self->pt_early)(obj);
1079792cc0e1Sad 		}
108015e9cec1Sad 		pthread__spinunlock(self, lock);
108150fa8db4Sad 	}
10828ccc6e06Sad 	self->pt_early = NULL;
108366ac2ffaSad 	self->pt_blocking--;
10841ac6a89bSad 
10851ac6a89bSad 	return rv;
10861ac6a89bSad }
10871ac6a89bSad 
10881ac6a89bSad void
1089792cc0e1Sad pthread__unpark(pthread_t self, pthread_spin_t *lock,
109050fa8db4Sad 		pthread_queue_t *queue, pthread_t target)
10911ac6a89bSad {
10921ac6a89bSad 	int rv;
10931ac6a89bSad 
10940c61b6a6Sad 	if (target == NULL) {
109515e9cec1Sad 		pthread__spinunlock(self, lock);
10960c61b6a6Sad 		return;
10970c61b6a6Sad 	}
10980c61b6a6Sad 
1099ded26025Sad 	/*
1100ded26025Sad 	 * Easy: the thread has already been removed from
1101ded26025Sad 	 * the queue, so just awaken it.
1102ded26025Sad 	 */
11031ac6a89bSad 	target->pt_sleepobj = NULL;
1104ded26025Sad 	target->pt_sleeponq = 0;
110550fa8db4Sad 
110650fa8db4Sad 	/*
110750fa8db4Sad 	 * Releasing the spinlock serves as a store barrier,
110850fa8db4Sad 	 * which ensures that all our modifications are visible
110950fa8db4Sad 	 * to the thread in pthread__park() before the unpark
111050fa8db4Sad 	 * operation is set in motion.
111150fa8db4Sad 	 */
111215e9cec1Sad 	pthread__spinunlock(self, lock);
11131ac6a89bSad 
1114c3f8e2eeSad 	/*
1115c3f8e2eeSad 	 * If the calling thread is about to block, defer
1116c3f8e2eeSad 	 * unparking the target until _lwp_park() is called.
1117c3f8e2eeSad 	 */
1118c3f8e2eeSad 	if (self->pt_willpark && self->pt_unpark == 0) {
1119c3f8e2eeSad 		self->pt_unpark = target->pt_lid;
1120c3f8e2eeSad 		self->pt_unparkhint = queue;
1121c3f8e2eeSad 	} else {
1122c3f8e2eeSad 		rv = _lwp_unpark(target->pt_lid, queue);
11231ac6a89bSad 		if (rv != 0 && errno != EALREADY && errno != EINTR) {
11241ac6a89bSad 			OOPS("_lwp_unpark failed");
11251ac6a89bSad 		}
11261ac6a89bSad 	}
1127c3f8e2eeSad }
11281ac6a89bSad 
11291ac6a89bSad void
1130792cc0e1Sad pthread__unpark_all(pthread_t self, pthread_spin_t *lock,
113150fa8db4Sad 		    pthread_queue_t *queue)
11321ac6a89bSad {
113367513ce0Sad 	ssize_t n, rv;
1134ded26025Sad 	pthread_t thread, next;
11358ccc6e06Sad 	void *wakeobj;
1136ded26025Sad 
11378ccc6e06Sad 	if (PTQ_EMPTY(queue) && self->pt_nwaiters == 0) {
113815e9cec1Sad 		pthread__spinunlock(self, lock);
1139ded26025Sad 		return;
1140ded26025Sad 	}
1141ded26025Sad 
11428ccc6e06Sad 	wakeobj = queue;
11431ac6a89bSad 
11448ccc6e06Sad 	for (;; n = 0) {
11458ccc6e06Sad 		/*
11468ccc6e06Sad 		 * Pull waiters from the queue and add to this
11478ccc6e06Sad 		 * thread's waiters list.
11488ccc6e06Sad 		 */
1149ded26025Sad 		thread = PTQ_FIRST(queue);
11508ccc6e06Sad 		for (n = self->pt_nwaiters, self->pt_nwaiters = 0;
11518ccc6e06Sad 		    n < pthread__unpark_max && thread != NULL;
1152ded26025Sad 		    thread = next) {
1153ded26025Sad 			/*
1154ded26025Sad 			 * If the sleepobj pointer is non-NULL, it
1155ded26025Sad 			 * means one of two things:
1156ded26025Sad 			 *
1157ded26025Sad 			 * o The thread has awoken early, spun
1158ded26025Sad 			 *   through application code and is
1159ded26025Sad 			 *   once more asleep on this object.
1160ded26025Sad 			 *
1161ded26025Sad 			 * o This is a new thread that has blocked
1162ded26025Sad 			 *   on the object after we have released
1163ded26025Sad 			 *   the interlock in this loop.
1164ded26025Sad 			 *
1165ded26025Sad 			 * In both cases we shouldn't remove the
1166ded26025Sad 			 * thread from the queue.
1167ded26025Sad 			 */
1168ded26025Sad 			next = PTQ_NEXT(thread, pt_sleep);
11698ccc6e06Sad 			if (thread->pt_sleepobj != wakeobj)
1170ded26025Sad 				continue;
11718ccc6e06Sad 			thread->pt_sleepobj = NULL;
1172ded26025Sad 			thread->pt_sleeponq = 0;
11738ccc6e06Sad 			self->pt_waiters[n++] = thread->pt_lid;
11741ac6a89bSad 			PTQ_REMOVE(queue, thread, pt_sleep);
11751ac6a89bSad 		}
1176ded26025Sad 
117750fa8db4Sad 		/*
117850fa8db4Sad 		 * Releasing the spinlock serves as a store barrier,
117950fa8db4Sad 		 * which ensures that all our modifications are visible
118050fa8db4Sad 		 * to the thread in pthread__park() before the unpark
118150fa8db4Sad 		 * operation is set in motion.
118250fa8db4Sad 		 */
1183ded26025Sad 		switch (n) {
11841ac6a89bSad 		case 0:
118515e9cec1Sad 			pthread__spinunlock(self, lock);
11861ac6a89bSad 			return;
11871ac6a89bSad 		case 1:
1188c3f8e2eeSad 			/*
1189c3f8e2eeSad 			 * If the calling thread is about to block,
1190c3f8e2eeSad 			 * defer unparking the target until _lwp_park()
1191c3f8e2eeSad 			 * is called.
1192c3f8e2eeSad 			 */
119315e9cec1Sad 			pthread__spinunlock(self, lock);
1194c3f8e2eeSad 			if (self->pt_willpark && self->pt_unpark == 0) {
11958ccc6e06Sad 				self->pt_unpark = self->pt_waiters[0];
1196c3f8e2eeSad 				self->pt_unparkhint = queue;
1197c3f8e2eeSad 				return;
1198c3f8e2eeSad 			}
11998ccc6e06Sad 			rv = (ssize_t)_lwp_unpark(self->pt_waiters[0], queue);
12001ac6a89bSad 			if (rv != 0 && errno != EALREADY && errno != EINTR) {
12011ac6a89bSad 				OOPS("_lwp_unpark failed");
12021ac6a89bSad 			}
12031ac6a89bSad 			return;
12041ac6a89bSad 		default:
12058ccc6e06Sad 			/*
12068ccc6e06Sad 			 * Clear all sleepobj pointers, since we
12078ccc6e06Sad 			 * release the spin lock before awkening
12088ccc6e06Sad 			 * everybody, and must synchronise with
12098ccc6e06Sad 			 * pthread__park().
12108ccc6e06Sad 			 */
12118ccc6e06Sad 			while (thread != NULL) {
12128ccc6e06Sad 				thread->pt_sleepobj = NULL;
12138ccc6e06Sad 				thread = PTQ_NEXT(thread, pt_sleep);
12148ccc6e06Sad 			}
12158ccc6e06Sad 			/*
12168ccc6e06Sad 			 * Now only interested in waking threads
12178ccc6e06Sad 			 * marked to be woken (sleepobj == NULL).
12188ccc6e06Sad 			 */
12198ccc6e06Sad 			wakeobj = NULL;
122015e9cec1Sad 			pthread__spinunlock(self, lock);
12218ccc6e06Sad 			rv = _lwp_unpark_all(self->pt_waiters, (size_t)n,
12228ccc6e06Sad 			    queue);
12231ac6a89bSad 			if (rv != 0 && errno != EINTR) {
12241ac6a89bSad 				OOPS("_lwp_unpark_all failed");
12251ac6a89bSad 			}
12261ac6a89bSad 			break;
12271ac6a89bSad 		}
122815e9cec1Sad 		pthread__spinlock(self, lock);
12291ac6a89bSad 	}
12301ac6a89bSad }
12311ac6a89bSad 
12321ac6a89bSad #undef	OOPS
12339e287199Sad 
12349e287199Sad /*
12359e287199Sad  * Allocate a stack for a thread, and set it up. It needs to be aligned, so
12369e287199Sad  * that a thread can find itself by its stack pointer.
12379e287199Sad  */
12389e287199Sad static int
12399e287199Sad pthread__stackalloc(pthread_t *newt)
12409e287199Sad {
12419e287199Sad 	void *addr;
12429e287199Sad 
12439e287199Sad 	addr = mmap(NULL, pthread__stacksize, PROT_READ|PROT_WRITE,
12449e287199Sad 	    MAP_ANON|MAP_PRIVATE | MAP_ALIGNED(pthread__stacksize_lg),
12459e287199Sad 	    -1, (off_t)0);
12469e287199Sad 
12479e287199Sad 	if (addr == MAP_FAILED)
12489e287199Sad 		return ENOMEM;
12499e287199Sad 
12509e287199Sad 	pthread__assert(((intptr_t)addr & pthread__stackmask) == 0);
12519e287199Sad 
12529e287199Sad 	return pthread__stackid_setup(addr, pthread__stacksize, newt);
12539e287199Sad }
12549e287199Sad 
12559e287199Sad 
12569e287199Sad /*
12579e287199Sad  * Set up the slightly special stack for the "initial" thread, which
12589e287199Sad  * runs on the normal system stack, and thus gets slightly different
12599e287199Sad  * treatment.
12609e287199Sad  */
12619e287199Sad static void
12629e287199Sad pthread__initmain(pthread_t *newt)
12639e287199Sad {
12649e287199Sad 	struct rlimit slimit;
12659e287199Sad 	size_t pagesize;
12669e287199Sad 	pthread_t t;
12679e287199Sad 	void *base;
12689e287199Sad 	size_t size;
12699e287199Sad 	int error, ret;
12709e287199Sad 	char *value;
12719e287199Sad 
12729e287199Sad 	pagesize = (size_t)sysconf(_SC_PAGESIZE);
12739e287199Sad 	pthread__stacksize = 0;
12749e287199Sad 	ret = getrlimit(RLIMIT_STACK, &slimit);
12759e287199Sad 	if (ret == -1)
12769e287199Sad 		err(1, "Couldn't get stack resource consumption limits");
127715e9cec1Sad 
127815e9cec1Sad 	value = pthread__getenv("PTHREAD_STACKSIZE");
127915e9cec1Sad 	if (value != NULL) {
12809e287199Sad 		pthread__stacksize = atoi(value) * 1024;
12819e287199Sad 		if (pthread__stacksize > slimit.rlim_cur)
12829e287199Sad 			pthread__stacksize = (size_t)slimit.rlim_cur;
12839e287199Sad 	}
12849e287199Sad 	if (pthread__stacksize == 0)
12859e287199Sad 		pthread__stacksize = (size_t)slimit.rlim_cur;
12869e287199Sad 	if (pthread__stacksize < 4 * pagesize)
12879e287199Sad 		errx(1, "Stacksize limit is too low, minimum %zd kbyte.",
12889e287199Sad 		    4 * pagesize / 1024);
12899e287199Sad 
12909e287199Sad 	pthread__stacksize_lg = -1;
12919e287199Sad 	while (pthread__stacksize) {
12929e287199Sad 		pthread__stacksize >>= 1;
12939e287199Sad 		pthread__stacksize_lg++;
12949e287199Sad 	}
12959e287199Sad 
12969e287199Sad 	pthread__stacksize = (1 << pthread__stacksize_lg);
12979e287199Sad 	pthread__stackmask = pthread__stacksize - 1;
1298f4fd6b79Sad 	pthread__threadmask = ~pthread__stackmask;
12999e287199Sad 
1300f4fd6b79Sad 	base = (void *)(pthread__sp() & pthread__threadmask);
13019e287199Sad 	size = pthread__stacksize;
13029e287199Sad 
13039e287199Sad 	error = pthread__stackid_setup(base, size, &t);
13049e287199Sad 	if (error) {
13059e287199Sad 		/* XXX */
13069e287199Sad 		errx(2, "failed to setup main thread: error=%d", error);
13079e287199Sad 	}
13089e287199Sad 
13099e287199Sad 	*newt = t;
131066ac2ffaSad 
131166ac2ffaSad #ifdef PTHREAD__HAVE_THREADREG
131266ac2ffaSad 	/* Set up identity register. */
131366ac2ffaSad 	pthread__threadreg_set(t);
131466ac2ffaSad #endif
13159e287199Sad }
13169e287199Sad 
13179e287199Sad static int
13189e287199Sad /*ARGSUSED*/
13199e287199Sad pthread__stackid_setup(void *base, size_t size, pthread_t *tp)
13209e287199Sad {
13219e287199Sad 	pthread_t t;
13229e287199Sad 	void *redaddr;
13239e287199Sad 	size_t pagesize;
13249e287199Sad 	int ret;
13259e287199Sad 
13269e287199Sad 	t = base;
13279e287199Sad 	pagesize = (size_t)sysconf(_SC_PAGESIZE);
13289e287199Sad 
13299e287199Sad 	/*
13309e287199Sad 	 * Put a pointer to the pthread in the bottom (but
13319e287199Sad          * redzone-protected section) of the stack.
13329e287199Sad 	 */
13339e287199Sad 	redaddr = STACK_SHRINK(STACK_MAX(base, size), pagesize);
13349e287199Sad 	t->pt_stack.ss_size = size - 2 * pagesize;
13359e287199Sad #ifdef __MACHINE_STACK_GROWS_UP
13369e287199Sad 	t->pt_stack.ss_sp = (char *)(void *)base + pagesize;
13379e287199Sad #else
13389e287199Sad 	t->pt_stack.ss_sp = (char *)(void *)base + 2 * pagesize;
13399e287199Sad #endif
13409e287199Sad 
13419e287199Sad 	/* Protect the next-to-bottom stack page as a red zone. */
13429e287199Sad 	ret = mprotect(redaddr, pagesize, PROT_NONE);
13439e287199Sad 	if (ret == -1) {
13449e287199Sad 		return errno;
13459e287199Sad 	}
13469e287199Sad 	*tp = t;
13479e287199Sad 	return 0;
13489e287199Sad }
13499583eeb2Sad 
13509583eeb2Sad #ifndef lint
13519583eeb2Sad static int
13529583eeb2Sad pthread__cmp(struct __pthread_st *a, struct __pthread_st *b)
13539583eeb2Sad {
13549583eeb2Sad 	return b - a;
13559583eeb2Sad }
13569583eeb2Sad RB_GENERATE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp)
13579583eeb2Sad #endif
13589583eeb2Sad 
135915e9cec1Sad /* Because getenv() wants to use locks. */
136015e9cec1Sad char *
136115e9cec1Sad pthread__getenv(const char *name)
136215e9cec1Sad {
136315e9cec1Sad 	extern char *__findenv(const char *, int *);
136415e9cec1Sad 	int off;
136515e9cec1Sad 
136615e9cec1Sad 	return __findenv(name, &off);
136715e9cec1Sad }
136815e9cec1Sad 
136915e9cec1Sad 
1370