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