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