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