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