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