xref: /titanic_41/usr/src/uts/common/os/lwp.c (revision c719c59a5efa45b0a47db940384816b4ed77db7d)
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 2005 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 	t->t_procp = &p0;
789 
790 	/*
791 	 * Notify the HAT about the change of address space
792 	 */
793 	hat_thread_exit(t);
794 	/*
795 	 * When this is the last running lwp in this process and some lwp is
796 	 * waiting for this condition to become true, or this thread was being
797 	 * suspended, then the waiting lwp is awakened.
798 	 *
799 	 * Also, if the process is exiting, we may have a thread waiting in
800 	 * exitlwps() that needs to be notified.
801 	 */
802 	if (--p->p_lwprcnt == 0 || (t->t_proc_flag & TP_HOLDLWP) ||
803 	    (p->p_flag & SEXITLWPS))
804 		cv_broadcast(&p->p_holdlwps);
805 
806 	/*
807 	 * Need to drop p_lock so we can reacquire pidlock.
808 	 */
809 	mutex_exit(&p->p_lock);
810 	mutex_enter(&pidlock);
811 
812 	ASSERT(t != t->t_next);		/* t0 never exits */
813 	t->t_next->t_prev = t->t_prev;
814 	t->t_prev->t_next = t->t_next;
815 	cv_broadcast(&t->t_joincv);	/* wake up anyone in thread_join */
816 	mutex_exit(&pidlock);
817 
818 	lwp_pcb_exit();
819 
820 	if (t->t_ctx != NULL)
821 		exitctx(t);
822 
823 	t->t_state = TS_ZOMB;
824 	swtch_from_zombie();
825 	/* never returns */
826 }
827 
828 
829 /*
830  * Cleanup function for an exiting lwp.
831  * Called both from lwp_exit() and from proc_exit().
832  * p->p_lock is repeatedly released and grabbed in this function.
833  */
834 void
835 lwp_cleanup(void)
836 {
837 	kthread_t *t = curthread;
838 	proc_t *p = ttoproc(t);
839 
840 	ASSERT(MUTEX_HELD(&p->p_lock));
841 
842 	/* untimeout any lwp-bound realtime timers */
843 	if (p->p_itimer != NULL)
844 		timer_lwpexit();
845 
846 	/*
847 	 * If this is the /proc agent lwp that is exiting, readjust p_lwpid
848 	 * so it appears that the agent never existed, and clear p_agenttp.
849 	 */
850 	if (t == p->p_agenttp) {
851 		ASSERT(t->t_tid == p->p_lwpid);
852 		p->p_lwpid--;
853 		p->p_agenttp = NULL;
854 	}
855 
856 	/*
857 	 * Do lgroup bookkeeping to account for thread exiting.
858 	 */
859 	kpreempt_disable();
860 	lgrp_move_thread(t, NULL, 1);
861 	kpreempt_enable();
862 
863 	lwp_ctmpl_clear(ttolwp(t));
864 }
865 
866 int
867 lwp_suspend(kthread_t *t)
868 {
869 	int tid;
870 	proc_t *p = ttoproc(t);
871 
872 	ASSERT(MUTEX_HELD(&p->p_lock));
873 
874 	/*
875 	 * Set the thread's TP_HOLDLWP flag so it will stop in holdlwp().
876 	 * If an lwp is stopping itself, there is no need to wait.
877 	 */
878 	t->t_proc_flag |= TP_HOLDLWP;
879 	if (t == curthread) {
880 		t->t_sig_check = 1;
881 	} else {
882 		/*
883 		 * Make sure the lwp stops promptly.
884 		 */
885 		thread_lock(t);
886 		t->t_sig_check = 1;
887 		/*
888 		 * XXX Should use virtual stop like /proc does instead of
889 		 * XXX waking the thread to get it to stop.
890 		 */
891 		if (t->t_state == TS_SLEEP && (t->t_flag & T_WAKEABLE))
892 			setrun_locked(t);
893 		else if (t->t_state == TS_ONPROC && t->t_cpu != CPU)
894 			poke_cpu(t->t_cpu->cpu_id);
895 		tid = t->t_tid;	 /* remember thread ID */
896 		/*
897 		 * Wait for lwp to stop
898 		 */
899 		while (!SUSPENDED(t)) {
900 			/*
901 			 * Drop the thread lock before waiting and reacquire it
902 			 * afterwards, so the thread can change its t_state
903 			 * field.
904 			 */
905 			thread_unlock(t);
906 
907 			/*
908 			 * Check if aborted by exitlwps().
909 			 */
910 			if (p->p_flag & SEXITLWPS)
911 				lwp_exit();
912 
913 			/*
914 			 * Cooperate with jobcontrol signals and /proc stopping
915 			 * by calling cv_wait_sig() to wait for the target
916 			 * lwp to stop.  Just using cv_wait() can lead to
917 			 * deadlock because, if some other lwp has stopped
918 			 * by either of these mechanisms, then p_lwprcnt will
919 			 * never become zero if we do a cv_wait().
920 			 */
921 			if (!cv_wait_sig(&p->p_holdlwps, &p->p_lock))
922 				return (EINTR);
923 
924 			/*
925 			 * Check to see if thread died while we were
926 			 * waiting for it to suspend.
927 			 */
928 			if (idtot(p, tid) == NULL)
929 				return (ESRCH);
930 
931 			thread_lock(t);
932 			/*
933 			 * If TP_HOLDLWP flag goes away, lwp_continue() must
934 			 * have been called while we were waiting, so cancel
935 			 * the suspend.
936 			 */
937 			if ((t->t_proc_flag & TP_HOLDLWP) == 0) {
938 				thread_unlock(t);
939 				return (0);
940 			}
941 		}
942 		thread_unlock(t);
943 	}
944 	return (0);
945 }
946 
947 /*
948  * continue a lwp that's been stopped by lwp_suspend().
949  */
950 void
951 lwp_continue(kthread_t *t)
952 {
953 	proc_t *p = ttoproc(t);
954 	int was_suspended = t->t_proc_flag & TP_HOLDLWP;
955 
956 	ASSERT(MUTEX_HELD(&p->p_lock));
957 
958 	t->t_proc_flag &= ~TP_HOLDLWP;
959 	thread_lock(t);
960 	if (SUSPENDED(t) &&
961 	    !(p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH))) {
962 		p->p_lwprcnt++;
963 		t->t_schedflag |= TS_CSTART;
964 		setrun_locked(t);
965 	}
966 	thread_unlock(t);
967 	/*
968 	 * Wakeup anyone waiting for this thread to be suspended
969 	 */
970 	if (was_suspended)
971 		cv_broadcast(&p->p_holdlwps);
972 }
973 
974 /*
975  * ********************************
976  *  Miscellaneous lwp routines	  *
977  * ********************************
978  */
979 /*
980  * When a process is undergoing a forkall(), its p_flag is set to SHOLDFORK.
981  * This will cause the process's lwps to stop at a hold point.  A hold
982  * point is where a kernel thread has a flat stack.  This is at the
983  * return from a system call and at the return from a user level trap.
984  *
985  * When a process is undergoing a fork1() or vfork(), its p_flag is set to
986  * SHOLDFORK1.  This will cause the process's lwps to stop at a modified
987  * hold point.  The lwps in the process are not being cloned, so they
988  * are held at the usual hold points and also within issig_forreal().
989  * This has the side-effect that their system calls do not return
990  * showing EINTR.
991  *
992  * An lwp can also be held.  This is identified by the TP_HOLDLWP flag on
993  * the thread.  The TP_HOLDLWP flag is set in lwp_suspend(), where the active
994  * lwp is waiting for the target lwp to be stopped.
995  */
996 void
997 holdlwp(void)
998 {
999 	proc_t *p = curproc;
1000 	kthread_t *t = curthread;
1001 
1002 	mutex_enter(&p->p_lock);
1003 	/*
1004 	 * Don't terminate immediately if the process is dumping core.
1005 	 * Once the process has dumped core, all lwps are terminated.
1006 	 */
1007 	if (!(p->p_flag & SCOREDUMP)) {
1008 		if ((p->p_flag & SEXITLWPS) || (t->t_proc_flag & TP_EXITLWP))
1009 			lwp_exit();
1010 	}
1011 	if (!(ISHOLD(p)) && !(p->p_flag & (SHOLDFORK1 | SHOLDWATCH))) {
1012 		mutex_exit(&p->p_lock);
1013 		return;
1014 	}
1015 	/*
1016 	 * stop() decrements p->p_lwprcnt and cv_signal()s &p->p_holdlwps
1017 	 * when p->p_lwprcnt becomes zero.
1018 	 */
1019 	stop(PR_SUSPENDED, SUSPEND_NORMAL);
1020 	if (p->p_flag & SEXITLWPS)
1021 		lwp_exit();
1022 	mutex_exit(&p->p_lock);
1023 }
1024 
1025 /*
1026  * Have all lwps within the process hold at a point where they are
1027  * cloneable (SHOLDFORK) or just safe w.r.t. fork1 (SHOLDFORK1).
1028  */
1029 int
1030 holdlwps(int holdflag)
1031 {
1032 	proc_t *p = curproc;
1033 
1034 	ASSERT(holdflag == SHOLDFORK || holdflag == SHOLDFORK1);
1035 	mutex_enter(&p->p_lock);
1036 	schedctl_finish_sigblock(curthread);
1037 again:
1038 	while (p->p_flag & (SEXITLWPS | SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) {
1039 		/*
1040 		 * If another lwp is doing a forkall() or proc_exit(), bail out.
1041 		 */
1042 		if (p->p_flag & (SEXITLWPS | SHOLDFORK)) {
1043 			mutex_exit(&p->p_lock);
1044 			return (0);
1045 		}
1046 		/*
1047 		 * Another lwp is doing a fork1() or is undergoing
1048 		 * watchpoint activity.  We hold here for it to complete.
1049 		 */
1050 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1051 	}
1052 	p->p_flag |= holdflag;
1053 	pokelwps(p);
1054 	--p->p_lwprcnt;
1055 	/*
1056 	 * Wait for the process to become quiescent (p->p_lwprcnt == 0).
1057 	 */
1058 	while (p->p_lwprcnt > 0) {
1059 		/*
1060 		 * Check if aborted by exitlwps().
1061 		 * Also check if SHOLDWATCH is set; it takes precedence.
1062 		 */
1063 		if (p->p_flag & (SEXITLWPS | SHOLDWATCH)) {
1064 			p->p_lwprcnt++;
1065 			p->p_flag &= ~holdflag;
1066 			cv_broadcast(&p->p_holdlwps);
1067 			goto again;
1068 		}
1069 		/*
1070 		 * Cooperate with jobcontrol signals and /proc stopping.
1071 		 * If some other lwp has stopped by either of these
1072 		 * mechanisms, then p_lwprcnt will never become zero
1073 		 * and the process will appear deadlocked unless we
1074 		 * stop here in sympathy with the other lwp before
1075 		 * doing the cv_wait() below.
1076 		 *
1077 		 * If the other lwp stops after we do the cv_wait(), it
1078 		 * will wake us up to loop around and do the sympathy stop.
1079 		 *
1080 		 * Since stop() drops p->p_lock, we must start from
1081 		 * the top again on returning from stop().
1082 		 */
1083 		if (p->p_stopsig | (curthread->t_proc_flag & TP_PRSTOP)) {
1084 			int whystop = p->p_stopsig? PR_JOBCONTROL :
1085 			    PR_REQUESTED;
1086 			p->p_lwprcnt++;
1087 			p->p_flag &= ~holdflag;
1088 			stop(whystop, p->p_stopsig);
1089 			goto again;
1090 		}
1091 		cv_wait(&p->p_holdlwps, &p->p_lock);
1092 	}
1093 	p->p_lwprcnt++;
1094 	p->p_flag &= ~holdflag;
1095 	mutex_exit(&p->p_lock);
1096 	return (1);
1097 }
1098 
1099 /*
1100  * See comments for holdwatch(), below.
1101  */
1102 static int
1103 holdcheck(int clearflags)
1104 {
1105 	proc_t *p = curproc;
1106 
1107 	/*
1108 	 * If we are trying to exit, that takes precedence over anything else.
1109 	 */
1110 	if (p->p_flag & SEXITLWPS) {
1111 		p->p_lwprcnt++;
1112 		p->p_flag &= ~clearflags;
1113 		lwp_exit();
1114 	}
1115 
1116 	/*
1117 	 * If another thread is calling fork1(), stop the current thread so the
1118 	 * other can complete.
1119 	 */
1120 	if (p->p_flag & SHOLDFORK1) {
1121 		p->p_lwprcnt++;
1122 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1123 		if (p->p_flag & SEXITLWPS) {
1124 			p->p_flag &= ~clearflags;
1125 			lwp_exit();
1126 		}
1127 		return (-1);
1128 	}
1129 
1130 	/*
1131 	 * If another thread is calling fork(), then indicate we are doing
1132 	 * watchpoint activity.  This will cause holdlwps() above to stop the
1133 	 * forking thread, at which point we can continue with watchpoint
1134 	 * activity.
1135 	 */
1136 	if (p->p_flag & SHOLDFORK) {
1137 		p->p_lwprcnt++;
1138 		while (p->p_flag & SHOLDFORK) {
1139 			p->p_flag |= SHOLDWATCH;
1140 			cv_broadcast(&p->p_holdlwps);
1141 			cv_wait(&p->p_holdlwps, &p->p_lock);
1142 			p->p_flag &= ~SHOLDWATCH;
1143 		}
1144 		return (-1);
1145 	}
1146 
1147 	return (0);
1148 }
1149 
1150 /*
1151  * Stop all lwps within the process, holding themselves in the kernel while the
1152  * active lwp undergoes watchpoint activity.  This is more complicated than
1153  * expected because stop() relies on calling holdwatch() in order to copyin data
1154  * from the user's address space.  A double barrier is used to prevent an
1155  * infinite loop.
1156  *
1157  * 	o The first thread into holdwatch() is the 'master' thread and does
1158  *        the following:
1159  *
1160  *              - Sets SHOLDWATCH on the current process
1161  *              - Sets TP_WATCHSTOP on the current thread
1162  *              - Waits for all threads to be either stopped or have
1163  *                TP_WATCHSTOP set.
1164  *              - Sets the SWATCHOK flag on the process
1165  *              - Unsets TP_WATCHSTOP
1166  *              - Waits for the other threads to completely stop
1167  *              - Unsets SWATCHOK
1168  *
1169  * 	o If SHOLDWATCH is already set when we enter this function, then another
1170  *        thread is already trying to stop this thread.  This 'slave' thread
1171  *        does the following:
1172  *
1173  *              - Sets TP_WATCHSTOP on the current thread
1174  *              - Waits for SWATCHOK flag to be set
1175  *              - Calls stop()
1176  *
1177  * 	o If SWATCHOK is set on the process, then this function immediately
1178  *        returns, as we must have been called via stop().
1179  *
1180  * In addition, there are other flags that take precedence over SHOLDWATCH:
1181  *
1182  * 	o If SEXITLWPS is set, exit immediately.
1183  *
1184  * 	o If SHOLDFORK1 is set, wait for fork1() to complete.
1185  *
1186  * 	o If SHOLDFORK is set, then watchpoint activity takes precedence In this
1187  *        case, set SHOLDWATCH, signalling the forking thread to stop first.
1188  *
1189  * 	o If the process is being stopped via /proc (TP_PRSTOP is set), then we
1190  *        stop the current thread.
1191  *
1192  * Returns 0 if all threads have been quiesced.  Returns non-zero if not all
1193  * threads were stopped, or the list of watched pages has changed.
1194  */
1195 int
1196 holdwatch(void)
1197 {
1198 	proc_t *p = curproc;
1199 	kthread_t *t = curthread;
1200 	int ret = 0;
1201 
1202 	mutex_enter(&p->p_lock);
1203 
1204 	p->p_lwprcnt--;
1205 
1206 	/*
1207 	 * Check for bail-out conditions as outlined above.
1208 	 */
1209 	if (holdcheck(0) != 0) {
1210 		mutex_exit(&p->p_lock);
1211 		return (-1);
1212 	}
1213 
1214 	if (!(p->p_flag & SHOLDWATCH)) {
1215 		/*
1216 		 * We are the master watchpoint thread.  Set SHOLDWATCH and poke
1217 		 * the other threads.
1218 		 */
1219 		p->p_flag |= SHOLDWATCH;
1220 		pokelwps(p);
1221 
1222 		/*
1223 		 * Wait for all threads to be stopped or have TP_WATCHSTOP set.
1224 		 */
1225 		while (pr_allstopped(p, 1) > 0) {
1226 			if (holdcheck(SHOLDWATCH) != 0) {
1227 				p->p_flag &= ~SHOLDWATCH;
1228 				mutex_exit(&p->p_lock);
1229 				return (-1);
1230 			}
1231 
1232 			cv_wait(&p->p_holdlwps, &p->p_lock);
1233 		}
1234 
1235 		/*
1236 		 * All threads are now stopped or in the process of stopping.
1237 		 * Set SWATCHOK and let them stop completely.
1238 		 */
1239 		p->p_flag |= SWATCHOK;
1240 		t->t_proc_flag &= ~TP_WATCHSTOP;
1241 		cv_broadcast(&p->p_holdlwps);
1242 
1243 		while (pr_allstopped(p, 0) > 0) {
1244 			/*
1245 			 * At first glance, it may appear that we don't need a
1246 			 * call to holdcheck() here.  But if the process gets a
1247 			 * SIGKILL signal, one of our stopped threads may have
1248 			 * been awakened and is waiting in exitlwps(), which
1249 			 * takes precedence over watchpoints.
1250 			 */
1251 			if (holdcheck(SHOLDWATCH | SWATCHOK) != 0) {
1252 				p->p_flag &= ~(SHOLDWATCH | SWATCHOK);
1253 				mutex_exit(&p->p_lock);
1254 				return (-1);
1255 			}
1256 
1257 			cv_wait(&p->p_holdlwps, &p->p_lock);
1258 		}
1259 
1260 		/*
1261 		 * All threads are now completely stopped.
1262 		 */
1263 		p->p_flag &= ~SWATCHOK;
1264 		p->p_flag &= ~SHOLDWATCH;
1265 		p->p_lwprcnt++;
1266 
1267 	} else if (!(p->p_flag & SWATCHOK)) {
1268 
1269 		/*
1270 		 * SHOLDWATCH is set, so another thread is trying to do
1271 		 * watchpoint activity.  Indicate this thread is stopping, and
1272 		 * wait for the OK from the master thread.
1273 		 */
1274 		t->t_proc_flag |= TP_WATCHSTOP;
1275 		cv_broadcast(&p->p_holdlwps);
1276 
1277 		while (!(p->p_flag & SWATCHOK)) {
1278 			if (holdcheck(0) != 0) {
1279 				t->t_proc_flag &= ~TP_WATCHSTOP;
1280 				mutex_exit(&p->p_lock);
1281 				return (-1);
1282 			}
1283 
1284 			cv_wait(&p->p_holdlwps, &p->p_lock);
1285 		}
1286 
1287 		/*
1288 		 * Once the master thread has given the OK, this thread can
1289 		 * actually call stop().
1290 		 */
1291 		t->t_proc_flag &= ~TP_WATCHSTOP;
1292 		p->p_lwprcnt++;
1293 
1294 		stop(PR_SUSPENDED, SUSPEND_NORMAL);
1295 
1296 		/*
1297 		 * It's not OK to do watchpoint activity, notify caller to
1298 		 * retry.
1299 		 */
1300 		ret = -1;
1301 
1302 	} else {
1303 
1304 		/*
1305 		 * The only way we can hit the case where SHOLDWATCH is set and
1306 		 * SWATCHOK is set is if we are triggering this from within a
1307 		 * stop() call.  Assert that this is the case.
1308 		 */
1309 
1310 		ASSERT(t->t_proc_flag & TP_STOPPING);
1311 		p->p_lwprcnt++;
1312 	}
1313 
1314 	mutex_exit(&p->p_lock);
1315 
1316 	return (ret);
1317 }
1318 
1319 /*
1320  * force all interruptible lwps to trap into the kernel.
1321  */
1322 void
1323 pokelwps(proc_t *p)
1324 {
1325 	kthread_t *t;
1326 
1327 	ASSERT(MUTEX_HELD(&p->p_lock));
1328 
1329 	t = p->p_tlist;
1330 	do {
1331 		if (t == curthread)
1332 			continue;
1333 		thread_lock(t);
1334 		aston(t);	/* make thread trap or do post_syscall */
1335 		if (t->t_state == TS_SLEEP) {
1336 			if (t->t_flag & T_WAKEABLE)
1337 				setrun_locked(t);
1338 		} else if (t->t_state == TS_STOPPED) {
1339 			/*
1340 			 * Ensure that proc_exit() is not blocked by lwps
1341 			 * that were stopped via jobcontrol or /proc.
1342 			 */
1343 			if (p->p_flag & SEXITLWPS) {
1344 				p->p_stopsig = 0;
1345 				t->t_schedflag |= (TS_XSTART | TS_PSTART);
1346 				setrun_locked(t);
1347 			}
1348 			/*
1349 			 * If we are holding lwps for a forkall(),
1350 			 * force lwps that have been suspended via
1351 			 * lwp_suspend() and are suspended inside
1352 			 * of a system call to proceed to their
1353 			 * holdlwp() points where they are clonable.
1354 			 */
1355 			if ((p->p_flag & SHOLDFORK) && SUSPENDED(t)) {
1356 				if ((t->t_schedflag & TS_CSTART) == 0) {
1357 					p->p_lwprcnt++;
1358 					t->t_schedflag |= TS_CSTART;
1359 					setrun_locked(t);
1360 				}
1361 			}
1362 		} else if (t->t_state == TS_ONPROC) {
1363 			if (t->t_cpu != CPU)
1364 				poke_cpu(t->t_cpu->cpu_id);
1365 		}
1366 		thread_unlock(t);
1367 	} while ((t = t->t_forw) != p->p_tlist);
1368 }
1369 
1370 /*
1371  * undo the effects of holdlwps() or holdwatch().
1372  */
1373 void
1374 continuelwps(proc_t *p)
1375 {
1376 	kthread_t *t;
1377 
1378 	/*
1379 	 * If this flag is set, then the original holdwatch() didn't actually
1380 	 * stop the process.  See comments for holdwatch().
1381 	 */
1382 	if (p->p_flag & SWATCHOK) {
1383 		ASSERT(curthread->t_proc_flag & TP_STOPPING);
1384 		return;
1385 	}
1386 
1387 	ASSERT(MUTEX_HELD(&p->p_lock));
1388 	ASSERT((p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) == 0);
1389 
1390 	t = p->p_tlist;
1391 	do {
1392 		thread_lock(t);		/* SUSPENDED looks at t_schedflag */
1393 		if (SUSPENDED(t) && !(t->t_proc_flag & TP_HOLDLWP)) {
1394 			p->p_lwprcnt++;
1395 			t->t_schedflag |= TS_CSTART;
1396 			setrun_locked(t);
1397 		}
1398 		thread_unlock(t);
1399 	} while ((t = t->t_forw) != p->p_tlist);
1400 }
1401 
1402 /*
1403  * Force all other LWPs in the current process other than the caller to exit,
1404  * and then cv_wait() on p_holdlwps for them to exit.  The exitlwps() function
1405  * is typically used in these situations:
1406  *
1407  *   (a) prior to an exec() system call
1408  *   (b) prior to dumping a core file
1409  *   (c) prior to a uadmin() shutdown
1410  *
1411  * If the 'coredump' flag is set, other LWPs are quiesced but not destroyed.
1412  * Multiple threads in the process can call this function at one time by
1413  * triggering execs or core dumps simultaneously, so the SEXITLWPS bit is used
1414  * to declare one particular thread the winner who gets to kill the others.
1415  * If a thread wins the exitlwps() dance, zero is returned; otherwise an
1416  * appropriate errno value is returned to caller for its system call to return.
1417  */
1418 int
1419 exitlwps(int coredump)
1420 {
1421 	proc_t *p = curproc;
1422 	int heldcnt;
1423 
1424 	if (curthread->t_door)
1425 		door_slam();
1426 	if (p->p_door_list)
1427 		door_revoke_all();
1428 	if (curthread->t_schedctl != NULL)
1429 		schedctl_lwp_cleanup(curthread);
1430 
1431 	/*
1432 	 * Ensure that before starting to wait for other lwps to exit,
1433 	 * cleanup all upimutexes held by curthread. Otherwise, some other
1434 	 * lwp could be waiting (uninterruptibly) for a upimutex held by
1435 	 * curthread, and the call to pokelwps() below would deadlock.
1436 	 * Even if a blocked upimutex_lock is made interruptible,
1437 	 * curthread's upimutexes need to be unlocked: do it here.
1438 	 */
1439 	if (curthread->t_upimutex != NULL)
1440 		upimutex_cleanup();
1441 
1442 	/*
1443 	 * Grab p_lock in order to check and set SEXITLWPS to declare a winner.
1444 	 * We must also block any further /proc access from this point forward.
1445 	 */
1446 	mutex_enter(&p->p_lock);
1447 	prbarrier(p);
1448 
1449 	if (p->p_flag & SEXITLWPS) {
1450 		mutex_exit(&p->p_lock);
1451 		aston(curthread);	/* force a trip through post_syscall */
1452 		return (set_errno(EINTR));
1453 	}
1454 
1455 	p->p_flag |= SEXITLWPS;
1456 	if (coredump)		/* tell other lwps to stop, not exit */
1457 		p->p_flag |= SCOREDUMP;
1458 
1459 	/*
1460 	 * Give precedence to exitlwps() if a holdlwps() is
1461 	 * in progress. The lwp doing the holdlwps() operation
1462 	 * is aborted when it is awakened.
1463 	 */
1464 	while (p->p_flag & (SHOLDFORK | SHOLDFORK1 | SHOLDWATCH)) {
1465 		cv_broadcast(&p->p_holdlwps);
1466 		cv_wait(&p->p_holdlwps, &p->p_lock);
1467 		prbarrier(p);
1468 	}
1469 	p->p_flag |= SHOLDFORK;
1470 	pokelwps(p);
1471 
1472 	/*
1473 	 * Wait for process to become quiescent.
1474 	 */
1475 	--p->p_lwprcnt;
1476 	while (p->p_lwprcnt > 0) {
1477 		cv_wait(&p->p_holdlwps, &p->p_lock);
1478 		prbarrier(p);
1479 	}
1480 	p->p_lwprcnt++;
1481 	ASSERT(p->p_lwprcnt == 1);
1482 
1483 	/*
1484 	 * The SCOREDUMP flag puts the process into a quiescent
1485 	 * state.  The process's lwps remain attached to this
1486 	 * process until exitlwps() is called again without the
1487 	 * 'coredump' flag set, then the lwps are terminated
1488 	 * and the process can exit.
1489 	 */
1490 	if (coredump) {
1491 		p->p_flag &= ~(SCOREDUMP | SHOLDFORK | SEXITLWPS);
1492 		goto out;
1493 	}
1494 
1495 	/*
1496 	 * Determine if there are any lwps left dangling in
1497 	 * the stopped state.  This happens when exitlwps()
1498 	 * aborts a holdlwps() operation.
1499 	 */
1500 	p->p_flag &= ~SHOLDFORK;
1501 	if ((heldcnt = p->p_lwpcnt) > 1) {
1502 		kthread_t *t;
1503 		for (t = curthread->t_forw; --heldcnt > 0; t = t->t_forw) {
1504 			t->t_proc_flag &= ~TP_TWAIT;
1505 			lwp_continue(t);
1506 		}
1507 	}
1508 
1509 	/*
1510 	 * Wait for all other lwps to exit.
1511 	 */
1512 	--p->p_lwprcnt;
1513 	while (p->p_lwpcnt > 1) {
1514 		cv_wait(&p->p_holdlwps, &p->p_lock);
1515 		prbarrier(p);
1516 	}
1517 	++p->p_lwprcnt;
1518 	ASSERT(p->p_lwpcnt == 1 && p->p_lwprcnt == 1);
1519 
1520 	p->p_flag &= ~SEXITLWPS;
1521 	curthread->t_proc_flag &= ~TP_TWAIT;
1522 
1523 out:
1524 	if (!coredump && p->p_zombcnt) {	/* cleanup the zombie lwps */
1525 		lwpdir_t *ldp;
1526 		lwpent_t *lep;
1527 		int i;
1528 
1529 		for (ldp = p->p_lwpdir, i = 0; i < p->p_lwpdir_sz; i++, ldp++) {
1530 			lep = ldp->ld_entry;
1531 			if (lep != NULL && lep->le_thread != curthread) {
1532 				ASSERT(lep->le_thread == NULL);
1533 				p->p_zombcnt--;
1534 				lwp_hash_out(p, lep->le_lwpid);
1535 			}
1536 		}
1537 		ASSERT(p->p_zombcnt == 0);
1538 	}
1539 
1540 	/*
1541 	 * If some other LWP in the process wanted us to suspend ourself,
1542 	 * then we will not do it.  The other LWP is now terminated and
1543 	 * no one will ever continue us again if we suspend ourself.
1544 	 */
1545 	curthread->t_proc_flag &= ~TP_HOLDLWP;
1546 	p->p_flag &= ~(SHOLDFORK | SHOLDFORK1 | SHOLDWATCH | SLWPWRAP);
1547 	mutex_exit(&p->p_lock);
1548 	return (0);
1549 }
1550 
1551 /*
1552  * duplicate a lwp.
1553  */
1554 klwp_t *
1555 forklwp(klwp_t *lwp, proc_t *cp, id_t lwpid)
1556 {
1557 	klwp_t *clwp;
1558 	void *tregs, *tfpu;
1559 	kthread_t *t = lwptot(lwp);
1560 	kthread_t *ct;
1561 	proc_t *p = lwptoproc(lwp);
1562 	int cid;
1563 	void *bufp;
1564 	int val;
1565 
1566 	ASSERT(p == curproc);
1567 	ASSERT(t == curthread || (SUSPENDED(t) && lwp->lwp_asleep == 0));
1568 
1569 #if defined(__sparc)
1570 	if (t == curthread)
1571 		(void) flush_user_windows_to_stack(NULL);
1572 #endif
1573 
1574 	if (t == curthread)
1575 		/* copy args out of registers first */
1576 		(void) save_syscall_args();
1577 	clwp = lwp_create(cp->p_lwpcnt == 0 ? lwp_rtt_initial : lwp_rtt,
1578 	    NULL, 0, cp, TS_STOPPED, t->t_pri, &t->t_hold, NOCLASS, lwpid);
1579 	if (clwp == NULL)
1580 		return (NULL);
1581 
1582 	/*
1583 	 * most of the parent's lwp can be copied to its duplicate,
1584 	 * except for the fields that are unique to each lwp, like
1585 	 * lwp_thread, lwp_procp, lwp_regs, and lwp_ap.
1586 	 */
1587 	ct = clwp->lwp_thread;
1588 	tregs = clwp->lwp_regs;
1589 	tfpu = clwp->lwp_fpu;
1590 
1591 	/* copy parent lwp to child lwp */
1592 	*clwp = *lwp;
1593 
1594 	/* fix up child's lwp */
1595 
1596 	clwp->lwp_pcb.pcb_flags = 0;
1597 #if defined(__sparc)
1598 	clwp->lwp_pcb.pcb_step = STEP_NONE;
1599 #endif
1600 	clwp->lwp_cursig = 0;
1601 	clwp->lwp_extsig = 0;
1602 	clwp->lwp_curinfo = (struct sigqueue *)0;
1603 	clwp->lwp_thread = ct;
1604 	ct->t_sysnum = t->t_sysnum;
1605 	clwp->lwp_regs = tregs;
1606 	clwp->lwp_fpu = tfpu;
1607 	clwp->lwp_ap = clwp->lwp_arg;
1608 	clwp->lwp_procp = cp;
1609 	bzero(clwp->lwp_timer, sizeof (clwp->lwp_timer));
1610 	init_mstate(ct, LMS_STOPPED);
1611 	bzero(&clwp->lwp_ru, sizeof (clwp->lwp_ru));
1612 	clwp->lwp_lastfault = 0;
1613 	clwp->lwp_lastfaddr = 0;
1614 
1615 	/* copy parent's struct regs to child. */
1616 	lwp_forkregs(lwp, clwp);
1617 
1618 	/*
1619 	 * fork device context, if any.
1620 	 *
1621 	 * Someday we could do the work to support the possibility of
1622 	 * forkctx() or lwp_createctx() failing.  Currently, this would
1623 	 * only be needed on x86 for the occasional process using a
1624 	 * private LDT.
1625 	 */
1626 	if (t->t_ctx)
1627 		forkctx(t, ct);
1628 
1629 	/* fix door state in the child */
1630 	if (t->t_door)
1631 		door_fork(t, ct);
1632 
1633 	/* copy current contract templates, clear latest contracts */
1634 	lwp_ctmpl_copy(clwp, lwp);
1635 
1636 	mutex_enter(&cp->p_lock);
1637 	/* lwp_create() set the TP_HOLDLWP flag */
1638 	if (!(t->t_proc_flag & TP_HOLDLWP))
1639 		ct->t_proc_flag &= ~TP_HOLDLWP;
1640 	if (cp->p_flag & SMSACCT)
1641 		ct->t_proc_flag |= TP_MSACCT;
1642 	mutex_exit(&cp->p_lock);
1643 
1644 retry:
1645 	cid = t->t_cid;
1646 
1647 	val = CL_ALLOC(&bufp, cid, KM_SLEEP);
1648 	ASSERT(val == 0);
1649 
1650 	mutex_enter(&p->p_lock);
1651 	if (cid != t->t_cid) {
1652 		/*
1653 		 * Someone just changed this thread's scheduling class,
1654 		 * so try pre-allocating the buffer again.  Hopefully we
1655 		 * don't hit this often.
1656 		 */
1657 		mutex_exit(&p->p_lock);
1658 		CL_FREE(cid, bufp);
1659 		goto retry;
1660 	}
1661 
1662 	ct->t_unpark = t->t_unpark;
1663 	ct->t_clfuncs = t->t_clfuncs;
1664 	CL_FORK(t, ct, bufp);
1665 	ct->t_cid = t->t_cid;	/* after data allocated so prgetpsinfo works */
1666 	mutex_exit(&p->p_lock);
1667 
1668 	return (clwp);
1669 }
1670 
1671 /*
1672  * Add a new lwp entry to the lwp directory and to the lwpid hash table.
1673  */
1674 void
1675 lwp_hash_in(proc_t *p, lwpent_t *lep)
1676 {
1677 	lwpdir_t **ldpp;
1678 	lwpdir_t *ldp;
1679 	kthread_t *t;
1680 
1681 	/*
1682 	 * Allocate a directory element from the free list.
1683 	 * Code elsewhere guarantees a free slot.
1684 	 */
1685 	ldp = p->p_lwpfree;
1686 	p->p_lwpfree = ldp->ld_next;
1687 	ASSERT(ldp->ld_entry == NULL);
1688 	ldp->ld_entry = lep;
1689 
1690 	/*
1691 	 * Insert it into the lwpid hash table.
1692 	 */
1693 	ldpp = &p->p_tidhash[TIDHASH(p, lep->le_lwpid)];
1694 	ldp->ld_next = *ldpp;
1695 	*ldpp = ldp;
1696 
1697 	/*
1698 	 * Set the active thread's directory slot entry.
1699 	 */
1700 	if ((t = lep->le_thread) != NULL) {
1701 		ASSERT(lep->le_lwpid == t->t_tid);
1702 		t->t_dslot = (int)(ldp - p->p_lwpdir);
1703 	}
1704 }
1705 
1706 /*
1707  * Remove an lwp from the lwpid hash table and free its directory entry.
1708  * This is done when a detached lwp exits in lwp_exit() or
1709  * when a non-detached lwp is waited for in lwp_wait() or
1710  * when a zombie lwp is detached in lwp_detach().
1711  */
1712 void
1713 lwp_hash_out(proc_t *p, id_t lwpid)
1714 {
1715 	lwpdir_t **ldpp;
1716 	lwpdir_t *ldp;
1717 	lwpent_t *lep;
1718 
1719 	for (ldpp = &p->p_tidhash[TIDHASH(p, lwpid)];
1720 	    (ldp = *ldpp) != NULL; ldpp = &ldp->ld_next) {
1721 		lep = ldp->ld_entry;
1722 		if (lep->le_lwpid == lwpid) {
1723 			prlwpfree(p, lep);	/* /proc deals with le_trace */
1724 			*ldpp = ldp->ld_next;
1725 			ldp->ld_entry = NULL;
1726 			ldp->ld_next = p->p_lwpfree;
1727 			p->p_lwpfree = ldp;
1728 			kmem_free(lep, sizeof (*lep));
1729 			break;
1730 		}
1731 	}
1732 }
1733 
1734 /*
1735  * Lookup an lwp in the lwpid hash table by lwpid.
1736  */
1737 lwpdir_t *
1738 lwp_hash_lookup(proc_t *p, id_t lwpid)
1739 {
1740 	lwpdir_t *ldp;
1741 
1742 	/*
1743 	 * The process may be exiting, after p_tidhash has been set to NULL in
1744 	 * proc_exit() but before prfee() has been called.  Return failure in
1745 	 * this case.
1746 	 */
1747 	if (p->p_tidhash == NULL)
1748 		return (NULL);
1749 
1750 	for (ldp = p->p_tidhash[TIDHASH(p, lwpid)];
1751 	    ldp != NULL; ldp = ldp->ld_next) {
1752 		if (ldp->ld_entry->le_lwpid == lwpid)
1753 			return (ldp);
1754 	}
1755 
1756 	return (NULL);
1757 }
1758 
1759 /*
1760  * Update the indicated LWP usage statistic for the current LWP.
1761  */
1762 void
1763 lwp_stat_update(lwp_stat_id_t lwp_stat_id, long inc)
1764 {
1765 	klwp_t *lwp = ttolwp(curthread);
1766 
1767 	if (lwp == NULL)
1768 		return;
1769 
1770 	switch (lwp_stat_id) {
1771 	case LWP_STAT_INBLK:
1772 		lwp->lwp_ru.inblock += inc;
1773 		break;
1774 	case LWP_STAT_OUBLK:
1775 		lwp->lwp_ru.oublock += inc;
1776 		break;
1777 	case LWP_STAT_MSGRCV:
1778 		lwp->lwp_ru.msgrcv += inc;
1779 		break;
1780 	case LWP_STAT_MSGSND:
1781 		lwp->lwp_ru.msgsnd += inc;
1782 		break;
1783 	default:
1784 		panic("lwp_stat_update: invalid lwp_stat_id 0x%x", lwp_stat_id);
1785 	}
1786 }
1787