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