xref: /titanic_50/usr/src/uts/common/os/lwp.c (revision 982b4ad2dc6b5ed2a2c8c1670e94ecf1fe63fc56)
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 <sys/param.h>
28 #include <sys/types.h>
29 #include <sys/sysmacros.h>
30 #include <sys/systm.h>
31 #include <sys/thread.h>
32 #include <sys/proc.h>
33 #include <sys/task.h>
34 #include <sys/project.h>
35 #include <sys/signal.h>
36 #include <sys/errno.h>
37 #include <sys/vmparam.h>
38 #include <sys/stack.h>
39 #include <sys/procfs.h>
40 #include <sys/prsystm.h>
41 #include <sys/cpuvar.h>
42 #include <sys/kmem.h>
43 #include <sys/vtrace.h>
44 #include <sys/door.h>
45 #include <vm/seg_kp.h>
46 #include <sys/debug.h>
47 #include <sys/tnf.h>
48 #include <sys/schedctl.h>
49 #include <sys/poll.h>
50 #include <sys/copyops.h>
51 #include <sys/lwp_upimutex_impl.h>
52 #include <sys/cpupart.h>
53 #include <sys/lgrp.h>
54 #include <sys/rctl.h>
55 #include <sys/contract_impl.h>
56 #include <sys/cpc_impl.h>
57 #include <sys/sdt.h>
58 #include <sys/cmn_err.h>
59 #include <sys/brand.h>
60 
61 /* hash function for the lwpid hash table, p->p_tidhash[] */
62 #define	TIDHASH(tid, hash_sz)	((tid) & ((hash_sz) - 1))
63 
64 void *segkp_lwp;		/* cookie for pool of segkp resources */
65 extern void reapq_move_lq_to_tq(kthread_t *);
66 extern void freectx_ctx(struct ctxop *);
67 
68 /*
69  * Create a thread that appears to be stopped at sys_rtt.
70  */
71 klwp_t *
72 lwp_create(void (*proc)(), caddr_t arg, size_t len, proc_t *p,
73     int state, int pri, const k_sigset_t *smask, int cid, id_t lwpid)
74 {
75 	klwp_t *lwp = NULL;
76 	kthread_t *t;
77 	kthread_t *tx;
78 	cpupart_t *oldpart = NULL;
79 	size_t	stksize;
80 	caddr_t lwpdata = NULL;
81 	processorid_t	binding;
82 	int err = 0;
83 	kproject_t *oldkpj, *newkpj;
84 	void *bufp = NULL;
85 	klwp_t *curlwp = ttolwp(curthread);
86 	lwpent_t *lep;
87 	lwpdir_t *old_dir = NULL;
88 	uint_t old_dirsz = 0;
89 	tidhash_t *old_hash = NULL;
90 	uint_t old_hashsz = 0;
91 	ret_tidhash_t *ret_tidhash = NULL;
92 	int i;
93 	int rctlfail = 0;
94 	boolean_t branded = 0;
95 	struct ctxop *ctx = NULL;
96 
97 	mutex_enter(&p->p_lock);
98 	mutex_enter(&p->p_zone->zone_nlwps_lock);
99 	/*
100 	 * don't enforce rctl limits on system processes
101 	 */
102 	if (cid != syscid) {
103 		if (p->p_task->tk_nlwps >= p->p_task->tk_nlwps_ctl)
104 			if (rctl_test(rc_task_lwps, p->p_task->tk_rctls, p,
105 			    1, 0) & RCT_DENY)
106 				rctlfail = 1;
107 		if (p->p_task->tk_proj->kpj_nlwps >=
108 		    p->p_task->tk_proj->kpj_nlwps_ctl)
109 			if (rctl_test(rc_project_nlwps,
110 			    p->p_task->tk_proj->kpj_rctls, p, 1, 0)
111 			    & RCT_DENY)
112 				rctlfail = 1;
113 		if (p->p_zone->zone_nlwps >= p->p_zone->zone_nlwps_ctl)
114 			if (rctl_test(rc_zone_nlwps, p->p_zone->zone_rctls, p,
115 			    1, 0) & RCT_DENY)
116 				rctlfail = 1;
117 	}
118 	if (rctlfail) {
119 		mutex_exit(&p->p_zone->zone_nlwps_lock);
120 		mutex_exit(&p->p_lock);
121 		return (NULL);
122 	}
123 	p->p_task->tk_nlwps++;
124 	p->p_task->tk_proj->kpj_nlwps++;
125 	p->p_zone->zone_nlwps++;
126 	mutex_exit(&p->p_zone->zone_nlwps_lock);
127 	mutex_exit(&p->p_lock);
128 
129 	if (curlwp == NULL || (stksize = curlwp->lwp_childstksz) == 0)
130 		stksize = lwp_default_stksize;
131 
132 	/*
133 	 * Try to reclaim a <lwp,stack> from 'deathrow'
134 	 */
135 	if (stksize == lwp_default_stksize) {
136 		if (lwp_reapcnt > 0) {
137 			mutex_enter(&reaplock);
138 			if ((t = lwp_deathrow) != NULL) {
139 				ASSERT(t->t_swap);
140 				lwp_deathrow = t->t_forw;
141 				lwp_reapcnt--;
142 				lwpdata = t->t_swap;
143 				lwp = t->t_lwp;
144 				ctx = t->t_ctx;
145 				t->t_swap = NULL;
146 				t->t_lwp = NULL;
147 				t->t_ctx = NULL;
148 				reapq_move_lq_to_tq(t);
149 			}
150 			mutex_exit(&reaplock);
151 			if (lwp != NULL) {
152 				lwp_stk_fini(lwp);
153 			}
154 			if (ctx != NULL) {
155 				freectx_ctx(ctx);
156 			}
157 		}
158 		if (lwpdata == NULL &&
159 		    (lwpdata = (caddr_t)segkp_cache_get(segkp_lwp)) == NULL) {
160 			mutex_enter(&p->p_lock);
161 			mutex_enter(&p->p_zone->zone_nlwps_lock);
162 			p->p_task->tk_nlwps--;
163 			p->p_task->tk_proj->kpj_nlwps--;
164 			p->p_zone->zone_nlwps--;
165 			mutex_exit(&p->p_zone->zone_nlwps_lock);
166 			mutex_exit(&p->p_lock);
167 			return (NULL);
168 		}
169 	} else {
170 		stksize = roundup(stksize, PAGESIZE);
171 		if ((lwpdata = (caddr_t)segkp_get(segkp, stksize,
172 		    (KPD_NOWAIT | KPD_HASREDZONE | KPD_LOCKED))) == NULL) {
173 			mutex_enter(&p->p_lock);
174 			mutex_enter(&p->p_zone->zone_nlwps_lock);
175 			p->p_task->tk_nlwps--;
176 			p->p_task->tk_proj->kpj_nlwps--;
177 			p->p_zone->zone_nlwps--;
178 			mutex_exit(&p->p_zone->zone_nlwps_lock);
179 			mutex_exit(&p->p_lock);
180 			return (NULL);
181 		}
182 	}
183 
184 	/*
185 	 * Create a thread, initializing the stack pointer
186 	 */
187 	t = thread_create(lwpdata, stksize, NULL, NULL, 0, p, TS_STOPPED, pri);
188 
189 	t->t_swap = lwpdata;	/* Start of page-able data */
190 	if (lwp == NULL)
191 		lwp = kmem_cache_alloc(lwp_cache, KM_SLEEP);
192 	bzero(lwp, sizeof (*lwp));
193 	t->t_lwp = lwp;
194 
195 	t->t_hold = *smask;
196 	lwp->lwp_thread = t;
197 	lwp->lwp_procp = p;
198 	lwp->lwp_sigaltstack.ss_flags = SS_DISABLE;
199 	if (curlwp != NULL && curlwp->lwp_childstksz != 0)
200 		lwp->lwp_childstksz = curlwp->lwp_childstksz;
201 
202 	t->t_stk = lwp_stk_init(lwp, t->t_stk);
203 	thread_load(t, proc, arg, len);
204 
205 	/*
206 	 * Allocate the SIGPROF buffer if ITIMER_REALPROF is in effect.
207 	 */
208 	if (timerisset(&p->p_rprof_timer.it_value))
209 		t->t_rprof = kmem_zalloc(sizeof (struct rprof), KM_SLEEP);
210 
211 	if (cid != NOCLASS)
212 		(void) CL_ALLOC(&bufp, cid, KM_SLEEP);
213 
214 	/*
215 	 * Allocate an lwp directory entry for the new lwp.
216 	 */
217 	lep = kmem_zalloc(sizeof (*lep), KM_SLEEP);
218 
219 	mutex_enter(&p->p_lock);
220 grow:
221 	/*
222 	 * Grow the lwp (thread) directory and lwpid hash table if necessary.
223 	 * A note on the growth algorithm:
224 	 *	The new lwp directory size is computed as:
225 	 *		new = 2 * old + 2
226 	 *	Starting with an initial size of 2 (see exec_common()),
227 	 *	this yields numbers that are a power of two minus 2:
228 	 *		2, 6, 14, 30, 62, 126, 254, 510, 1022, ...
229 	 *	The size of the lwpid hash table must be a power of two
230 	 *	and must be commensurate in size with the lwp directory
231 	 *	so that hash bucket chains remain short.  Therefore,
232 	 *	the lwpid hash table size is computed as:
233 	 *		hashsz = (dirsz + 2) / 2
234 	 *	which leads to these hash table sizes corresponding to
235 	 *	the above directory sizes:
236 	 *		2, 4, 8, 16, 32, 64, 128, 256, 512, ...
237 	 * A note on growing the hash table:
238 	 *	For performance reasons, code in lwp_unpark() does not
239 	 *	acquire curproc->p_lock when searching the hash table.
240 	 *	Rather, it calls lwp_hash_lookup_and_lock() which
241 	 *	acquires only the individual hash bucket lock, taking
242 	 *	care to deal with reallocation of the hash table
243 	 *	during the time it takes to acquire the lock.
244 	 *
245 	 *	This is sufficient to protect the integrity of the
246 	 *	hash table, but it requires us to acquire all of the
247 	 *	old hash bucket locks before growing the hash table
248 	 *	and to release them afterwards.  It also requires us
249 	 *	not to free the old hash table because some thread
250 	 *	in lwp_hash_lookup_and_lock() might still be trying
251 	 *	to acquire the old bucket lock.
252 	 *
253 	 *	So we adopt the tactic of keeping all of the retired
254 	 *	hash tables on a linked list, so they can be safely
255 	 *	freed when the process exits or execs.
256 	 *
257 	 *	Because the hash table grows in powers of two, the
258 	 *	total size of all of the hash tables will be slightly
259 	 *	less than twice the size of the largest hash table.
260 	 */
261 	while (p->p_lwpfree == NULL) {
262 		uint_t dirsz = p->p_lwpdir_sz;
263 		lwpdir_t *new_dir;
264 		uint_t new_dirsz;
265 		lwpdir_t *ldp;
266 		tidhash_t *new_hash;
267 		uint_t new_hashsz;
268 
269 		mutex_exit(&p->p_lock);
270 
271 		/*
272 		 * Prepare to remember the old p_tidhash for later
273 		 * kmem_free()ing when the process exits or execs.
274 		 */
275 		if (ret_tidhash == NULL)
276 			ret_tidhash = kmem_zalloc(sizeof (ret_tidhash_t),
277 			    KM_SLEEP);
278 		if (old_dir != NULL)
279 			kmem_free(old_dir, old_dirsz * sizeof (*old_dir));
280 		if (old_hash != NULL)
281 			kmem_free(old_hash, old_hashsz * sizeof (*old_hash));
282 
283 		new_dirsz = 2 * dirsz + 2;
284 		new_dir = kmem_zalloc(new_dirsz * sizeof (lwpdir_t), KM_SLEEP);
285 		for (ldp = new_dir, i = 1; i < new_dirsz; i++, ldp++)
286 			ldp->ld_next = ldp + 1;
287 		new_hashsz = (new_dirsz + 2) / 2;
288 		new_hash = kmem_zalloc(new_hashsz * sizeof (tidhash_t),
289 		    KM_SLEEP);
290 
291 		mutex_enter(&p->p_lock);
292 		if (p == curproc)
293 			prbarrier(p);
294 
295 		if (dirsz != p->p_lwpdir_sz || p->p_lwpfree != NULL) {
296 			/*
297 			 * Someone else beat us to it or some lwp exited.
298 			 * Set up to free our memory and take a lap.
299 			 */
300 			old_dir = new_dir;
301 			old_dirsz = new_dirsz;
302 			old_hash = new_hash;
303 			old_hashsz = new_hashsz;
304 		} else {
305 			/*
306 			 * For the benefit of lwp_hash_lookup_and_lock(),
307 			 * called from lwp_unpark(), which searches the
308 			 * tid hash table without acquiring p->p_lock,
309 			 * we must acquire all of the tid hash table
310 			 * locks before replacing p->p_tidhash.
311 			 */
312 			old_hash = p->p_tidhash;
313 			old_hashsz = p->p_tidhash_sz;
314 			for (i = 0; i < old_hashsz; i++) {
315 				mutex_enter(&old_hash[i].th_lock);
316 				mutex_enter(&new_hash[i].th_lock);
317 			}
318 
319 			/*
320 			 * We simply hash in all of the old directory entries.
321 			 * This works because the old directory has no empty
322 			 * slots and the new hash table starts out empty.
323 			 * This reproduces the original directory ordering
324 			 * (required for /proc directory semantics).
325 			 */
326 			old_dir = p->p_lwpdir;
327 			old_dirsz = p->p_lwpdir_sz;
328 			p->p_lwpdir = new_dir;
329 			p->p_lwpfree = new_dir;
330 			p->p_lwpdir_sz = new_dirsz;
331 			for (ldp = old_dir, i = 0; i < old_dirsz; i++, ldp++)
332 				lwp_hash_in(p, ldp->ld_entry,
333 				    new_hash, new_hashsz, 0);
334 
335 			/*
336 			 * Remember the old hash table along with all
337 			 * of the previously-remembered hash tables.
338 			 * We will free them at process exit or exec.
339 			 */
340 			ret_tidhash->rth_tidhash = old_hash;
341 			ret_tidhash->rth_tidhash_sz = old_hashsz;
342 			ret_tidhash->rth_next = p->p_ret_tidhash;
343 			p->p_ret_tidhash = ret_tidhash;
344 
345 			/*
346 			 * Now establish the new tid hash table.
347 			 * As soon as we assign p->p_tidhash,
348 			 * code in lwp_unpark() can start using it.
349 			 */
350 			membar_producer();
351 			p->p_tidhash = new_hash;
352 
353 			/*
354 			 * It is necessary that p_tidhash reach global
355 			 * visibility before p_tidhash_sz.  Otherwise,
356 			 * code in lwp_hash_lookup_and_lock() could
357 			 * index into the old p_tidhash using the new
358 			 * p_tidhash_sz and thereby access invalid data.
359 			 */
360 			membar_producer();
361 			p->p_tidhash_sz = new_hashsz;
362 
363 			/*
364 			 * Release the locks; allow lwp_unpark() to carry on.
365 			 */
366 			for (i = 0; i < old_hashsz; i++) {
367 				mutex_exit(&old_hash[i].th_lock);
368 				mutex_exit(&new_hash[i].th_lock);
369 			}
370 
371 			/*
372 			 * Avoid freeing these objects below.
373 			 */
374 			ret_tidhash = NULL;
375 			old_hash = NULL;
376 			old_hashsz = 0;
377 		}
378 	}
379 
380 	/*
381 	 * Block the process against /proc while we manipulate p->p_tlist,
382 	 * unless lwp_create() was called by /proc for the PCAGENT operation.
383 	 * We want to do this early enough so that we don't drop p->p_lock
384 	 * until the thread is put on the p->p_tlist.
385 	 */
386 	if (p == curproc) {
387 		prbarrier(p);
388 		/*
389 		 * If the current lwp has been requested to stop, do so now.
390 		 * Otherwise we have a race condition between /proc attempting
391 		 * to stop the process and this thread creating a new lwp
392 		 * that was not seen when the /proc PCSTOP request was issued.
393 		 * We rely on stop() to call prbarrier(p) before returning.
394 		 */
395 		while ((curthread->t_proc_flag & TP_PRSTOP) &&
396 		    !ttolwp(curthread)->lwp_nostop)
397 			stop(PR_REQUESTED, 0);
398 
399 		/*
400 		 * If process is exiting, there could be a race between
401 		 * the agent lwp creation and the new lwp currently being
402 		 * created. So to prevent this race lwp creation is failed
403 		 * if the process is exiting.
404 		 */
405 		if (p->p_flag & (SEXITLWPS|SKILLED)) {
406 			err = 1;
407 			goto error;
408 		}
409 
410 		/*
411 		 * Since we might have dropped p->p_lock, the
412 		 * lwp directory free list might have changed.
413 		 */
414 		if (p->p_lwpfree == NULL)
415 			goto grow;
416 	}
417 
418 	kpreempt_disable();	/* can't grab cpu_lock here */
419 
420 	/*
421 	 * Inherit processor and processor set bindings from curthread,
422 	 * unless we're creating a new kernel process, in which case
423 	 * clear all bindings.
424 	 */
425 	if (cid == syscid) {
426 		t->t_bind_cpu = binding = PBIND_NONE;
427 		t->t_cpupart = oldpart = &cp_default;
428 		t->t_bind_pset = PS_NONE;
429 		t->t_bindflag = (uchar_t)default_binding_mode;
430 	} else {
431 		binding = curthread->t_bind_cpu;
432 		t->t_bind_cpu = binding;
433 		oldpart = t->t_cpupart;
434 		t->t_cpupart = curthread->t_cpupart;
435 		t->t_bind_pset = curthread->t_bind_pset;
436 		t->t_bindflag = curthread->t_bindflag |
437 		    (uchar_t)default_binding_mode;
438 	}
439 
440 	/*
441 	 * thread_create() initializes this thread's home lgroup to the root.
442 	 * Choose a more suitable lgroup, since this thread is associated
443 	 * with an lwp.
444 	 */
445 	ASSERT(oldpart != NULL);
446 	if (binding != PBIND_NONE && t->t_affinitycnt == 0) {
447 		t->t_bound_cpu = cpu[binding];
448 		if (t->t_lpl != t->t_bound_cpu->cpu_lpl)
449 			lgrp_move_thread(t, t->t_bound_cpu->cpu_lpl, 1);
450 	} else {
451 		lgrp_move_thread(t, lgrp_choose(t, t->t_cpupart), 1);
452 	}
453 
454 	kpreempt_enable();
455 
456 	/*
457 	 * make sure lpl points to our own partition
458 	 */
459 	ASSERT(t->t_lpl >= t->t_cpupart->cp_lgrploads);
460 	ASSERT(t->t_lpl < t->t_cpupart->cp_lgrploads +
461 	    t->t_cpupart->cp_nlgrploads);
462 
463 	/*
464 	 * If we're creating a new process, then inherit the project from our
465 	 * parent. If we're only creating an additional lwp then use the
466 	 * project pointer of the target process.
467 	 */
468 	if (p->p_task == NULL)
469 		newkpj = ttoproj(curthread);
470 	else
471 		newkpj = p->p_task->tk_proj;
472 
473 	/*
474 	 * It is safe to point the thread to the new project without holding it
475 	 * since we're holding the target process' p_lock here and therefore
476 	 * we're guaranteed that it will not move to another project.
477 	 */
478 	oldkpj = ttoproj(t);
479 	if (newkpj != oldkpj) {
480 		t->t_proj = newkpj;
481 		(void) project_hold(newkpj);
482 		project_rele(oldkpj);
483 	}
484 
485 	if (cid != NOCLASS) {
486 		/*
487 		 * If the lwp is being created in the current process
488 		 * and matches the current thread's scheduling class,
489 		 * we should propagate the current thread's scheduling
490 		 * parameters by calling CL_FORK.  Otherwise just use
491 		 * the defaults by calling CL_ENTERCLASS.
492 		 */
493 		if (p != curproc || curthread->t_cid != cid) {
494 			err = CL_ENTERCLASS(t, cid, NULL, NULL, bufp);
495 			t->t_pri = pri;	/* CL_ENTERCLASS may have changed it */
496 			/*
497 			 * We don't call schedctl_set_cidpri(t) here
498 			 * because the schedctl data is not yet set
499 			 * up for the newly-created lwp.
500 			 */
501 		} else {
502 			t->t_clfuncs = &(sclass[cid].cl_funcs->thread);
503 			err = CL_FORK(curthread, t, bufp);
504 			t->t_cid = cid;
505 		}
506 		if (err)
507 			goto error;
508 		else
509 			bufp = NULL;
510 	}
511 
512 	/*
513 	 * If we were given an lwpid then use it, else allocate one.
514 	 */
515 	if (lwpid != 0)
516 		t->t_tid = lwpid;
517 	else {
518 		/*
519 		 * lwp/thread id 0 is never valid; reserved for special checks.
520 		 * lwp/thread id 1 is reserved for the main thread.
521 		 * Start again at 2 when INT_MAX has been reached
522 		 * (id_t is a signed 32-bit integer).
523 		 */
524 		id_t prev_id = p->p_lwpid;	/* last allocated tid */
525 
526 		do {			/* avoid lwpid duplication */
527 			if (p->p_lwpid == INT_MAX) {
528 				p->p_flag |= SLWPWRAP;
529 				p->p_lwpid = 1;
530 			}
531 			if ((t->t_tid = ++p->p_lwpid) == prev_id) {
532 				/*
533 				 * All lwpids are allocated; fail the request.
534 				 */
535 				err = 1;
536 				goto error;
537 			}
538 			/*
539 			 * We only need to worry about colliding with an id
540 			 * that's already in use if this process has
541 			 * cycled through all available lwp ids.
542 			 */
543 			if ((p->p_flag & SLWPWRAP) == 0)
544 				break;
545 		} while (lwp_hash_lookup(p, t->t_tid) != NULL);
546 	}
547 
548 	/*
549 	 * If this is a branded process, let the brand do any necessary lwp
550 	 * initialization.
551 	 */
552 	if (PROC_IS_BRANDED(p)) {
553 		if (BROP(p)->b_initlwp(lwp)) {
554 			err = 1;
555 			goto error;
556 		}
557 		branded = 1;
558 	}
559 
560 	if (t->t_tid == 1) {
561 		kpreempt_disable();
562 		ASSERT(t->t_lpl != NULL);
563 		p->p_t1_lgrpid = t->t_lpl->lpl_lgrpid;
564 		kpreempt_enable();
565 		if (p->p_tr_lgrpid != LGRP_NONE &&
566 		    p->p_tr_lgrpid != p->p_t1_lgrpid) {
567 			lgrp_update_trthr_migrations(1);
568 		}
569 	}
570 
571 	p->p_lwpcnt++;
572 	t->t_waitfor = -1;
573 
574 	/*
575 	 * Turn microstate accounting on for thread if on for process.
576 	 */
577 	if (p->p_flag & SMSACCT)
578 		t->t_proc_flag |= TP_MSACCT;
579 
580 	/*
581 	 * If the process has watchpoints, mark the new thread as such.
582 	 */
583 	if (pr_watch_active(p))
584 		watch_enable(t);
585 
586 	/*
587 	 * The lwp is being created in the stopped state.
588 	 * We set all the necessary flags to indicate that fact here.
589 	 * We omit the TS_CREATE flag from t_schedflag so that the lwp
590 	 * cannot be set running until the caller is finished with it,
591 	 * even if lwp_continue() is called on it after we drop p->p_lock.
592 	 * When the caller is finished with the newly-created lwp,
593 	 * the caller must call lwp_create_done() to allow the lwp
594 	 * to be set running.  If the TP_HOLDLWP is left set, the
595 	 * lwp will suspend itself after reaching system call exit.
596 	 */
597 	init_mstate(t, LMS_STOPPED);
598 	t->t_proc_flag |= TP_HOLDLWP;
599 	t->t_schedflag |= (TS_ALLSTART & ~(TS_CSTART | TS_CREATE));
600 	t->t_whystop = PR_SUSPENDED;
601 	t->t_whatstop = SUSPEND_NORMAL;
602 	t->t_sig_check = 1;	/* ensure that TP_HOLDLWP is honored */
603 
604 	/*
605 	 * Set system call processing flags in case tracing or profiling
606 	 * is set.  The first system call will evaluate these and turn
607 	 * them off if they aren't needed.
608 	 */
609 	t->t_pre_sys = 1;
610 	t->t_post_sys = 1;
611 
612 	/*
613 	 * Insert the new thread into the list of all threads.
614 	 */
615 	if ((tx = p->p_tlist) == NULL) {
616 		t->t_back = t;
617 		t->t_forw = t;
618 		p->p_tlist = t;
619 	} else {
620 		t->t_forw = tx;
621 		t->t_back = tx->t_back;
622 		tx->t_back->t_forw = t;
623 		tx->t_back = t;
624 	}
625 
626 	/*
627 	 * Insert the new lwp into an lwp directory slot position
628 	 * and into the lwpid hash table.
629 	 */
630 	lep->le_thread = t;
631 	lep->le_lwpid = t->t_tid;
632 	lep->le_start = t->t_start;
633 	lwp_hash_in(p, lep, p->p_tidhash, p->p_tidhash_sz, 1);
634 
635 	if (state == TS_RUN) {
636 		/*
637 		 * We set the new lwp running immediately.
638 		 */
639 		t->t_proc_flag &= ~TP_HOLDLWP;
640 		lwp_create_done(t);
641 	}
642 
643 error:
644 	if (err) {
645 		/*
646 		 * We have failed to create an lwp, so decrement the number
647 		 * of lwps in the task and let the lgroup load averages know
648 		 * that this thread isn't going to show up.
649 		 */
650 		kpreempt_disable();
651 		lgrp_move_thread(t, NULL, 1);
652 		kpreempt_enable();
653 
654 		ASSERT(MUTEX_HELD(&p->p_lock));
655 		mutex_enter(&p->p_zone->zone_nlwps_lock);
656 		p->p_task->tk_nlwps--;
657 		p->p_task->tk_proj->kpj_nlwps--;
658 		p->p_zone->zone_nlwps--;
659 		mutex_exit(&p->p_zone->zone_nlwps_lock);
660 		if (cid != NOCLASS && bufp != NULL)
661 			CL_FREE(cid, bufp);
662 
663 		if (branded)
664 			BROP(p)->b_freelwp(lwp);
665 
666 		mutex_exit(&p->p_lock);
667 		t->t_state = TS_FREE;
668 		thread_rele(t);
669 
670 		/*
671 		 * We need to remove t from the list of all threads
672 		 * because thread_exit()/lwp_exit() isn't called on t.
673 		 */
674 		mutex_enter(&pidlock);
675 		ASSERT(t != t->t_next);		/* t0 never exits */
676 		t->t_next->t_prev = t->t_prev;
677 		t->t_prev->t_next = t->t_next;
678 		mutex_exit(&pidlock);
679 
680 		thread_free(t);
681 		kmem_free(lep, sizeof (*lep));
682 		lwp = NULL;
683 	} else {
684 		mutex_exit(&p->p_lock);
685 	}
686 
687 	if (old_dir != NULL)
688 		kmem_free(old_dir, old_dirsz * sizeof (*old_dir));
689 	if (old_hash != NULL)
690 		kmem_free(old_hash, old_hashsz * sizeof (*old_hash));
691 	if (ret_tidhash != NULL)
692 		kmem_free(ret_tidhash, sizeof (ret_tidhash_t));
693 
694 	DTRACE_PROC1(lwp__create, kthread_t *, t);
695 	return (lwp);
696 }
697 
698 /*
699  * lwp_create_done() is called by the caller of lwp_create() to set the
700  * newly-created lwp running after the caller has finished manipulating it.
701  */
702 void
703 lwp_create_done(kthread_t *t)
704 {
705 	proc_t *p = ttoproc(t);
706 
707 	ASSERT(MUTEX_HELD(&p->p_lock));
708 
709 	/*
710 	 * We set the TS_CREATE and TS_CSTART flags and call setrun_locked().
711 	 * (The absence of the TS_CREATE flag prevents the lwp from running
712 	 * until we are finished with it, even if lwp_continue() is called on
713 	 * it by some other lwp in the process or elsewhere in the kernel.)
714 	 */
715 	thread_lock(t);
716 	ASSERT(t->t_state == TS_STOPPED && !(t->t_schedflag & TS_CREATE));
717 	/*
718 	 * If TS_CSTART is set, lwp_continue(t) has been called and
719 	 * has already incremented p_lwprcnt; avoid doing this twice.
720 	 */
721 	if (!(t->t_schedflag & TS_CSTART))
722 		p->p_lwprcnt++;
723 	t->t_schedflag |= (TS_CSTART | TS_CREATE);
724 	setrun_locked(t);
725 	thread_unlock(t);
726 }
727 
728 /*
729  * Copy an LWP's active templates, and clear the latest contracts.
730  */
731 void
732 lwp_ctmpl_copy(klwp_t *dst, klwp_t *src)
733 {
734 	int i;
735 
736 	for (i = 0; i < ct_ntypes; i++) {
737 		dst->lwp_ct_active[i] = ctmpl_dup(src->lwp_ct_active[i]);
738 		dst->lwp_ct_latest[i] = NULL;
739 	}
740 }
741 
742 /*
743  * Clear an LWP's contract template state.
744  */
745 void
746 lwp_ctmpl_clear(klwp_t *lwp)
747 {
748 	ct_template_t *tmpl;
749 	int i;
750 
751 	for (i = 0; i < ct_ntypes; i++) {
752 		if ((tmpl = lwp->lwp_ct_active[i]) != NULL) {
753 			ctmpl_free(tmpl);
754 			lwp->lwp_ct_active[i] = NULL;
755 		}
756 
757 		if (lwp->lwp_ct_latest[i] != NULL) {
758 			contract_rele(lwp->lwp_ct_latest[i]);
759 			lwp->lwp_ct_latest[i] = NULL;
760 		}
761 	}
762 }
763 
764 /*
765  * Individual lwp exit.
766  * If this is the last lwp, exit the whole process.
767  */
768 void
769 lwp_exit(void)
770 {
771 	kthread_t *t = curthread;
772 	klwp_t *lwp = ttolwp(t);
773 	proc_t *p = ttoproc(t);
774 
775 	ASSERT(MUTEX_HELD(&p->p_lock));
776 
777 	mutex_exit(&p->p_lock);
778 
779 #if defined(__sparc)
780 	/*
781 	 * Ensure that the user stack is fully abandoned..
782 	 */
783 	trash_user_windows();
784 #endif
785 
786 	tsd_exit();			/* free thread specific data */
787 
788 	kcpc_passivate();		/* Clean up performance counter state */
789 
790 	pollcleanup();
791 
792 	if (t->t_door)
793 		door_slam();
794 
795 	if (t->t_schedctl != NULL)
796 		schedctl_lwp_cleanup(t);
797 
798 	if (t->t_upimutex != NULL)
799 		upimutex_cleanup();
800 
801 	/*
802 	 * Perform any brand specific exit processing, then release any
803 	 * brand data associated with the lwp
804 	 */
805 	if (PROC_IS_BRANDED(p))
806 		BROP(p)->b_lwpexit(lwp);
807 
808 	mutex_enter(&p->p_lock);
809 	lwp_cleanup();
810 
811 	/*
812 	 * When this process is dumping core, its lwps are held here
813 	 * until the core dump is finished. Then exitlwps() is called
814 	 * again to release these lwps so that they can finish exiting.
815 	 */
816 	if (p->p_flag & SCOREDUMP)
817 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
818 
819 	/*
820 	 * Block the process against /proc now that we have really acquired
821 	 * p->p_lock (to decrement p_lwpcnt and manipulate p_tlist at least).
822 	 */
823 	prbarrier(p);
824 
825 	/*
826 	 * Call proc_exit() if this is the last non-daemon lwp in the process.
827 	 */
828 	if (!(t->t_proc_flag & TP_DAEMON) &&
829 	    p->p_lwpcnt == p->p_lwpdaemon + 1) {
830 		mutex_exit(&p->p_lock);
831 		if (proc_exit(CLD_EXITED, 0) == 0) {
832 			/* Restarting init. */
833 			return;
834 		}
835 
836 		/*
837 		 * proc_exit() returns a non-zero value when some other
838 		 * lwp got there first.  We just have to continue in
839 		 * lwp_exit().
840 		 */
841 		mutex_enter(&p->p_lock);
842 		ASSERT(curproc->p_flag & SEXITLWPS);
843 		prbarrier(p);
844 	}
845 
846 	DTRACE_PROC(lwp__exit);
847 
848 	/*
849 	 * If the lwp is a detached lwp or if the process is exiting,
850 	 * remove (lwp_hash_out()) the lwp from the lwp directory.
851 	 * Otherwise null out the lwp's le_thread pointer in the lwp
852 	 * directory so that other threads will see it as a zombie lwp.
853 	 */
854 	prlwpexit(t);		/* notify /proc */
855 	if (!(t->t_proc_flag & TP_TWAIT) || (p->p_flag & SEXITLWPS))
856 		lwp_hash_out(p, t->t_tid);
857 	else {
858 		ASSERT(!(t->t_proc_flag & TP_DAEMON));
859 		p->p_lwpdir[t->t_dslot].ld_entry->le_thread = NULL;
860 		p->p_zombcnt++;
861 		cv_broadcast(&p->p_lwpexit);
862 	}
863 	if (t->t_proc_flag & TP_DAEMON) {
864 		p->p_lwpdaemon--;
865 		t->t_proc_flag &= ~TP_DAEMON;
866 	}
867 	t->t_proc_flag &= ~TP_TWAIT;
868 
869 	/*
870 	 * Maintain accurate lwp count for task.max-lwps resource control.
871 	 */
872 	mutex_enter(&p->p_zone->zone_nlwps_lock);
873 	p->p_task->tk_nlwps--;
874 	p->p_task->tk_proj->kpj_nlwps--;
875 	p->p_zone->zone_nlwps--;
876 	mutex_exit(&p->p_zone->zone_nlwps_lock);
877 
878 	CL_EXIT(t);		/* tell the scheduler that t is exiting */
879 	ASSERT(p->p_lwpcnt != 0);
880 	p->p_lwpcnt--;
881 
882 	/*
883 	 * If all remaining non-daemon lwps are waiting in lwp_wait(),
884 	 * wake them up so someone can return EDEADLK.
885 	 * (See the block comment preceeding lwp_wait().)
886 	 */
887 	if (p->p_lwpcnt == p->p_lwpdaemon + (p->p_lwpwait - p->p_lwpdwait))
888 		cv_broadcast(&p->p_lwpexit);
889 
890 	t->t_proc_flag |= TP_LWPEXIT;
891 	term_mstate(t);
892 
893 #ifndef NPROBE
894 	/* Kernel probe */
895 	if (t->t_tnf_tpdp)
896 		tnf_thread_exit();
897 #endif /* NPROBE */
898 
899 	t->t_forw->t_back = t->t_back;
900 	t->t_back->t_forw = t->t_forw;
901 	if (t == p->p_tlist)
902 		p->p_tlist = t->t_forw;
903 
904 	/*
905 	 * Clean up the signal state.
906 	 */
907 	if (t->t_sigqueue != NULL)
908 		sigdelq(p, t, 0);
909 	if (lwp->lwp_curinfo != NULL) {
910 		siginfofree(lwp->lwp_curinfo);
911 		lwp->lwp_curinfo = NULL;
912 	}
913 
914 	thread_rele(t);
915 
916 	/*
917 	 * Terminated lwps are associated with process zero and are put onto
918 	 * death-row by resume().  Avoid preemption after resetting t->t_procp.
919 	 */
920 	t->t_preempt++;
921 
922 	if (t->t_ctx != NULL)
923 		exitctx(t);
924 	if (p->p_pctx != NULL)
925 		exitpctx(p);
926 
927 	t->t_procp = &p0;
928 
929 	/*
930 	 * Notify the HAT about the change of address space
931 	 */
932 	hat_thread_exit(t);
933 	/*
934 	 * When this is the last running lwp in this process and some lwp is
935 	 * waiting for this condition to become true, or this thread was being
936 	 * suspended, then the waiting lwp is awakened.
937 	 *
938 	 * Also, if the process is exiting, we may have a thread waiting in
939 	 * exitlwps() that needs to be notified.
940 	 */
941 	if (--p->p_lwprcnt == 0 || (t->t_proc_flag & TP_HOLDLWP) ||
942 	    (p->p_flag & SEXITLWPS))
943 		cv_broadcast(&p->p_holdlwps);
944 
945 	/*
946 	 * Need to drop p_lock so we can reacquire pidlock.
947 	 */
948 	mutex_exit(&p->p_lock);
949 	mutex_enter(&pidlock);
950 
951 	ASSERT(t != t->t_next);		/* t0 never exits */
952 	t->t_next->t_prev = t->t_prev;
953 	t->t_prev->t_next = t->t_next;
954 	cv_broadcast(&t->t_joincv);	/* wake up anyone in thread_join */
955 	mutex_exit(&pidlock);
956 
957 	lwp_pcb_exit();
958 
959 	t->t_state = TS_ZOMB;
960 	swtch_from_zombie();
961 	/* never returns */
962 }
963 
964 
965 /*
966  * Cleanup function for an exiting lwp.
967  * Called both from lwp_exit() and from proc_exit().
968  * p->p_lock is repeatedly released and grabbed in this function.
969  */
970 void
971 lwp_cleanup(void)
972 {
973 	kthread_t *t = curthread;
974 	proc_t *p = ttoproc(t);
975 
976 	ASSERT(MUTEX_HELD(&p->p_lock));
977 
978 	/* untimeout any lwp-bound realtime timers */
979 	if (p->p_itimer != NULL)
980 		timer_lwpexit();
981 
982 	/*
983 	 * If this is the /proc agent lwp that is exiting, readjust p_lwpid
984 	 * so it appears that the agent never existed, and clear p_agenttp.
985 	 */
986 	if (t == p->p_agenttp) {
987 		ASSERT(t->t_tid == p->p_lwpid);
988 		p->p_lwpid--;
989 		p->p_agenttp = NULL;
990 	}
991 
992 	/*
993 	 * Do lgroup bookkeeping to account for thread exiting.
994 	 */
995 	kpreempt_disable();
996 	lgrp_move_thread(t, NULL, 1);
997 	if (t->t_tid == 1) {
998 		p->p_t1_lgrpid = LGRP_NONE;
999 	}
1000 	kpreempt_enable();
1001 
1002 	lwp_ctmpl_clear(ttolwp(t));
1003 }
1004 
1005 int
1006 lwp_suspend(kthread_t *t)
1007 {
1008 	int tid;
1009 	proc_t *p = ttoproc(t);
1010 
1011 	ASSERT(MUTEX_HELD(&p->p_lock));
1012 
1013 	/*
1014 	 * Set the thread's TP_HOLDLWP flag so it will stop in holdlwp().
1015 	 * If an lwp is stopping itself, there is no need to wait.
1016 	 */
1017 top:
1018 	t->t_proc_flag |= TP_HOLDLWP;
1019 	if (t == curthread) {
1020 		t->t_sig_check = 1;
1021 	} else {
1022 		/*
1023 		 * Make sure the lwp stops promptly.
1024 		 */
1025 		thread_lock(t);
1026 		t->t_sig_check = 1;
1027 		/*
1028 		 * XXX Should use virtual stop like /proc does instead of
1029 		 * XXX waking the thread to get it to stop.
1030 		 */
1031 		if (ISWAKEABLE(t) || ISWAITING(t)) {
1032 			setrun_locked(t);
1033 		} else if (t->t_state == TS_ONPROC && t->t_cpu != CPU) {
1034 			poke_cpu(t->t_cpu->cpu_id);
1035 		}
1036 
1037 		tid = t->t_tid;	 /* remember thread ID */
1038 		/*
1039 		 * Wait for lwp to stop
1040 		 */
1041 		while (!SUSPENDED(t)) {
1042 			/*
1043 			 * Drop the thread lock before waiting and reacquire it
1044 			 * afterwards, so the thread can change its t_state
1045 			 * field.
1046 			 */
1047 			thread_unlock(t);
1048 
1049 			/*
1050 			 * Check if aborted by exitlwps().
1051 			 */
1052 			if (p->p_flag & SEXITLWPS)
1053 				lwp_exit();
1054 
1055 			/*
1056 			 * Cooperate with jobcontrol signals and /proc stopping
1057 			 * by calling cv_wait_sig() to wait for the target
1058 			 * lwp to stop.  Just using cv_wait() can lead to
1059 			 * deadlock because, if some other lwp has stopped
1060 			 * by either of these mechanisms, then p_lwprcnt will
1061 			 * never become zero if we do a cv_wait().
1062 			 */
1063 			if (!cv_wait_sig(&p->p_holdlwps, &p->p_lock))
1064 				return (EINTR);
1065 
1066 			/*
1067 			 * Check to see if thread died while we were
1068 			 * waiting for it to suspend.
1069 			 */
1070 			if (idtot(p, tid) == NULL)
1071 				return (ESRCH);
1072 
1073 			thread_lock(t);
1074 			/*
1075 			 * If the TP_HOLDLWP flag went away, lwp_continue()
1076 			 * or vfork() must have been called while we were
1077 			 * waiting, so start over again.
1078 			 */
1079 			if ((t->t_proc_flag & TP_HOLDLWP) == 0) {
1080 				thread_unlock(t);
1081 				goto top;
1082 			}
1083 		}
1084 		thread_unlock(t);
1085 	}
1086 	return (0);
1087 }
1088 
1089 /*
1090  * continue a lwp that's been stopped by lwp_suspend().
1091  */
1092 void
1093 lwp_continue(kthread_t *t)
1094 {
1095 	proc_t *p = ttoproc(t);
1096 	int was_suspended = t->t_proc_flag & TP_HOLDLWP;
1097 
1098 	ASSERT(MUTEX_HELD(&p->p_lock));
1099 
1100 	t->t_proc_flag &= ~TP_HOLDLWP;
1101 	thread_lock(t);
1102 	if (SUSPENDED(t) &&
1103 	    !(p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH))) {
1104 		p->p_lwprcnt++;
1105 		t->t_schedflag |= TS_CSTART;
1106 		setrun_locked(t);
1107 	}
1108 	thread_unlock(t);
1109 	/*
1110 	 * Wakeup anyone waiting for this thread to be suspended
1111 	 */
1112 	if (was_suspended)
1113 		cv_broadcast(&p->p_holdlwps);
1114 }
1115 
1116 /*
1117  * ********************************
1118  *  Miscellaneous lwp routines	  *
1119  * ********************************
1120  */
1121 /*
1122  * When a process is undergoing a forkall(), its p_flag is set to SHOLDFORK.
1123  * This will cause the process's lwps to stop at a hold point.  A hold
1124  * point is where a kernel thread has a flat stack.  This is at the
1125  * return from a system call and at the return from a user level trap.
1126  *
1127  * When a process is undergoing a fork1() or vfork(), its p_flag is set to
1128  * SHOLDFORK1.  This will cause the process's lwps to stop at a modified
1129  * hold point.  The lwps in the process are not being cloned, so they
1130  * are held at the usual hold points and also within issig_forreal().
1131  * This has the side-effect that their system calls do not return
1132  * showing EINTR.
1133  *
1134  * An lwp can also be held.  This is identified by the TP_HOLDLWP flag on
1135  * the thread.  The TP_HOLDLWP flag is set in lwp_suspend(), where the active
1136  * lwp is waiting for the target lwp to be stopped.
1137  */
1138 void
1139 holdlwp(void)
1140 {
1141 	proc_t *p = curproc;
1142 	kthread_t *t = curthread;
1143 
1144 	mutex_enter(&p->p_lock);
1145 	/*
1146 	 * Don't terminate immediately if the process is dumping core.
1147 	 * Once the process has dumped core, all lwps are terminated.
1148 	 */
1149 	if (!(p->p_flag & SCOREDUMP)) {
1150 		if ((p->p_flag & SEXITLWPS) || (t->t_proc_flag & TP_EXITLWP))
1151 			lwp_exit();
1152 	}
1153 	if (!(ISHOLD(p)) && !(p->p_flag & (SHOLDFORK1 | SHOLDWATCH))) {
1154 		mutex_exit(&p->p_lock);
1155 		return;
1156 	}
1157 	/*
1158 	 * stop() decrements p->p_lwprcnt and cv_signal()s &p->p_holdlwps
1159 	 * when p->p_lwprcnt becomes zero.
1160 	 */
1161 	stop(PR_SUSPENDED, SUSPEND_NORMAL);
1162 	if (p->p_flag & SEXITLWPS)
1163 		lwp_exit();
1164 	mutex_exit(&p->p_lock);
1165 }
1166 
1167 /*
1168  * Have all lwps within the process hold at a point where they are
1169  * cloneable (SHOLDFORK) or just safe w.r.t. fork1 (SHOLDFORK1).
1170  */
1171 int
1172 holdlwps(int holdflag)
1173 {
1174 	proc_t *p = curproc;
1175 
1176 	ASSERT(holdflag == SHOLDFORK || holdflag == SHOLDFORK1);
1177 	mutex_enter(&p->p_lock);
1178 	schedctl_finish_sigblock(curthread);
1179 again:
1180 	while (p->p_flag & (SEXITLWPS | SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) {
1181 		/*
1182 		 * If another lwp is doing a forkall() or proc_exit(), bail out.
1183 		 */
1184 		if (p->p_flag & (SEXITLWPS | SHOLDFORK)) {
1185 			mutex_exit(&p->p_lock);
1186 			return (0);
1187 		}
1188 		/*
1189 		 * Another lwp is doing a fork1() or is undergoing
1190 		 * watchpoint activity.  We hold here for it to complete.
1191 		 */
1192 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1193 	}
1194 	p->p_flag |= holdflag;
1195 	pokelwps(p);
1196 	--p->p_lwprcnt;
1197 	/*
1198 	 * Wait for the process to become quiescent (p->p_lwprcnt == 0).
1199 	 */
1200 	while (p->p_lwprcnt > 0) {
1201 		/*
1202 		 * Check if aborted by exitlwps().
1203 		 * Also check if SHOLDWATCH is set; it takes precedence.
1204 		 */
1205 		if (p->p_flag & (SEXITLWPS | SHOLDWATCH)) {
1206 			p->p_lwprcnt++;
1207 			p->p_flag &= ~holdflag;
1208 			cv_broadcast(&p->p_holdlwps);
1209 			goto again;
1210 		}
1211 		/*
1212 		 * Cooperate with jobcontrol signals and /proc stopping.
1213 		 * If some other lwp has stopped by either of these
1214 		 * mechanisms, then p_lwprcnt will never become zero
1215 		 * and the process will appear deadlocked unless we
1216 		 * stop here in sympathy with the other lwp before
1217 		 * doing the cv_wait() below.
1218 		 *
1219 		 * If the other lwp stops after we do the cv_wait(), it
1220 		 * will wake us up to loop around and do the sympathy stop.
1221 		 *
1222 		 * Since stop() drops p->p_lock, we must start from
1223 		 * the top again on returning from stop().
1224 		 */
1225 		if (p->p_stopsig | (curthread->t_proc_flag & TP_PRSTOP)) {
1226 			int whystop = p->p_stopsig? PR_JOBCONTROL :
1227 			    PR_REQUESTED;
1228 			p->p_lwprcnt++;
1229 			p->p_flag &= ~holdflag;
1230 			stop(whystop, p->p_stopsig);
1231 			goto again;
1232 		}
1233 		cv_wait(&p->p_holdlwps, &p->p_lock);
1234 	}
1235 	p->p_lwprcnt++;
1236 	p->p_flag &= ~holdflag;
1237 	mutex_exit(&p->p_lock);
1238 	return (1);
1239 }
1240 
1241 /*
1242  * See comments for holdwatch(), below.
1243  */
1244 static int
1245 holdcheck(int clearflags)
1246 {
1247 	proc_t *p = curproc;
1248 
1249 	/*
1250 	 * If we are trying to exit, that takes precedence over anything else.
1251 	 */
1252 	if (p->p_flag & SEXITLWPS) {
1253 		p->p_lwprcnt++;
1254 		p->p_flag &= ~clearflags;
1255 		lwp_exit();
1256 	}
1257 
1258 	/*
1259 	 * If another thread is calling fork1(), stop the current thread so the
1260 	 * other can complete.
1261 	 */
1262 	if (p->p_flag & SHOLDFORK1) {
1263 		p->p_lwprcnt++;
1264 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1265 		if (p->p_flag & SEXITLWPS) {
1266 			p->p_flag &= ~clearflags;
1267 			lwp_exit();
1268 		}
1269 		return (-1);
1270 	}
1271 
1272 	/*
1273 	 * If another thread is calling fork(), then indicate we are doing
1274 	 * watchpoint activity.  This will cause holdlwps() above to stop the
1275 	 * forking thread, at which point we can continue with watchpoint
1276 	 * activity.
1277 	 */
1278 	if (p->p_flag & SHOLDFORK) {
1279 		p->p_lwprcnt++;
1280 		while (p->p_flag & SHOLDFORK) {
1281 			p->p_flag |= SHOLDWATCH;
1282 			cv_broadcast(&p->p_holdlwps);
1283 			cv_wait(&p->p_holdlwps, &p->p_lock);
1284 			p->p_flag &= ~SHOLDWATCH;
1285 		}
1286 		return (-1);
1287 	}
1288 
1289 	return (0);
1290 }
1291 
1292 /*
1293  * Stop all lwps within the process, holding themselves in the kernel while the
1294  * active lwp undergoes watchpoint activity.  This is more complicated than
1295  * expected because stop() relies on calling holdwatch() in order to copyin data
1296  * from the user's address space.  A double barrier is used to prevent an
1297  * infinite loop.
1298  *
1299  * 	o The first thread into holdwatch() is the 'master' thread and does
1300  *        the following:
1301  *
1302  *              - Sets SHOLDWATCH on the current process
1303  *              - Sets TP_WATCHSTOP on the current thread
1304  *              - Waits for all threads to be either stopped or have
1305  *                TP_WATCHSTOP set.
1306  *              - Sets the SWATCHOK flag on the process
1307  *              - Unsets TP_WATCHSTOP
1308  *              - Waits for the other threads to completely stop
1309  *              - Unsets SWATCHOK
1310  *
1311  * 	o If SHOLDWATCH is already set when we enter this function, then another
1312  *        thread is already trying to stop this thread.  This 'slave' thread
1313  *        does the following:
1314  *
1315  *              - Sets TP_WATCHSTOP on the current thread
1316  *              - Waits for SWATCHOK flag to be set
1317  *              - Calls stop()
1318  *
1319  * 	o If SWATCHOK is set on the process, then this function immediately
1320  *        returns, as we must have been called via stop().
1321  *
1322  * In addition, there are other flags that take precedence over SHOLDWATCH:
1323  *
1324  * 	o If SEXITLWPS is set, exit immediately.
1325  *
1326  * 	o If SHOLDFORK1 is set, wait for fork1() to complete.
1327  *
1328  * 	o If SHOLDFORK is set, then watchpoint activity takes precedence In this
1329  *        case, set SHOLDWATCH, signalling the forking thread to stop first.
1330  *
1331  * 	o If the process is being stopped via /proc (TP_PRSTOP is set), then we
1332  *        stop the current thread.
1333  *
1334  * Returns 0 if all threads have been quiesced.  Returns non-zero if not all
1335  * threads were stopped, or the list of watched pages has changed.
1336  */
1337 int
1338 holdwatch(void)
1339 {
1340 	proc_t *p = curproc;
1341 	kthread_t *t = curthread;
1342 	int ret = 0;
1343 
1344 	mutex_enter(&p->p_lock);
1345 
1346 	p->p_lwprcnt--;
1347 
1348 	/*
1349 	 * Check for bail-out conditions as outlined above.
1350 	 */
1351 	if (holdcheck(0) != 0) {
1352 		mutex_exit(&p->p_lock);
1353 		return (-1);
1354 	}
1355 
1356 	if (!(p->p_flag & SHOLDWATCH)) {
1357 		/*
1358 		 * We are the master watchpoint thread.  Set SHOLDWATCH and poke
1359 		 * the other threads.
1360 		 */
1361 		p->p_flag |= SHOLDWATCH;
1362 		pokelwps(p);
1363 
1364 		/*
1365 		 * Wait for all threads to be stopped or have TP_WATCHSTOP set.
1366 		 */
1367 		while (pr_allstopped(p, 1) > 0) {
1368 			if (holdcheck(SHOLDWATCH) != 0) {
1369 				p->p_flag &= ~SHOLDWATCH;
1370 				mutex_exit(&p->p_lock);
1371 				return (-1);
1372 			}
1373 
1374 			cv_wait(&p->p_holdlwps, &p->p_lock);
1375 		}
1376 
1377 		/*
1378 		 * All threads are now stopped or in the process of stopping.
1379 		 * Set SWATCHOK and let them stop completely.
1380 		 */
1381 		p->p_flag |= SWATCHOK;
1382 		t->t_proc_flag &= ~TP_WATCHSTOP;
1383 		cv_broadcast(&p->p_holdlwps);
1384 
1385 		while (pr_allstopped(p, 0) > 0) {
1386 			/*
1387 			 * At first glance, it may appear that we don't need a
1388 			 * call to holdcheck() here.  But if the process gets a
1389 			 * SIGKILL signal, one of our stopped threads may have
1390 			 * been awakened and is waiting in exitlwps(), which
1391 			 * takes precedence over watchpoints.
1392 			 */
1393 			if (holdcheck(SHOLDWATCH | SWATCHOK) != 0) {
1394 				p->p_flag &= ~(SHOLDWATCH | SWATCHOK);
1395 				mutex_exit(&p->p_lock);
1396 				return (-1);
1397 			}
1398 
1399 			cv_wait(&p->p_holdlwps, &p->p_lock);
1400 		}
1401 
1402 		/*
1403 		 * All threads are now completely stopped.
1404 		 */
1405 		p->p_flag &= ~SWATCHOK;
1406 		p->p_flag &= ~SHOLDWATCH;
1407 		p->p_lwprcnt++;
1408 
1409 	} else if (!(p->p_flag & SWATCHOK)) {
1410 
1411 		/*
1412 		 * SHOLDWATCH is set, so another thread is trying to do
1413 		 * watchpoint activity.  Indicate this thread is stopping, and
1414 		 * wait for the OK from the master thread.
1415 		 */
1416 		t->t_proc_flag |= TP_WATCHSTOP;
1417 		cv_broadcast(&p->p_holdlwps);
1418 
1419 		while (!(p->p_flag & SWATCHOK)) {
1420 			if (holdcheck(0) != 0) {
1421 				t->t_proc_flag &= ~TP_WATCHSTOP;
1422 				mutex_exit(&p->p_lock);
1423 				return (-1);
1424 			}
1425 
1426 			cv_wait(&p->p_holdlwps, &p->p_lock);
1427 		}
1428 
1429 		/*
1430 		 * Once the master thread has given the OK, this thread can
1431 		 * actually call stop().
1432 		 */
1433 		t->t_proc_flag &= ~TP_WATCHSTOP;
1434 		p->p_lwprcnt++;
1435 
1436 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1437 
1438 		/*
1439 		 * It's not OK to do watchpoint activity, notify caller to
1440 		 * retry.
1441 		 */
1442 		ret = -1;
1443 
1444 	} else {
1445 
1446 		/*
1447 		 * The only way we can hit the case where SHOLDWATCH is set and
1448 		 * SWATCHOK is set is if we are triggering this from within a
1449 		 * stop() call.  Assert that this is the case.
1450 		 */
1451 
1452 		ASSERT(t->t_proc_flag & TP_STOPPING);
1453 		p->p_lwprcnt++;
1454 	}
1455 
1456 	mutex_exit(&p->p_lock);
1457 
1458 	return (ret);
1459 }
1460 
1461 /*
1462  * force all interruptible lwps to trap into the kernel.
1463  */
1464 void
1465 pokelwps(proc_t *p)
1466 {
1467 	kthread_t *t;
1468 
1469 	ASSERT(MUTEX_HELD(&p->p_lock));
1470 
1471 	t = p->p_tlist;
1472 	do {
1473 		if (t == curthread)
1474 			continue;
1475 		thread_lock(t);
1476 		aston(t);	/* make thread trap or do post_syscall */
1477 		if (ISWAKEABLE(t) || ISWAITING(t)) {
1478 			setrun_locked(t);
1479 		} else if (t->t_state == TS_STOPPED) {
1480 			/*
1481 			 * Ensure that proc_exit() is not blocked by lwps
1482 			 * that were stopped via jobcontrol or /proc.
1483 			 */
1484 			if (p->p_flag & SEXITLWPS) {
1485 				p->p_stopsig = 0;
1486 				t->t_schedflag |= (TS_XSTART | TS_PSTART);
1487 				setrun_locked(t);
1488 			}
1489 			/*
1490 			 * If we are holding lwps for a forkall(),
1491 			 * force lwps that have been suspended via
1492 			 * lwp_suspend() and are suspended inside
1493 			 * of a system call to proceed to their
1494 			 * holdlwp() points where they are clonable.
1495 			 */
1496 			if ((p->p_flag & SHOLDFORK) && SUSPENDED(t)) {
1497 				if ((t->t_schedflag & TS_CSTART) == 0) {
1498 					p->p_lwprcnt++;
1499 					t->t_schedflag |= TS_CSTART;
1500 					setrun_locked(t);
1501 				}
1502 			}
1503 		} else if (t->t_state == TS_ONPROC) {
1504 			if (t->t_cpu != CPU)
1505 				poke_cpu(t->t_cpu->cpu_id);
1506 		}
1507 		thread_unlock(t);
1508 	} while ((t = t->t_forw) != p->p_tlist);
1509 }
1510 
1511 /*
1512  * undo the effects of holdlwps() or holdwatch().
1513  */
1514 void
1515 continuelwps(proc_t *p)
1516 {
1517 	kthread_t *t;
1518 
1519 	/*
1520 	 * If this flag is set, then the original holdwatch() didn't actually
1521 	 * stop the process.  See comments for holdwatch().
1522 	 */
1523 	if (p->p_flag & SWATCHOK) {
1524 		ASSERT(curthread->t_proc_flag & TP_STOPPING);
1525 		return;
1526 	}
1527 
1528 	ASSERT(MUTEX_HELD(&p->p_lock));
1529 	ASSERT((p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) == 0);
1530 
1531 	t = p->p_tlist;
1532 	do {
1533 		thread_lock(t);		/* SUSPENDED looks at t_schedflag */
1534 		if (SUSPENDED(t) && !(t->t_proc_flag & TP_HOLDLWP)) {
1535 			p->p_lwprcnt++;
1536 			t->t_schedflag |= TS_CSTART;
1537 			setrun_locked(t);
1538 		}
1539 		thread_unlock(t);
1540 	} while ((t = t->t_forw) != p->p_tlist);
1541 }
1542 
1543 /*
1544  * Force all other LWPs in the current process other than the caller to exit,
1545  * and then cv_wait() on p_holdlwps for them to exit.  The exitlwps() function
1546  * is typically used in these situations:
1547  *
1548  *   (a) prior to an exec() system call
1549  *   (b) prior to dumping a core file
1550  *   (c) prior to a uadmin() shutdown
1551  *
1552  * If the 'coredump' flag is set, other LWPs are quiesced but not destroyed.
1553  * Multiple threads in the process can call this function at one time by
1554  * triggering execs or core dumps simultaneously, so the SEXITLWPS bit is used
1555  * to declare one particular thread the winner who gets to kill the others.
1556  * If a thread wins the exitlwps() dance, zero is returned; otherwise an
1557  * appropriate errno value is returned to caller for its system call to return.
1558  */
1559 int
1560 exitlwps(int coredump)
1561 {
1562 	proc_t *p = curproc;
1563 	int heldcnt;
1564 
1565 	if (curthread->t_door)
1566 		door_slam();
1567 	if (p->p_door_list)
1568 		door_revoke_all();
1569 	if (curthread->t_schedctl != NULL)
1570 		schedctl_lwp_cleanup(curthread);
1571 
1572 	/*
1573 	 * Ensure that before starting to wait for other lwps to exit,
1574 	 * cleanup all upimutexes held by curthread. Otherwise, some other
1575 	 * lwp could be waiting (uninterruptibly) for a upimutex held by
1576 	 * curthread, and the call to pokelwps() below would deadlock.
1577 	 * Even if a blocked upimutex_lock is made interruptible,
1578 	 * curthread's upimutexes need to be unlocked: do it here.
1579 	 */
1580 	if (curthread->t_upimutex != NULL)
1581 		upimutex_cleanup();
1582 
1583 	/*
1584 	 * Grab p_lock in order to check and set SEXITLWPS to declare a winner.
1585 	 * We must also block any further /proc access from this point forward.
1586 	 */
1587 	mutex_enter(&p->p_lock);
1588 	prbarrier(p);
1589 
1590 	if (p->p_flag & SEXITLWPS) {
1591 		mutex_exit(&p->p_lock);
1592 		aston(curthread);	/* force a trip through post_syscall */
1593 		return (set_errno(EINTR));
1594 	}
1595 
1596 	p->p_flag |= SEXITLWPS;
1597 	if (coredump)		/* tell other lwps to stop, not exit */
1598 		p->p_flag |= SCOREDUMP;
1599 
1600 	/*
1601 	 * Give precedence to exitlwps() if a holdlwps() is
1602 	 * in progress. The lwp doing the holdlwps() operation
1603 	 * is aborted when it is awakened.
1604 	 */
1605 	while (p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) {
1606 		cv_broadcast(&p->p_holdlwps);
1607 		cv_wait(&p->p_holdlwps, &p->p_lock);
1608 		prbarrier(p);
1609 	}
1610 	p->p_flag |= SHOLDFORK;
1611 	pokelwps(p);
1612 
1613 	/*
1614 	 * Wait for process to become quiescent.
1615 	 */
1616 	--p->p_lwprcnt;
1617 	while (p->p_lwprcnt > 0) {
1618 		cv_wait(&p->p_holdlwps, &p->p_lock);
1619 		prbarrier(p);
1620 	}
1621 	p->p_lwprcnt++;
1622 	ASSERT(p->p_lwprcnt == 1);
1623 
1624 	/*
1625 	 * The SCOREDUMP flag puts the process into a quiescent
1626 	 * state.  The process's lwps remain attached to this
1627 	 * process until exitlwps() is called again without the
1628 	 * 'coredump' flag set, then the lwps are terminated
1629 	 * and the process can exit.
1630 	 */
1631 	if (coredump) {
1632 		p->p_flag &= ~(SCOREDUMP | SHOLDFORK | SEXITLWPS);
1633 		goto out;
1634 	}
1635 
1636 	/*
1637 	 * Determine if there are any lwps left dangling in
1638 	 * the stopped state.  This happens when exitlwps()
1639 	 * aborts a holdlwps() operation.
1640 	 */
1641 	p->p_flag &= ~SHOLDFORK;
1642 	if ((heldcnt = p->p_lwpcnt) > 1) {
1643 		kthread_t *t;
1644 		for (t = curthread->t_forw; --heldcnt > 0; t = t->t_forw) {
1645 			t->t_proc_flag &= ~TP_TWAIT;
1646 			lwp_continue(t);
1647 		}
1648 	}
1649 
1650 	/*
1651 	 * Wait for all other lwps to exit.
1652 	 */
1653 	--p->p_lwprcnt;
1654 	while (p->p_lwpcnt > 1) {
1655 		cv_wait(&p->p_holdlwps, &p->p_lock);
1656 		prbarrier(p);
1657 	}
1658 	++p->p_lwprcnt;
1659 	ASSERT(p->p_lwpcnt == 1 && p->p_lwprcnt == 1);
1660 
1661 	p->p_flag &= ~SEXITLWPS;
1662 	curthread->t_proc_flag &= ~TP_TWAIT;
1663 
1664 out:
1665 	if (!coredump && p->p_zombcnt) {	/* cleanup the zombie lwps */
1666 		lwpdir_t *ldp;
1667 		lwpent_t *lep;
1668 		int i;
1669 
1670 		for (ldp = p->p_lwpdir, i = 0; i < p->p_lwpdir_sz; i++, ldp++) {
1671 			lep = ldp->ld_entry;
1672 			if (lep != NULL && lep->le_thread != curthread) {
1673 				ASSERT(lep->le_thread == NULL);
1674 				p->p_zombcnt--;
1675 				lwp_hash_out(p, lep->le_lwpid);
1676 			}
1677 		}
1678 		ASSERT(p->p_zombcnt == 0);
1679 	}
1680 
1681 	/*
1682 	 * If some other LWP in the process wanted us to suspend ourself,
1683 	 * then we will not do it.  The other LWP is now terminated and
1684 	 * no one will ever continue us again if we suspend ourself.
1685 	 */
1686 	curthread->t_proc_flag &= ~TP_HOLDLWP;
1687 	p->p_flag &= ~(SHOLDFORK | SHOLDFORK1 | SHOLDWATCH | SLWPWRAP);
1688 	mutex_exit(&p->p_lock);
1689 	return (0);
1690 }
1691 
1692 /*
1693  * duplicate a lwp.
1694  */
1695 klwp_t *
1696 forklwp(klwp_t *lwp, proc_t *cp, id_t lwpid)
1697 {
1698 	klwp_t *clwp;
1699 	void *tregs, *tfpu;
1700 	kthread_t *t = lwptot(lwp);
1701 	kthread_t *ct;
1702 	proc_t *p = lwptoproc(lwp);
1703 	int cid;
1704 	void *bufp;
1705 	void *brand_data;
1706 	int val;
1707 
1708 	ASSERT(p == curproc);
1709 	ASSERT(t == curthread || (SUSPENDED(t) && lwp->lwp_asleep == 0));
1710 
1711 #if defined(__sparc)
1712 	if (t == curthread)
1713 		(void) flush_user_windows_to_stack(NULL);
1714 #endif
1715 
1716 	if (t == curthread)
1717 		/* copy args out of registers first */
1718 		(void) save_syscall_args();
1719 
1720 	clwp = lwp_create(cp->p_lwpcnt == 0 ? lwp_rtt_initial : lwp_rtt,
1721 	    NULL, 0, cp, TS_STOPPED, t->t_pri, &t->t_hold, NOCLASS, lwpid);
1722 	if (clwp == NULL)
1723 		return (NULL);
1724 
1725 	/*
1726 	 * most of the parent's lwp can be copied to its duplicate,
1727 	 * except for the fields that are unique to each lwp, like
1728 	 * lwp_thread, lwp_procp, lwp_regs, and lwp_ap.
1729 	 */
1730 	ct = clwp->lwp_thread;
1731 	tregs = clwp->lwp_regs;
1732 	tfpu = clwp->lwp_fpu;
1733 	brand_data = clwp->lwp_brand;
1734 
1735 	/*
1736 	 * Copy parent lwp to child lwp.  Hold child's p_lock to prevent
1737 	 * mstate_aggr_state() from reading stale mstate entries copied
1738 	 * from lwp to clwp.
1739 	 */
1740 	mutex_enter(&cp->p_lock);
1741 	*clwp = *lwp;
1742 
1743 	/* clear microstate and resource usage data in new lwp */
1744 	init_mstate(ct, LMS_STOPPED);
1745 	bzero(&clwp->lwp_ru, sizeof (clwp->lwp_ru));
1746 	mutex_exit(&cp->p_lock);
1747 
1748 	/* fix up child's lwp */
1749 
1750 	clwp->lwp_pcb.pcb_flags = 0;
1751 #if defined(__sparc)
1752 	clwp->lwp_pcb.pcb_step = STEP_NONE;
1753 #endif
1754 	clwp->lwp_cursig = 0;
1755 	clwp->lwp_extsig = 0;
1756 	clwp->lwp_curinfo = (struct sigqueue *)0;
1757 	clwp->lwp_thread = ct;
1758 	ct->t_sysnum = t->t_sysnum;
1759 	clwp->lwp_regs = tregs;
1760 	clwp->lwp_fpu = tfpu;
1761 	clwp->lwp_brand = brand_data;
1762 	clwp->lwp_ap = clwp->lwp_arg;
1763 	clwp->lwp_procp = cp;
1764 	bzero(clwp->lwp_timer, sizeof (clwp->lwp_timer));
1765 	clwp->lwp_lastfault = 0;
1766 	clwp->lwp_lastfaddr = 0;
1767 
1768 	/* copy parent's struct regs to child. */
1769 	lwp_forkregs(lwp, clwp);
1770 
1771 	/*
1772 	 * Fork thread context ops, if any.
1773 	 */
1774 	if (t->t_ctx)
1775 		forkctx(t, ct);
1776 
1777 	/* fix door state in the child */
1778 	if (t->t_door)
1779 		door_fork(t, ct);
1780 
1781 	/* copy current contract templates, clear latest contracts */
1782 	lwp_ctmpl_copy(clwp, lwp);
1783 
1784 	mutex_enter(&cp->p_lock);
1785 	/* lwp_create() set the TP_HOLDLWP flag */
1786 	if (!(t->t_proc_flag & TP_HOLDLWP))
1787 		ct->t_proc_flag &= ~TP_HOLDLWP;
1788 	if (cp->p_flag & SMSACCT)
1789 		ct->t_proc_flag |= TP_MSACCT;
1790 	mutex_exit(&cp->p_lock);
1791 
1792 	/* Allow brand to propagate brand-specific state */
1793 	if (PROC_IS_BRANDED(p))
1794 		BROP(p)->b_forklwp(lwp, clwp);
1795 
1796 retry:
1797 	cid = t->t_cid;
1798 
1799 	val = CL_ALLOC(&bufp, cid, KM_SLEEP);
1800 	ASSERT(val == 0);
1801 
1802 	mutex_enter(&p->p_lock);
1803 	if (cid != t->t_cid) {
1804 		/*
1805 		 * Someone just changed this thread's scheduling class,
1806 		 * so try pre-allocating the buffer again.  Hopefully we
1807 		 * don't hit this often.
1808 		 */
1809 		mutex_exit(&p->p_lock);
1810 		CL_FREE(cid, bufp);
1811 		goto retry;
1812 	}
1813 
1814 	ct->t_unpark = t->t_unpark;
1815 	ct->t_clfuncs = t->t_clfuncs;
1816 	CL_FORK(t, ct, bufp);
1817 	ct->t_cid = t->t_cid;	/* after data allocated so prgetpsinfo works */
1818 	mutex_exit(&p->p_lock);
1819 
1820 	return (clwp);
1821 }
1822 
1823 /*
1824  * Add a new lwp entry to the lwp directory and to the lwpid hash table.
1825  */
1826 void
1827 lwp_hash_in(proc_t *p, lwpent_t *lep, tidhash_t *tidhash, uint_t tidhash_sz,
1828     int do_lock)
1829 {
1830 	tidhash_t *thp = &tidhash[TIDHASH(lep->le_lwpid, tidhash_sz)];
1831 	lwpdir_t **ldpp;
1832 	lwpdir_t *ldp;
1833 	kthread_t *t;
1834 
1835 	/*
1836 	 * Allocate a directory element from the free list.
1837 	 * Code elsewhere guarantees a free slot.
1838 	 */
1839 	ldp = p->p_lwpfree;
1840 	p->p_lwpfree = ldp->ld_next;
1841 	ASSERT(ldp->ld_entry == NULL);
1842 	ldp->ld_entry = lep;
1843 
1844 	if (do_lock)
1845 		mutex_enter(&thp->th_lock);
1846 
1847 	/*
1848 	 * Insert it into the lwpid hash table.
1849 	 */
1850 	ldpp = &thp->th_list;
1851 	ldp->ld_next = *ldpp;
1852 	*ldpp = ldp;
1853 
1854 	/*
1855 	 * Set the active thread's directory slot entry.
1856 	 */
1857 	if ((t = lep->le_thread) != NULL) {
1858 		ASSERT(lep->le_lwpid == t->t_tid);
1859 		t->t_dslot = (int)(ldp - p->p_lwpdir);
1860 	}
1861 
1862 	if (do_lock)
1863 		mutex_exit(&thp->th_lock);
1864 }
1865 
1866 /*
1867  * Remove an lwp from the lwpid hash table and free its directory entry.
1868  * This is done when a detached lwp exits in lwp_exit() or
1869  * when a non-detached lwp is waited for in lwp_wait() or
1870  * when a zombie lwp is detached in lwp_detach().
1871  */
1872 void
1873 lwp_hash_out(proc_t *p, id_t lwpid)
1874 {
1875 	tidhash_t *thp = &p->p_tidhash[TIDHASH(lwpid, p->p_tidhash_sz)];
1876 	lwpdir_t **ldpp;
1877 	lwpdir_t *ldp;
1878 	lwpent_t *lep;
1879 
1880 	mutex_enter(&thp->th_lock);
1881 	for (ldpp = &thp->th_list;
1882 	    (ldp = *ldpp) != NULL; ldpp = &ldp->ld_next) {
1883 		lep = ldp->ld_entry;
1884 		if (lep->le_lwpid == lwpid) {
1885 			prlwpfree(p, lep);	/* /proc deals with le_trace */
1886 			*ldpp = ldp->ld_next;
1887 			ldp->ld_entry = NULL;
1888 			ldp->ld_next = p->p_lwpfree;
1889 			p->p_lwpfree = ldp;
1890 			kmem_free(lep, sizeof (*lep));
1891 			break;
1892 		}
1893 	}
1894 	mutex_exit(&thp->th_lock);
1895 }
1896 
1897 /*
1898  * Lookup an lwp in the lwpid hash table by lwpid.
1899  */
1900 lwpdir_t *
1901 lwp_hash_lookup(proc_t *p, id_t lwpid)
1902 {
1903 	tidhash_t *thp;
1904 	lwpdir_t *ldp;
1905 
1906 	/*
1907 	 * The process may be exiting, after p_tidhash has been set to NULL in
1908 	 * proc_exit() but before prfee() has been called.  Return failure in
1909 	 * this case.
1910 	 */
1911 	if (p->p_tidhash == NULL)
1912 		return (NULL);
1913 
1914 	thp = &p->p_tidhash[TIDHASH(lwpid, p->p_tidhash_sz)];
1915 	for (ldp = thp->th_list; ldp != NULL; ldp = ldp->ld_next) {
1916 		if (ldp->ld_entry->le_lwpid == lwpid)
1917 			return (ldp);
1918 	}
1919 
1920 	return (NULL);
1921 }
1922 
1923 /*
1924  * Same as lwp_hash_lookup(), but acquire and return
1925  * the tid hash table entry lock on success.
1926  */
1927 lwpdir_t *
1928 lwp_hash_lookup_and_lock(proc_t *p, id_t lwpid, kmutex_t **mpp)
1929 {
1930 	tidhash_t *tidhash;
1931 	uint_t tidhash_sz;
1932 	tidhash_t *thp;
1933 	lwpdir_t *ldp;
1934 
1935 top:
1936 	tidhash_sz = p->p_tidhash_sz;
1937 	membar_consumer();
1938 	if ((tidhash = p->p_tidhash) == NULL)
1939 		return (NULL);
1940 
1941 	thp = &tidhash[TIDHASH(lwpid, tidhash_sz)];
1942 	mutex_enter(&thp->th_lock);
1943 
1944 	/*
1945 	 * Since we are not holding p->p_lock, the tid hash table
1946 	 * may have changed.  If so, start over.  If not, then
1947 	 * it cannot change until after we drop &thp->th_lock;
1948 	 */
1949 	if (tidhash != p->p_tidhash || tidhash_sz != p->p_tidhash_sz) {
1950 		mutex_exit(&thp->th_lock);
1951 		goto top;
1952 	}
1953 
1954 	for (ldp = thp->th_list; ldp != NULL; ldp = ldp->ld_next) {
1955 		if (ldp->ld_entry->le_lwpid == lwpid) {
1956 			*mpp = &thp->th_lock;
1957 			return (ldp);
1958 		}
1959 	}
1960 
1961 	mutex_exit(&thp->th_lock);
1962 	return (NULL);
1963 }
1964 
1965 /*
1966  * Update the indicated LWP usage statistic for the current LWP.
1967  */
1968 void
1969 lwp_stat_update(lwp_stat_id_t lwp_stat_id, long inc)
1970 {
1971 	klwp_t *lwp = ttolwp(curthread);
1972 
1973 	if (lwp == NULL)
1974 		return;
1975 
1976 	switch (lwp_stat_id) {
1977 	case LWP_STAT_INBLK:
1978 		lwp->lwp_ru.inblock += inc;
1979 		break;
1980 	case LWP_STAT_OUBLK:
1981 		lwp->lwp_ru.oublock += inc;
1982 		break;
1983 	case LWP_STAT_MSGRCV:
1984 		lwp->lwp_ru.msgrcv += inc;
1985 		break;
1986 	case LWP_STAT_MSGSND:
1987 		lwp->lwp_ru.msgsnd += inc;
1988 		break;
1989 	default:
1990 		panic("lwp_stat_update: invalid lwp_stat_id 0x%x", lwp_stat_id);
1991 	}
1992 }
1993