xref: /titanic_41/usr/src/lib/libc/port/threads/thr.c (revision eb0cc229f19c437a6b538d3ac0d0443268290b7e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include "lint.h"
30 #include "thr_uberdata.h"
31 #include <pthread.h>
32 #include <procfs.h>
33 #include <sys/uio.h>
34 #include <ctype.h>
35 #include "libc.h"
36 
37 #undef errno
38 extern int errno;
39 
40 /*
41  * Between Solaris 2.5 and Solaris 9, __threaded was used to indicate
42  * "we are linked with libthread".  The Sun Workshop 6 update 1 compilation
43  * system used it illegally (it is a consolidation private symbol).
44  * To accommodate this and possibly other abusers of the symbol,
45  * we make it always equal to 1 now that libthread has been folded
46  * into libc.  The new __libc_threaded symbol is used to indicate
47  * the new meaning, "more than one thread exists".
48  */
49 int __threaded = 1;		/* always equal to 1 */
50 int __libc_threaded = 0;	/* zero until first thr_create() */
51 
52 /*
53  * thr_concurrency and pthread_concurrency are not used by the library.
54  * They exist solely to hold and return the values set by calls to
55  * thr_setconcurrency() and pthread_setconcurrency().
56  * Because thr_concurrency is affected by the THR_NEW_LWP flag
57  * to thr_create(), thr_concurrency is protected by link_lock.
58  */
59 static	int	thr_concurrency = 1;
60 static	int	pthread_concurrency;
61 
62 #define	HASHTBLSZ	1024	/* must be a power of two */
63 #define	TIDHASH(tid, udp)	(tid & (udp)->hash_mask)
64 
65 /* initial allocation, just enough for one lwp */
66 #pragma align 64(init_hash_table)
67 thr_hash_table_t init_hash_table[1] = {
68 	{ DEFAULTMUTEX, DEFAULTCV, NULL },
69 };
70 
71 extern const Lc_interface rtld_funcs[];
72 
73 /*
74  * The weak version is known to libc_db and mdb.
75  */
76 #pragma weak _uberdata = __uberdata
77 uberdata_t __uberdata = {
78 	{ DEFAULTMUTEX, NULL, 0 },	/* link_lock */
79 	{ RECURSIVEMUTEX, NULL, 0 },	/* fork_lock */
80 	{ RECURSIVEMUTEX, NULL, 0 },	/* atfork_lock */
81 	{ RECURSIVEMUTEX, NULL, 0 },	/* callout_lock */
82 	{ DEFAULTMUTEX, NULL, 0 },	/* tdb_hash_lock */
83 	{ 0, },				/* tdb_hash_lock_stats */
84 	{ { 0 }, },			/* siguaction[NSIG] */
85 	{{ DEFAULTMUTEX, NULL, 0 },		/* bucket[NBUCKETS] */
86 	{ DEFAULTMUTEX, NULL, 0 },
87 	{ DEFAULTMUTEX, NULL, 0 },
88 	{ DEFAULTMUTEX, NULL, 0 },
89 	{ DEFAULTMUTEX, NULL, 0 },
90 	{ DEFAULTMUTEX, NULL, 0 },
91 	{ DEFAULTMUTEX, NULL, 0 },
92 	{ DEFAULTMUTEX, NULL, 0 },
93 	{ DEFAULTMUTEX, NULL, 0 },
94 	{ DEFAULTMUTEX, NULL, 0 }},
95 	{ RECURSIVEMUTEX, NULL, NULL },		/* atexit_root */
96 	{ DEFAULTMUTEX, 0, 0, NULL },		/* tsd_metadata */
97 	{ DEFAULTMUTEX, {0, 0}, {0, 0} },	/* tls_metadata */
98 	0,			/* primary_map */
99 	0,			/* bucket_init */
100 	0,			/* pad[0] */
101 	0,			/* pad[1] */
102 	{ 0 },			/* uberflags */
103 	NULL,			/* queue_head */
104 	init_hash_table,	/* thr_hash_table */
105 	1,			/* hash_size: size of the hash table */
106 	0,			/* hash_mask: hash_size - 1 */
107 	NULL,			/* ulwp_one */
108 	NULL,			/* all_lwps */
109 	NULL,			/* all_zombies */
110 	0,			/* nthreads */
111 	0,			/* nzombies */
112 	0,			/* ndaemons */
113 	0,			/* pid */
114 	sigacthandler,		/* sigacthandler */
115 	NULL,			/* lwp_stacks */
116 	NULL,			/* lwp_laststack */
117 	0,			/* nfreestack */
118 	10,			/* thread_stack_cache */
119 	NULL,			/* ulwp_freelist */
120 	NULL,			/* ulwp_lastfree */
121 	NULL,			/* ulwp_replace_free */
122 	NULL,			/* ulwp_replace_last */
123 	NULL,			/* atforklist */
124 	NULL,			/* robustlocks */
125 	NULL,			/* __tdb_bootstrap */
126 	{			/* tdb */
127 		NULL,		/* tdb_sync_addr_hash */
128 		0,		/* tdb_register_count */
129 		0,		/* tdb_hash_alloc_failed */
130 		NULL,		/* tdb_sync_addr_free */
131 		NULL,		/* tdb_sync_addr_last */
132 		0,		/* tdb_sync_alloc */
133 		{ 0, 0 },	/* tdb_ev_global_mask */
134 		tdb_events,	/* tdb_events array */
135 	},
136 };
137 
138 /*
139  * The weak version is known to libc_db and mdb.
140  */
141 #pragma weak _tdb_bootstrap = __tdb_bootstrap
142 uberdata_t **__tdb_bootstrap = NULL;
143 
144 int	thread_queue_fifo = 4;
145 int	thread_queue_dump = 0;
146 int	thread_cond_wait_defer = 0;
147 int	thread_error_detection = 0;
148 int	thread_async_safe = 0;
149 int	thread_stack_cache = 10;
150 
151 int	thread_door_noreserve = 0;
152 
153 static	ulwp_t	*ulwp_alloc(void);
154 static	void	ulwp_free(ulwp_t *);
155 
156 /*
157  * Insert the lwp into the hash table.
158  */
159 void
160 hash_in_unlocked(ulwp_t *ulwp, int ix, uberdata_t *udp)
161 {
162 	ulwp->ul_hash = udp->thr_hash_table[ix].hash_bucket;
163 	udp->thr_hash_table[ix].hash_bucket = ulwp;
164 	ulwp->ul_ix = ix;
165 }
166 
167 void
168 hash_in(ulwp_t *ulwp, uberdata_t *udp)
169 {
170 	int ix = TIDHASH(ulwp->ul_lwpid, udp);
171 	mutex_t *mp = &udp->thr_hash_table[ix].hash_lock;
172 
173 	lmutex_lock(mp);
174 	hash_in_unlocked(ulwp, ix, udp);
175 	lmutex_unlock(mp);
176 }
177 
178 /*
179  * Delete the lwp from the hash table.
180  */
181 void
182 hash_out_unlocked(ulwp_t *ulwp, int ix, uberdata_t *udp)
183 {
184 	ulwp_t **ulwpp;
185 
186 	for (ulwpp = &udp->thr_hash_table[ix].hash_bucket;
187 	    ulwp != *ulwpp;
188 	    ulwpp = &(*ulwpp)->ul_hash)
189 		;
190 	*ulwpp = ulwp->ul_hash;
191 	ulwp->ul_hash = NULL;
192 	ulwp->ul_ix = -1;
193 }
194 
195 void
196 hash_out(ulwp_t *ulwp, uberdata_t *udp)
197 {
198 	int ix;
199 
200 	if ((ix = ulwp->ul_ix) >= 0) {
201 		mutex_t *mp = &udp->thr_hash_table[ix].hash_lock;
202 
203 		lmutex_lock(mp);
204 		hash_out_unlocked(ulwp, ix, udp);
205 		lmutex_unlock(mp);
206 	}
207 }
208 
209 /*
210  * Retain stack information for thread structures that are being recycled for
211  * new threads.  All other members of the thread structure should be zeroed.
212  */
213 static void
214 ulwp_clean(ulwp_t *ulwp)
215 {
216 	caddr_t stk = ulwp->ul_stk;
217 	size_t mapsiz = ulwp->ul_mapsiz;
218 	size_t guardsize = ulwp->ul_guardsize;
219 	uintptr_t stktop = ulwp->ul_stktop;
220 	size_t stksiz = ulwp->ul_stksiz;
221 
222 	(void) _private_memset(ulwp, 0, sizeof (*ulwp));
223 
224 	ulwp->ul_stk = stk;
225 	ulwp->ul_mapsiz = mapsiz;
226 	ulwp->ul_guardsize = guardsize;
227 	ulwp->ul_stktop = stktop;
228 	ulwp->ul_stksiz = stksiz;
229 }
230 
231 static int stackprot;
232 
233 /*
234  * Answer the question, "Is the lwp in question really dead?"
235  * We must inquire of the operating system to be really sure
236  * because the lwp may have called lwp_exit() but it has not
237  * yet completed the exit.
238  */
239 static int
240 dead_and_buried(ulwp_t *ulwp)
241 {
242 	if (ulwp->ul_lwpid == (lwpid_t)(-1))
243 		return (1);
244 	if (ulwp->ul_dead && ulwp->ul_detached &&
245 	    __lwp_kill(ulwp->ul_lwpid, 0) == ESRCH) {
246 		ulwp->ul_lwpid = (lwpid_t)(-1);
247 		return (1);
248 	}
249 	return (0);
250 }
251 
252 /*
253  * Attempt to keep the stack cache within the specified cache limit.
254  */
255 static void
256 trim_stack_cache(int cache_limit)
257 {
258 	ulwp_t *self = curthread;
259 	uberdata_t *udp = self->ul_uberdata;
260 	ulwp_t *prev = NULL;
261 	ulwp_t **ulwpp = &udp->lwp_stacks;
262 	ulwp_t *ulwp;
263 
264 	ASSERT(udp->nthreads <= 1 || MUTEX_OWNED(&udp->link_lock, self));
265 
266 	while (udp->nfreestack > cache_limit && (ulwp = *ulwpp) != NULL) {
267 		if (dead_and_buried(ulwp)) {
268 			*ulwpp = ulwp->ul_next;
269 			if (ulwp == udp->lwp_laststack)
270 				udp->lwp_laststack = prev;
271 			hash_out(ulwp, udp);
272 			udp->nfreestack--;
273 			(void) _private_munmap(ulwp->ul_stk, ulwp->ul_mapsiz);
274 			/*
275 			 * Now put the free ulwp on the ulwp freelist.
276 			 */
277 			ulwp->ul_mapsiz = 0;
278 			ulwp->ul_next = NULL;
279 			if (udp->ulwp_freelist == NULL)
280 				udp->ulwp_freelist = udp->ulwp_lastfree = ulwp;
281 			else {
282 				udp->ulwp_lastfree->ul_next = ulwp;
283 				udp->ulwp_lastfree = ulwp;
284 			}
285 		} else {
286 			prev = ulwp;
287 			ulwpp = &ulwp->ul_next;
288 		}
289 	}
290 }
291 
292 /*
293  * Find an unused stack of the requested size
294  * or create a new stack of the requested size.
295  * Return a pointer to the ulwp_t structure referring to the stack, or NULL.
296  * thr_exit() stores 1 in the ul_dead member.
297  * thr_join() stores -1 in the ul_lwpid member.
298  */
299 ulwp_t *
300 find_stack(size_t stksize, size_t guardsize)
301 {
302 	static size_t pagesize = 0;
303 
304 	uberdata_t *udp = curthread->ul_uberdata;
305 	size_t mapsize;
306 	ulwp_t *prev;
307 	ulwp_t *ulwp;
308 	ulwp_t **ulwpp;
309 	void *stk;
310 
311 	/*
312 	 * The stack is allocated PROT_READ|PROT_WRITE|PROT_EXEC
313 	 * unless overridden by the system's configuration.
314 	 */
315 	if (stackprot == 0) {	/* do this once */
316 		long lprot = _sysconf(_SC_STACK_PROT);
317 		if (lprot <= 0)
318 			lprot = (PROT_READ|PROT_WRITE|PROT_EXEC);
319 		stackprot = (int)lprot;
320 	}
321 	if (pagesize == 0)	/* do this once */
322 		pagesize = _sysconf(_SC_PAGESIZE);
323 
324 	/*
325 	 * One megabyte stacks by default, but subtract off
326 	 * two pages for the system-created red zones.
327 	 * Round up a non-zero stack size to a pagesize multiple.
328 	 */
329 	if (stksize == 0)
330 		stksize = DEFAULTSTACK - 2 * pagesize;
331 	else
332 		stksize = ((stksize + pagesize - 1) & -pagesize);
333 
334 	/*
335 	 * Round up the mapping size to a multiple of pagesize.
336 	 * Note: mmap() provides at least one page of red zone
337 	 * so we deduct that from the value of guardsize.
338 	 */
339 	if (guardsize != 0)
340 		guardsize = ((guardsize + pagesize - 1) & -pagesize) - pagesize;
341 	mapsize = stksize + guardsize;
342 
343 	lmutex_lock(&udp->link_lock);
344 	for (prev = NULL, ulwpp = &udp->lwp_stacks;
345 	    (ulwp = *ulwpp) != NULL;
346 	    prev = ulwp, ulwpp = &ulwp->ul_next) {
347 		if (ulwp->ul_mapsiz == mapsize &&
348 		    ulwp->ul_guardsize == guardsize &&
349 		    dead_and_buried(ulwp)) {
350 			/*
351 			 * The previous lwp is gone; reuse the stack.
352 			 * Remove the ulwp from the stack list.
353 			 */
354 			*ulwpp = ulwp->ul_next;
355 			ulwp->ul_next = NULL;
356 			if (ulwp == udp->lwp_laststack)
357 				udp->lwp_laststack = prev;
358 			hash_out(ulwp, udp);
359 			udp->nfreestack--;
360 			lmutex_unlock(&udp->link_lock);
361 			ulwp_clean(ulwp);
362 			return (ulwp);
363 		}
364 	}
365 
366 	/*
367 	 * None of the cached stacks matched our mapping size.
368 	 * Reduce the stack cache to get rid of possibly
369 	 * very old stacks that will never be reused.
370 	 */
371 	if (udp->nfreestack > udp->thread_stack_cache)
372 		trim_stack_cache(udp->thread_stack_cache);
373 	else if (udp->nfreestack > 0)
374 		trim_stack_cache(udp->nfreestack - 1);
375 	lmutex_unlock(&udp->link_lock);
376 
377 	/*
378 	 * Create a new stack.
379 	 */
380 	if ((stk = _private_mmap(NULL, mapsize, stackprot,
381 	    MAP_PRIVATE|MAP_NORESERVE|MAP_ANON, -1, (off_t)0)) != MAP_FAILED) {
382 		/*
383 		 * We have allocated our stack.  Now allocate the ulwp.
384 		 */
385 		ulwp = ulwp_alloc();
386 		if (ulwp == NULL)
387 			(void) _private_munmap(stk, mapsize);
388 		else {
389 			ulwp->ul_stk = stk;
390 			ulwp->ul_mapsiz = mapsize;
391 			ulwp->ul_guardsize = guardsize;
392 			ulwp->ul_stktop = (uintptr_t)stk + mapsize;
393 			ulwp->ul_stksiz = stksize;
394 			ulwp->ul_ix = -1;
395 			if (guardsize)	/* protect the extra red zone */
396 				(void) _private_mprotect(stk,
397 				    guardsize, PROT_NONE);
398 		}
399 	}
400 	return (ulwp);
401 }
402 
403 /*
404  * Get a ulwp_t structure from the free list or allocate a new one.
405  * Such ulwp_t's do not have a stack allocated by the library.
406  */
407 static ulwp_t *
408 ulwp_alloc(void)
409 {
410 	ulwp_t *self = curthread;
411 	uberdata_t *udp = self->ul_uberdata;
412 	size_t tls_size;
413 	ulwp_t *prev;
414 	ulwp_t *ulwp;
415 	ulwp_t **ulwpp;
416 	caddr_t data;
417 
418 	lmutex_lock(&udp->link_lock);
419 	for (prev = NULL, ulwpp = &udp->ulwp_freelist;
420 	    (ulwp = *ulwpp) != NULL;
421 	    prev = ulwp, ulwpp = &ulwp->ul_next) {
422 		if (dead_and_buried(ulwp)) {
423 			*ulwpp = ulwp->ul_next;
424 			ulwp->ul_next = NULL;
425 			if (ulwp == udp->ulwp_lastfree)
426 				udp->ulwp_lastfree = prev;
427 			hash_out(ulwp, udp);
428 			lmutex_unlock(&udp->link_lock);
429 			ulwp_clean(ulwp);
430 			return (ulwp);
431 		}
432 	}
433 	lmutex_unlock(&udp->link_lock);
434 
435 	tls_size = roundup64(udp->tls_metadata.static_tls.tls_size);
436 	data = lmalloc(sizeof (*ulwp) + tls_size);
437 	if (data != NULL) {
438 		/* LINTED pointer cast may result in improper alignment */
439 		ulwp = (ulwp_t *)(data + tls_size);
440 	}
441 	return (ulwp);
442 }
443 
444 /*
445  * Free a ulwp structure.
446  * If there is an associated stack, put it on the stack list and
447  * munmap() previously freed stacks up to the residual cache limit.
448  * Else put it on the ulwp free list and never call lfree() on it.
449  */
450 static void
451 ulwp_free(ulwp_t *ulwp)
452 {
453 	uberdata_t *udp = curthread->ul_uberdata;
454 
455 	ASSERT(udp->nthreads <= 1 || MUTEX_OWNED(&udp->link_lock, curthread));
456 	ulwp->ul_next = NULL;
457 	if (ulwp == udp->ulwp_one)	/* don't reuse the primoridal stack */
458 		/*EMPTY*/;
459 	else if (ulwp->ul_mapsiz != 0) {
460 		if (udp->lwp_stacks == NULL)
461 			udp->lwp_stacks = udp->lwp_laststack = ulwp;
462 		else {
463 			udp->lwp_laststack->ul_next = ulwp;
464 			udp->lwp_laststack = ulwp;
465 		}
466 		if (++udp->nfreestack > udp->thread_stack_cache)
467 			trim_stack_cache(udp->thread_stack_cache);
468 	} else {
469 		if (udp->ulwp_freelist == NULL)
470 			udp->ulwp_freelist = udp->ulwp_lastfree = ulwp;
471 		else {
472 			udp->ulwp_lastfree->ul_next = ulwp;
473 			udp->ulwp_lastfree = ulwp;
474 		}
475 	}
476 }
477 
478 /*
479  * Find a named lwp and return a pointer to its hash list location.
480  * On success, returns with the hash lock held.
481  */
482 ulwp_t **
483 find_lwpp(thread_t tid)
484 {
485 	uberdata_t *udp = curthread->ul_uberdata;
486 	int ix = TIDHASH(tid, udp);
487 	mutex_t *mp = &udp->thr_hash_table[ix].hash_lock;
488 	ulwp_t *ulwp;
489 	ulwp_t **ulwpp;
490 
491 	if (tid == 0)
492 		return (NULL);
493 
494 	lmutex_lock(mp);
495 	for (ulwpp = &udp->thr_hash_table[ix].hash_bucket;
496 	    (ulwp = *ulwpp) != NULL;
497 	    ulwpp = &ulwp->ul_hash) {
498 		if (ulwp->ul_lwpid == tid)
499 			return (ulwpp);
500 	}
501 	lmutex_unlock(mp);
502 	return (NULL);
503 }
504 
505 /*
506  * Wake up all lwps waiting on this lwp for some reason.
507  */
508 void
509 ulwp_broadcast(ulwp_t *ulwp)
510 {
511 	ulwp_t *self = curthread;
512 	uberdata_t *udp = self->ul_uberdata;
513 
514 	ASSERT(MUTEX_OWNED(ulwp_mutex(ulwp, udp), self));
515 	(void) cond_broadcast_internal(ulwp_condvar(ulwp, udp));
516 }
517 
518 /*
519  * Find a named lwp and return a pointer to it.
520  * Returns with the hash lock held.
521  */
522 ulwp_t *
523 find_lwp(thread_t tid)
524 {
525 	ulwp_t *self = curthread;
526 	uberdata_t *udp = self->ul_uberdata;
527 	ulwp_t *ulwp = NULL;
528 	ulwp_t **ulwpp;
529 
530 	if (self->ul_lwpid == tid) {
531 		ulwp = self;
532 		ulwp_lock(ulwp, udp);
533 	} else if ((ulwpp = find_lwpp(tid)) != NULL) {
534 		ulwp = *ulwpp;
535 	}
536 
537 	if (ulwp && ulwp->ul_dead) {
538 		ulwp_unlock(ulwp, udp);
539 		ulwp = NULL;
540 	}
541 
542 	return (ulwp);
543 }
544 
545 int
546 _thrp_create(void *stk, size_t stksize, void *(*func)(void *), void *arg,
547 	long flags, thread_t *new_thread, size_t guardsize)
548 {
549 	ulwp_t *self = curthread;
550 	uberdata_t *udp = self->ul_uberdata;
551 	ucontext_t uc;
552 	uint_t lwp_flags;
553 	thread_t tid;
554 	int error = 0;
555 	ulwp_t *ulwp;
556 
557 	/*
558 	 * Enforce the restriction of not creating any threads
559 	 * until the primary link map has been initialized.
560 	 * Also, disallow thread creation to a child of vfork().
561 	 */
562 	if (!self->ul_primarymap || self->ul_vfork)
563 		return (ENOTSUP);
564 
565 	if (udp->hash_size == 1)
566 		finish_init();
567 
568 	if ((stk || stksize) && stksize < MINSTACK)
569 		return (EINVAL);
570 
571 	if (stk == NULL) {
572 		if ((ulwp = find_stack(stksize, guardsize)) == NULL)
573 			return (ENOMEM);
574 		stksize = ulwp->ul_mapsiz - ulwp->ul_guardsize;
575 	} else {
576 		/* initialize the private stack */
577 		if ((ulwp = ulwp_alloc()) == NULL)
578 			return (ENOMEM);
579 		ulwp->ul_stk = stk;
580 		ulwp->ul_stktop = (uintptr_t)stk + stksize;
581 		ulwp->ul_stksiz = stksize;
582 		ulwp->ul_ix = -1;
583 	}
584 	ulwp->ul_errnop = &ulwp->ul_errno;
585 
586 	lwp_flags = LWP_SUSPENDED;
587 	if (flags & (THR_DETACHED|THR_DAEMON)) {
588 		flags |= THR_DETACHED;
589 		lwp_flags |= LWP_DETACHED;
590 	}
591 	if (flags & THR_DAEMON)
592 		lwp_flags |= LWP_DAEMON;
593 
594 	/* creating a thread: enforce mt-correctness in _mutex_lock() */
595 	self->ul_async_safe = 1;
596 
597 	/* per-thread copies of global variables, for speed */
598 	ulwp->ul_queue_fifo = self->ul_queue_fifo;
599 	ulwp->ul_cond_wait_defer = self->ul_cond_wait_defer;
600 	ulwp->ul_error_detection = self->ul_error_detection;
601 	ulwp->ul_async_safe = self->ul_async_safe;
602 	ulwp->ul_max_spinners = self->ul_max_spinners;
603 	ulwp->ul_adaptive_spin = self->ul_adaptive_spin;
604 	ulwp->ul_queue_spin = self->ul_queue_spin;
605 	ulwp->ul_door_noreserve = self->ul_door_noreserve;
606 
607 	/* new thread inherits creating thread's scheduling parameters */
608 	ulwp->ul_policy = self->ul_policy;
609 	ulwp->ul_pri = (self->ul_epri? self->ul_epri : self->ul_pri);
610 	ulwp->ul_cid = self->ul_cid;
611 	ulwp->ul_rtclassid = self->ul_rtclassid;
612 
613 	ulwp->ul_primarymap = self->ul_primarymap;
614 	ulwp->ul_self = ulwp;
615 	ulwp->ul_uberdata = udp;
616 
617 	/* debugger support */
618 	ulwp->ul_usropts = flags;
619 
620 #ifdef __sparc
621 	/*
622 	 * We cache several instructions in the thread structure for use
623 	 * by the fasttrap DTrace provider. When changing this, read the
624 	 * comment in fasttrap.h for the all the other places that must
625 	 * be changed.
626 	 */
627 	ulwp->ul_dsave = 0x9de04000;	/* save %g1, %g0, %sp */
628 	ulwp->ul_drestore = 0x81e80000;	/* restore %g0, %g0, %g0 */
629 	ulwp->ul_dftret = 0x91d0203a;	/* ta 0x3a */
630 	ulwp->ul_dreturn = 0x81ca0000;	/* return %o0 */
631 #endif
632 
633 	ulwp->ul_startpc = func;
634 	ulwp->ul_startarg = arg;
635 	_fpinherit(ulwp);
636 	/*
637 	 * Defer signals on the new thread until its TLS constructors
638 	 * have been called.  _thr_setup() will call sigon() after
639 	 * it has called tls_setup().
640 	 */
641 	ulwp->ul_sigdefer = 1;
642 
643 	if (setup_context(&uc, _thr_setup, ulwp,
644 	    (caddr_t)ulwp->ul_stk + ulwp->ul_guardsize, stksize) != 0)
645 		error = EAGAIN;
646 
647 	/*
648 	 * Call enter_critical() to avoid being suspended until we
649 	 * have linked the new thread into the proper lists.
650 	 * This is necessary because forkall() and fork1() must
651 	 * suspend all threads and they must see a complete list.
652 	 */
653 	enter_critical(self);
654 	uc.uc_sigmask = ulwp->ul_sigmask = self->ul_sigmask;
655 	if (error != 0 ||
656 	    (error = __lwp_create(&uc, lwp_flags, &tid)) != 0) {
657 		exit_critical(self);
658 		ulwp->ul_lwpid = (lwpid_t)(-1);
659 		ulwp->ul_dead = 1;
660 		ulwp->ul_detached = 1;
661 		lmutex_lock(&udp->link_lock);
662 		ulwp_free(ulwp);
663 		lmutex_unlock(&udp->link_lock);
664 		return (error);
665 	}
666 	self->ul_nocancel = 0;	/* cancellation is now possible */
667 	udp->uberflags.uf_mt = 1;
668 	if (new_thread)
669 		*new_thread = tid;
670 	if (flags & THR_DETACHED)
671 		ulwp->ul_detached = 1;
672 	ulwp->ul_lwpid = tid;
673 	ulwp->ul_stop = TSTP_REGULAR;
674 	if (flags & THR_SUSPENDED)
675 		ulwp->ul_created = 1;
676 
677 	lmutex_lock(&udp->link_lock);
678 	ulwp->ul_forw = udp->all_lwps;
679 	ulwp->ul_back = udp->all_lwps->ul_back;
680 	ulwp->ul_back->ul_forw = ulwp;
681 	ulwp->ul_forw->ul_back = ulwp;
682 	hash_in(ulwp, udp);
683 	udp->nthreads++;
684 	if (flags & THR_DAEMON)
685 		udp->ndaemons++;
686 	if (flags & THR_NEW_LWP)
687 		thr_concurrency++;
688 	__libc_threaded = 1;		/* inform stdio */
689 	lmutex_unlock(&udp->link_lock);
690 
691 	if (__td_event_report(self, TD_CREATE, udp)) {
692 		self->ul_td_evbuf.eventnum = TD_CREATE;
693 		self->ul_td_evbuf.eventdata = (void *)(uintptr_t)tid;
694 		tdb_event(TD_CREATE, udp);
695 	}
696 
697 	exit_critical(self);
698 
699 	if (!(flags & THR_SUSPENDED))
700 		(void) _thrp_continue(tid, TSTP_REGULAR);
701 
702 	return (0);
703 }
704 
705 #pragma weak thr_create = _thr_create
706 int
707 _thr_create(void *stk, size_t stksize, void *(*func)(void *), void *arg,
708 	long flags, thread_t *new_thread)
709 {
710 	return (_thrp_create(stk, stksize, func, arg, flags, new_thread, 0));
711 }
712 
713 /*
714  * A special cancellation cleanup hook for DCE.
715  * cleanuphndlr, when it is not NULL, will contain a callback
716  * function to be called before a thread is terminated in
717  * _thr_exit() as a result of being cancelled.
718  */
719 static void (*cleanuphndlr)(void) = NULL;
720 
721 /*
722  * _pthread_setcleanupinit: sets the cleanup hook.
723  */
724 int
725 _pthread_setcleanupinit(void (*func)(void))
726 {
727 	cleanuphndlr = func;
728 	return (0);
729 }
730 
731 void
732 _thrp_exit()
733 {
734 	ulwp_t *self = curthread;
735 	uberdata_t *udp = self->ul_uberdata;
736 	ulwp_t *replace = NULL;
737 
738 	if (__td_event_report(self, TD_DEATH, udp)) {
739 		self->ul_td_evbuf.eventnum = TD_DEATH;
740 		tdb_event(TD_DEATH, udp);
741 	}
742 
743 	ASSERT(self->ul_sigdefer != 0);
744 
745 	lmutex_lock(&udp->link_lock);
746 	udp->nthreads--;
747 	if (self->ul_usropts & THR_NEW_LWP)
748 		thr_concurrency--;
749 	if (self->ul_usropts & THR_DAEMON)
750 		udp->ndaemons--;
751 	else if (udp->nthreads == udp->ndaemons) {
752 		/*
753 		 * We are the last non-daemon thread exiting.
754 		 * Exit the process.  We retain our TSD and TLS so
755 		 * that atexit() application functions can use them.
756 		 */
757 		lmutex_unlock(&udp->link_lock);
758 		exit(0);
759 		thr_panic("_thrp_exit(): exit(0) returned");
760 	}
761 	lmutex_unlock(&udp->link_lock);
762 
763 	tsd_exit();		/* deallocate thread-specific data */
764 	tls_exit();		/* deallocate thread-local storage */
765 	heldlock_exit();	/* deal with left-over held locks */
766 
767 	/* block all signals to finish exiting */
768 	block_all_signals(self);
769 	/* also prevent ourself from being suspended */
770 	enter_critical(self);
771 	rwl_free(self);
772 	lmutex_lock(&udp->link_lock);
773 	ulwp_free(self);
774 	(void) ulwp_lock(self, udp);
775 
776 	if (self->ul_mapsiz && !self->ul_detached) {
777 		/*
778 		 * We want to free the stack for reuse but must keep
779 		 * the ulwp_t struct for the benefit of thr_join().
780 		 * For this purpose we allocate a replacement ulwp_t.
781 		 */
782 		if ((replace = udp->ulwp_replace_free) == NULL)
783 			replace = lmalloc(REPLACEMENT_SIZE);
784 		else if ((udp->ulwp_replace_free = replace->ul_next) == NULL)
785 			udp->ulwp_replace_last = NULL;
786 	}
787 
788 	if (udp->all_lwps == self)
789 		udp->all_lwps = self->ul_forw;
790 	if (udp->all_lwps == self)
791 		udp->all_lwps = NULL;
792 	else {
793 		self->ul_forw->ul_back = self->ul_back;
794 		self->ul_back->ul_forw = self->ul_forw;
795 	}
796 	self->ul_forw = self->ul_back = NULL;
797 #if defined(THREAD_DEBUG)
798 	/* collect queue lock statistics before marking ourself dead */
799 	record_spin_locks(self);
800 #endif
801 	self->ul_dead = 1;
802 	self->ul_pleasestop = 0;
803 	if (replace != NULL) {
804 		int ix = self->ul_ix;		/* the hash index */
805 		(void) _private_memcpy(replace, self, REPLACEMENT_SIZE);
806 		replace->ul_self = replace;
807 		replace->ul_next = NULL;	/* clone not on stack list */
808 		replace->ul_mapsiz = 0;		/* allows clone to be freed */
809 		replace->ul_replace = 1;	/* requires clone to be freed */
810 		hash_out_unlocked(self, ix, udp);
811 		hash_in_unlocked(replace, ix, udp);
812 		ASSERT(!(self->ul_detached));
813 		self->ul_detached = 1;		/* this frees the stack */
814 		self->ul_schedctl = NULL;
815 		self->ul_schedctl_called = &udp->uberflags;
816 		set_curthread(self = replace);
817 		/*
818 		 * Having just changed the address of curthread, we
819 		 * must reset the ownership of the locks we hold so
820 		 * that assertions will not fire when we release them.
821 		 */
822 		udp->link_lock.mutex_owner = (uintptr_t)self;
823 		ulwp_mutex(self, udp)->mutex_owner = (uintptr_t)self;
824 		/*
825 		 * NOTE:
826 		 * On i386, %gs still references the original, not the
827 		 * replacement, ulwp structure.  Fetching the replacement
828 		 * curthread pointer via %gs:0 works correctly since the
829 		 * original ulwp structure will not be reallocated until
830 		 * this lwp has completed its lwp_exit() system call (see
831 		 * dead_and_buried()), but from here on out, we must make
832 		 * no references to %gs:<offset> other than %gs:0.
833 		 */
834 	}
835 	/*
836 	 * Put non-detached terminated threads in the all_zombies list.
837 	 */
838 	if (!self->ul_detached) {
839 		udp->nzombies++;
840 		if (udp->all_zombies == NULL) {
841 			ASSERT(udp->nzombies == 1);
842 			udp->all_zombies = self->ul_forw = self->ul_back = self;
843 		} else {
844 			self->ul_forw = udp->all_zombies;
845 			self->ul_back = udp->all_zombies->ul_back;
846 			self->ul_back->ul_forw = self;
847 			self->ul_forw->ul_back = self;
848 		}
849 	}
850 	/*
851 	 * Notify everyone waiting for this thread.
852 	 */
853 	ulwp_broadcast(self);
854 	(void) ulwp_unlock(self, udp);
855 	/*
856 	 * Prevent any more references to the schedctl data.
857 	 * We are exiting and continue_fork() may not find us.
858 	 * Do this just before dropping link_lock, since fork
859 	 * serializes on link_lock.
860 	 */
861 	self->ul_schedctl = NULL;
862 	self->ul_schedctl_called = &udp->uberflags;
863 	lmutex_unlock(&udp->link_lock);
864 
865 	ASSERT(self->ul_critical == 1);
866 	ASSERT(self->ul_preempt == 0);
867 	_lwp_terminate();	/* never returns */
868 	thr_panic("_thrp_exit(): _lwp_terminate() returned");
869 }
870 
871 #if defined(THREAD_DEBUG)
872 void
873 collect_queue_statistics()
874 {
875 	uberdata_t *udp = curthread->ul_uberdata;
876 	ulwp_t *ulwp;
877 
878 	if (thread_queue_dump) {
879 		lmutex_lock(&udp->link_lock);
880 		if ((ulwp = udp->all_lwps) != NULL) {
881 			do {
882 				record_spin_locks(ulwp);
883 			} while ((ulwp = ulwp->ul_forw) != udp->all_lwps);
884 		}
885 		lmutex_unlock(&udp->link_lock);
886 	}
887 }
888 #endif
889 
890 void
891 _thr_exit_common(void *status, int unwind)
892 {
893 	ulwp_t *self = curthread;
894 	int cancelled = (self->ul_cancel_pending && status == PTHREAD_CANCELED);
895 
896 	ASSERT(self->ul_critical == 0 && self->ul_preempt == 0);
897 
898 	/*
899 	 * Disable cancellation and call the special DCE cancellation
900 	 * cleanup hook if it is enabled.  Do nothing else before calling
901 	 * the DCE cancellation cleanup hook; it may call longjmp() and
902 	 * never return here.
903 	 */
904 	self->ul_cancel_disabled = 1;
905 	self->ul_cancel_async = 0;
906 	self->ul_save_async = 0;
907 	self->ul_cancelable = 0;
908 	self->ul_cancel_pending = 0;
909 	set_cancel_pending_flag(self, 1);
910 	if (cancelled && cleanuphndlr != NULL)
911 		(*cleanuphndlr)();
912 
913 	/*
914 	 * Block application signals while we are exiting.
915 	 * We call out to C++, TSD, and TLS destructors while exiting
916 	 * and these are application-defined, so we cannot be assured
917 	 * that they won't reset the signal mask.  We use sigoff() to
918 	 * defer any signals that may be received as a result of this
919 	 * bad behavior.  Such signals will be lost to the process
920 	 * when the thread finishes exiting.
921 	 */
922 	(void) _thr_sigsetmask(SIG_SETMASK, &maskset, NULL);
923 	sigoff(self);
924 
925 	self->ul_rval = status;
926 
927 	/*
928 	 * If thr_exit is being called from the places where
929 	 * C++ destructors are to be called such as cancellation
930 	 * points, then set this flag. It is checked in _t_cancel()
931 	 * to decide whether _ex_unwind() is to be called or not.
932 	 */
933 	if (unwind)
934 		self->ul_unwind = 1;
935 
936 	/*
937 	 * _thrp_unwind() will eventually call _thrp_exit().
938 	 * It never returns.
939 	 */
940 	_thrp_unwind(NULL);
941 	thr_panic("_thr_exit_common(): _thrp_unwind() returned");
942 }
943 
944 /*
945  * Called when a thread returns from its start function.
946  * We are at the top of the stack; no unwinding is necessary.
947  */
948 void
949 _thr_terminate(void *status)
950 {
951 	_thr_exit_common(status, 0);
952 }
953 
954 #pragma weak thr_exit = _thr_exit
955 #pragma weak pthread_exit = _thr_exit
956 #pragma weak _pthread_exit = _thr_exit
957 void
958 _thr_exit(void *status)
959 {
960 	_thr_exit_common(status, 1);
961 }
962 
963 int
964 _thrp_join(thread_t tid, thread_t *departed, void **status, int do_cancel)
965 {
966 	uberdata_t *udp = curthread->ul_uberdata;
967 	mutex_t *mp;
968 	void *rval;
969 	thread_t found;
970 	ulwp_t *ulwp;
971 	ulwp_t **ulwpp;
972 	int replace;
973 	int error;
974 
975 	if (do_cancel)
976 		error = lwp_wait(tid, &found);
977 	else {
978 		while ((error = __lwp_wait(tid, &found)) == EINTR)
979 			;
980 	}
981 	if (error)
982 		return (error);
983 
984 	/*
985 	 * We must hold link_lock to avoid a race condition with find_stack().
986 	 */
987 	lmutex_lock(&udp->link_lock);
988 	if ((ulwpp = find_lwpp(found)) == NULL) {
989 		/*
990 		 * lwp_wait() found an lwp that the library doesn't know
991 		 * about.  It must have been created with _lwp_create().
992 		 * Just return its lwpid; we can't know its status.
993 		 */
994 		lmutex_unlock(&udp->link_lock);
995 		rval = NULL;
996 	} else {
997 		/*
998 		 * Remove ulwp from the hash table.
999 		 */
1000 		ulwp = *ulwpp;
1001 		*ulwpp = ulwp->ul_hash;
1002 		ulwp->ul_hash = NULL;
1003 		/*
1004 		 * Remove ulwp from all_zombies list.
1005 		 */
1006 		ASSERT(udp->nzombies >= 1);
1007 		if (udp->all_zombies == ulwp)
1008 			udp->all_zombies = ulwp->ul_forw;
1009 		if (udp->all_zombies == ulwp)
1010 			udp->all_zombies = NULL;
1011 		else {
1012 			ulwp->ul_forw->ul_back = ulwp->ul_back;
1013 			ulwp->ul_back->ul_forw = ulwp->ul_forw;
1014 		}
1015 		ulwp->ul_forw = ulwp->ul_back = NULL;
1016 		udp->nzombies--;
1017 		ASSERT(ulwp->ul_dead && !ulwp->ul_detached &&
1018 		    !(ulwp->ul_usropts & (THR_DETACHED|THR_DAEMON)));
1019 		/*
1020 		 * We can't call ulwp_unlock(ulwp) after we set
1021 		 * ulwp->ul_ix = -1 so we have to get a pointer to the
1022 		 * ulwp's hash table mutex now in order to unlock it below.
1023 		 */
1024 		mp = ulwp_mutex(ulwp, udp);
1025 		ulwp->ul_lwpid = (lwpid_t)(-1);
1026 		ulwp->ul_ix = -1;
1027 		rval = ulwp->ul_rval;
1028 		replace = ulwp->ul_replace;
1029 		lmutex_unlock(mp);
1030 		if (replace) {
1031 			ulwp->ul_next = NULL;
1032 			if (udp->ulwp_replace_free == NULL)
1033 				udp->ulwp_replace_free =
1034 				    udp->ulwp_replace_last = ulwp;
1035 			else {
1036 				udp->ulwp_replace_last->ul_next = ulwp;
1037 				udp->ulwp_replace_last = ulwp;
1038 			}
1039 		}
1040 		lmutex_unlock(&udp->link_lock);
1041 	}
1042 
1043 	if (departed != NULL)
1044 		*departed = found;
1045 	if (status != NULL)
1046 		*status = rval;
1047 	return (0);
1048 }
1049 
1050 #pragma weak thr_join = _thr_join
1051 int
1052 _thr_join(thread_t tid, thread_t *departed, void **status)
1053 {
1054 	int error = _thrp_join(tid, departed, status, 1);
1055 	return ((error == EINVAL)? ESRCH : error);
1056 }
1057 
1058 /*
1059  * pthread_join() differs from Solaris thr_join():
1060  * It does not return the departed thread's id
1061  * and hence does not have a "departed" argument.
1062  * It returns EINVAL if tid refers to a detached thread.
1063  */
1064 #pragma weak pthread_join = _pthread_join
1065 int
1066 _pthread_join(pthread_t tid, void **status)
1067 {
1068 	return ((tid == 0)? ESRCH : _thrp_join(tid, NULL, status, 1));
1069 }
1070 
1071 #pragma weak pthread_detach = _thr_detach
1072 #pragma weak _pthread_detach = _thr_detach
1073 int
1074 _thr_detach(thread_t tid)
1075 {
1076 	uberdata_t *udp = curthread->ul_uberdata;
1077 	ulwp_t *ulwp;
1078 	ulwp_t **ulwpp;
1079 	int error = 0;
1080 
1081 	if ((ulwpp = find_lwpp(tid)) == NULL)
1082 		return (ESRCH);
1083 	ulwp = *ulwpp;
1084 
1085 	if (ulwp->ul_dead) {
1086 		ulwp_unlock(ulwp, udp);
1087 		error = _thrp_join(tid, NULL, NULL, 0);
1088 	} else {
1089 		error = __lwp_detach(tid);
1090 		ulwp->ul_detached = 1;
1091 		ulwp->ul_usropts |= THR_DETACHED;
1092 		ulwp_unlock(ulwp, udp);
1093 	}
1094 	return (error);
1095 }
1096 
1097 /*
1098  * Static local string compare function to avoid calling strncmp()
1099  * (and hence the dynamic linker) during library initialization.
1100  */
1101 static int
1102 sncmp(const char *s1, const char *s2, size_t n)
1103 {
1104 	n++;
1105 	while (--n != 0 && *s1 == *s2++)
1106 		if (*s1++ == '\0')
1107 			return (0);
1108 	return (n == 0 ? 0 : *(uchar_t *)s1 - *(uchar_t *)--s2);
1109 }
1110 
1111 static const char *
1112 ematch(const char *ev, const char *match)
1113 {
1114 	int c;
1115 
1116 	while ((c = *match++) != '\0') {
1117 		if (*ev++ != c)
1118 			return (NULL);
1119 	}
1120 	if (*ev++ != '=')
1121 		return (NULL);
1122 	return (ev);
1123 }
1124 
1125 static int
1126 envvar(const char *ev, const char *match, int limit)
1127 {
1128 	int val = -1;
1129 	const char *ename;
1130 
1131 	if ((ename = ematch(ev, match)) != NULL) {
1132 		int c;
1133 		for (val = 0; (c = *ename) != '\0'; ename++) {
1134 			if (!isdigit(c)) {
1135 				val = -1;
1136 				break;
1137 			}
1138 			val = val * 10 + (c - '0');
1139 			if (val > limit) {
1140 				val = limit;
1141 				break;
1142 			}
1143 		}
1144 	}
1145 	return (val);
1146 }
1147 
1148 static void
1149 etest(const char *ev)
1150 {
1151 	int value;
1152 
1153 	if ((value = envvar(ev, "QUEUE_SPIN", 1000000)) >= 0)
1154 		thread_queue_spin = value;
1155 	if ((value = envvar(ev, "ADAPTIVE_SPIN", 1000000)) >= 0)
1156 		thread_adaptive_spin = value;
1157 	if ((value = envvar(ev, "MAX_SPINNERS", 255)) >= 0)
1158 		thread_max_spinners = value;
1159 	if ((value = envvar(ev, "QUEUE_FIFO", 8)) >= 0)
1160 		thread_queue_fifo = value;
1161 #if defined(THREAD_DEBUG)
1162 	if ((value = envvar(ev, "QUEUE_VERIFY", 1)) >= 0)
1163 		thread_queue_verify = value;
1164 	if ((value = envvar(ev, "QUEUE_DUMP", 1)) >= 0)
1165 		thread_queue_dump = value;
1166 #endif
1167 	if ((value = envvar(ev, "STACK_CACHE", 10000)) >= 0)
1168 		thread_stack_cache = value;
1169 	if ((value = envvar(ev, "COND_WAIT_DEFER", 1)) >= 0)
1170 		thread_cond_wait_defer = value;
1171 	if ((value = envvar(ev, "ERROR_DETECTION", 2)) >= 0)
1172 		thread_error_detection = value;
1173 	if ((value = envvar(ev, "ASYNC_SAFE", 1)) >= 0)
1174 		thread_async_safe = value;
1175 	if ((value = envvar(ev, "DOOR_NORESERVE", 1)) >= 0)
1176 		thread_door_noreserve = value;
1177 }
1178 
1179 /*
1180  * Look for and evaluate environment variables of the form "_THREAD_*".
1181  * For compatibility with the past, we also look for environment
1182  * names of the form "LIBTHREAD_*".
1183  */
1184 static void
1185 set_thread_vars()
1186 {
1187 	extern const char **_environ;
1188 	const char **pev;
1189 	const char *ev;
1190 	char c;
1191 
1192 	if ((pev = _environ) == NULL)
1193 		return;
1194 	while ((ev = *pev++) != NULL) {
1195 		c = *ev;
1196 		if (c == '_' && sncmp(ev, "_THREAD_", 8) == 0)
1197 			etest(ev + 8);
1198 		if (c == 'L' && sncmp(ev, "LIBTHREAD_", 10) == 0)
1199 			etest(ev + 10);
1200 	}
1201 }
1202 
1203 /* PROBE_SUPPORT begin */
1204 #pragma weak __tnf_probe_notify
1205 extern void __tnf_probe_notify(void);
1206 /* PROBE_SUPPORT end */
1207 
1208 /* same as atexit() but private to the library */
1209 extern int _atexit(void (*)(void));
1210 
1211 /* same as _cleanup() but private to the library */
1212 extern void __cleanup(void);
1213 
1214 extern void atfork_init(void);
1215 
1216 #ifdef __amd64
1217 extern void __proc64id(void);
1218 #endif
1219 
1220 /*
1221  * libc_init() is called by ld.so.1 for library initialization.
1222  * We perform minimal initialization; enough to work with the main thread.
1223  */
1224 void
1225 libc_init(void)
1226 {
1227 	uberdata_t *udp = &__uberdata;
1228 	ulwp_t *oldself = __curthread();
1229 	ucontext_t uc;
1230 	ulwp_t *self;
1231 	struct rlimit rl;
1232 	caddr_t data;
1233 	size_t tls_size;
1234 	int setmask;
1235 
1236 	/*
1237 	 * For the initial stage of initialization, we must be careful
1238 	 * not to call any function that could possibly call _cerror().
1239 	 * For this purpose, we call only the raw system call wrappers.
1240 	 */
1241 
1242 #ifdef __amd64
1243 	/*
1244 	 * Gather information about cache layouts for optimized
1245 	 * AMD and Intel assembler strfoo() and memfoo() functions.
1246 	 */
1247 	__proc64id();
1248 #endif
1249 
1250 	/*
1251 	 * Every libc, regardless of which link map, must register __cleanup().
1252 	 */
1253 	(void) _atexit(__cleanup);
1254 
1255 	/*
1256 	 * We keep our uberdata on one of (a) the first alternate link map
1257 	 * or (b) the primary link map.  We switch to the primary link map
1258 	 * and stay there once we see it.  All intermediate link maps are
1259 	 * subject to being unloaded at any time.
1260 	 */
1261 	if (oldself != NULL && (oldself->ul_primarymap || !primary_link_map)) {
1262 		__tdb_bootstrap = oldself->ul_uberdata->tdb_bootstrap;
1263 		mutex_setup();
1264 		atfork_init();	/* every link map needs atfork() processing */
1265 		return;
1266 	}
1267 
1268 	/*
1269 	 * To establish the main stack information, we have to get our context.
1270 	 * This is also convenient to use for getting our signal mask.
1271 	 */
1272 	uc.uc_flags = UC_ALL;
1273 	(void) __getcontext_syscall(&uc);
1274 	ASSERT(uc.uc_link == NULL);
1275 
1276 	tls_size = roundup64(udp->tls_metadata.static_tls.tls_size);
1277 	ASSERT(primary_link_map || tls_size == 0);
1278 	data = lmalloc(sizeof (ulwp_t) + tls_size);
1279 	if (data == NULL)
1280 		thr_panic("cannot allocate thread structure for main thread");
1281 	/* LINTED pointer cast may result in improper alignment */
1282 	self = (ulwp_t *)(data + tls_size);
1283 	init_hash_table[0].hash_bucket = self;
1284 
1285 	self->ul_sigmask = uc.uc_sigmask;
1286 	delete_reserved_signals(&self->ul_sigmask);
1287 	/*
1288 	 * Are the old and new sets different?
1289 	 * (This can happen if we are currently blocking SIGCANCEL.)
1290 	 * If so, we must explicitly set our signal mask, below.
1291 	 */
1292 	setmask =
1293 	    ((self->ul_sigmask.__sigbits[0] ^ uc.uc_sigmask.__sigbits[0]) |
1294 	    (self->ul_sigmask.__sigbits[1] ^ uc.uc_sigmask.__sigbits[1]));
1295 
1296 #ifdef __sparc
1297 	/*
1298 	 * We cache several instructions in the thread structure for use
1299 	 * by the fasttrap DTrace provider. When changing this, read the
1300 	 * comment in fasttrap.h for the all the other places that must
1301 	 * be changed.
1302 	 */
1303 	self->ul_dsave = 0x9de04000;	/* save %g1, %g0, %sp */
1304 	self->ul_drestore = 0x81e80000;	/* restore %g0, %g0, %g0 */
1305 	self->ul_dftret = 0x91d0203a;	/* ta 0x3a */
1306 	self->ul_dreturn = 0x81ca0000;	/* return %o0 */
1307 #endif
1308 
1309 	self->ul_stktop = (uintptr_t)uc.uc_stack.ss_sp + uc.uc_stack.ss_size;
1310 	(void) _private_getrlimit(RLIMIT_STACK, &rl);
1311 	self->ul_stksiz = rl.rlim_cur;
1312 	self->ul_stk = (caddr_t)(self->ul_stktop - self->ul_stksiz);
1313 
1314 	self->ul_forw = self->ul_back = self;
1315 	self->ul_hash = NULL;
1316 	self->ul_ix = 0;
1317 	self->ul_lwpid = 1; /* __lwp_self() */
1318 	self->ul_main = 1;
1319 	self->ul_self = self;
1320 	self->ul_policy = -1;		/* initialize only when needed */
1321 	self->ul_pri = 0;
1322 	self->ul_cid = 0;
1323 	self->ul_rtclassid = -1;
1324 	self->ul_uberdata = udp;
1325 	if (oldself != NULL) {
1326 		int i;
1327 
1328 		ASSERT(primary_link_map);
1329 		ASSERT(oldself->ul_main == 1);
1330 		self->ul_stsd = oldself->ul_stsd;
1331 		for (i = 0; i < TSD_NFAST; i++)
1332 			self->ul_ftsd[i] = oldself->ul_ftsd[i];
1333 		self->ul_tls = oldself->ul_tls;
1334 		/*
1335 		 * Retrieve all pointers to uberdata allocated
1336 		 * while running on previous link maps.
1337 		 * We would like to do a structure assignment here, but
1338 		 * gcc turns structure assignments into calls to memcpy(),
1339 		 * a function exported from libc.  We can't call any such
1340 		 * external functions until we establish curthread, below,
1341 		 * so we just call our private version of memcpy().
1342 		 */
1343 		(void) _private_memcpy(udp,
1344 		    oldself->ul_uberdata, sizeof (*udp));
1345 		/*
1346 		 * These items point to global data on the primary link map.
1347 		 */
1348 		udp->thr_hash_table = init_hash_table;
1349 		udp->sigacthandler = sigacthandler;
1350 		udp->tdb.tdb_events = tdb_events;
1351 		ASSERT(udp->nthreads == 1 && !udp->uberflags.uf_mt);
1352 		ASSERT(udp->lwp_stacks == NULL);
1353 		ASSERT(udp->ulwp_freelist == NULL);
1354 		ASSERT(udp->ulwp_replace_free == NULL);
1355 		ASSERT(udp->hash_size == 1);
1356 	}
1357 	udp->all_lwps = self;
1358 	udp->ulwp_one = self;
1359 	udp->pid = _private_getpid();
1360 	udp->nthreads = 1;
1361 	/*
1362 	 * In every link map, tdb_bootstrap points to the same piece of
1363 	 * allocated memory.  When the primary link map is initialized,
1364 	 * the allocated memory is assigned a pointer to the one true
1365 	 * uberdata.  This allows libc_db to initialize itself regardless
1366 	 * of which instance of libc it finds in the address space.
1367 	 */
1368 	if (udp->tdb_bootstrap == NULL)
1369 		udp->tdb_bootstrap = lmalloc(sizeof (uberdata_t *));
1370 	__tdb_bootstrap = udp->tdb_bootstrap;
1371 	if (primary_link_map) {
1372 		self->ul_primarymap = 1;
1373 		udp->primary_map = 1;
1374 		*udp->tdb_bootstrap = udp;
1375 	}
1376 	/*
1377 	 * Cancellation can't happen until:
1378 	 *	pthread_cancel() is called
1379 	 * or:
1380 	 *	another thread is created
1381 	 * For now, as a single-threaded process, set the flag that tells
1382 	 * PROLOGUE/EPILOGUE (in scalls.c) that cancellation can't happen.
1383 	 */
1384 	self->ul_nocancel = 1;
1385 
1386 #if defined(__amd64)
1387 	(void) ___lwp_private(_LWP_SETPRIVATE, _LWP_FSBASE, self);
1388 #elif defined(__i386)
1389 	(void) ___lwp_private(_LWP_SETPRIVATE, _LWP_GSBASE, self);
1390 #endif	/* __i386 || __amd64 */
1391 	set_curthread(self);		/* redundant on i386 */
1392 	/*
1393 	 * Now curthread is established and it is safe to call any
1394 	 * function in libc except one that uses thread-local storage.
1395 	 */
1396 	self->ul_errnop = &errno;
1397 	if (oldself != NULL) {
1398 		/* tls_size was zero when oldself was allocated */
1399 		lfree(oldself, sizeof (ulwp_t));
1400 	}
1401 	mutex_setup();
1402 	atfork_init();
1403 	signal_init();
1404 
1405 	/*
1406 	 * If the stack is unlimited, we set the size to zero to disable
1407 	 * stack checking.
1408 	 * XXX: Work harder here.  Get the stack size from /proc/self/rmap
1409 	 */
1410 	if (self->ul_stksiz == RLIM_INFINITY) {
1411 		self->ul_ustack.ss_sp = (void *)self->ul_stktop;
1412 		self->ul_ustack.ss_size = 0;
1413 	} else {
1414 		self->ul_ustack.ss_sp = self->ul_stk;
1415 		self->ul_ustack.ss_size = self->ul_stksiz;
1416 	}
1417 	self->ul_ustack.ss_flags = 0;
1418 	(void) _private_setustack(&self->ul_ustack);
1419 
1420 	/*
1421 	 * Get the variables that affect thread behavior from the environment.
1422 	 */
1423 	set_thread_vars();
1424 	udp->uberflags.uf_thread_error_detection = (char)thread_error_detection;
1425 	udp->thread_stack_cache = thread_stack_cache;
1426 
1427 	/*
1428 	 * Make per-thread copies of global variables, for speed.
1429 	 */
1430 	self->ul_queue_fifo = (char)thread_queue_fifo;
1431 	self->ul_cond_wait_defer = (char)thread_cond_wait_defer;
1432 	self->ul_error_detection = (char)thread_error_detection;
1433 	self->ul_async_safe = (char)thread_async_safe;
1434 	self->ul_door_noreserve = (char)thread_door_noreserve;
1435 	self->ul_max_spinners = (uint8_t)thread_max_spinners;
1436 	self->ul_adaptive_spin = thread_adaptive_spin;
1437 	self->ul_queue_spin = thread_queue_spin;
1438 
1439 	/*
1440 	 * When we have initialized the primary link map, inform
1441 	 * the dynamic linker about our interface functions.
1442 	 */
1443 	if (self->ul_primarymap)
1444 		_ld_libc((void *)rtld_funcs);
1445 
1446 	/*
1447 	 * Defer signals until TLS constructors have been called.
1448 	 */
1449 	sigoff(self);
1450 	tls_setup();
1451 	sigon(self);
1452 	if (setmask)
1453 		(void) restore_signals(self);
1454 
1455 	/*
1456 	 * Make private copies of __xpg4 and __xpg6 so libc can test
1457 	 * them after this point without invoking the dynamic linker.
1458 	 */
1459 	libc__xpg4 = __xpg4;
1460 	libc__xpg6 = __xpg6;
1461 
1462 	/* PROBE_SUPPORT begin */
1463 	if (self->ul_primarymap && __tnf_probe_notify != NULL)
1464 		__tnf_probe_notify();
1465 	/* PROBE_SUPPORT end */
1466 
1467 	init_sigev_thread();
1468 	init_aio();
1469 
1470 	/*
1471 	 * We need to reset __threaded dynamically at runtime, so that
1472 	 * __threaded can be bound to __threaded outside libc which may not
1473 	 * have initial value of 1 (without a copy relocation in a.out).
1474 	 */
1475 	__threaded = 1;
1476 }
1477 
1478 #pragma fini(libc_fini)
1479 void
1480 libc_fini()
1481 {
1482 	/*
1483 	 * If we are doing fini processing for the instance of libc
1484 	 * on the first alternate link map (this happens only when
1485 	 * the dynamic linker rejects a bad audit library), then clear
1486 	 * __curthread().  We abandon whatever memory was allocated by
1487 	 * lmalloc() while running on this alternate link-map but we
1488 	 * don't care (and can't find the memory in any case); we just
1489 	 * want to protect the application from this bad audit library.
1490 	 * No fini processing is done by libc in the normal case.
1491 	 */
1492 
1493 	uberdata_t *udp = curthread->ul_uberdata;
1494 
1495 	if (udp->primary_map == 0 && udp == &__uberdata)
1496 		set_curthread(NULL);
1497 }
1498 
1499 /*
1500  * finish_init is called when we are about to become multi-threaded,
1501  * that is, on the first call to thr_create().
1502  */
1503 void
1504 finish_init()
1505 {
1506 	ulwp_t *self = curthread;
1507 	uberdata_t *udp = self->ul_uberdata;
1508 	thr_hash_table_t *htp;
1509 	void *data;
1510 	int i;
1511 
1512 	/*
1513 	 * No locks needed here; we are single-threaded on the first call.
1514 	 * We can be called only after the primary link map has been set up.
1515 	 */
1516 	ASSERT(self->ul_primarymap);
1517 	ASSERT(self == udp->ulwp_one);
1518 	ASSERT(!udp->uberflags.uf_mt);
1519 	ASSERT(udp->hash_size == 1);
1520 
1521 	/*
1522 	 * Initialize self->ul_policy, self->ul_cid, and self->ul_pri.
1523 	 */
1524 	update_sched(self);
1525 
1526 	/*
1527 	 * Allocate the queue_head array if not already allocated.
1528 	 */
1529 	if (udp->queue_head == NULL)
1530 		queue_alloc();
1531 
1532 	/*
1533 	 * Now allocate the thread hash table.
1534 	 */
1535 	if ((data = _private_mmap(NULL, HASHTBLSZ * sizeof (thr_hash_table_t),
1536 	    PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, (off_t)0))
1537 	    == MAP_FAILED)
1538 		thr_panic("cannot allocate thread hash table");
1539 
1540 	udp->thr_hash_table = htp = (thr_hash_table_t *)data;
1541 	udp->hash_size = HASHTBLSZ;
1542 	udp->hash_mask = HASHTBLSZ - 1;
1543 
1544 	for (i = 0; i < HASHTBLSZ; i++, htp++) {
1545 		htp->hash_lock.mutex_flag = LOCK_INITED;
1546 		htp->hash_lock.mutex_magic = MUTEX_MAGIC;
1547 		htp->hash_cond.cond_magic = COND_MAGIC;
1548 	}
1549 	hash_in_unlocked(self, TIDHASH(self->ul_lwpid, udp), udp);
1550 
1551 	/*
1552 	 * Set up the SIGCANCEL handler for threads cancellation.
1553 	 */
1554 	setup_cancelsig(SIGCANCEL);
1555 
1556 	/*
1557 	 * Arrange to do special things on exit --
1558 	 * - collect queue statistics from all remaining active threads.
1559 	 * - dump queue statistics to stderr if _THREAD_QUEUE_DUMP is set.
1560 	 * - grab assert_lock to ensure that assertion failures
1561 	 *   and a core dump take precedence over _exit().
1562 	 * (Functions are called in the reverse order of their registration.)
1563 	 */
1564 	(void) _atexit(grab_assert_lock);
1565 #if defined(THREAD_DEBUG)
1566 	(void) _atexit(dump_queue_statistics);
1567 	(void) _atexit(collect_queue_statistics);
1568 #endif
1569 }
1570 
1571 /*
1572  * Used only by postfork1_child(), below.
1573  */
1574 static void
1575 mark_dead_and_buried(ulwp_t *ulwp)
1576 {
1577 	ulwp->ul_dead = 1;
1578 	ulwp->ul_lwpid = (lwpid_t)(-1);
1579 	ulwp->ul_hash = NULL;
1580 	ulwp->ul_ix = -1;
1581 	ulwp->ul_schedctl = NULL;
1582 	ulwp->ul_schedctl_called = NULL;
1583 }
1584 
1585 /*
1586  * This is called from fork1() in the child.
1587  * Reset our data structures to reflect one lwp.
1588  */
1589 void
1590 postfork1_child()
1591 {
1592 	ulwp_t *self = curthread;
1593 	uberdata_t *udp = self->ul_uberdata;
1594 	queue_head_t *qp;
1595 	ulwp_t *next;
1596 	ulwp_t *ulwp;
1597 	int i;
1598 
1599 	/* daemon threads shouldn't call fork1(), but oh well... */
1600 	self->ul_usropts &= ~THR_DAEMON;
1601 	udp->nthreads = 1;
1602 	udp->ndaemons = 0;
1603 	udp->uberflags.uf_mt = 0;
1604 	__libc_threaded = 0;
1605 	for (i = 0; i < udp->hash_size; i++)
1606 		udp->thr_hash_table[i].hash_bucket = NULL;
1607 	self->ul_lwpid = __lwp_self();
1608 	hash_in_unlocked(self, TIDHASH(self->ul_lwpid, udp), udp);
1609 
1610 	/*
1611 	 * Some thread in the parent might have been suspended while
1612 	 * holding udp->callout_lock.  Reinitialize the child's copy.
1613 	 */
1614 	_private_mutex_init(&udp->callout_lock,
1615 	    USYNC_THREAD | LOCK_RECURSIVE, NULL);
1616 
1617 	/* no one in the child is on a sleep queue; reinitialize */
1618 	if ((qp = udp->queue_head) != NULL) {
1619 		(void) _private_memset(qp, 0,
1620 		    2 * QHASHSIZE * sizeof (queue_head_t));
1621 		for (i = 0; i < 2 * QHASHSIZE; qp++, i++) {
1622 			qp->qh_type = (i < QHASHSIZE)? MX : CV;
1623 			qp->qh_lock.mutex_flag = LOCK_INITED;
1624 			qp->qh_lock.mutex_magic = MUTEX_MAGIC;
1625 			qp->qh_hlist = &qp->qh_def_root;
1626 #if defined(THREAD_DEBUG)
1627 			qp->qh_hlen = 1;
1628 			qp->qh_hmax = 1;
1629 #endif
1630 		}
1631 	}
1632 
1633 	/*
1634 	 * All lwps except ourself are gone.  Mark them so.
1635 	 * First mark all of the lwps that have already been freed.
1636 	 * Then mark and free all of the active lwps except ourself.
1637 	 * Since we are single-threaded, no locks are required here.
1638 	 */
1639 	for (ulwp = udp->lwp_stacks; ulwp != NULL; ulwp = ulwp->ul_next)
1640 		mark_dead_and_buried(ulwp);
1641 	for (ulwp = udp->ulwp_freelist; ulwp != NULL; ulwp = ulwp->ul_next)
1642 		mark_dead_and_buried(ulwp);
1643 	for (ulwp = self->ul_forw; ulwp != self; ulwp = next) {
1644 		next = ulwp->ul_forw;
1645 		ulwp->ul_forw = ulwp->ul_back = NULL;
1646 		mark_dead_and_buried(ulwp);
1647 		tsd_free(ulwp);
1648 		tls_free(ulwp);
1649 		rwl_free(ulwp);
1650 		heldlock_free(ulwp);
1651 		ulwp_free(ulwp);
1652 	}
1653 	self->ul_forw = self->ul_back = udp->all_lwps = self;
1654 	if (self != udp->ulwp_one)
1655 		mark_dead_and_buried(udp->ulwp_one);
1656 	if ((ulwp = udp->all_zombies) != NULL) {
1657 		ASSERT(udp->nzombies != 0);
1658 		do {
1659 			next = ulwp->ul_forw;
1660 			ulwp->ul_forw = ulwp->ul_back = NULL;
1661 			mark_dead_and_buried(ulwp);
1662 			udp->nzombies--;
1663 			if (ulwp->ul_replace) {
1664 				ulwp->ul_next = NULL;
1665 				if (udp->ulwp_replace_free == NULL) {
1666 					udp->ulwp_replace_free =
1667 					    udp->ulwp_replace_last = ulwp;
1668 				} else {
1669 					udp->ulwp_replace_last->ul_next = ulwp;
1670 					udp->ulwp_replace_last = ulwp;
1671 				}
1672 			}
1673 		} while ((ulwp = next) != udp->all_zombies);
1674 		ASSERT(udp->nzombies == 0);
1675 		udp->all_zombies = NULL;
1676 		udp->nzombies = 0;
1677 	}
1678 	trim_stack_cache(0);
1679 
1680 	/*
1681 	 * Do post-fork1 processing for subsystems that need it.
1682 	 */
1683 	postfork1_child_tpool();
1684 	postfork1_child_sigev_aio();
1685 	postfork1_child_sigev_mq();
1686 	postfork1_child_sigev_timer();
1687 	postfork1_child_aio();
1688 }
1689 
1690 lwpid_t
1691 lwp_self(void)
1692 {
1693 	return (curthread->ul_lwpid);
1694 }
1695 
1696 #pragma weak _ti_thr_self = _thr_self
1697 #pragma weak thr_self = _thr_self
1698 #pragma weak pthread_self = _thr_self
1699 #pragma weak _pthread_self = _thr_self
1700 thread_t
1701 _thr_self()
1702 {
1703 	return (curthread->ul_lwpid);
1704 }
1705 
1706 #pragma weak thr_main = _thr_main
1707 int
1708 _thr_main()
1709 {
1710 	ulwp_t *self = __curthread();
1711 
1712 	return ((self == NULL)? -1 : self->ul_main);
1713 }
1714 
1715 int
1716 _thrp_cancelled(void)
1717 {
1718 	return (curthread->ul_rval == PTHREAD_CANCELED);
1719 }
1720 
1721 int
1722 _thrp_stksegment(ulwp_t *ulwp, stack_t *stk)
1723 {
1724 	stk->ss_sp = (void *)ulwp->ul_stktop;
1725 	stk->ss_size = ulwp->ul_stksiz;
1726 	stk->ss_flags = 0;
1727 	return (0);
1728 }
1729 
1730 #pragma weak thr_stksegment = _thr_stksegment
1731 int
1732 _thr_stksegment(stack_t *stk)
1733 {
1734 	return (_thrp_stksegment(curthread, stk));
1735 }
1736 
1737 void
1738 force_continue(ulwp_t *ulwp)
1739 {
1740 #if defined(THREAD_DEBUG)
1741 	ulwp_t *self = curthread;
1742 	uberdata_t *udp = self->ul_uberdata;
1743 #endif
1744 	int error;
1745 	timespec_t ts;
1746 
1747 	ASSERT(MUTEX_OWNED(&udp->fork_lock, self));
1748 	ASSERT(MUTEX_OWNED(ulwp_mutex(ulwp, udp), self));
1749 
1750 	for (;;) {
1751 		error = __lwp_continue(ulwp->ul_lwpid);
1752 		if (error != 0 && error != EINTR)
1753 			break;
1754 		error = 0;
1755 		if (ulwp->ul_stopping) {	/* he is stopping himself */
1756 			ts.tv_sec = 0;		/* give him a chance to run */
1757 			ts.tv_nsec = 100000;	/* 100 usecs or clock tick */
1758 			(void) __nanosleep(&ts, NULL);
1759 		}
1760 		if (!ulwp->ul_stopping)		/* he is running now */
1761 			break;			/* so we are done */
1762 		/*
1763 		 * He is marked as being in the process of stopping
1764 		 * himself.  Loop around and continue him again.
1765 		 * He may not have been stopped the first time.
1766 		 */
1767 	}
1768 }
1769 
1770 /*
1771  * Suspend an lwp with lwp_suspend(), then move it to a safe
1772  * point, that is, to a point where ul_critical is zero.
1773  * On return, the ulwp_lock() is dropped as with ulwp_unlock().
1774  * If 'link_dropped' is non-NULL, then 'link_lock' is held on entry.
1775  * If we have to drop link_lock, we store 1 through link_dropped.
1776  * If the lwp exits before it can be suspended, we return ESRCH.
1777  */
1778 int
1779 safe_suspend(ulwp_t *ulwp, uchar_t whystopped, int *link_dropped)
1780 {
1781 	ulwp_t *self = curthread;
1782 	uberdata_t *udp = self->ul_uberdata;
1783 	cond_t *cvp = ulwp_condvar(ulwp, udp);
1784 	mutex_t *mp = ulwp_mutex(ulwp, udp);
1785 	thread_t tid = ulwp->ul_lwpid;
1786 	int ix = ulwp->ul_ix;
1787 	int error = 0;
1788 
1789 	ASSERT(whystopped == TSTP_REGULAR ||
1790 	    whystopped == TSTP_MUTATOR ||
1791 	    whystopped == TSTP_FORK);
1792 	ASSERT(ulwp != self);
1793 	ASSERT(!ulwp->ul_stop);
1794 	ASSERT(MUTEX_OWNED(&udp->fork_lock, self));
1795 	ASSERT(MUTEX_OWNED(mp, self));
1796 
1797 	if (link_dropped != NULL)
1798 		*link_dropped = 0;
1799 
1800 	/*
1801 	 * We must grab the target's spin lock before suspending it.
1802 	 * See the comments below and in _thrp_suspend() for why.
1803 	 */
1804 	spin_lock_set(&ulwp->ul_spinlock);
1805 	(void) ___lwp_suspend(tid);
1806 	spin_lock_clear(&ulwp->ul_spinlock);
1807 
1808 top:
1809 	if (ulwp->ul_critical == 0 || ulwp->ul_stopping) {
1810 		/* thread is already safe */
1811 		ulwp->ul_stop |= whystopped;
1812 	} else {
1813 		/*
1814 		 * Setting ul_pleasestop causes the target thread to stop
1815 		 * itself in _thrp_suspend(), below, after we drop its lock.
1816 		 * We must continue the critical thread before dropping
1817 		 * link_lock because the critical thread may be holding
1818 		 * the queue lock for link_lock.  This is delicate.
1819 		 */
1820 		ulwp->ul_pleasestop |= whystopped;
1821 		force_continue(ulwp);
1822 		if (link_dropped != NULL) {
1823 			*link_dropped = 1;
1824 			lmutex_unlock(&udp->link_lock);
1825 			/* be sure to drop link_lock only once */
1826 			link_dropped = NULL;
1827 		}
1828 
1829 		/*
1830 		 * The thread may disappear by calling thr_exit() so we
1831 		 * cannot rely on the ulwp pointer after dropping the lock.
1832 		 * Instead, we search the hash table to find it again.
1833 		 * When we return, we may find that the thread has been
1834 		 * continued by some other thread.  The suspend/continue
1835 		 * interfaces are prone to such race conditions by design.
1836 		 */
1837 		while (ulwp && !ulwp->ul_dead && !ulwp->ul_stop &&
1838 		    (ulwp->ul_pleasestop & whystopped)) {
1839 			(void) __cond_wait(cvp, mp);
1840 			for (ulwp = udp->thr_hash_table[ix].hash_bucket;
1841 			    ulwp != NULL; ulwp = ulwp->ul_hash) {
1842 				if (ulwp->ul_lwpid == tid)
1843 					break;
1844 			}
1845 		}
1846 
1847 		if (ulwp == NULL || ulwp->ul_dead)
1848 			error = ESRCH;
1849 		else {
1850 			/*
1851 			 * Do another lwp_suspend() to make sure we don't
1852 			 * return until the target thread is fully stopped
1853 			 * in the kernel.  Don't apply lwp_suspend() until
1854 			 * we know that the target is not holding any
1855 			 * queue locks, that is, that it has completed
1856 			 * ulwp_unlock(self) and has, or at least is
1857 			 * about to, call lwp_suspend() on itself.  We do
1858 			 * this by grabbing the target's spin lock.
1859 			 */
1860 			ASSERT(ulwp->ul_lwpid == tid);
1861 			spin_lock_set(&ulwp->ul_spinlock);
1862 			(void) ___lwp_suspend(tid);
1863 			spin_lock_clear(&ulwp->ul_spinlock);
1864 			/*
1865 			 * If some other thread did a thr_continue()
1866 			 * on the target thread we have to start over.
1867 			 */
1868 			if (!ulwp->ul_stopping || !(ulwp->ul_stop & whystopped))
1869 				goto top;
1870 		}
1871 	}
1872 
1873 	(void) cond_broadcast_internal(cvp);
1874 	lmutex_unlock(mp);
1875 	return (error);
1876 }
1877 
1878 int
1879 _thrp_suspend(thread_t tid, uchar_t whystopped)
1880 {
1881 	ulwp_t *self = curthread;
1882 	uberdata_t *udp = self->ul_uberdata;
1883 	ulwp_t *ulwp;
1884 	int error = 0;
1885 
1886 	ASSERT((whystopped & (TSTP_REGULAR|TSTP_MUTATOR|TSTP_FORK)) != 0);
1887 	ASSERT((whystopped & ~(TSTP_REGULAR|TSTP_MUTATOR|TSTP_FORK)) == 0);
1888 
1889 	/*
1890 	 * We can't suspend anyone except ourself while
1891 	 * some other thread is performing a fork.
1892 	 * This also allows only one suspension at a time.
1893 	 */
1894 	if (tid != self->ul_lwpid)
1895 		fork_lock_enter();
1896 
1897 	if ((ulwp = find_lwp(tid)) == NULL)
1898 		error = ESRCH;
1899 	else if (whystopped == TSTP_MUTATOR && !ulwp->ul_mutator) {
1900 		ulwp_unlock(ulwp, udp);
1901 		error = EINVAL;
1902 	} else if (ulwp->ul_stop) {	/* already stopped */
1903 		ulwp->ul_stop |= whystopped;
1904 		ulwp_broadcast(ulwp);
1905 		ulwp_unlock(ulwp, udp);
1906 	} else if (ulwp != self) {
1907 		/*
1908 		 * After suspending the other thread, move it out of a
1909 		 * critical section and deal with the schedctl mappings.
1910 		 * safe_suspend() suspends the other thread, calls
1911 		 * ulwp_broadcast(ulwp) and drops the ulwp lock.
1912 		 */
1913 		error = safe_suspend(ulwp, whystopped, NULL);
1914 	} else {
1915 		int schedctl_after_fork = 0;
1916 
1917 		/*
1918 		 * We are suspending ourself.  We must not take a signal
1919 		 * until we return from lwp_suspend() and clear ul_stopping.
1920 		 * This is to guard against siglongjmp().
1921 		 */
1922 		enter_critical(self);
1923 		self->ul_sp = stkptr();
1924 		_flush_windows();	/* sparc */
1925 		self->ul_pleasestop = 0;
1926 		self->ul_stop |= whystopped;
1927 		/*
1928 		 * Grab our spin lock before dropping ulwp_mutex(self).
1929 		 * This prevents the suspending thread from applying
1930 		 * lwp_suspend() to us before we emerge from
1931 		 * lmutex_unlock(mp) and have dropped mp's queue lock.
1932 		 */
1933 		spin_lock_set(&self->ul_spinlock);
1934 		self->ul_stopping = 1;
1935 		ulwp_broadcast(self);
1936 		ulwp_unlock(self, udp);
1937 		/*
1938 		 * From this point until we return from lwp_suspend(),
1939 		 * we must not call any function that might invoke the
1940 		 * dynamic linker, that is, we can only call functions
1941 		 * private to the library.
1942 		 *
1943 		 * Also, this is a nasty race condition for a process
1944 		 * that is undergoing a forkall() operation:
1945 		 * Once we clear our spinlock (below), we are vulnerable
1946 		 * to being suspended by the forkall() thread before
1947 		 * we manage to suspend ourself in ___lwp_suspend().
1948 		 * See safe_suspend() and force_continue().
1949 		 *
1950 		 * To avoid a SIGSEGV due to the disappearance
1951 		 * of the schedctl mappings in the child process,
1952 		 * which can happen in spin_lock_clear() if we
1953 		 * are suspended while we are in the middle of
1954 		 * its call to preempt(), we preemptively clear
1955 		 * our own schedctl pointer before dropping our
1956 		 * spinlock.  We reinstate it, in both the parent
1957 		 * and (if this really is a forkall()) the child.
1958 		 */
1959 		if (whystopped & TSTP_FORK) {
1960 			schedctl_after_fork = 1;
1961 			self->ul_schedctl = NULL;
1962 			self->ul_schedctl_called = &udp->uberflags;
1963 		}
1964 		spin_lock_clear(&self->ul_spinlock);
1965 		(void) ___lwp_suspend(tid);
1966 		/*
1967 		 * Somebody else continued us.
1968 		 * We can't grab ulwp_lock(self)
1969 		 * until after clearing ul_stopping.
1970 		 * force_continue() relies on this.
1971 		 */
1972 		self->ul_stopping = 0;
1973 		self->ul_sp = 0;
1974 		if (schedctl_after_fork) {
1975 			self->ul_schedctl_called = NULL;
1976 			self->ul_schedctl = NULL;
1977 			(void) setup_schedctl();
1978 		}
1979 		ulwp_lock(self, udp);
1980 		ulwp_broadcast(self);
1981 		ulwp_unlock(self, udp);
1982 		exit_critical(self);
1983 	}
1984 
1985 	if (tid != self->ul_lwpid)
1986 		fork_lock_exit();
1987 
1988 	return (error);
1989 }
1990 
1991 /*
1992  * Suspend all lwps other than ourself in preparation for fork.
1993  */
1994 void
1995 suspend_fork()
1996 {
1997 	ulwp_t *self = curthread;
1998 	uberdata_t *udp = self->ul_uberdata;
1999 	ulwp_t *ulwp;
2000 	int link_dropped;
2001 
2002 	ASSERT(MUTEX_OWNED(&udp->fork_lock, self));
2003 top:
2004 	lmutex_lock(&udp->link_lock);
2005 
2006 	for (ulwp = self->ul_forw; ulwp != self; ulwp = ulwp->ul_forw) {
2007 		ulwp_lock(ulwp, udp);
2008 		if (ulwp->ul_stop) {	/* already stopped */
2009 			ulwp->ul_stop |= TSTP_FORK;
2010 			ulwp_broadcast(ulwp);
2011 			ulwp_unlock(ulwp, udp);
2012 		} else {
2013 			/*
2014 			 * Move the stopped lwp out of a critical section.
2015 			 */
2016 			if (safe_suspend(ulwp, TSTP_FORK, &link_dropped) ||
2017 			    link_dropped)
2018 				goto top;
2019 		}
2020 	}
2021 
2022 	lmutex_unlock(&udp->link_lock);
2023 }
2024 
2025 void
2026 continue_fork(int child)
2027 {
2028 	ulwp_t *self = curthread;
2029 	uberdata_t *udp = self->ul_uberdata;
2030 	ulwp_t *ulwp;
2031 
2032 	ASSERT(MUTEX_OWNED(&udp->fork_lock, self));
2033 
2034 	/*
2035 	 * Clear the schedctl pointers in the child of forkall().
2036 	 */
2037 	if (child) {
2038 		for (ulwp = self->ul_forw; ulwp != self; ulwp = ulwp->ul_forw) {
2039 			ulwp->ul_schedctl_called =
2040 			    ulwp->ul_dead? &udp->uberflags : NULL;
2041 			ulwp->ul_schedctl = NULL;
2042 		}
2043 	}
2044 
2045 	/*
2046 	 * Set all lwps that were stopped for fork() running again.
2047 	 */
2048 	lmutex_lock(&udp->link_lock);
2049 	for (ulwp = self->ul_forw; ulwp != self; ulwp = ulwp->ul_forw) {
2050 		mutex_t *mp = ulwp_mutex(ulwp, udp);
2051 		lmutex_lock(mp);
2052 		ASSERT(ulwp->ul_stop & TSTP_FORK);
2053 		ulwp->ul_stop &= ~TSTP_FORK;
2054 		ulwp_broadcast(ulwp);
2055 		if (!ulwp->ul_stop)
2056 			force_continue(ulwp);
2057 		lmutex_unlock(mp);
2058 	}
2059 	lmutex_unlock(&udp->link_lock);
2060 }
2061 
2062 int
2063 _thrp_continue(thread_t tid, uchar_t whystopped)
2064 {
2065 	uberdata_t *udp = curthread->ul_uberdata;
2066 	ulwp_t *ulwp;
2067 	mutex_t *mp;
2068 	int error = 0;
2069 
2070 	ASSERT(whystopped == TSTP_REGULAR ||
2071 	    whystopped == TSTP_MUTATOR);
2072 
2073 	/*
2074 	 * We single-thread the entire thread suspend/continue mechanism.
2075 	 */
2076 	fork_lock_enter();
2077 
2078 	if ((ulwp = find_lwp(tid)) == NULL) {
2079 		fork_lock_exit();
2080 		return (ESRCH);
2081 	}
2082 
2083 	mp = ulwp_mutex(ulwp, udp);
2084 	if ((whystopped == TSTP_MUTATOR && !ulwp->ul_mutator)) {
2085 		error = EINVAL;
2086 	} else if (ulwp->ul_stop & whystopped) {
2087 		ulwp->ul_stop &= ~whystopped;
2088 		ulwp_broadcast(ulwp);
2089 		if (!ulwp->ul_stop) {
2090 			if (whystopped == TSTP_REGULAR && ulwp->ul_created) {
2091 				ulwp->ul_sp = 0;
2092 				ulwp->ul_created = 0;
2093 			}
2094 			force_continue(ulwp);
2095 		}
2096 	}
2097 	lmutex_unlock(mp);
2098 
2099 	fork_lock_exit();
2100 	return (error);
2101 }
2102 
2103 #pragma weak thr_suspend = _thr_suspend
2104 int
2105 _thr_suspend(thread_t tid)
2106 {
2107 	return (_thrp_suspend(tid, TSTP_REGULAR));
2108 }
2109 
2110 #pragma weak thr_continue = _thr_continue
2111 int
2112 _thr_continue(thread_t tid)
2113 {
2114 	return (_thrp_continue(tid, TSTP_REGULAR));
2115 }
2116 
2117 #pragma weak thr_yield = _thr_yield
2118 void
2119 _thr_yield()
2120 {
2121 	lwp_yield();
2122 }
2123 
2124 #pragma weak thr_kill = _thr_kill
2125 #pragma weak pthread_kill = _thr_kill
2126 #pragma weak _pthread_kill = _thr_kill
2127 int
2128 _thr_kill(thread_t tid, int sig)
2129 {
2130 	if (sig == SIGCANCEL)
2131 		return (EINVAL);
2132 	return (__lwp_kill(tid, sig));
2133 }
2134 
2135 /*
2136  * Exit a critical section, take deferred actions if necessary.
2137  */
2138 void
2139 do_exit_critical()
2140 {
2141 	ulwp_t *self = curthread;
2142 	int sig;
2143 
2144 	ASSERT(self->ul_critical == 0);
2145 	if (self->ul_dead)
2146 		return;
2147 
2148 	while (self->ul_pleasestop ||
2149 	    (self->ul_cursig != 0 && self->ul_sigdefer == 0)) {
2150 		/*
2151 		 * Avoid a recursive call to exit_critical() in _thrp_suspend()
2152 		 * by keeping self->ul_critical == 1 here.
2153 		 */
2154 		self->ul_critical++;
2155 		while (self->ul_pleasestop) {
2156 			/*
2157 			 * Guard against suspending ourself while on a sleep
2158 			 * queue.  See the comments in call_user_handler().
2159 			 */
2160 			unsleep_self();
2161 			set_parking_flag(self, 0);
2162 			(void) _thrp_suspend(self->ul_lwpid,
2163 			    self->ul_pleasestop);
2164 		}
2165 		self->ul_critical--;
2166 
2167 		if ((sig = self->ul_cursig) != 0 && self->ul_sigdefer == 0) {
2168 			/*
2169 			 * Clear ul_cursig before proceeding.
2170 			 * This protects us from the dynamic linker's
2171 			 * calls to bind_guard()/bind_clear() in the
2172 			 * event that it is invoked to resolve a symbol
2173 			 * like take_deferred_signal() below.
2174 			 */
2175 			self->ul_cursig = 0;
2176 			take_deferred_signal(sig);
2177 			ASSERT(self->ul_cursig == 0);
2178 		}
2179 	}
2180 	ASSERT(self->ul_critical == 0);
2181 }
2182 
2183 /*
2184  * _ti_bind_guard() and _ti_bind_clear() are called by the dynamic linker
2185  * (ld.so.1) when it has do do something, like resolve a symbol to be called
2186  * by the application or one of its libraries.  _ti_bind_guard() is called
2187  * on entry to ld.so.1, _ti_bind_clear() on exit from ld.so.1 back to the
2188  * application.  The dynamic linker gets special dispensation from libc to
2189  * run in a critical region (all signals deferred and no thread suspension
2190  * or forking allowed), and to be immune from cancellation for the duration.
2191  */
2192 int
2193 _ti_bind_guard(int bindflag)
2194 {
2195 	ulwp_t *self = curthread;
2196 
2197 	if ((self->ul_bindflags & bindflag) == bindflag)
2198 		return (0);
2199 	enter_critical(self);
2200 	self->ul_save_state = self->ul_cancel_disabled;
2201 	self->ul_cancel_disabled = 1;
2202 	set_cancel_pending_flag(self, 0);
2203 	self->ul_bindflags |= bindflag;
2204 	return (1);
2205 }
2206 
2207 int
2208 _ti_bind_clear(int bindflag)
2209 {
2210 	ulwp_t *self = curthread;
2211 
2212 	if ((self->ul_bindflags & bindflag) == 0)
2213 		return (self->ul_bindflags);
2214 	self->ul_bindflags &= ~bindflag;
2215 	self->ul_cancel_disabled = self->ul_save_state;
2216 	set_cancel_pending_flag(self, 0);
2217 	exit_critical(self);
2218 	return (self->ul_bindflags);
2219 }
2220 
2221 /*
2222  * sigoff() and sigon() enable cond_wait() to behave (optionally) like
2223  * it does in the old libthread (see the comments in cond_wait_queue()).
2224  * Also, signals are deferred at thread startup until TLS constructors
2225  * have all been called, at which time _thr_setup() calls sigon().
2226  *
2227  * _sigoff() and _sigon() are external consolidation-private interfaces to
2228  * sigoff() and sigon(), respectively, in libc.  These are used in libnsl.
2229  * Also, _sigoff() and _sigon() are called from dbx's run-time checking
2230  * (librtc.so) to defer signals during its critical sections (not to be
2231  * confused with libc critical sections [see exit_critical() above]).
2232  */
2233 void
2234 _sigoff(void)
2235 {
2236 	sigoff(curthread);
2237 }
2238 
2239 void
2240 _sigon(void)
2241 {
2242 	sigon(curthread);
2243 }
2244 
2245 void
2246 sigon(ulwp_t *self)
2247 {
2248 	int sig;
2249 
2250 	ASSERT(self->ul_sigdefer > 0);
2251 	if (--self->ul_sigdefer == 0) {
2252 		if ((sig = self->ul_cursig) != 0 && self->ul_critical == 0) {
2253 			self->ul_cursig = 0;
2254 			take_deferred_signal(sig);
2255 			ASSERT(self->ul_cursig == 0);
2256 		}
2257 	}
2258 }
2259 
2260 #pragma weak thr_getconcurrency = _thr_getconcurrency
2261 int
2262 _thr_getconcurrency()
2263 {
2264 	return (thr_concurrency);
2265 }
2266 
2267 #pragma weak pthread_getconcurrency = _pthread_getconcurrency
2268 int
2269 _pthread_getconcurrency()
2270 {
2271 	return (pthread_concurrency);
2272 }
2273 
2274 #pragma weak thr_setconcurrency = _thr_setconcurrency
2275 int
2276 _thr_setconcurrency(int new_level)
2277 {
2278 	uberdata_t *udp = curthread->ul_uberdata;
2279 
2280 	if (new_level < 0)
2281 		return (EINVAL);
2282 	if (new_level > 65536)		/* 65536 is totally arbitrary */
2283 		return (EAGAIN);
2284 	lmutex_lock(&udp->link_lock);
2285 	if (new_level > thr_concurrency)
2286 		thr_concurrency = new_level;
2287 	lmutex_unlock(&udp->link_lock);
2288 	return (0);
2289 }
2290 
2291 #pragma weak pthread_setconcurrency = _pthread_setconcurrency
2292 int
2293 _pthread_setconcurrency(int new_level)
2294 {
2295 	if (new_level < 0)
2296 		return (EINVAL);
2297 	if (new_level > 65536)		/* 65536 is totally arbitrary */
2298 		return (EAGAIN);
2299 	pthread_concurrency = new_level;
2300 	return (0);
2301 }
2302 
2303 #pragma weak thr_min_stack = _thr_min_stack
2304 #pragma weak __pthread_min_stack = _thr_min_stack
2305 size_t
2306 _thr_min_stack(void)
2307 {
2308 	return (MINSTACK);
2309 }
2310 
2311 int
2312 __nthreads(void)
2313 {
2314 	return (curthread->ul_uberdata->nthreads);
2315 }
2316 
2317 /*
2318  * XXX
2319  * The remainder of this file implements the private interfaces to java for
2320  * garbage collection.  It is no longer used, at least by java 1.2.
2321  * It can all go away once all old JVMs have disappeared.
2322  */
2323 
2324 int	suspendingallmutators;	/* when non-zero, suspending all mutators. */
2325 int	suspendedallmutators;	/* when non-zero, all mutators suspended. */
2326 int	mutatorsbarrier;	/* when non-zero, mutators barrier imposed. */
2327 mutex_t	mutatorslock = DEFAULTMUTEX;	/* used to enforce mutators barrier. */
2328 cond_t	mutatorscv = DEFAULTCV;		/* where non-mutators sleep. */
2329 
2330 /*
2331  * Get the available register state for the target thread.
2332  * Return non-volatile registers: TRS_NONVOLATILE
2333  */
2334 #pragma weak thr_getstate = _thr_getstate
2335 int
2336 _thr_getstate(thread_t tid, int *flag, lwpid_t *lwp, stack_t *ss, gregset_t rs)
2337 {
2338 	ulwp_t *self = curthread;
2339 	uberdata_t *udp = self->ul_uberdata;
2340 	ulwp_t **ulwpp;
2341 	ulwp_t *ulwp;
2342 	int error = 0;
2343 	int trs_flag = TRS_LWPID;
2344 
2345 	if (tid == 0 || self->ul_lwpid == tid) {
2346 		ulwp = self;
2347 		ulwp_lock(ulwp, udp);
2348 	} else if ((ulwpp = find_lwpp(tid)) != NULL) {
2349 		ulwp = *ulwpp;
2350 	} else {
2351 		if (flag)
2352 			*flag = TRS_INVALID;
2353 		return (ESRCH);
2354 	}
2355 
2356 	if (ulwp->ul_dead) {
2357 		trs_flag = TRS_INVALID;
2358 	} else if (!ulwp->ul_stop && !suspendedallmutators) {
2359 		error = EINVAL;
2360 		trs_flag = TRS_INVALID;
2361 	} else if (ulwp->ul_stop) {
2362 		trs_flag = TRS_NONVOLATILE;
2363 		getgregs(ulwp, rs);
2364 	}
2365 
2366 	if (flag)
2367 		*flag = trs_flag;
2368 	if (lwp)
2369 		*lwp = tid;
2370 	if (ss != NULL)
2371 		(void) _thrp_stksegment(ulwp, ss);
2372 
2373 	ulwp_unlock(ulwp, udp);
2374 	return (error);
2375 }
2376 
2377 /*
2378  * Set the appropriate register state for the target thread.
2379  * This is not used by java.  It exists solely for the MSTC test suite.
2380  */
2381 #pragma weak thr_setstate = _thr_setstate
2382 int
2383 _thr_setstate(thread_t tid, int flag, gregset_t rs)
2384 {
2385 	uberdata_t *udp = curthread->ul_uberdata;
2386 	ulwp_t *ulwp;
2387 	int error = 0;
2388 
2389 	if ((ulwp = find_lwp(tid)) == NULL)
2390 		return (ESRCH);
2391 
2392 	if (!ulwp->ul_stop && !suspendedallmutators)
2393 		error = EINVAL;
2394 	else if (rs != NULL) {
2395 		switch (flag) {
2396 		case TRS_NONVOLATILE:
2397 			/* do /proc stuff here? */
2398 			if (ulwp->ul_stop)
2399 				setgregs(ulwp, rs);
2400 			else
2401 				error = EINVAL;
2402 			break;
2403 		case TRS_LWPID:		/* do /proc stuff here? */
2404 		default:
2405 			error = EINVAL;
2406 			break;
2407 		}
2408 	}
2409 
2410 	ulwp_unlock(ulwp, udp);
2411 	return (error);
2412 }
2413 
2414 int
2415 getlwpstatus(thread_t tid, struct lwpstatus *sp)
2416 {
2417 	extern ssize_t __pread(int, void *, size_t, off_t);
2418 	char buf[100];
2419 	int fd;
2420 
2421 	/* "/proc/self/lwp/%u/lwpstatus" w/o stdio */
2422 	(void) strcpy(buf, "/proc/self/lwp/");
2423 	ultos((uint64_t)tid, 10, buf + strlen(buf));
2424 	(void) strcat(buf, "/lwpstatus");
2425 	if ((fd = _private_open(buf, O_RDONLY, 0)) >= 0) {
2426 		while (__pread(fd, sp, sizeof (*sp), 0) == sizeof (*sp)) {
2427 			if (sp->pr_flags & PR_STOPPED) {
2428 				(void) _private_close(fd);
2429 				return (0);
2430 			}
2431 			lwp_yield();	/* give him a chance to stop */
2432 		}
2433 		(void) _private_close(fd);
2434 	}
2435 	return (-1);
2436 }
2437 
2438 int
2439 putlwpregs(thread_t tid, prgregset_t prp)
2440 {
2441 	extern ssize_t __writev(int, const struct iovec *, int);
2442 	char buf[100];
2443 	int fd;
2444 	long dstop_sreg[2];
2445 	long run_null[2];
2446 	iovec_t iov[3];
2447 
2448 	/* "/proc/self/lwp/%u/lwpctl" w/o stdio */
2449 	(void) strcpy(buf, "/proc/self/lwp/");
2450 	ultos((uint64_t)tid, 10, buf + strlen(buf));
2451 	(void) strcat(buf, "/lwpctl");
2452 	if ((fd = _private_open(buf, O_WRONLY, 0)) >= 0) {
2453 		dstop_sreg[0] = PCDSTOP;	/* direct it to stop */
2454 		dstop_sreg[1] = PCSREG;		/* set the registers */
2455 		iov[0].iov_base = (caddr_t)dstop_sreg;
2456 		iov[0].iov_len = sizeof (dstop_sreg);
2457 		iov[1].iov_base = (caddr_t)prp;	/* from the register set */
2458 		iov[1].iov_len = sizeof (prgregset_t);
2459 		run_null[0] = PCRUN;		/* make it runnable again */
2460 		run_null[1] = 0;
2461 		iov[2].iov_base = (caddr_t)run_null;
2462 		iov[2].iov_len = sizeof (run_null);
2463 		if (__writev(fd, iov, 3) >= 0) {
2464 			(void) _private_close(fd);
2465 			return (0);
2466 		}
2467 		(void) _private_close(fd);
2468 	}
2469 	return (-1);
2470 }
2471 
2472 static ulong_t
2473 gettsp_slow(thread_t tid)
2474 {
2475 	char buf[100];
2476 	struct lwpstatus status;
2477 
2478 	if (getlwpstatus(tid, &status) != 0) {
2479 		/* "__gettsp(%u): can't read lwpstatus" w/o stdio */
2480 		(void) strcpy(buf, "__gettsp(");
2481 		ultos((uint64_t)tid, 10, buf + strlen(buf));
2482 		(void) strcat(buf, "): can't read lwpstatus");
2483 		thr_panic(buf);
2484 	}
2485 	return (status.pr_reg[R_SP]);
2486 }
2487 
2488 ulong_t
2489 __gettsp(thread_t tid)
2490 {
2491 	uberdata_t *udp = curthread->ul_uberdata;
2492 	ulwp_t *ulwp;
2493 	ulong_t result;
2494 
2495 	if ((ulwp = find_lwp(tid)) == NULL)
2496 		return (0);
2497 
2498 	if (ulwp->ul_stop && (result = ulwp->ul_sp) != 0) {
2499 		ulwp_unlock(ulwp, udp);
2500 		return (result);
2501 	}
2502 
2503 	result = gettsp_slow(tid);
2504 	ulwp_unlock(ulwp, udp);
2505 	return (result);
2506 }
2507 
2508 /*
2509  * This tells java stack walkers how to find the ucontext
2510  * structure passed to signal handlers.
2511  */
2512 #pragma weak thr_sighndlrinfo = _thr_sighndlrinfo
2513 void
2514 _thr_sighndlrinfo(void (**func)(), int *funcsize)
2515 {
2516 	*func = &__sighndlr;
2517 	*funcsize = (char *)&__sighndlrend - (char *)&__sighndlr;
2518 }
2519 
2520 /*
2521  * Mark a thread a mutator or reset a mutator to being a default,
2522  * non-mutator thread.
2523  */
2524 #pragma weak thr_setmutator = _thr_setmutator
2525 int
2526 _thr_setmutator(thread_t tid, int enabled)
2527 {
2528 	ulwp_t *self = curthread;
2529 	uberdata_t *udp = self->ul_uberdata;
2530 	ulwp_t *ulwp;
2531 	int error;
2532 	int cancel_state;
2533 
2534 	enabled = enabled? 1 : 0;
2535 top:
2536 	if (tid == 0) {
2537 		ulwp = self;
2538 		ulwp_lock(ulwp, udp);
2539 	} else if ((ulwp = find_lwp(tid)) == NULL) {
2540 		return (ESRCH);
2541 	}
2542 
2543 	/*
2544 	 * The target thread should be the caller itself or a suspended thread.
2545 	 * This prevents the target from also changing its ul_mutator field.
2546 	 */
2547 	error = 0;
2548 	if (ulwp != self && !ulwp->ul_stop && enabled)
2549 		error = EINVAL;
2550 	else if (ulwp->ul_mutator != enabled) {
2551 		lmutex_lock(&mutatorslock);
2552 		if (mutatorsbarrier) {
2553 			ulwp_unlock(ulwp, udp);
2554 			(void) _pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,
2555 			    &cancel_state);
2556 			while (mutatorsbarrier)
2557 				(void) _cond_wait(&mutatorscv, &mutatorslock);
2558 			(void) _pthread_setcancelstate(cancel_state, NULL);
2559 			lmutex_unlock(&mutatorslock);
2560 			goto top;
2561 		}
2562 		ulwp->ul_mutator = enabled;
2563 		lmutex_unlock(&mutatorslock);
2564 	}
2565 
2566 	ulwp_unlock(ulwp, udp);
2567 	return (error);
2568 }
2569 
2570 /*
2571  * Establish a barrier against new mutators.  Any non-mutator trying
2572  * to become a mutator is suspended until the barrier is removed.
2573  */
2574 #pragma weak thr_mutators_barrier = _thr_mutators_barrier
2575 void
2576 _thr_mutators_barrier(int enabled)
2577 {
2578 	int oldvalue;
2579 	int cancel_state;
2580 
2581 	lmutex_lock(&mutatorslock);
2582 
2583 	/*
2584 	 * Wait if trying to set the barrier while it is already set.
2585 	 */
2586 	(void) _pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
2587 	while (mutatorsbarrier && enabled)
2588 		(void) _cond_wait(&mutatorscv, &mutatorslock);
2589 	(void) _pthread_setcancelstate(cancel_state, NULL);
2590 
2591 	oldvalue = mutatorsbarrier;
2592 	mutatorsbarrier = enabled;
2593 	/*
2594 	 * Wakeup any blocked non-mutators when barrier is removed.
2595 	 */
2596 	if (oldvalue && !enabled)
2597 		(void) cond_broadcast_internal(&mutatorscv);
2598 	lmutex_unlock(&mutatorslock);
2599 }
2600 
2601 /*
2602  * Suspend the set of all mutators except for the caller.  The list
2603  * of actively running threads is searched and only the mutators
2604  * in this list are suspended.  Actively running non-mutators remain
2605  * running.  Any other thread is suspended.
2606  */
2607 #pragma weak thr_suspend_allmutators = _thr_suspend_allmutators
2608 int
2609 _thr_suspend_allmutators(void)
2610 {
2611 	ulwp_t *self = curthread;
2612 	uberdata_t *udp = self->ul_uberdata;
2613 	ulwp_t *ulwp;
2614 	int link_dropped;
2615 
2616 	/*
2617 	 * We single-thread the entire thread suspend/continue mechanism.
2618 	 */
2619 	fork_lock_enter();
2620 
2621 top:
2622 	lmutex_lock(&udp->link_lock);
2623 
2624 	if (suspendingallmutators || suspendedallmutators) {
2625 		lmutex_unlock(&udp->link_lock);
2626 		fork_lock_exit();
2627 		return (EINVAL);
2628 	}
2629 	suspendingallmutators = 1;
2630 
2631 	for (ulwp = self->ul_forw; ulwp != self; ulwp = ulwp->ul_forw) {
2632 		ulwp_lock(ulwp, udp);
2633 		if (!ulwp->ul_mutator) {
2634 			ulwp_unlock(ulwp, udp);
2635 		} else if (ulwp->ul_stop) {	/* already stopped */
2636 			ulwp->ul_stop |= TSTP_MUTATOR;
2637 			ulwp_broadcast(ulwp);
2638 			ulwp_unlock(ulwp, udp);
2639 		} else {
2640 			/*
2641 			 * Move the stopped lwp out of a critical section.
2642 			 */
2643 			if (safe_suspend(ulwp, TSTP_MUTATOR, &link_dropped) ||
2644 			    link_dropped) {
2645 				suspendingallmutators = 0;
2646 				goto top;
2647 			}
2648 		}
2649 	}
2650 
2651 	suspendedallmutators = 1;
2652 	suspendingallmutators = 0;
2653 	lmutex_unlock(&udp->link_lock);
2654 	fork_lock_exit();
2655 	return (0);
2656 }
2657 
2658 /*
2659  * Suspend the target mutator.  The caller is permitted to suspend
2660  * itself.  If a mutator barrier is enabled, the caller will suspend
2661  * itself as though it had been suspended by thr_suspend_allmutators().
2662  * When the barrier is removed, this thread will be resumed.  Any
2663  * suspended mutator, whether suspended by thr_suspend_mutator(), or by
2664  * thr_suspend_allmutators(), can be resumed by thr_continue_mutator().
2665  */
2666 #pragma weak thr_suspend_mutator = _thr_suspend_mutator
2667 int
2668 _thr_suspend_mutator(thread_t tid)
2669 {
2670 	if (tid == 0)
2671 		tid = curthread->ul_lwpid;
2672 	return (_thrp_suspend(tid, TSTP_MUTATOR));
2673 }
2674 
2675 /*
2676  * Resume the set of all suspended mutators.
2677  */
2678 #pragma weak thr_continue_allmutators = _thr_continue_allmutators
2679 int
2680 _thr_continue_allmutators()
2681 {
2682 	ulwp_t *self = curthread;
2683 	uberdata_t *udp = self->ul_uberdata;
2684 	ulwp_t *ulwp;
2685 
2686 	/*
2687 	 * We single-thread the entire thread suspend/continue mechanism.
2688 	 */
2689 	fork_lock_enter();
2690 
2691 	lmutex_lock(&udp->link_lock);
2692 	if (!suspendedallmutators) {
2693 		lmutex_unlock(&udp->link_lock);
2694 		fork_lock_exit();
2695 		return (EINVAL);
2696 	}
2697 	suspendedallmutators = 0;
2698 
2699 	for (ulwp = self->ul_forw; ulwp != self; ulwp = ulwp->ul_forw) {
2700 		mutex_t *mp = ulwp_mutex(ulwp, udp);
2701 		lmutex_lock(mp);
2702 		if (ulwp->ul_stop & TSTP_MUTATOR) {
2703 			ulwp->ul_stop &= ~TSTP_MUTATOR;
2704 			ulwp_broadcast(ulwp);
2705 			if (!ulwp->ul_stop)
2706 				force_continue(ulwp);
2707 		}
2708 		lmutex_unlock(mp);
2709 	}
2710 
2711 	lmutex_unlock(&udp->link_lock);
2712 	fork_lock_exit();
2713 	return (0);
2714 }
2715 
2716 /*
2717  * Resume a suspended mutator.
2718  */
2719 #pragma weak thr_continue_mutator = _thr_continue_mutator
2720 int
2721 _thr_continue_mutator(thread_t tid)
2722 {
2723 	return (_thrp_continue(tid, TSTP_MUTATOR));
2724 }
2725 
2726 #pragma weak thr_wait_mutator = _thr_wait_mutator
2727 int
2728 _thr_wait_mutator(thread_t tid, int dontwait)
2729 {
2730 	uberdata_t *udp = curthread->ul_uberdata;
2731 	ulwp_t *ulwp;
2732 	int cancel_state;
2733 	int error = 0;
2734 
2735 	(void) _pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
2736 top:
2737 	if ((ulwp = find_lwp(tid)) == NULL) {
2738 		(void) _pthread_setcancelstate(cancel_state, NULL);
2739 		return (ESRCH);
2740 	}
2741 
2742 	if (!ulwp->ul_mutator)
2743 		error = EINVAL;
2744 	else if (dontwait) {
2745 		if (!(ulwp->ul_stop & TSTP_MUTATOR))
2746 			error = EWOULDBLOCK;
2747 	} else if (!(ulwp->ul_stop & TSTP_MUTATOR)) {
2748 		cond_t *cvp = ulwp_condvar(ulwp, udp);
2749 		mutex_t *mp = ulwp_mutex(ulwp, udp);
2750 
2751 		(void) _cond_wait(cvp, mp);
2752 		(void) lmutex_unlock(mp);
2753 		goto top;
2754 	}
2755 
2756 	ulwp_unlock(ulwp, udp);
2757 	(void) _pthread_setcancelstate(cancel_state, NULL);
2758 	return (error);
2759 }
2760 
2761 /* PROBE_SUPPORT begin */
2762 
2763 void
2764 thr_probe_setup(void *data)
2765 {
2766 	curthread->ul_tpdp = data;
2767 }
2768 
2769 static void *
2770 _thread_probe_getfunc()
2771 {
2772 	return (curthread->ul_tpdp);
2773 }
2774 
2775 void * (*thr_probe_getfunc_addr)(void) = _thread_probe_getfunc;
2776 
2777 /* ARGSUSED */
2778 void
2779 _resume(ulwp_t *ulwp, caddr_t sp, int dontsave)
2780 {
2781 	/* never called */
2782 }
2783 
2784 /* ARGSUSED */
2785 void
2786 _resume_ret(ulwp_t *oldlwp)
2787 {
2788 	/* never called */
2789 }
2790 
2791 /* PROBE_SUPPORT end */
2792