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