Thu Mar 8 16:40:45 2012 UTC ()
Actually use the stack thread attributes when creating a new thread.


(joerg)
diff -r1.127 -r1.128 src/lib/libpthread/pthread.c

cvs diff -r1.127 -r1.128 src/lib/libpthread/pthread.c (switch to unified diff)

--- src/lib/libpthread/pthread.c 2012/03/08 16:33:45 1.127
+++ src/lib/libpthread/pthread.c 2012/03/08 16:40:45 1.128
@@ -1,1318 +1,1333 @@ @@ -1,1318 +1,1333 @@
1/* $NetBSD: pthread.c,v 1.127 2012/03/08 16:33:45 joerg Exp $ */ 1/* $NetBSD: pthread.c,v 1.128 2012/03/08 16:40:45 joerg Exp $ */
2 2
3/*- 3/*-
4 * Copyright (c) 2001, 2002, 2003, 2006, 2007, 2008 The NetBSD Foundation, Inc. 4 * Copyright (c) 2001, 2002, 2003, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5 * All rights reserved. 5 * All rights reserved.
6 * 6 *
7 * This code is derived from software contributed to The NetBSD Foundation 7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Nathan J. Williams and Andrew Doran. 8 * by Nathan J. Williams and Andrew Doran.
9 * 9 *
10 * Redistribution and use in source and binary forms, with or without 10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions 11 * modification, are permitted provided that the following conditions
12 * are met: 12 * are met:
13 * 1. Redistributions of source code must retain the above copyright 13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer. 14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright 15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the 16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution. 17 * documentation and/or other materials provided with the distribution.
18 * 18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE. 29 * POSSIBILITY OF SUCH DAMAGE.
30 */ 30 */
31 31
32#include <sys/cdefs.h> 32#include <sys/cdefs.h>
33__RCSID("$NetBSD: pthread.c,v 1.127 2012/03/08 16:33:45 joerg Exp $"); 33__RCSID("$NetBSD: pthread.c,v 1.128 2012/03/08 16:40:45 joerg Exp $");
34 34
35#define __EXPOSE_STACK 1 35#define __EXPOSE_STACK 1
36 36
37#include <sys/param.h> 37#include <sys/param.h>
38#include <sys/exec_elf.h> 38#include <sys/exec_elf.h>
39#include <sys/mman.h> 39#include <sys/mman.h>
40#include <sys/sysctl.h> 40#include <sys/sysctl.h>
41#include <sys/lwpctl.h> 41#include <sys/lwpctl.h>
42#include <sys/tls.h> 42#include <sys/tls.h>
43 43
44#include <assert.h> 44#include <assert.h>
45#include <dlfcn.h> 45#include <dlfcn.h>
46#include <err.h> 46#include <err.h>
47#include <errno.h> 47#include <errno.h>
48#include <lwp.h> 48#include <lwp.h>
49#include <signal.h> 49#include <signal.h>
50#include <stdio.h> 50#include <stdio.h>
51#include <stdlib.h> 51#include <stdlib.h>
52#include <string.h> 52#include <string.h>
53#include <syslog.h> 53#include <syslog.h>
54#include <ucontext.h> 54#include <ucontext.h>
55#include <unistd.h> 55#include <unistd.h>
56#include <sched.h> 56#include <sched.h>
57 57
58#include "pthread.h" 58#include "pthread.h"
59#include "pthread_int.h" 59#include "pthread_int.h"
60 60
61pthread_rwlock_t pthread__alltree_lock = PTHREAD_RWLOCK_INITIALIZER; 61pthread_rwlock_t pthread__alltree_lock = PTHREAD_RWLOCK_INITIALIZER;
62RB_HEAD(__pthread__alltree, __pthread_st) pthread__alltree; 62RB_HEAD(__pthread__alltree, __pthread_st) pthread__alltree;
63 63
64#ifndef lint 64#ifndef lint
65static int pthread__cmp(struct __pthread_st *, struct __pthread_st *); 65static int pthread__cmp(struct __pthread_st *, struct __pthread_st *);
66RB_PROTOTYPE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp) 66RB_PROTOTYPE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp)
67#endif 67#endif
68 68
69static void pthread__create_tramp(void *); 69static void pthread__create_tramp(void *);
70static void pthread__initthread(pthread_t); 70static void pthread__initthread(pthread_t);
71static void pthread__scrubthread(pthread_t, char *, int); 71static void pthread__scrubthread(pthread_t, char *, int);
72static void pthread__initmain(pthread_t *); 72static void pthread__initmain(pthread_t *);
73static void pthread__fork_callback(void); 73static void pthread__fork_callback(void);
74static void pthread__reap(pthread_t); 74static void pthread__reap(pthread_t);
75static void pthread__child_callback(void); 75static void pthread__child_callback(void);
76static void pthread__start(void); 76static void pthread__start(void);
77 77
78void pthread__init(void); 78void pthread__init(void);
79 79
80int pthread__started; 80int pthread__started;
81pthread_mutex_t pthread__deadqueue_lock = PTHREAD_MUTEX_INITIALIZER; 81pthread_mutex_t pthread__deadqueue_lock = PTHREAD_MUTEX_INITIALIZER;
82pthread_queue_t pthread__deadqueue; 82pthread_queue_t pthread__deadqueue;
83pthread_queue_t pthread__allqueue; 83pthread_queue_t pthread__allqueue;
84 84
85static pthread_attr_t pthread_default_attr; 85static pthread_attr_t pthread_default_attr;
86static lwpctl_t pthread__dummy_lwpctl = { .lc_curcpu = LWPCTL_CPU_NONE }; 86static lwpctl_t pthread__dummy_lwpctl = { .lc_curcpu = LWPCTL_CPU_NONE };
87static pthread_t pthread__first; 87static pthread_t pthread__first;
88 88
89enum { 89enum {
90 DIAGASSERT_ABORT = 1<<0, 90 DIAGASSERT_ABORT = 1<<0,
91 DIAGASSERT_STDERR = 1<<1, 91 DIAGASSERT_STDERR = 1<<1,
92 DIAGASSERT_SYSLOG = 1<<2 92 DIAGASSERT_SYSLOG = 1<<2
93}; 93};
94 94
95static int pthread__diagassert; 95static int pthread__diagassert;
96 96
97int pthread__concurrency; 97int pthread__concurrency;
98int pthread__nspins; 98int pthread__nspins;
99int pthread__unpark_max = PTHREAD__UNPARK_MAX; 99int pthread__unpark_max = PTHREAD__UNPARK_MAX;
100int pthread__dbg; /* set by libpthread_dbg if active */ 100int pthread__dbg; /* set by libpthread_dbg if active */
101 101
102/*  102/*
103 * We have to initialize the pthread_stack* variables here because 103 * We have to initialize the pthread_stack* variables here because
104 * mutexes are used before pthread_init() and thus pthread__initmain() 104 * mutexes are used before pthread_init() and thus pthread__initmain()
105 * are called. Since mutexes only save the stack pointer and not a 105 * are called. Since mutexes only save the stack pointer and not a
106 * pointer to the thread data, it is safe to change the mapping from 106 * pointer to the thread data, it is safe to change the mapping from
107 * stack pointer to thread data afterwards. 107 * stack pointer to thread data afterwards.
108 */ 108 */
109size_t pthread__stacksize; 109size_t pthread__stacksize;
110size_t pthread__pagesize; 110size_t pthread__pagesize;
111static struct __pthread_st pthread__main; 111static struct __pthread_st pthread__main;
112 112
113int _sys___sigprocmask14(int, const sigset_t *, sigset_t *); 113int _sys___sigprocmask14(int, const sigset_t *, sigset_t *);
114 114
115__strong_alias(__libc_thr_self,pthread_self) 115__strong_alias(__libc_thr_self,pthread_self)
116__strong_alias(__libc_thr_create,pthread_create) 116__strong_alias(__libc_thr_create,pthread_create)
117__strong_alias(__libc_thr_exit,pthread_exit) 117__strong_alias(__libc_thr_exit,pthread_exit)
118__strong_alias(__libc_thr_errno,pthread__errno) 118__strong_alias(__libc_thr_errno,pthread__errno)
119__strong_alias(__libc_thr_setcancelstate,pthread_setcancelstate) 119__strong_alias(__libc_thr_setcancelstate,pthread_setcancelstate)
120__strong_alias(__libc_thr_equal,pthread_equal) 120__strong_alias(__libc_thr_equal,pthread_equal)
121__strong_alias(__libc_thr_init,pthread__init) 121__strong_alias(__libc_thr_init,pthread__init)
122 122
123/* 123/*
124 * Static library kludge. Place a reference to a symbol any library 124 * Static library kludge. Place a reference to a symbol any library
125 * file which does not already have a reference here. 125 * file which does not already have a reference here.
126 */ 126 */
127extern int pthread__cancel_stub_binder; 127extern int pthread__cancel_stub_binder;
128 128
129void *pthread__static_lib_binder[] = { 129void *pthread__static_lib_binder[] = {
130 &pthread__cancel_stub_binder, 130 &pthread__cancel_stub_binder,
131 pthread_cond_init, 131 pthread_cond_init,
132 pthread_mutex_init, 132 pthread_mutex_init,
133 pthread_rwlock_init, 133 pthread_rwlock_init,
134 pthread_barrier_init, 134 pthread_barrier_init,
135 pthread_key_create, 135 pthread_key_create,
136 pthread_setspecific, 136 pthread_setspecific,
137}; 137};
138 138
139#define NHASHLOCK 64 139#define NHASHLOCK 64
140 140
141static union hashlock { 141static union hashlock {
142 pthread_mutex_t mutex; 142 pthread_mutex_t mutex;
143 char pad[64]; 143 char pad[64];
144} hashlocks[NHASHLOCK] __aligned(64); 144} hashlocks[NHASHLOCK] __aligned(64);
145 145
146/* 146/*
147 * This needs to be started by the library loading code, before main() 147 * This needs to be started by the library loading code, before main()
148 * gets to run, for various things that use the state of the initial thread 148 * gets to run, for various things that use the state of the initial thread
149 * to work properly (thread-specific data is an application-visible example; 149 * to work properly (thread-specific data is an application-visible example;
150 * spinlock counts for mutexes is an internal example). 150 * spinlock counts for mutexes is an internal example).
151 */ 151 */
152void 152void
153pthread__init(void) 153pthread__init(void)
154{ 154{
155 pthread_t first; 155 pthread_t first;
156 char *p; 156 char *p;
157 int i, mib[2]; 157 int i, mib[2];
158 size_t len; 158 size_t len;
159 extern int __isthreaded; 159 extern int __isthreaded;
160 160
161 pthread__pagesize = (size_t)sysconf(_SC_PAGESIZE); 161 pthread__pagesize = (size_t)sysconf(_SC_PAGESIZE);
162 162
163 mib[0] = CTL_HW; 163 mib[0] = CTL_HW;
164 mib[1] = HW_NCPU;  164 mib[1] = HW_NCPU;
165 165
166 len = sizeof(pthread__concurrency); 166 len = sizeof(pthread__concurrency);
167 if (sysctl(mib, 2, &pthread__concurrency, &len, NULL, 0) == -1) 167 if (sysctl(mib, 2, &pthread__concurrency, &len, NULL, 0) == -1)
168 err(1, "sysctl(hw.ncpu"); 168 err(1, "sysctl(hw.ncpu");
169 169
170 mib[0] = CTL_KERN; 170 mib[0] = CTL_KERN;
171 mib[1] = KERN_OSREV;  171 mib[1] = KERN_OSREV;
172 172
173 /* Initialize locks first; they're needed elsewhere. */ 173 /* Initialize locks first; they're needed elsewhere. */
174 pthread__lockprim_init(); 174 pthread__lockprim_init();
175 for (i = 0; i < NHASHLOCK; i++) { 175 for (i = 0; i < NHASHLOCK; i++) {
176 pthread_mutex_init(&hashlocks[i].mutex, NULL); 176 pthread_mutex_init(&hashlocks[i].mutex, NULL);
177 } 177 }
178 178
179 /* Fetch parameters. */ 179 /* Fetch parameters. */
180 i = (int)_lwp_unpark_all(NULL, 0, NULL); 180 i = (int)_lwp_unpark_all(NULL, 0, NULL);
181 if (i == -1) 181 if (i == -1)
182 err(1, "_lwp_unpark_all"); 182 err(1, "_lwp_unpark_all");
183 if (i < pthread__unpark_max) 183 if (i < pthread__unpark_max)
184 pthread__unpark_max = i; 184 pthread__unpark_max = i;
185 185
186 /* Basic data structure setup */ 186 /* Basic data structure setup */
187 pthread_attr_init(&pthread_default_attr); 187 pthread_attr_init(&pthread_default_attr);
188 PTQ_INIT(&pthread__allqueue); 188 PTQ_INIT(&pthread__allqueue);
189 PTQ_INIT(&pthread__deadqueue); 189 PTQ_INIT(&pthread__deadqueue);
190 RB_INIT(&pthread__alltree); 190 RB_INIT(&pthread__alltree);
191 191
192 /* Create the thread structure corresponding to main() */ 192 /* Create the thread structure corresponding to main() */
193 pthread__initmain(&first); 193 pthread__initmain(&first);
194 pthread__initthread(first); 194 pthread__initthread(first);
195 pthread__scrubthread(first, NULL, 0); 195 pthread__scrubthread(first, NULL, 0);
196 196
197 first->pt_lid = _lwp_self(); 197 first->pt_lid = _lwp_self();
198 PTQ_INSERT_HEAD(&pthread__allqueue, first, pt_allq); 198 PTQ_INSERT_HEAD(&pthread__allqueue, first, pt_allq);
199 RB_INSERT(__pthread__alltree, &pthread__alltree, first); 199 RB_INSERT(__pthread__alltree, &pthread__alltree, first);
200 200
201 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &first->pt_lwpctl) != 0) { 201 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &first->pt_lwpctl) != 0) {
202 err(1, "_lwp_ctl"); 202 err(1, "_lwp_ctl");
203 } 203 }
204 204
205 /* Start subsystems */ 205 /* Start subsystems */
206 PTHREAD_MD_INIT 206 PTHREAD_MD_INIT
207 207
208 for (p = pthread__getenv("PTHREAD_DIAGASSERT"); p && *p; p++) { 208 for (p = pthread__getenv("PTHREAD_DIAGASSERT"); p && *p; p++) {
209 switch (*p) { 209 switch (*p) {
210 case 'a': 210 case 'a':
211 pthread__diagassert |= DIAGASSERT_ABORT; 211 pthread__diagassert |= DIAGASSERT_ABORT;
212 break; 212 break;
213 case 'A': 213 case 'A':
214 pthread__diagassert &= ~DIAGASSERT_ABORT; 214 pthread__diagassert &= ~DIAGASSERT_ABORT;
215 break; 215 break;
216 case 'e': 216 case 'e':
217 pthread__diagassert |= DIAGASSERT_STDERR; 217 pthread__diagassert |= DIAGASSERT_STDERR;
218 break; 218 break;
219 case 'E': 219 case 'E':
220 pthread__diagassert &= ~DIAGASSERT_STDERR; 220 pthread__diagassert &= ~DIAGASSERT_STDERR;
221 break; 221 break;
222 case 'l': 222 case 'l':
223 pthread__diagassert |= DIAGASSERT_SYSLOG; 223 pthread__diagassert |= DIAGASSERT_SYSLOG;
224 break; 224 break;
225 case 'L': 225 case 'L':
226 pthread__diagassert &= ~DIAGASSERT_SYSLOG; 226 pthread__diagassert &= ~DIAGASSERT_SYSLOG;
227 break; 227 break;
228 } 228 }
229 } 229 }
230 230
231 /* Tell libc that we're here and it should role-play accordingly. */ 231 /* Tell libc that we're here and it should role-play accordingly. */
232 pthread__first = first; 232 pthread__first = first;
233 pthread_atfork(NULL, NULL, pthread__fork_callback); 233 pthread_atfork(NULL, NULL, pthread__fork_callback);
234 __isthreaded = 1; 234 __isthreaded = 1;
235} 235}
236 236
237static void 237static void
238pthread__fork_callback(void) 238pthread__fork_callback(void)
239{ 239{
240 struct __pthread_st *self; 240 struct __pthread_st *self;
241 241
242 /* lwpctl state is not copied across fork. */ 242 /* lwpctl state is not copied across fork. */
243 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &pthread__first->pt_lwpctl)) { 243 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &pthread__first->pt_lwpctl)) {
244 err(1, "_lwp_ctl"); 244 err(1, "_lwp_ctl");
245 } 245 }
246 self = pthread__self(); 246 self = pthread__self();
247 self->pt_lid = _lwp_self(); 247 self->pt_lid = _lwp_self();
248} 248}
249 249
250static void 250static void
251pthread__child_callback(void) 251pthread__child_callback(void)
252{ 252{
253 253
254 /* 254 /*
255 * Clean up data structures that a forked child process might 255 * Clean up data structures that a forked child process might
256 * trip over. Note that if threads have been created (causing 256 * trip over. Note that if threads have been created (causing
257 * this handler to be registered) the standards say that the 257 * this handler to be registered) the standards say that the
258 * child will trigger undefined behavior if it makes any 258 * child will trigger undefined behavior if it makes any
259 * pthread_* calls (or any other calls that aren't 259 * pthread_* calls (or any other calls that aren't
260 * async-signal-safe), so we don't really have to clean up 260 * async-signal-safe), so we don't really have to clean up
261 * much. Anything that permits some pthread_* calls to work is 261 * much. Anything that permits some pthread_* calls to work is
262 * merely being polite. 262 * merely being polite.
263 */ 263 */
264 pthread__started = 0; 264 pthread__started = 0;
265} 265}
266 266
267static void 267static void
268pthread__start(void) 268pthread__start(void)
269{ 269{
270 270
271 /* 271 /*
272 * Per-process timers are cleared by fork(); despite the 272 * Per-process timers are cleared by fork(); despite the
273 * various restrictions on fork() and threads, it's legal to 273 * various restrictions on fork() and threads, it's legal to
274 * fork() before creating any threads.  274 * fork() before creating any threads.
275 */ 275 */
276 pthread_atfork(NULL, NULL, pthread__child_callback); 276 pthread_atfork(NULL, NULL, pthread__child_callback);
277} 277}
278 278
279 279
280/* General-purpose thread data structure sanitization. */ 280/* General-purpose thread data structure sanitization. */
281/* ARGSUSED */ 281/* ARGSUSED */
282static void 282static void
283pthread__initthread(pthread_t t) 283pthread__initthread(pthread_t t)
284{ 284{
285 285
286 t->pt_self = t; 286 t->pt_self = t;
287 t->pt_magic = PT_MAGIC; 287 t->pt_magic = PT_MAGIC;
288 t->pt_willpark = 0; 288 t->pt_willpark = 0;
289 t->pt_unpark = 0; 289 t->pt_unpark = 0;
290 t->pt_nwaiters = 0; 290 t->pt_nwaiters = 0;
291 t->pt_sleepobj = NULL; 291 t->pt_sleepobj = NULL;
292 t->pt_signalled = 0; 292 t->pt_signalled = 0;
293 t->pt_havespecific = 0; 293 t->pt_havespecific = 0;
294 t->pt_early = NULL; 294 t->pt_early = NULL;
295 t->pt_lwpctl = &pthread__dummy_lwpctl; 295 t->pt_lwpctl = &pthread__dummy_lwpctl;
296 t->pt_blocking = 0; 296 t->pt_blocking = 0;
297 t->pt_droplock = NULL; 297 t->pt_droplock = NULL;
298 298
299 memcpy(&t->pt_lockops, pthread__lock_ops, sizeof(t->pt_lockops)); 299 memcpy(&t->pt_lockops, pthread__lock_ops, sizeof(t->pt_lockops));
300 pthread_mutex_init(&t->pt_lock, NULL); 300 pthread_mutex_init(&t->pt_lock, NULL);
301 PTQ_INIT(&t->pt_cleanup_stack); 301 PTQ_INIT(&t->pt_cleanup_stack);
302 pthread_cond_init(&t->pt_joiners, NULL); 302 pthread_cond_init(&t->pt_joiners, NULL);
303 memset(&t->pt_specific, 0, sizeof(t->pt_specific)); 303 memset(&t->pt_specific, 0, sizeof(t->pt_specific));
304} 304}
305 305
306static void 306static void
307pthread__scrubthread(pthread_t t, char *name, int flags) 307pthread__scrubthread(pthread_t t, char *name, int flags)
308{ 308{
309 309
310 t->pt_state = PT_STATE_RUNNING; 310 t->pt_state = PT_STATE_RUNNING;
311 t->pt_exitval = NULL; 311 t->pt_exitval = NULL;
312 t->pt_flags = flags; 312 t->pt_flags = flags;
313 t->pt_cancel = 0; 313 t->pt_cancel = 0;
314 t->pt_errno = 0; 314 t->pt_errno = 0;
315 t->pt_name = name; 315 t->pt_name = name;
316 t->pt_lid = 0; 316 t->pt_lid = 0;
317} 317}
318 318
319static int 319static int
320pthread__newstack(pthread_t newthread) 320pthread__newstack(pthread_t newthread, const pthread_attr_t *attr)
321{ 321{
322 void *stackbase, *redzone; 322 void *stackbase, *redzone;
 323 size_t stacksize;
 324 bool mapped_stack = false;
323 325
324 stackbase = mmap(NULL, pthread__stacksize, 326 if (attr != NULL) {
325 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, (off_t)0); 327 pthread_attr_getstack(attr, &stackbase, &stacksize);
326 if (stackbase == MAP_FAILED) 328 } else {
327 return ENOMEM; 329 stackbase = NULL;
 330 stacksize = 0;
 331 }
 332 if (stacksize == 0)
 333 stacksize = pthread__stacksize;
 334
 335 if (stackbase == NULL) {
 336 stackbase = mmap(NULL, stacksize,
 337 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, (off_t)0);
 338 if (stackbase == MAP_FAILED)
 339 return ENOMEM;
 340 mapped_stack = true;
 341 }
328 newthread->pt_stack.ss_size = pthread__stacksize - pthread__pagesize; 342 newthread->pt_stack.ss_size = pthread__stacksize - pthread__pagesize;
329 newthread->pt_stack.ss_sp = stackbase; 343 newthread->pt_stack.ss_sp = stackbase;
330#ifdef __MACHINE_STACK_GROWS_UP 344#ifdef __MACHINE_STACK_GROWS_UP
331 redzone = (char *)stackbase + newthread->pt_stack.ss_size; 345 redzone = (char *)stackbase + newthread->pt_stack.ss_size;
332#else 346#else
333 redzone = (char *)stackbase; 347 redzone = (char *)stackbase;
334#endif 348#endif
335 if (mprotect(redzone, pthread__pagesize, PROT_NONE) == -1) { 349 if (mprotect(redzone, pthread__pagesize, PROT_NONE) == -1) {
336 munmap(stackbase, pthread__stacksize); 350 if (mapped_stack)
 351 munmap(stackbase, pthread__stacksize);
337 return EPERM; 352 return EPERM;
338 } 353 }
339 return 0; 354 return 0;
340} 355}
341 356
342int 357int
343pthread_create(pthread_t *thread, const pthread_attr_t *attr, 358pthread_create(pthread_t *thread, const pthread_attr_t *attr,
344 void *(*startfunc)(void *), void *arg) 359 void *(*startfunc)(void *), void *arg)
345{ 360{
346 pthread_t newthread; 361 pthread_t newthread;
347 pthread_attr_t nattr; 362 pthread_attr_t nattr;
348 struct pthread_attr_private *p; 363 struct pthread_attr_private *p;
349 char * volatile name; 364 char * volatile name;
350 unsigned long flag; 365 unsigned long flag;
351 void *private_area; 366 void *private_area;
352 int ret; 367 int ret;
353 368
354 /* 369 /*
355 * It's okay to check this without a lock because there can 370 * It's okay to check this without a lock because there can
356 * only be one thread before it becomes true. 371 * only be one thread before it becomes true.
357 */ 372 */
358 if (pthread__started == 0) { 373 if (pthread__started == 0) {
359 pthread__start(); 374 pthread__start();
360 pthread__started = 1; 375 pthread__started = 1;
361 } 376 }
362 377
363 if (attr == NULL) 378 if (attr == NULL)
364 nattr = pthread_default_attr; 379 nattr = pthread_default_attr;
365 else if (attr->pta_magic == PT_ATTR_MAGIC) 380 else if (attr->pta_magic == PT_ATTR_MAGIC)
366 nattr = *attr; 381 nattr = *attr;
367 else 382 else
368 return EINVAL; 383 return EINVAL;
369 384
370 /* Fetch misc. attributes from the attr structure. */ 385 /* Fetch misc. attributes from the attr structure. */
371 name = NULL; 386 name = NULL;
372 if ((p = nattr.pta_private) != NULL) 387 if ((p = nattr.pta_private) != NULL)
373 if (p->ptap_name[0] != '\0') 388 if (p->ptap_name[0] != '\0')
374 if ((name = strdup(p->ptap_name)) == NULL) 389 if ((name = strdup(p->ptap_name)) == NULL)
375 return ENOMEM; 390 return ENOMEM;
376 391
377 newthread = NULL; 392 newthread = NULL;
378 393
379 /* 394 /*
380 * Try to reclaim a dead thread. 395 * Try to reclaim a dead thread.
381 */ 396 */
382 if (!PTQ_EMPTY(&pthread__deadqueue)) { 397 if (!PTQ_EMPTY(&pthread__deadqueue)) {
383 pthread_mutex_lock(&pthread__deadqueue_lock); 398 pthread_mutex_lock(&pthread__deadqueue_lock);
384 PTQ_FOREACH(newthread, &pthread__deadqueue, pt_deadq) { 399 PTQ_FOREACH(newthread, &pthread__deadqueue, pt_deadq) {
385 /* Still running? */ 400 /* Still running? */
386 if (newthread->pt_lwpctl->lc_curcpu == 401 if (newthread->pt_lwpctl->lc_curcpu ==
387 LWPCTL_CPU_EXITED || 402 LWPCTL_CPU_EXITED ||
388 (_lwp_kill(newthread->pt_lid, 0) == -1 && 403 (_lwp_kill(newthread->pt_lid, 0) == -1 &&
389 errno == ESRCH)) 404 errno == ESRCH))
390 break; 405 break;
391 } 406 }
392 if (newthread) 407 if (newthread)
393 PTQ_REMOVE(&pthread__deadqueue, newthread, pt_deadq); 408 PTQ_REMOVE(&pthread__deadqueue, newthread, pt_deadq);
394 pthread_mutex_unlock(&pthread__deadqueue_lock); 409 pthread_mutex_unlock(&pthread__deadqueue_lock);
395#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II) 410#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
396 if (newthread && newthread->pt_tls) { 411 if (newthread && newthread->pt_tls) {
397 _rtld_tls_free(newthread->pt_tls); 412 _rtld_tls_free(newthread->pt_tls);
398 newthread->pt_tls = NULL; 413 newthread->pt_tls = NULL;
399 } 414 }
400#endif 415#endif
401 } 416 }
402 417
403 /* 418 /*
404 * If necessary set up a stack, allocate space for a pthread_st, 419 * If necessary set up a stack, allocate space for a pthread_st,
405 * and initialize it. 420 * and initialize it.
406 */ 421 */
407 if (newthread == NULL) { 422 if (newthread == NULL) {
408 newthread = malloc(sizeof(*newthread)); 423 newthread = malloc(sizeof(*newthread));
409 if (newthread == NULL) { 424 if (newthread == NULL) {
410 free(name); 425 free(name);
411 return ENOMEM; 426 return ENOMEM;
412 } 427 }
413 428
414 if (pthread__newstack(newthread)) { 429 if (pthread__newstack(newthread, attr)) {
415 free(newthread); 430 free(newthread);
416 free(name); 431 free(name);
417 return ENOMEM; 432 return ENOMEM;
418 } 433 }
419 434
420 /* This is used only when creating the thread. */ 435 /* This is used only when creating the thread. */
421 _INITCONTEXT_U(&newthread->pt_uc); 436 _INITCONTEXT_U(&newthread->pt_uc);
422 newthread->pt_uc.uc_stack = newthread->pt_stack; 437 newthread->pt_uc.uc_stack = newthread->pt_stack;
423 newthread->pt_uc.uc_link = NULL; 438 newthread->pt_uc.uc_link = NULL;
424#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II) 439#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
425 newthread->pt_tls = NULL; 440 newthread->pt_tls = NULL;
426#endif 441#endif
427 442
428 /* Add to list of all threads. */ 443 /* Add to list of all threads. */
429 pthread_rwlock_wrlock(&pthread__alltree_lock); 444 pthread_rwlock_wrlock(&pthread__alltree_lock);
430 PTQ_INSERT_TAIL(&pthread__allqueue, newthread, pt_allq); 445 PTQ_INSERT_TAIL(&pthread__allqueue, newthread, pt_allq);
431 RB_INSERT(__pthread__alltree, &pthread__alltree, newthread); 446 RB_INSERT(__pthread__alltree, &pthread__alltree, newthread);
432 pthread_rwlock_unlock(&pthread__alltree_lock); 447 pthread_rwlock_unlock(&pthread__alltree_lock);
433 448
434 /* Will be reset by the thread upon exit. */ 449 /* Will be reset by the thread upon exit. */
435 pthread__initthread(newthread); 450 pthread__initthread(newthread);
436 } 451 }
437 452
438 /* 453 /*
439 * Create the new LWP. 454 * Create the new LWP.
440 */ 455 */
441 pthread__scrubthread(newthread, name, nattr.pta_flags); 456 pthread__scrubthread(newthread, name, nattr.pta_flags);
442 newthread->pt_func = startfunc; 457 newthread->pt_func = startfunc;
443 newthread->pt_arg = arg; 458 newthread->pt_arg = arg;
444#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II) 459#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
445 private_area = newthread->pt_tls = _rtld_tls_allocate(); 460 private_area = newthread->pt_tls = _rtld_tls_allocate();
446 newthread->pt_tls->tcb_pthread = newthread; 461 newthread->pt_tls->tcb_pthread = newthread;
447#else 462#else
448 private_area = newthread; 463 private_area = newthread;
449#endif 464#endif
450 465
451 _lwp_makecontext(&newthread->pt_uc, pthread__create_tramp, 466 _lwp_makecontext(&newthread->pt_uc, pthread__create_tramp,
452 newthread, private_area, newthread->pt_stack.ss_sp, 467 newthread, private_area, newthread->pt_stack.ss_sp,
453 newthread->pt_stack.ss_size); 468 newthread->pt_stack.ss_size);
454 469
455 flag = LWP_DETACHED; 470 flag = LWP_DETACHED;
456 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) != 0 || 471 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) != 0 ||
457 (nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0) 472 (nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0)
458 flag |= LWP_SUSPENDED; 473 flag |= LWP_SUSPENDED;
459 ret = _lwp_create(&newthread->pt_uc, flag, &newthread->pt_lid); 474 ret = _lwp_create(&newthread->pt_uc, flag, &newthread->pt_lid);
460 if (ret != 0) { 475 if (ret != 0) {
461 pthread_mutex_lock(&newthread->pt_lock); 476 pthread_mutex_lock(&newthread->pt_lock);
462 /* Will unlock and free name. */ 477 /* Will unlock and free name. */
463 pthread__reap(newthread); 478 pthread__reap(newthread);
464 return ret; 479 return ret;
465 } 480 }
466 481
467 if ((nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0) { 482 if ((nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0) {
468 if (p != NULL) { 483 if (p != NULL) {
469 (void)pthread_setschedparam(newthread, p->ptap_policy, 484 (void)pthread_setschedparam(newthread, p->ptap_policy,
470 &p->ptap_sp); 485 &p->ptap_sp);
471 } 486 }
472 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) == 0) { 487 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) == 0) {
473 (void)_lwp_continue(newthread->pt_lid); 488 (void)_lwp_continue(newthread->pt_lid);
474 } 489 }
475 } 490 }
476 491
477 *thread = newthread; 492 *thread = newthread;
478 493
479 return 0; 494 return 0;
480} 495}
481 496
482 497
483__dead static void 498__dead static void
484pthread__create_tramp(void *cookie) 499pthread__create_tramp(void *cookie)
485{ 500{
486 pthread_t self; 501 pthread_t self;
487 void *retval; 502 void *retval;
488 503
489 self = cookie; 504 self = cookie;
490 505
491 /* 506 /*
492 * Throw away some stack in a feeble attempt to reduce cache 507 * Throw away some stack in a feeble attempt to reduce cache
493 * thrash. May help for SMT processors. XXX We should not 508 * thrash. May help for SMT processors. XXX We should not
494 * be allocating stacks on fixed 2MB boundaries. Needs a 509 * be allocating stacks on fixed 2MB boundaries. Needs a
495 * thread register or decent thread local storage. 510 * thread register or decent thread local storage.
496 * 511 *
497 * Note that we may race with the kernel in _lwp_create(), 512 * Note that we may race with the kernel in _lwp_create(),
498 * and so pt_lid can be unset at this point, but we don't 513 * and so pt_lid can be unset at this point, but we don't
499 * care. 514 * care.
500 */ 515 */
501 (void)alloca(((unsigned)self->pt_lid & 7) << 8); 516 (void)alloca(((unsigned)self->pt_lid & 7) << 8);
502 517
503 if (self->pt_name != NULL) { 518 if (self->pt_name != NULL) {
504 pthread_mutex_lock(&self->pt_lock); 519 pthread_mutex_lock(&self->pt_lock);
505 if (self->pt_name != NULL) 520 if (self->pt_name != NULL)
506 (void)_lwp_setname(0, self->pt_name); 521 (void)_lwp_setname(0, self->pt_name);
507 pthread_mutex_unlock(&self->pt_lock); 522 pthread_mutex_unlock(&self->pt_lock);
508 } 523 }
509 524
510 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &self->pt_lwpctl)) { 525 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &self->pt_lwpctl)) {
511 err(1, "_lwp_ctl"); 526 err(1, "_lwp_ctl");
512 } 527 }
513 528
514 retval = (*self->pt_func)(self->pt_arg); 529 retval = (*self->pt_func)(self->pt_arg);
515 530
516 pthread_exit(retval); 531 pthread_exit(retval);
517 532
518 /*NOTREACHED*/ 533 /*NOTREACHED*/
519 pthread__abort(); 534 pthread__abort();
520} 535}
521 536
522int 537int
523pthread_suspend_np(pthread_t thread) 538pthread_suspend_np(pthread_t thread)
524{ 539{
525 pthread_t self; 540 pthread_t self;
526 541
527 self = pthread__self(); 542 self = pthread__self();
528 if (self == thread) { 543 if (self == thread) {
529 return EDEADLK; 544 return EDEADLK;
530 } 545 }
531 if (pthread__find(thread) != 0) 546 if (pthread__find(thread) != 0)
532 return ESRCH; 547 return ESRCH;
533 if (_lwp_suspend(thread->pt_lid) == 0) 548 if (_lwp_suspend(thread->pt_lid) == 0)
534 return 0; 549 return 0;
535 return errno; 550 return errno;
536} 551}
537 552
538int 553int
539pthread_resume_np(pthread_t thread) 554pthread_resume_np(pthread_t thread)
540{ 555{
541  556
542 if (pthread__find(thread) != 0) 557 if (pthread__find(thread) != 0)
543 return ESRCH; 558 return ESRCH;
544 if (_lwp_continue(thread->pt_lid) == 0) 559 if (_lwp_continue(thread->pt_lid) == 0)
545 return 0; 560 return 0;
546 return errno; 561 return errno;
547} 562}
548 563
549void 564void
550pthread_exit(void *retval) 565pthread_exit(void *retval)
551{ 566{
552 pthread_t self; 567 pthread_t self;
553 struct pt_clean_t *cleanup; 568 struct pt_clean_t *cleanup;
554 char *name; 569 char *name;
555 570
556 self = pthread__self(); 571 self = pthread__self();
557 572
558 /* Disable cancellability. */ 573 /* Disable cancellability. */
559 pthread_mutex_lock(&self->pt_lock); 574 pthread_mutex_lock(&self->pt_lock);
560 self->pt_flags |= PT_FLAG_CS_DISABLED; 575 self->pt_flags |= PT_FLAG_CS_DISABLED;
561 self->pt_cancel = 0; 576 self->pt_cancel = 0;
562 577
563 /* Call any cancellation cleanup handlers */ 578 /* Call any cancellation cleanup handlers */
564 if (!PTQ_EMPTY(&self->pt_cleanup_stack)) { 579 if (!PTQ_EMPTY(&self->pt_cleanup_stack)) {
565 pthread_mutex_unlock(&self->pt_lock); 580 pthread_mutex_unlock(&self->pt_lock);
566 while (!PTQ_EMPTY(&self->pt_cleanup_stack)) { 581 while (!PTQ_EMPTY(&self->pt_cleanup_stack)) {
567 cleanup = PTQ_FIRST(&self->pt_cleanup_stack); 582 cleanup = PTQ_FIRST(&self->pt_cleanup_stack);
568 PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next); 583 PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next);
569 (*cleanup->ptc_cleanup)(cleanup->ptc_arg); 584 (*cleanup->ptc_cleanup)(cleanup->ptc_arg);
570 } 585 }
571 pthread_mutex_lock(&self->pt_lock); 586 pthread_mutex_lock(&self->pt_lock);
572 } 587 }
573 588
574 /* Perform cleanup of thread-specific data */ 589 /* Perform cleanup of thread-specific data */
575 pthread__destroy_tsd(self); 590 pthread__destroy_tsd(self);
576 591
577 /* Signal our exit. */ 592 /* Signal our exit. */
578 self->pt_exitval = retval; 593 self->pt_exitval = retval;
579 if (self->pt_flags & PT_FLAG_DETACHED) { 594 if (self->pt_flags & PT_FLAG_DETACHED) {
580 self->pt_state = PT_STATE_DEAD; 595 self->pt_state = PT_STATE_DEAD;
581 name = self->pt_name; 596 name = self->pt_name;
582 self->pt_name = NULL; 597 self->pt_name = NULL;
583 pthread_mutex_unlock(&self->pt_lock); 598 pthread_mutex_unlock(&self->pt_lock);
584 if (name != NULL) 599 if (name != NULL)
585 free(name); 600 free(name);
586 pthread_mutex_lock(&pthread__deadqueue_lock); 601 pthread_mutex_lock(&pthread__deadqueue_lock);
587 PTQ_INSERT_TAIL(&pthread__deadqueue, self, pt_deadq); 602 PTQ_INSERT_TAIL(&pthread__deadqueue, self, pt_deadq);
588 pthread_mutex_unlock(&pthread__deadqueue_lock); 603 pthread_mutex_unlock(&pthread__deadqueue_lock);
589 _lwp_exit(); 604 _lwp_exit();
590 } else { 605 } else {
591 self->pt_state = PT_STATE_ZOMBIE; 606 self->pt_state = PT_STATE_ZOMBIE;
592 pthread_cond_broadcast(&self->pt_joiners); 607 pthread_cond_broadcast(&self->pt_joiners);
593 pthread_mutex_unlock(&self->pt_lock); 608 pthread_mutex_unlock(&self->pt_lock);
594 /* Note: name will be freed by the joiner. */ 609 /* Note: name will be freed by the joiner. */
595 _lwp_exit(); 610 _lwp_exit();
596 } 611 }
597 612
598 /*NOTREACHED*/ 613 /*NOTREACHED*/
599 pthread__abort(); 614 pthread__abort();
600 exit(1); 615 exit(1);
601} 616}
602 617
603 618
604int 619int
605pthread_join(pthread_t thread, void **valptr) 620pthread_join(pthread_t thread, void **valptr)
606{ 621{
607 pthread_t self; 622 pthread_t self;
608 int error; 623 int error;
609 624
610 self = pthread__self(); 625 self = pthread__self();
611 626
612 if (pthread__find(thread) != 0) 627 if (pthread__find(thread) != 0)
613 return ESRCH; 628 return ESRCH;
614 629
615 if (thread->pt_magic != PT_MAGIC) 630 if (thread->pt_magic != PT_MAGIC)
616 return EINVAL; 631 return EINVAL;
617 632
618 if (thread == self) 633 if (thread == self)
619 return EDEADLK; 634 return EDEADLK;
620 635
621 self->pt_droplock = &thread->pt_lock; 636 self->pt_droplock = &thread->pt_lock;
622 pthread_mutex_lock(&thread->pt_lock); 637 pthread_mutex_lock(&thread->pt_lock);
623 for (;;) { 638 for (;;) {
624 if (thread->pt_state == PT_STATE_ZOMBIE) 639 if (thread->pt_state == PT_STATE_ZOMBIE)
625 break; 640 break;
626 if (thread->pt_state == PT_STATE_DEAD) { 641 if (thread->pt_state == PT_STATE_DEAD) {
627 pthread_mutex_unlock(&thread->pt_lock); 642 pthread_mutex_unlock(&thread->pt_lock);
628 self->pt_droplock = NULL; 643 self->pt_droplock = NULL;
629 return ESRCH; 644 return ESRCH;
630 } 645 }
631 if ((thread->pt_flags & PT_FLAG_DETACHED) != 0) { 646 if ((thread->pt_flags & PT_FLAG_DETACHED) != 0) {
632 pthread_mutex_unlock(&thread->pt_lock); 647 pthread_mutex_unlock(&thread->pt_lock);
633 self->pt_droplock = NULL; 648 self->pt_droplock = NULL;
634 return EINVAL; 649 return EINVAL;
635 } 650 }
636 error = pthread_cond_wait(&thread->pt_joiners, 651 error = pthread_cond_wait(&thread->pt_joiners,
637 &thread->pt_lock); 652 &thread->pt_lock);
638 if (error != 0) { 653 if (error != 0) {
639 pthread__errorfunc(__FILE__, __LINE__, 654 pthread__errorfunc(__FILE__, __LINE__,
640 __func__, "unexpected return from cond_wait()"); 655 __func__, "unexpected return from cond_wait()");
641 } 656 }
642 657
643 } 658 }
644 pthread__testcancel(self); 659 pthread__testcancel(self);
645 if (valptr != NULL) 660 if (valptr != NULL)
646 *valptr = thread->pt_exitval; 661 *valptr = thread->pt_exitval;
647 /* pthread__reap() will drop the lock. */ 662 /* pthread__reap() will drop the lock. */
648 pthread__reap(thread); 663 pthread__reap(thread);
649 self->pt_droplock = NULL; 664 self->pt_droplock = NULL;
650 665
651 return 0; 666 return 0;
652} 667}
653 668
654static void 669static void
655pthread__reap(pthread_t thread) 670pthread__reap(pthread_t thread)
656{ 671{
657 char *name; 672 char *name;
658 673
659 name = thread->pt_name; 674 name = thread->pt_name;
660 thread->pt_name = NULL; 675 thread->pt_name = NULL;
661 thread->pt_state = PT_STATE_DEAD; 676 thread->pt_state = PT_STATE_DEAD;
662 pthread_mutex_unlock(&thread->pt_lock); 677 pthread_mutex_unlock(&thread->pt_lock);
663 678
664 pthread_mutex_lock(&pthread__deadqueue_lock); 679 pthread_mutex_lock(&pthread__deadqueue_lock);
665 PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_deadq); 680 PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_deadq);
666 pthread_mutex_unlock(&pthread__deadqueue_lock); 681 pthread_mutex_unlock(&pthread__deadqueue_lock);
667 682
668 if (name != NULL) 683 if (name != NULL)
669 free(name); 684 free(name);
670} 685}
671 686
672int 687int
673pthread_equal(pthread_t t1, pthread_t t2) 688pthread_equal(pthread_t t1, pthread_t t2)
674{ 689{
675 690
676 /* Nothing special here. */ 691 /* Nothing special here. */
677 return (t1 == t2); 692 return (t1 == t2);
678} 693}
679 694
680 695
681int 696int
682pthread_detach(pthread_t thread) 697pthread_detach(pthread_t thread)
683{ 698{
684 699
685 if (pthread__find(thread) != 0) 700 if (pthread__find(thread) != 0)
686 return ESRCH; 701 return ESRCH;
687 702
688 if (thread->pt_magic != PT_MAGIC) 703 if (thread->pt_magic != PT_MAGIC)
689 return EINVAL; 704 return EINVAL;
690 705
691 pthread_mutex_lock(&thread->pt_lock); 706 pthread_mutex_lock(&thread->pt_lock);
692 thread->pt_flags |= PT_FLAG_DETACHED; 707 thread->pt_flags |= PT_FLAG_DETACHED;
693 if (thread->pt_state == PT_STATE_ZOMBIE) { 708 if (thread->pt_state == PT_STATE_ZOMBIE) {
694 /* pthread__reap() will drop the lock. */ 709 /* pthread__reap() will drop the lock. */
695 pthread__reap(thread); 710 pthread__reap(thread);
696 } else { 711 } else {
697 /* 712 /*
698 * Not valid for threads to be waiting in 713 * Not valid for threads to be waiting in
699 * pthread_join() (there are intractable 714 * pthread_join() (there are intractable
700 * sync issues from the application 715 * sync issues from the application
701 * perspective), but give those threads 716 * perspective), but give those threads
702 * a chance anyway. 717 * a chance anyway.
703 */ 718 */
704 pthread_cond_broadcast(&thread->pt_joiners); 719 pthread_cond_broadcast(&thread->pt_joiners);
705 pthread_mutex_unlock(&thread->pt_lock); 720 pthread_mutex_unlock(&thread->pt_lock);
706 } 721 }
707 722
708 return 0; 723 return 0;
709} 724}
710 725
711 726
712int 727int
713pthread_getname_np(pthread_t thread, char *name, size_t len) 728pthread_getname_np(pthread_t thread, char *name, size_t len)
714{ 729{
715 730
716 if (pthread__find(thread) != 0) 731 if (pthread__find(thread) != 0)
717 return ESRCH; 732 return ESRCH;
718 733
719 if (thread->pt_magic != PT_MAGIC) 734 if (thread->pt_magic != PT_MAGIC)
720 return EINVAL; 735 return EINVAL;
721 736
722 pthread_mutex_lock(&thread->pt_lock); 737 pthread_mutex_lock(&thread->pt_lock);
723 if (thread->pt_name == NULL) 738 if (thread->pt_name == NULL)
724 name[0] = '\0'; 739 name[0] = '\0';
725 else 740 else
726 strlcpy(name, thread->pt_name, len); 741 strlcpy(name, thread->pt_name, len);
727 pthread_mutex_unlock(&thread->pt_lock); 742 pthread_mutex_unlock(&thread->pt_lock);
728 743
729 return 0; 744 return 0;
730} 745}
731 746
732 747
733int 748int
734pthread_setname_np(pthread_t thread, const char *name, void *arg) 749pthread_setname_np(pthread_t thread, const char *name, void *arg)
735{ 750{
736 char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP]; 751 char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP];
737 int namelen; 752 int namelen;
738 753
739 if (pthread__find(thread) != 0) 754 if (pthread__find(thread) != 0)
740 return ESRCH; 755 return ESRCH;
741 756
742 if (thread->pt_magic != PT_MAGIC) 757 if (thread->pt_magic != PT_MAGIC)
743 return EINVAL; 758 return EINVAL;
744 759
745 namelen = snprintf(newname, sizeof(newname), name, arg); 760 namelen = snprintf(newname, sizeof(newname), name, arg);
746 if (namelen >= PTHREAD_MAX_NAMELEN_NP) 761 if (namelen >= PTHREAD_MAX_NAMELEN_NP)
747 return EINVAL; 762 return EINVAL;
748 763
749 cp = strdup(newname); 764 cp = strdup(newname);
750 if (cp == NULL) 765 if (cp == NULL)
751 return ENOMEM; 766 return ENOMEM;
752 767
753 pthread_mutex_lock(&thread->pt_lock); 768 pthread_mutex_lock(&thread->pt_lock);
754 oldname = thread->pt_name; 769 oldname = thread->pt_name;
755 thread->pt_name = cp; 770 thread->pt_name = cp;
756 (void)_lwp_setname(thread->pt_lid, cp); 771 (void)_lwp_setname(thread->pt_lid, cp);
757 pthread_mutex_unlock(&thread->pt_lock); 772 pthread_mutex_unlock(&thread->pt_lock);
758 773
759 if (oldname != NULL) 774 if (oldname != NULL)
760 free(oldname); 775 free(oldname);
761 776
762 return 0; 777 return 0;
763} 778}
764 779
765 780
766 781
767/* 782/*
768 * XXX There should be a way for applications to use the efficent 783 * XXX There should be a way for applications to use the efficent
769 * inline version, but there are opacity/namespace issues. 784 * inline version, but there are opacity/namespace issues.
770 */ 785 */
771pthread_t 786pthread_t
772pthread_self(void) 787pthread_self(void)
773{ 788{
774 789
775 return pthread__self(); 790 return pthread__self();
776} 791}
777 792
778 793
779int 794int
780pthread_cancel(pthread_t thread) 795pthread_cancel(pthread_t thread)
781{ 796{
782 797
783 if (pthread__find(thread) != 0) 798 if (pthread__find(thread) != 0)
784 return ESRCH; 799 return ESRCH;
785 pthread_mutex_lock(&thread->pt_lock); 800 pthread_mutex_lock(&thread->pt_lock);
786 thread->pt_flags |= PT_FLAG_CS_PENDING; 801 thread->pt_flags |= PT_FLAG_CS_PENDING;
787 if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) { 802 if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) {
788 thread->pt_cancel = 1; 803 thread->pt_cancel = 1;
789 pthread_mutex_unlock(&thread->pt_lock); 804 pthread_mutex_unlock(&thread->pt_lock);
790 _lwp_wakeup(thread->pt_lid); 805 _lwp_wakeup(thread->pt_lid);
791 } else 806 } else
792 pthread_mutex_unlock(&thread->pt_lock); 807 pthread_mutex_unlock(&thread->pt_lock);
793 808
794 return 0; 809 return 0;
795} 810}
796 811
797 812
798int 813int
799pthread_setcancelstate(int state, int *oldstate) 814pthread_setcancelstate(int state, int *oldstate)
800{ 815{
801 pthread_t self; 816 pthread_t self;
802 int retval; 817 int retval;
803 818
804 self = pthread__self(); 819 self = pthread__self();
805 retval = 0; 820 retval = 0;
806 821
807 pthread_mutex_lock(&self->pt_lock); 822 pthread_mutex_lock(&self->pt_lock);
808 823
809 if (oldstate != NULL) { 824 if (oldstate != NULL) {
810 if (self->pt_flags & PT_FLAG_CS_DISABLED) 825 if (self->pt_flags & PT_FLAG_CS_DISABLED)
811 *oldstate = PTHREAD_CANCEL_DISABLE; 826 *oldstate = PTHREAD_CANCEL_DISABLE;
812 else 827 else
813 *oldstate = PTHREAD_CANCEL_ENABLE; 828 *oldstate = PTHREAD_CANCEL_ENABLE;
814 } 829 }
815 830
816 if (state == PTHREAD_CANCEL_DISABLE) { 831 if (state == PTHREAD_CANCEL_DISABLE) {
817 self->pt_flags |= PT_FLAG_CS_DISABLED; 832 self->pt_flags |= PT_FLAG_CS_DISABLED;
818 if (self->pt_cancel) { 833 if (self->pt_cancel) {
819 self->pt_flags |= PT_FLAG_CS_PENDING; 834 self->pt_flags |= PT_FLAG_CS_PENDING;
820 self->pt_cancel = 0; 835 self->pt_cancel = 0;
821 } 836 }
822 } else if (state == PTHREAD_CANCEL_ENABLE) { 837 } else if (state == PTHREAD_CANCEL_ENABLE) {
823 self->pt_flags &= ~PT_FLAG_CS_DISABLED; 838 self->pt_flags &= ~PT_FLAG_CS_DISABLED;
824 /* 839 /*
825 * If a cancellation was requested while cancellation 840 * If a cancellation was requested while cancellation
826 * was disabled, note that fact for future 841 * was disabled, note that fact for future
827 * cancellation tests. 842 * cancellation tests.
828 */ 843 */
829 if (self->pt_flags & PT_FLAG_CS_PENDING) { 844 if (self->pt_flags & PT_FLAG_CS_PENDING) {
830 self->pt_cancel = 1; 845 self->pt_cancel = 1;
831 /* This is not a deferred cancellation point. */ 846 /* This is not a deferred cancellation point. */
832 if (self->pt_flags & PT_FLAG_CS_ASYNC) { 847 if (self->pt_flags & PT_FLAG_CS_ASYNC) {
833 pthread_mutex_unlock(&self->pt_lock); 848 pthread_mutex_unlock(&self->pt_lock);
834 pthread__cancelled(); 849 pthread__cancelled();
835 } 850 }
836 } 851 }
837 } else 852 } else
838 retval = EINVAL; 853 retval = EINVAL;
839 854
840 pthread_mutex_unlock(&self->pt_lock); 855 pthread_mutex_unlock(&self->pt_lock);
841 856
842 return retval; 857 return retval;
843} 858}
844 859
845 860
846int 861int
847pthread_setcanceltype(int type, int *oldtype) 862pthread_setcanceltype(int type, int *oldtype)
848{ 863{
849 pthread_t self; 864 pthread_t self;
850 int retval; 865 int retval;
851 866
852 self = pthread__self(); 867 self = pthread__self();
853 retval = 0; 868 retval = 0;
854 869
855 pthread_mutex_lock(&self->pt_lock); 870 pthread_mutex_lock(&self->pt_lock);
856 871
857 if (oldtype != NULL) { 872 if (oldtype != NULL) {
858 if (self->pt_flags & PT_FLAG_CS_ASYNC) 873 if (self->pt_flags & PT_FLAG_CS_ASYNC)
859 *oldtype = PTHREAD_CANCEL_ASYNCHRONOUS; 874 *oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
860 else 875 else
861 *oldtype = PTHREAD_CANCEL_DEFERRED; 876 *oldtype = PTHREAD_CANCEL_DEFERRED;
862 } 877 }
863 878
864 if (type == PTHREAD_CANCEL_ASYNCHRONOUS) { 879 if (type == PTHREAD_CANCEL_ASYNCHRONOUS) {
865 self->pt_flags |= PT_FLAG_CS_ASYNC; 880 self->pt_flags |= PT_FLAG_CS_ASYNC;
866 if (self->pt_cancel) { 881 if (self->pt_cancel) {
867 pthread_mutex_unlock(&self->pt_lock); 882 pthread_mutex_unlock(&self->pt_lock);
868 pthread__cancelled(); 883 pthread__cancelled();
869 } 884 }
870 } else if (type == PTHREAD_CANCEL_DEFERRED) 885 } else if (type == PTHREAD_CANCEL_DEFERRED)
871 self->pt_flags &= ~PT_FLAG_CS_ASYNC; 886 self->pt_flags &= ~PT_FLAG_CS_ASYNC;
872 else 887 else
873 retval = EINVAL; 888 retval = EINVAL;
874 889
875 pthread_mutex_unlock(&self->pt_lock); 890 pthread_mutex_unlock(&self->pt_lock);
876 891
877 return retval; 892 return retval;
878} 893}
879 894
880 895
881void 896void
882pthread_testcancel(void) 897pthread_testcancel(void)
883{ 898{
884 pthread_t self; 899 pthread_t self;
885 900
886 self = pthread__self(); 901 self = pthread__self();
887 if (self->pt_cancel) 902 if (self->pt_cancel)
888 pthread__cancelled(); 903 pthread__cancelled();
889} 904}
890 905
891 906
892/* 907/*
893 * POSIX requires that certain functions return an error rather than 908 * POSIX requires that certain functions return an error rather than
894 * invoking undefined behavior even when handed completely bogus 909 * invoking undefined behavior even when handed completely bogus
895 * pthread_t values, e.g. stack garbage or (pthread_t)666. This 910 * pthread_t values, e.g. stack garbage or (pthread_t)666. This
896 * utility routine searches the list of threads for the pthread_t 911 * utility routine searches the list of threads for the pthread_t
897 * value without dereferencing it. 912 * value without dereferencing it.
898 */ 913 */
899int 914int
900pthread__find(pthread_t id) 915pthread__find(pthread_t id)
901{ 916{
902 pthread_t target; 917 pthread_t target;
903 918
904 pthread_rwlock_rdlock(&pthread__alltree_lock); 919 pthread_rwlock_rdlock(&pthread__alltree_lock);
905 /* LINTED */ 920 /* LINTED */
906 target = RB_FIND(__pthread__alltree, &pthread__alltree, id); 921 target = RB_FIND(__pthread__alltree, &pthread__alltree, id);
907 pthread_rwlock_unlock(&pthread__alltree_lock); 922 pthread_rwlock_unlock(&pthread__alltree_lock);
908 923
909 if (target == NULL || target->pt_state == PT_STATE_DEAD) 924 if (target == NULL || target->pt_state == PT_STATE_DEAD)
910 return ESRCH; 925 return ESRCH;
911 926
912 return 0; 927 return 0;
913} 928}
914 929
915 930
916void 931void
917pthread__testcancel(pthread_t self) 932pthread__testcancel(pthread_t self)
918{ 933{
919 934
920 if (self->pt_cancel) 935 if (self->pt_cancel)
921 pthread__cancelled(); 936 pthread__cancelled();
922} 937}
923 938
924 939
925void 940void
926pthread__cancelled(void) 941pthread__cancelled(void)
927{ 942{
928 pthread_mutex_t *droplock; 943 pthread_mutex_t *droplock;
929 pthread_t self; 944 pthread_t self;
930 945
931 self = pthread__self(); 946 self = pthread__self();
932 droplock = self->pt_droplock; 947 droplock = self->pt_droplock;
933 self->pt_droplock = NULL; 948 self->pt_droplock = NULL;
934 949
935 if (droplock != NULL && pthread_mutex_held_np(droplock)) 950 if (droplock != NULL && pthread_mutex_held_np(droplock))
936 pthread_mutex_unlock(droplock); 951 pthread_mutex_unlock(droplock);
937 952
938 pthread_exit(PTHREAD_CANCELED); 953 pthread_exit(PTHREAD_CANCELED);
939} 954}
940 955
941 956
942void 957void
943pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store) 958pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store)
944{ 959{
945 pthread_t self; 960 pthread_t self;
946 struct pt_clean_t *entry; 961 struct pt_clean_t *entry;
947 962
948 self = pthread__self(); 963 self = pthread__self();
949 entry = store; 964 entry = store;
950 entry->ptc_cleanup = cleanup; 965 entry->ptc_cleanup = cleanup;
951 entry->ptc_arg = arg; 966 entry->ptc_arg = arg;
952 PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next); 967 PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next);
953} 968}
954 969
955 970
956void 971void
957pthread__cleanup_pop(int ex, void *store) 972pthread__cleanup_pop(int ex, void *store)
958{ 973{
959 pthread_t self; 974 pthread_t self;
960 struct pt_clean_t *entry; 975 struct pt_clean_t *entry;
961 976
962 self = pthread__self(); 977 self = pthread__self();
963 entry = store; 978 entry = store;
964 979
965 PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next); 980 PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next);
966 if (ex) 981 if (ex)
967 (*entry->ptc_cleanup)(entry->ptc_arg); 982 (*entry->ptc_cleanup)(entry->ptc_arg);
968} 983}
969 984
970 985
971int * 986int *
972pthread__errno(void) 987pthread__errno(void)
973{ 988{
974 pthread_t self; 989 pthread_t self;
975 990
976 self = pthread__self(); 991 self = pthread__self();
977 992
978 return &(self->pt_errno); 993 return &(self->pt_errno);
979} 994}
980 995
981ssize_t _sys_write(int, const void *, size_t); 996ssize_t _sys_write(int, const void *, size_t);
982 997
983void 998void
984pthread__assertfunc(const char *file, int line, const char *function, 999pthread__assertfunc(const char *file, int line, const char *function,
985 const char *expr) 1000 const char *expr)
986{ 1001{
987 char buf[1024]; 1002 char buf[1024];
988 int len; 1003 int len;
989 1004
990 /* 1005 /*
991 * snprintf should not acquire any locks, or we could 1006 * snprintf should not acquire any locks, or we could
992 * end up deadlocked if the assert caller held locks. 1007 * end up deadlocked if the assert caller held locks.
993 */ 1008 */
994 len = snprintf(buf, 1024,  1009 len = snprintf(buf, 1024,
995 "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n", 1010 "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
996 expr, file, line, 1011 expr, file, line,
997 function ? ", function \"" : "", 1012 function ? ", function \"" : "",
998 function ? function : "", 1013 function ? function : "",
999 function ? "\"" : ""); 1014 function ? "\"" : "");
1000 1015
1001 _sys_write(STDERR_FILENO, buf, (size_t)len); 1016 _sys_write(STDERR_FILENO, buf, (size_t)len);
1002 (void)kill(getpid(), SIGABRT); 1017 (void)kill(getpid(), SIGABRT);
1003 1018
1004 _exit(1); 1019 _exit(1);
1005} 1020}
1006 1021
1007 1022
1008void 1023void
1009pthread__errorfunc(const char *file, int line, const char *function, 1024pthread__errorfunc(const char *file, int line, const char *function,
1010 const char *msg) 1025 const char *msg)
1011{ 1026{
1012 char buf[1024]; 1027 char buf[1024];
1013 size_t len; 1028 size_t len;
1014  1029
1015 if (pthread__diagassert == 0) 1030 if (pthread__diagassert == 0)
1016 return; 1031 return;
1017 1032
1018 /* 1033 /*
1019 * snprintf should not acquire any locks, or we could 1034 * snprintf should not acquire any locks, or we could
1020 * end up deadlocked if the assert caller held locks. 1035 * end up deadlocked if the assert caller held locks.
1021 */ 1036 */
1022 len = snprintf(buf, 1024,  1037 len = snprintf(buf, 1024,
1023 "%s: Error detected by libpthread: %s.\n" 1038 "%s: Error detected by libpthread: %s.\n"
1024 "Detected by file \"%s\", line %d%s%s%s.\n" 1039 "Detected by file \"%s\", line %d%s%s%s.\n"
1025 "See pthread(3) for information.\n", 1040 "See pthread(3) for information.\n",
1026 getprogname(), msg, file, line, 1041 getprogname(), msg, file, line,
1027 function ? ", function \"" : "", 1042 function ? ", function \"" : "",
1028 function ? function : "", 1043 function ? function : "",
1029 function ? "\"" : ""); 1044 function ? "\"" : "");
1030 1045
1031 if (pthread__diagassert & DIAGASSERT_STDERR) 1046 if (pthread__diagassert & DIAGASSERT_STDERR)
1032 _sys_write(STDERR_FILENO, buf, len); 1047 _sys_write(STDERR_FILENO, buf, len);
1033 1048
1034 if (pthread__diagassert & DIAGASSERT_SYSLOG) 1049 if (pthread__diagassert & DIAGASSERT_SYSLOG)
1035 syslog(LOG_DEBUG | LOG_USER, "%s", buf); 1050 syslog(LOG_DEBUG | LOG_USER, "%s", buf);
1036 1051
1037 if (pthread__diagassert & DIAGASSERT_ABORT) { 1052 if (pthread__diagassert & DIAGASSERT_ABORT) {
1038 (void)kill(getpid(), SIGABRT); 1053 (void)kill(getpid(), SIGABRT);
1039 _exit(1); 1054 _exit(1);
1040 } 1055 }
1041} 1056}
1042 1057
1043/* 1058/*
1044 * Thread park/unpark operations. The kernel operations are 1059 * Thread park/unpark operations. The kernel operations are
1045 * modelled after a brief description from "Multithreading in 1060 * modelled after a brief description from "Multithreading in
1046 * the Solaris Operating Environment": 1061 * the Solaris Operating Environment":
1047 * 1062 *
1048 * http://www.sun.com/software/whitepapers/solaris9/multithread.pdf 1063 * http://www.sun.com/software/whitepapers/solaris9/multithread.pdf
1049 */ 1064 */
1050 1065
1051#define OOPS(msg) \ 1066#define OOPS(msg) \
1052 pthread__errorfunc(__FILE__, __LINE__, __func__, msg) 1067 pthread__errorfunc(__FILE__, __LINE__, __func__, msg)
1053 1068
1054int 1069int
1055pthread__park(pthread_t self, pthread_mutex_t *lock, 1070pthread__park(pthread_t self, pthread_mutex_t *lock,
1056 pthread_queue_t *queue, const struct timespec *abstime, 1071 pthread_queue_t *queue, const struct timespec *abstime,
1057 int cancelpt, const void *hint) 1072 int cancelpt, const void *hint)
1058{ 1073{
1059 int rv, error; 1074 int rv, error;
1060 void *obj; 1075 void *obj;
1061 1076
1062 /* 1077 /*
1063 * For non-interlocked release of mutexes we need a store 1078 * For non-interlocked release of mutexes we need a store
1064 * barrier before incrementing pt_blocking away from zero.  1079 * barrier before incrementing pt_blocking away from zero.
1065 * This is provided by pthread_mutex_unlock(). 1080 * This is provided by pthread_mutex_unlock().
1066 */ 1081 */
1067 self->pt_willpark = 1; 1082 self->pt_willpark = 1;
1068 pthread_mutex_unlock(lock); 1083 pthread_mutex_unlock(lock);
1069 self->pt_willpark = 0; 1084 self->pt_willpark = 0;
1070 self->pt_blocking++; 1085 self->pt_blocking++;
1071 1086
1072 /* 1087 /*
1073 * Wait until we are awoken by a pending unpark operation, 1088 * Wait until we are awoken by a pending unpark operation,
1074 * a signal, an unpark posted after we have gone asleep, 1089 * a signal, an unpark posted after we have gone asleep,
1075 * or an expired timeout. 1090 * or an expired timeout.
1076 * 1091 *
1077 * It is fine to test the value of pt_sleepobj without 1092 * It is fine to test the value of pt_sleepobj without
1078 * holding any locks, because: 1093 * holding any locks, because:
1079 * 1094 *
1080 * o Only the blocking thread (this thread) ever sets them 1095 * o Only the blocking thread (this thread) ever sets them
1081 * to a non-NULL value. 1096 * to a non-NULL value.
1082 * 1097 *
1083 * o Other threads may set them NULL, but if they do so they 1098 * o Other threads may set them NULL, but if they do so they
1084 * must also make this thread return from _lwp_park. 1099 * must also make this thread return from _lwp_park.
1085 * 1100 *
1086 * o _lwp_park, _lwp_unpark and _lwp_unpark_all are system 1101 * o _lwp_park, _lwp_unpark and _lwp_unpark_all are system
1087 * calls and all make use of spinlocks in the kernel. So 1102 * calls and all make use of spinlocks in the kernel. So
1088 * these system calls act as full memory barriers, and will 1103 * these system calls act as full memory barriers, and will
1089 * ensure that the calling CPU's store buffers are drained. 1104 * ensure that the calling CPU's store buffers are drained.
1090 * In combination with the spinlock release before unpark, 1105 * In combination with the spinlock release before unpark,
1091 * this means that modification of pt_sleepobj/onq by another 1106 * this means that modification of pt_sleepobj/onq by another
1092 * thread will become globally visible before that thread 1107 * thread will become globally visible before that thread
1093 * schedules an unpark operation on this thread. 1108 * schedules an unpark operation on this thread.
1094 * 1109 *
1095 * Note: the test in the while() statement dodges the park op if 1110 * Note: the test in the while() statement dodges the park op if
1096 * we have already been awoken, unless there is another thread to 1111 * we have already been awoken, unless there is another thread to
1097 * awaken. This saves a syscall - if we were already awakened, 1112 * awaken. This saves a syscall - if we were already awakened,
1098 * the next call to _lwp_park() would need to return early in order 1113 * the next call to _lwp_park() would need to return early in order
1099 * to eat the previous wakeup. 1114 * to eat the previous wakeup.
1100 */ 1115 */
1101 rv = 0; 1116 rv = 0;
1102 do { 1117 do {
1103 /* 1118 /*
1104 * If we deferred unparking a thread, arrange to 1119 * If we deferred unparking a thread, arrange to
1105 * have _lwp_park() restart it before blocking. 1120 * have _lwp_park() restart it before blocking.
1106 */ 1121 */
1107 error = _lwp_park(abstime, self->pt_unpark, hint, hint); 1122 error = _lwp_park(abstime, self->pt_unpark, hint, hint);
1108 self->pt_unpark = 0; 1123 self->pt_unpark = 0;
1109 if (error != 0) { 1124 if (error != 0) {
1110 switch (rv = errno) { 1125 switch (rv = errno) {
1111 case EINTR: 1126 case EINTR:
1112 case EALREADY: 1127 case EALREADY:
1113 rv = 0; 1128 rv = 0;
1114 break; 1129 break;
1115 case ETIMEDOUT: 1130 case ETIMEDOUT:
1116 break; 1131 break;
1117 default: 1132 default:
1118 OOPS("_lwp_park failed"); 1133 OOPS("_lwp_park failed");
1119 break; 1134 break;
1120 } 1135 }
1121 } 1136 }
1122 /* Check for cancellation. */ 1137 /* Check for cancellation. */
1123 if (cancelpt && self->pt_cancel) 1138 if (cancelpt && self->pt_cancel)
1124 rv = EINTR; 1139 rv = EINTR;
1125 } while (self->pt_sleepobj != NULL && rv == 0); 1140 } while (self->pt_sleepobj != NULL && rv == 0);
1126 1141
1127 /* 1142 /*
1128 * If we have been awoken early but are still on the queue, 1143 * If we have been awoken early but are still on the queue,
1129 * then remove ourself. Again, it's safe to do the test 1144 * then remove ourself. Again, it's safe to do the test
1130 * without holding any locks. 1145 * without holding any locks.
1131 */ 1146 */
1132 if (__predict_false(self->pt_sleepobj != NULL)) { 1147 if (__predict_false(self->pt_sleepobj != NULL)) {
1133 pthread_mutex_lock(lock); 1148 pthread_mutex_lock(lock);
1134 if ((obj = self->pt_sleepobj) != NULL) { 1149 if ((obj = self->pt_sleepobj) != NULL) {
1135 PTQ_REMOVE(queue, self, pt_sleep); 1150 PTQ_REMOVE(queue, self, pt_sleep);
1136 self->pt_sleepobj = NULL; 1151 self->pt_sleepobj = NULL;
1137 if (obj != NULL && self->pt_early != NULL) 1152 if (obj != NULL && self->pt_early != NULL)
1138 (*self->pt_early)(obj); 1153 (*self->pt_early)(obj);
1139 } 1154 }
1140 pthread_mutex_unlock(lock); 1155 pthread_mutex_unlock(lock);
1141 } 1156 }
1142 self->pt_early = NULL; 1157 self->pt_early = NULL;
1143 self->pt_blocking--; 1158 self->pt_blocking--;
1144 membar_sync(); 1159 membar_sync();
1145 1160
1146 return rv; 1161 return rv;
1147} 1162}
1148 1163
1149void 1164void
1150pthread__unpark(pthread_queue_t *queue, pthread_t self, 1165pthread__unpark(pthread_queue_t *queue, pthread_t self,
1151 pthread_mutex_t *interlock) 1166 pthread_mutex_t *interlock)
1152{ 1167{
1153 pthread_t target; 1168 pthread_t target;
1154 u_int max; 1169 u_int max;
1155 size_t nwaiters; 1170 size_t nwaiters;
1156 1171
1157 max = pthread__unpark_max; 1172 max = pthread__unpark_max;
1158 nwaiters = self->pt_nwaiters; 1173 nwaiters = self->pt_nwaiters;
1159 target = PTQ_FIRST(queue); 1174 target = PTQ_FIRST(queue);
1160 if (nwaiters == max) { 1175 if (nwaiters == max) {
1161 /* Overflow. */ 1176 /* Overflow. */
1162 (void)_lwp_unpark_all(self->pt_waiters, nwaiters, 1177 (void)_lwp_unpark_all(self->pt_waiters, nwaiters,
1163 __UNVOLATILE(&interlock->ptm_waiters)); 1178 __UNVOLATILE(&interlock->ptm_waiters));
1164 nwaiters = 0; 1179 nwaiters = 0;
1165 } 1180 }
1166 target->pt_sleepobj = NULL; 1181 target->pt_sleepobj = NULL;
1167 self->pt_waiters[nwaiters++] = target->pt_lid; 1182 self->pt_waiters[nwaiters++] = target->pt_lid;
1168 PTQ_REMOVE(queue, target, pt_sleep); 1183 PTQ_REMOVE(queue, target, pt_sleep);
1169 self->pt_nwaiters = nwaiters; 1184 self->pt_nwaiters = nwaiters;
1170 pthread__mutex_deferwake(self, interlock); 1185 pthread__mutex_deferwake(self, interlock);
1171} 1186}
1172 1187
1173void 1188void
1174pthread__unpark_all(pthread_queue_t *queue, pthread_t self, 1189pthread__unpark_all(pthread_queue_t *queue, pthread_t self,
1175 pthread_mutex_t *interlock) 1190 pthread_mutex_t *interlock)
1176{ 1191{
1177 pthread_t target; 1192 pthread_t target;
1178 u_int max; 1193 u_int max;
1179 size_t nwaiters; 1194 size_t nwaiters;
1180 1195
1181 max = pthread__unpark_max; 1196 max = pthread__unpark_max;
1182 nwaiters = self->pt_nwaiters; 1197 nwaiters = self->pt_nwaiters;
1183 PTQ_FOREACH(target, queue, pt_sleep) { 1198 PTQ_FOREACH(target, queue, pt_sleep) {
1184 if (nwaiters == max) { 1199 if (nwaiters == max) {
1185 /* Overflow. */ 1200 /* Overflow. */
1186 (void)_lwp_unpark_all(self->pt_waiters, nwaiters, 1201 (void)_lwp_unpark_all(self->pt_waiters, nwaiters,
1187 __UNVOLATILE(&interlock->ptm_waiters)); 1202 __UNVOLATILE(&interlock->ptm_waiters));
1188 nwaiters = 0; 1203 nwaiters = 0;
1189 } 1204 }
1190 target->pt_sleepobj = NULL; 1205 target->pt_sleepobj = NULL;
1191 self->pt_waiters[nwaiters++] = target->pt_lid; 1206 self->pt_waiters[nwaiters++] = target->pt_lid;
1192 } 1207 }
1193 self->pt_nwaiters = nwaiters; 1208 self->pt_nwaiters = nwaiters;
1194 PTQ_INIT(queue); 1209 PTQ_INIT(queue);
1195 pthread__mutex_deferwake(self, interlock); 1210 pthread__mutex_deferwake(self, interlock);
1196} 1211}
1197 1212
1198#undef OOPS 1213#undef OOPS
1199 1214
1200static void 1215static void
1201pthread__initmainstack(void) 1216pthread__initmainstack(void)
1202{ 1217{
1203 struct rlimit slimit; 1218 struct rlimit slimit;
1204 const AuxInfo *aux; 1219 const AuxInfo *aux;
1205 size_t size; 1220 size_t size;
1206 1221
1207 _DIAGASSERT(_dlauxinfo() != NULL); 1222 _DIAGASSERT(_dlauxinfo() != NULL);
1208 1223
1209 if (getrlimit(RLIMIT_STACK, &slimit) == -1) 1224 if (getrlimit(RLIMIT_STACK, &slimit) == -1)
1210 err(1, "Couldn't get stack resource consumption limits"); 1225 err(1, "Couldn't get stack resource consumption limits");
1211 size = slimit.rlim_cur; 1226 size = slimit.rlim_cur;
1212 pthread__main.pt_stack.ss_size = size; 1227 pthread__main.pt_stack.ss_size = size;
1213 1228
1214 for (aux = _dlauxinfo(); aux->a_type != AT_NULL; ++aux) { 1229 for (aux = _dlauxinfo(); aux->a_type != AT_NULL; ++aux) {
1215 if (aux->a_type == AT_STACKBASE) { 1230 if (aux->a_type == AT_STACKBASE) {
1216 pthread__main.pt_stack.ss_sp = (void *)aux->a_v; 1231 pthread__main.pt_stack.ss_sp = (void *)aux->a_v;
1217#ifdef __MACHINE_STACK_GROWS_UP 1232#ifdef __MACHINE_STACK_GROWS_UP
1218 pthread__main.pt_stack.ss_sp = (void *)aux->a_v; 1233 pthread__main.pt_stack.ss_sp = (void *)aux->a_v;
1219#else 1234#else
1220 pthread__main.pt_stack.ss_sp = (char *)aux->a_v - size; 1235 pthread__main.pt_stack.ss_sp = (char *)aux->a_v - size;
1221#endif 1236#endif
1222 break; 1237 break;
1223 } 1238 }
1224 } 1239 }
1225} 1240}
1226 1241
1227/* 1242/*
1228 * Set up the slightly special stack for the "initial" thread, which 1243 * Set up the slightly special stack for the "initial" thread, which
1229 * runs on the normal system stack, and thus gets slightly different 1244 * runs on the normal system stack, and thus gets slightly different
1230 * treatment. 1245 * treatment.
1231 */ 1246 */
1232static void 1247static void
1233pthread__initmain(pthread_t *newt) 1248pthread__initmain(pthread_t *newt)
1234{ 1249{
1235 char *value; 1250 char *value;
1236 1251
1237 pthread__initmainstack(); 1252 pthread__initmainstack();
1238 1253
1239 value = pthread__getenv("PTHREAD_STACKSIZE"); 1254 value = pthread__getenv("PTHREAD_STACKSIZE");
1240 if (value != NULL) { 1255 if (value != NULL) {
1241 pthread__stacksize = atoi(value) * 1024; 1256 pthread__stacksize = atoi(value) * 1024;
1242 if (pthread__stacksize > pthread__main.pt_stack.ss_size) 1257 if (pthread__stacksize > pthread__main.pt_stack.ss_size)
1243 pthread__stacksize = pthread__main.pt_stack.ss_size; 1258 pthread__stacksize = pthread__main.pt_stack.ss_size;
1244 } 1259 }
1245 if (pthread__stacksize == 0) 1260 if (pthread__stacksize == 0)
1246 pthread__stacksize = pthread__main.pt_stack.ss_size; 1261 pthread__stacksize = pthread__main.pt_stack.ss_size;
1247 pthread__stacksize += pthread__pagesize - 1; 1262 pthread__stacksize += pthread__pagesize - 1;
1248 pthread__stacksize &= ~pthread__pagesize; 1263 pthread__stacksize &= ~pthread__pagesize;
1249 if (pthread__stacksize < 4 * pthread__pagesize) 1264 if (pthread__stacksize < 4 * pthread__pagesize)
1250 errx(1, "Stacksize limit is too low, minimum %zd kbyte.", 1265 errx(1, "Stacksize limit is too low, minimum %zd kbyte.",
1251 4 * pthread__pagesize / 1024); 1266 4 * pthread__pagesize / 1024);
1252 1267
1253 *newt = &pthread__main; 1268 *newt = &pthread__main;
1254#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II) 1269#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
1255# ifdef __HAVE___LWP_GETTCB_FAST 1270# ifdef __HAVE___LWP_GETTCB_FAST
1256 pthread__main.pt_tls = __lwp_gettcb_fast(); 1271 pthread__main.pt_tls = __lwp_gettcb_fast();
1257# else 1272# else
1258 pthread__main.pt_tls = _lwp_getprivate(); 1273 pthread__main.pt_tls = _lwp_getprivate();
1259# endif 1274# endif
1260 pthread__main.pt_tls->tcb_pthread = &pthread__main; 1275 pthread__main.pt_tls->tcb_pthread = &pthread__main;
1261#endif 1276#endif
1262} 1277}
1263 1278
1264#ifndef lint 1279#ifndef lint
1265static int 1280static int
1266pthread__cmp(struct __pthread_st *a, struct __pthread_st *b) 1281pthread__cmp(struct __pthread_st *a, struct __pthread_st *b)
1267{ 1282{
1268 1283
1269 if ((uintptr_t)a < (uintptr_t)b) 1284 if ((uintptr_t)a < (uintptr_t)b)
1270 return (-1); 1285 return (-1);
1271 else if (a == b) 1286 else if (a == b)
1272 return 0; 1287 return 0;
1273 else 1288 else
1274 return 1; 1289 return 1;
1275} 1290}
1276RB_GENERATE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp) 1291RB_GENERATE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp)
1277#endif 1292#endif
1278 1293
1279/* Because getenv() wants to use locks. */ 1294/* Because getenv() wants to use locks. */
1280char * 1295char *
1281pthread__getenv(const char *name) 1296pthread__getenv(const char *name)
1282{ 1297{
1283 extern char **environ; 1298 extern char **environ;
1284 size_t l_name, offset; 1299 size_t l_name, offset;
1285 1300
1286 l_name = strlen(name); 1301 l_name = strlen(name);
1287 for (offset = 0; environ[offset] != NULL; offset++) { 1302 for (offset = 0; environ[offset] != NULL; offset++) {
1288 if (strncmp(name, environ[offset], l_name) == 0 && 1303 if (strncmp(name, environ[offset], l_name) == 0 &&
1289 environ[offset][l_name] == '=') { 1304 environ[offset][l_name] == '=') {
1290 return environ[offset] + l_name + 1; 1305 return environ[offset] + l_name + 1;
1291 } 1306 }
1292 } 1307 }
1293 1308
1294 return NULL; 1309 return NULL;
1295} 1310}
1296 1311
1297pthread_mutex_t * 1312pthread_mutex_t *
1298pthread__hashlock(volatile const void *p) 1313pthread__hashlock(volatile const void *p)
1299{ 1314{
1300 uintptr_t v; 1315 uintptr_t v;
1301 1316
1302 v = (uintptr_t)p; 1317 v = (uintptr_t)p;
1303 return &hashlocks[((v >> 9) ^ (v >> 3)) & (NHASHLOCK - 1)].mutex; 1318 return &hashlocks[((v >> 9) ^ (v >> 3)) & (NHASHLOCK - 1)].mutex;
1304} 1319}
1305 1320
1306int 1321int
1307pthread__checkpri(int pri) 1322pthread__checkpri(int pri)
1308{ 1323{
1309 static int havepri; 1324 static int havepri;
1310 static long min, max; 1325 static long min, max;
1311 1326
1312 if (!havepri) { 1327 if (!havepri) {
1313 min = sysconf(_SC_SCHED_PRI_MIN); 1328 min = sysconf(_SC_SCHED_PRI_MIN);
1314 max = sysconf(_SC_SCHED_PRI_MAX); 1329 max = sysconf(_SC_SCHED_PRI_MAX);
1315 havepri = 1; 1330 havepri = 1;
1316 } 1331 }
1317 return (pri < min || pri > max) ? EINVAL : 0; 1332 return (pri < min || pri > max) ? EINVAL : 0;
1318} 1333}