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