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