xref: /titanic_50/usr/src/uts/common/disp/thread.c (revision e764d406651fd9ae1eb625acae7fb932af107587)
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  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/sysmacros.h>
31 #include <sys/signal.h>
32 #include <sys/stack.h>
33 #include <sys/pcb.h>
34 #include <sys/user.h>
35 #include <sys/systm.h>
36 #include <sys/sysinfo.h>
37 #include <sys/var.h>
38 #include <sys/errno.h>
39 #include <sys/cmn_err.h>
40 #include <sys/cred.h>
41 #include <sys/resource.h>
42 #include <sys/task.h>
43 #include <sys/project.h>
44 #include <sys/proc.h>
45 #include <sys/debug.h>
46 #include <sys/inline.h>
47 #include <sys/disp.h>
48 #include <sys/class.h>
49 #include <vm/seg_kmem.h>
50 #include <vm/seg_kp.h>
51 #include <sys/machlock.h>
52 #include <sys/kmem.h>
53 #include <sys/varargs.h>
54 #include <sys/turnstile.h>
55 #include <sys/poll.h>
56 #include <sys/vtrace.h>
57 #include <sys/callb.h>
58 #include <c2/audit.h>
59 #include <sys/tnf.h>
60 #include <sys/sobject.h>
61 #include <sys/cpupart.h>
62 #include <sys/pset.h>
63 #include <sys/door.h>
64 #include <sys/spl.h>
65 #include <sys/copyops.h>
66 #include <sys/rctl.h>
67 #include <sys/brand.h>
68 #include <sys/pool.h>
69 #include <sys/zone.h>
70 #include <sys/tsol/label.h>
71 #include <sys/tsol/tndb.h>
72 #include <sys/cpc_impl.h>
73 #include <sys/sdt.h>
74 #include <sys/reboot.h>
75 #include <sys/kdi.h>
76 #include <sys/waitq.h>
77 #include <sys/cpucaps.h>
78 
79 struct kmem_cache *thread_cache;	/* cache of free threads */
80 struct kmem_cache *lwp_cache;		/* cache of free lwps */
81 struct kmem_cache *turnstile_cache;	/* cache of free turnstiles */
82 
83 /*
84  * allthreads is only for use by kmem_readers.  All kernel loops can use
85  * the current thread as a start/end point.
86  */
87 static kthread_t *allthreads = &t0;	/* circular list of all threads */
88 
89 static kcondvar_t reaper_cv;		/* synchronization var */
90 kthread_t	*thread_deathrow;	/* circular list of reapable threads */
91 kthread_t	*lwp_deathrow;		/* circular list of reapable threads */
92 kmutex_t	reaplock;		/* protects lwp and thread deathrows */
93 kmutex_t	thread_free_lock;	/* protects clock from reaper */
94 int	thread_reapcnt = 0;		/* number of threads on deathrow */
95 int	lwp_reapcnt = 0;		/* number of lwps on deathrow */
96 int	reaplimit = 16;			/* delay reaping until reaplimit */
97 
98 extern int nthread;
99 
100 id_t	syscid;				/* system scheduling class ID */
101 void	*segkp_thread;			/* cookie for segkp pool */
102 
103 int lwp_cache_sz = 32;
104 int t_cache_sz = 8;
105 static kt_did_t next_t_id = 1;
106 
107 /*
108  * Min/Max stack sizes for stack size parameters
109  */
110 #define	MAX_STKSIZE	(32 * DEFAULTSTKSZ)
111 #define	MIN_STKSIZE	DEFAULTSTKSZ
112 
113 /*
114  * default_stksize overrides lwp_default_stksize if it is set.
115  */
116 int	default_stksize;
117 int	lwp_default_stksize;
118 
119 static zone_key_t zone_thread_key;
120 
121 /*
122  * forward declarations for internal thread specific data (tsd)
123  */
124 static void *tsd_realloc(void *, size_t, size_t);
125 
126 void thread_reaper(void);
127 
128 /*ARGSUSED*/
129 static int
130 turnstile_constructor(void *buf, void *cdrarg, int kmflags)
131 {
132 	bzero(buf, sizeof (turnstile_t));
133 	return (0);
134 }
135 
136 /*ARGSUSED*/
137 static void
138 turnstile_destructor(void *buf, void *cdrarg)
139 {
140 	turnstile_t *ts = buf;
141 
142 	ASSERT(ts->ts_free == NULL);
143 	ASSERT(ts->ts_waiters == 0);
144 	ASSERT(ts->ts_inheritor == NULL);
145 	ASSERT(ts->ts_sleepq[0].sq_first == NULL);
146 	ASSERT(ts->ts_sleepq[1].sq_first == NULL);
147 }
148 
149 void
150 thread_init(void)
151 {
152 	kthread_t *tp;
153 	extern char sys_name[];
154 	extern void idle();
155 	struct cpu *cpu = CPU;
156 
157 	mutex_init(&reaplock, NULL, MUTEX_SPIN, (void *)ipltospl(DISP_LEVEL));
158 
159 #if defined(__i386) || defined(__amd64)
160 	thread_cache = kmem_cache_create("thread_cache", sizeof (kthread_t),
161 	    PTR24_ALIGN, NULL, NULL, NULL, NULL, NULL, 0);
162 
163 	/*
164 	 * "struct _klwp" includes a "struct pcb", which includes a
165 	 * "struct fpu", which needs to be 16-byte aligned on amd64
166 	 * (and even on i386 for fxsave/fxrstor).
167 	 */
168 	lwp_cache = kmem_cache_create("lwp_cache", sizeof (klwp_t),
169 	    16, NULL, NULL, NULL, NULL, NULL, 0);
170 #else
171 	/*
172 	 * Allocate thread structures from static_arena.  This prevents
173 	 * issues where a thread tries to relocate its own thread
174 	 * structure and touches it after the mapping has been suspended.
175 	 */
176 	thread_cache = kmem_cache_create("thread_cache", sizeof (kthread_t),
177 	    PTR24_ALIGN, NULL, NULL, NULL, NULL, static_arena, 0);
178 
179 	lwp_stk_cache_init();
180 
181 	lwp_cache = kmem_cache_create("lwp_cache", sizeof (klwp_t),
182 	    0, NULL, NULL, NULL, NULL, NULL, 0);
183 #endif
184 
185 	turnstile_cache = kmem_cache_create("turnstile_cache",
186 	    sizeof (turnstile_t), 0,
187 	    turnstile_constructor, turnstile_destructor, NULL, NULL, NULL, 0);
188 
189 	label_init();
190 	cred_init();
191 
192 	/*
193 	 * Initialize various resource management facilities.
194 	 */
195 	rctl_init();
196 	cpucaps_init();
197 	/*
198 	 * Zone_init() should be called before project_init() so that project ID
199 	 * for the first project is initialized correctly.
200 	 */
201 	zone_init();
202 	project_init();
203 	brand_init();
204 	task_init();
205 	tcache_init();
206 	pool_init();
207 
208 	curthread->t_ts = kmem_cache_alloc(turnstile_cache, KM_SLEEP);
209 
210 	/*
211 	 * Originally, we had two parameters to set default stack
212 	 * size: one for lwp's (lwp_default_stksize), and one for
213 	 * kernel-only threads (DEFAULTSTKSZ, a.k.a. _defaultstksz).
214 	 * Now we have a third parameter that overrides both if it is
215 	 * set to a legal stack size, called default_stksize.
216 	 */
217 
218 	if (default_stksize == 0) {
219 		default_stksize = DEFAULTSTKSZ;
220 	} else if (default_stksize % PAGESIZE != 0 ||
221 	    default_stksize > MAX_STKSIZE ||
222 	    default_stksize < MIN_STKSIZE) {
223 		cmn_err(CE_WARN, "Illegal stack size. Using %d",
224 		    (int)DEFAULTSTKSZ);
225 		default_stksize = DEFAULTSTKSZ;
226 	} else {
227 		lwp_default_stksize = default_stksize;
228 	}
229 
230 	if (lwp_default_stksize == 0) {
231 		lwp_default_stksize = default_stksize;
232 	} else if (lwp_default_stksize % PAGESIZE != 0 ||
233 	    lwp_default_stksize > MAX_STKSIZE ||
234 	    lwp_default_stksize < MIN_STKSIZE) {
235 		cmn_err(CE_WARN, "Illegal stack size. Using %d",
236 		    default_stksize);
237 		lwp_default_stksize = default_stksize;
238 	}
239 
240 	segkp_lwp = segkp_cache_init(segkp, lwp_cache_sz,
241 	    lwp_default_stksize,
242 	    (KPD_NOWAIT | KPD_HASREDZONE | KPD_LOCKED));
243 
244 	segkp_thread = segkp_cache_init(segkp, t_cache_sz,
245 	    default_stksize, KPD_HASREDZONE | KPD_LOCKED | KPD_NO_ANON);
246 
247 	(void) getcid(sys_name, &syscid);
248 	curthread->t_cid = syscid;	/* current thread is t0 */
249 
250 	/*
251 	 * Set up the first CPU's idle thread.
252 	 * It runs whenever the CPU has nothing worthwhile to do.
253 	 */
254 	tp = thread_create(NULL, 0, idle, NULL, 0, &p0, TS_STOPPED, -1);
255 	cpu->cpu_idle_thread = tp;
256 	tp->t_preempt = 1;
257 	tp->t_disp_queue = cpu->cpu_disp;
258 	ASSERT(tp->t_disp_queue != NULL);
259 	tp->t_bound_cpu = cpu;
260 	tp->t_affinitycnt = 1;
261 
262 	/*
263 	 * Registering a thread in the callback table is usually
264 	 * done in the initialization code of the thread. In this
265 	 * case, we do it right after thread creation to avoid
266 	 * blocking idle thread while registering itself. It also
267 	 * avoids the possibility of reregistration in case a CPU
268 	 * restarts its idle thread.
269 	 */
270 	CALLB_CPR_INIT_SAFE(tp, "idle");
271 
272 	/*
273 	 * Create the thread_reaper daemon. From this point on, exited
274 	 * threads will get reaped.
275 	 */
276 	(void) thread_create(NULL, 0, (void (*)())thread_reaper,
277 	    NULL, 0, &p0, TS_RUN, minclsyspri);
278 
279 	/*
280 	 * Finish initializing the kernel memory allocator now that
281 	 * thread_create() is available.
282 	 */
283 	kmem_thread_init();
284 
285 	if (boothowto & RB_DEBUG)
286 		kdi_dvec_thravail();
287 }
288 
289 /*
290  * Create a thread.
291  *
292  * thread_create() blocks for memory if necessary.  It never fails.
293  *
294  * If stk is NULL, the thread is created at the base of the stack
295  * and cannot be swapped.
296  */
297 kthread_t *
298 thread_create(
299 	caddr_t	stk,
300 	size_t	stksize,
301 	void	(*proc)(),
302 	void	*arg,
303 	size_t	len,
304 	proc_t	 *pp,
305 	int	state,
306 	pri_t	pri)
307 {
308 	kthread_t *t;
309 	extern struct classfuncs sys_classfuncs;
310 	turnstile_t *ts;
311 
312 	/*
313 	 * Every thread keeps a turnstile around in case it needs to block.
314 	 * The only reason the turnstile is not simply part of the thread
315 	 * structure is that we may have to break the association whenever
316 	 * more than one thread blocks on a given synchronization object.
317 	 * From a memory-management standpoint, turnstiles are like the
318 	 * "attached mblks" that hang off dblks in the streams allocator.
319 	 */
320 	ts = kmem_cache_alloc(turnstile_cache, KM_SLEEP);
321 
322 	if (stk == NULL) {
323 		/*
324 		 * alloc both thread and stack in segkp chunk
325 		 */
326 
327 		if (stksize < default_stksize)
328 			stksize = default_stksize;
329 
330 		if (stksize == default_stksize) {
331 			stk = (caddr_t)segkp_cache_get(segkp_thread);
332 		} else {
333 			stksize = roundup(stksize, PAGESIZE);
334 			stk = (caddr_t)segkp_get(segkp, stksize,
335 			    (KPD_HASREDZONE | KPD_NO_ANON | KPD_LOCKED));
336 		}
337 
338 		ASSERT(stk != NULL);
339 
340 		/*
341 		 * The machine-dependent mutex code may require that
342 		 * thread pointers (since they may be used for mutex owner
343 		 * fields) have certain alignment requirements.
344 		 * PTR24_ALIGN is the size of the alignment quanta.
345 		 * XXX - assumes stack grows toward low addresses.
346 		 */
347 		if (stksize <= sizeof (kthread_t) + PTR24_ALIGN)
348 			cmn_err(CE_PANIC, "thread_create: proposed stack size"
349 			    " too small to hold thread.");
350 #ifdef STACK_GROWTH_DOWN
351 		stksize -= SA(sizeof (kthread_t) + PTR24_ALIGN - 1);
352 		stksize &= -PTR24_ALIGN;	/* make thread aligned */
353 		t = (kthread_t *)(stk + stksize);
354 		bzero(t, sizeof (kthread_t));
355 #ifdef	C2_AUDIT
356 		if (audit_active)
357 			audit_thread_create(t);
358 #endif
359 		t->t_stk = stk + stksize;
360 		t->t_stkbase = stk;
361 #else	/* stack grows to larger addresses */
362 		stksize -= SA(sizeof (kthread_t));
363 		t = (kthread_t *)(stk);
364 		bzero(t, sizeof (kthread_t));
365 		t->t_stk = stk + sizeof (kthread_t);
366 		t->t_stkbase = stk + stksize + sizeof (kthread_t);
367 #endif	/* STACK_GROWTH_DOWN */
368 		t->t_flag |= T_TALLOCSTK;
369 		t->t_swap = stk;
370 	} else {
371 		t = kmem_cache_alloc(thread_cache, KM_SLEEP);
372 		bzero(t, sizeof (kthread_t));
373 		ASSERT(((uintptr_t)t & (PTR24_ALIGN - 1)) == 0);
374 #ifdef	C2_AUDIT
375 		if (audit_active)
376 			audit_thread_create(t);
377 #endif
378 		/*
379 		 * Initialize t_stk to the kernel stack pointer to use
380 		 * upon entry to the kernel
381 		 */
382 #ifdef STACK_GROWTH_DOWN
383 		t->t_stk = stk + stksize;
384 		t->t_stkbase = stk;
385 #else
386 		t->t_stk = stk;			/* 3b2-like */
387 		t->t_stkbase = stk + stksize;
388 #endif /* STACK_GROWTH_DOWN */
389 	}
390 
391 	/* set default stack flag */
392 	if (stksize == lwp_default_stksize)
393 		t->t_flag |= T_DFLTSTK;
394 
395 	t->t_ts = ts;
396 
397 	/*
398 	 * p_cred could be NULL if it thread_create is called before cred_init
399 	 * is called in main.
400 	 */
401 	mutex_enter(&pp->p_crlock);
402 	if (pp->p_cred)
403 		crhold(t->t_cred = pp->p_cred);
404 	mutex_exit(&pp->p_crlock);
405 	t->t_start = gethrestime_sec();
406 	t->t_startpc = proc;
407 	t->t_procp = pp;
408 	t->t_clfuncs = &sys_classfuncs.thread;
409 	t->t_cid = syscid;
410 	t->t_pri = pri;
411 	t->t_stime = lbolt;
412 	t->t_schedflag = TS_LOAD | TS_DONT_SWAP;
413 	t->t_bind_cpu = PBIND_NONE;
414 	t->t_bind_pset = PS_NONE;
415 	t->t_plockp = &pp->p_lock;
416 	t->t_copyops = NULL;
417 	t->t_taskq = NULL;
418 	t->t_anttime = 0;
419 	t->t_hatdepth = 0;
420 
421 	t->t_dtrace_vtime = 1;	/* assure vtimestamp is always non-zero */
422 
423 	CPU_STATS_ADDQ(CPU, sys, nthreads, 1);
424 #ifndef NPROBE
425 	/* Kernel probe */
426 	tnf_thread_create(t);
427 #endif /* NPROBE */
428 	LOCK_INIT_CLEAR(&t->t_lock);
429 
430 	/*
431 	 * Callers who give us a NULL proc must do their own
432 	 * stack initialization.  e.g. lwp_create()
433 	 */
434 	if (proc != NULL) {
435 		t->t_stk = thread_stk_init(t->t_stk);
436 		thread_load(t, proc, arg, len);
437 	}
438 
439 	/*
440 	 * Put a hold on project0. If this thread is actually in a
441 	 * different project, then t_proj will be changed later in
442 	 * lwp_create().  All kernel-only threads must be in project 0.
443 	 */
444 	t->t_proj = project_hold(proj0p);
445 
446 	lgrp_affinity_init(&t->t_lgrp_affinity);
447 
448 	mutex_enter(&pidlock);
449 	nthread++;
450 	t->t_did = next_t_id++;
451 	t->t_prev = curthread->t_prev;
452 	t->t_next = curthread;
453 
454 	/*
455 	 * Add the thread to the list of all threads, and initialize
456 	 * its t_cpu pointer.  We need to block preemption since
457 	 * cpu_offline walks the thread list looking for threads
458 	 * with t_cpu pointing to the CPU being offlined.  We want
459 	 * to make sure that the list is consistent and that if t_cpu
460 	 * is set, the thread is on the list.
461 	 */
462 	kpreempt_disable();
463 	curthread->t_prev->t_next = t;
464 	curthread->t_prev = t;
465 
466 	/*
467 	 * Threads should never have a NULL t_cpu pointer so assign it
468 	 * here.  If the thread is being created with state TS_RUN a
469 	 * better CPU may be chosen when it is placed on the run queue.
470 	 *
471 	 * We need to keep kernel preemption disabled when setting all
472 	 * three fields to keep them in sync.  Also, always create in
473 	 * the default partition since that's where kernel threads go
474 	 * (if this isn't a kernel thread, t_cpupart will be changed
475 	 * in lwp_create before setting the thread runnable).
476 	 */
477 	t->t_cpupart = &cp_default;
478 
479 	/*
480 	 * For now, affiliate this thread with the root lgroup.
481 	 * Since the kernel does not (presently) allocate its memory
482 	 * in a locality aware fashion, the root is an appropriate home.
483 	 * If this thread is later associated with an lwp, it will have
484 	 * it's lgroup re-assigned at that time.
485 	 */
486 	lgrp_move_thread(t, &cp_default.cp_lgrploads[LGRP_ROOTID], 1);
487 
488 	/*
489 	 * Inherit the current cpu.  If this cpu isn't part of the chosen
490 	 * lgroup, a new cpu will be chosen by cpu_choose when the thread
491 	 * is ready to run.
492 	 */
493 	if (CPU->cpu_part == &cp_default)
494 		t->t_cpu = CPU;
495 	else
496 		t->t_cpu = disp_lowpri_cpu(cp_default.cp_cpulist, t->t_lpl,
497 		    t->t_pri, NULL);
498 
499 	t->t_disp_queue = t->t_cpu->cpu_disp;
500 	kpreempt_enable();
501 
502 	/*
503 	 * Initialize thread state and the dispatcher lock pointer.
504 	 * Need to hold onto pidlock to block allthreads walkers until
505 	 * the state is set.
506 	 */
507 	switch (state) {
508 	case TS_RUN:
509 		curthread->t_oldspl = splhigh();	/* get dispatcher spl */
510 		THREAD_SET_STATE(t, TS_STOPPED, &transition_lock);
511 		CL_SETRUN(t);
512 		thread_unlock(t);
513 		break;
514 
515 	case TS_ONPROC:
516 		THREAD_ONPROC(t, t->t_cpu);
517 		break;
518 
519 	case TS_FREE:
520 		/*
521 		 * Free state will be used for intr threads.
522 		 * The interrupt routine must set the thread dispatcher
523 		 * lock pointer (t_lockp) if starting on a CPU
524 		 * other than the current one.
525 		 */
526 		THREAD_FREEINTR(t, CPU);
527 		break;
528 
529 	case TS_STOPPED:
530 		THREAD_SET_STATE(t, TS_STOPPED, &stop_lock);
531 		break;
532 
533 	default:			/* TS_SLEEP, TS_ZOMB or TS_TRANS */
534 		cmn_err(CE_PANIC, "thread_create: invalid state %d", state);
535 	}
536 	mutex_exit(&pidlock);
537 	return (t);
538 }
539 
540 /*
541  * Move thread to project0 and take care of project reference counters.
542  */
543 void
544 thread_rele(kthread_t *t)
545 {
546 	kproject_t *kpj;
547 
548 	thread_lock(t);
549 
550 	ASSERT(t == curthread || t->t_state == TS_FREE || t->t_procp == &p0);
551 	kpj = ttoproj(t);
552 	t->t_proj = proj0p;
553 
554 	thread_unlock(t);
555 
556 	if (kpj != proj0p) {
557 		project_rele(kpj);
558 		(void) project_hold(proj0p);
559 	}
560 }
561 
562 
563 void	(*ip_cleanup_func)(void);
564 
565 void
566 thread_exit()
567 {
568 	kthread_t *t = curthread;
569 
570 	if ((t->t_proc_flag & TP_ZTHREAD) != 0)
571 		cmn_err(CE_PANIC, "thread_exit: zthread_exit() not called");
572 
573 	if (ip_cleanup_func != NULL)
574 		(*ip_cleanup_func)();
575 
576 	tsd_exit();		/* Clean up this thread's TSD */
577 
578 	kcpc_passivate();	/* clean up performance counter state */
579 
580 	/*
581 	 * No kernel thread should have called poll() without arranging
582 	 * calling pollcleanup() here.
583 	 */
584 	ASSERT(t->t_pollstate == NULL);
585 	ASSERT(t->t_schedctl == NULL);
586 	if (t->t_door)
587 		door_slam();	/* in case thread did an upcall */
588 
589 #ifndef NPROBE
590 	/* Kernel probe */
591 	if (t->t_tnf_tpdp)
592 		tnf_thread_exit();
593 #endif /* NPROBE */
594 
595 	thread_rele(t);
596 	t->t_preempt++;
597 
598 	/*
599 	 * remove thread from the all threads list so that
600 	 * death-row can use the same pointers.
601 	 */
602 	mutex_enter(&pidlock);
603 	t->t_next->t_prev = t->t_prev;
604 	t->t_prev->t_next = t->t_next;
605 	ASSERT(allthreads != t);	/* t0 never exits */
606 	cv_broadcast(&t->t_joincv);	/* wake up anyone in thread_join */
607 	mutex_exit(&pidlock);
608 
609 	if (t->t_ctx != NULL)
610 		exitctx(t);
611 	if (t->t_procp->p_pctx != NULL)
612 		exitpctx(t->t_procp);
613 
614 	t->t_state = TS_ZOMB;	/* set zombie thread */
615 
616 	swtch_from_zombie();	/* give up the CPU */
617 	/* NOTREACHED */
618 }
619 
620 /*
621  * Check to see if the specified thread is active (defined as being on
622  * the thread list).  This is certainly a slow way to do this; if there's
623  * ever a reason to speed it up, we could maintain a hash table of active
624  * threads indexed by their t_did.
625  */
626 static kthread_t *
627 did_to_thread(kt_did_t tid)
628 {
629 	kthread_t *t;
630 
631 	ASSERT(MUTEX_HELD(&pidlock));
632 	for (t = curthread->t_next; t != curthread; t = t->t_next) {
633 		if (t->t_did == tid)
634 			break;
635 	}
636 	if (t->t_did == tid)
637 		return (t);
638 	else
639 		return (NULL);
640 }
641 
642 /*
643  * Wait for specified thread to exit.  Returns immediately if the thread
644  * could not be found, meaning that it has either already exited or never
645  * existed.
646  */
647 void
648 thread_join(kt_did_t tid)
649 {
650 	kthread_t *t;
651 
652 	ASSERT(tid != curthread->t_did);
653 	ASSERT(tid != t0.t_did);
654 
655 	mutex_enter(&pidlock);
656 	/*
657 	 * Make sure we check that the thread is on the thread list
658 	 * before blocking on it; otherwise we could end up blocking on
659 	 * a cv that's already been freed.  In other words, don't cache
660 	 * the thread pointer across calls to cv_wait.
661 	 *
662 	 * The choice of loop invariant means that whenever a thread
663 	 * is taken off the allthreads list, a cv_broadcast must be
664 	 * performed on that thread's t_joincv to wake up any waiters.
665 	 * The broadcast doesn't have to happen right away, but it
666 	 * shouldn't be postponed indefinitely (e.g., by doing it in
667 	 * thread_free which may only be executed when the deathrow
668 	 * queue is processed.
669 	 */
670 	while (t = did_to_thread(tid))
671 		cv_wait(&t->t_joincv, &pidlock);
672 	mutex_exit(&pidlock);
673 }
674 
675 void
676 thread_free(kthread_t *t)
677 {
678 	ASSERT(t != &t0 && t->t_state == TS_FREE);
679 	ASSERT(t->t_door == NULL);
680 	ASSERT(t->t_schedctl == NULL);
681 	ASSERT(t->t_pollstate == NULL);
682 
683 	t->t_pri = 0;
684 	t->t_pc = 0;
685 	t->t_sp = 0;
686 	t->t_wchan0 = NULL;
687 	t->t_wchan = NULL;
688 	if (t->t_cred != NULL) {
689 		crfree(t->t_cred);
690 		t->t_cred = 0;
691 	}
692 	if (t->t_pdmsg) {
693 		kmem_free(t->t_pdmsg, strlen(t->t_pdmsg) + 1);
694 		t->t_pdmsg = NULL;
695 	}
696 #ifdef	C2_AUDIT
697 	if (audit_active)
698 		audit_thread_free(t);
699 #endif
700 #ifndef NPROBE
701 	if (t->t_tnf_tpdp)
702 		tnf_thread_free(t);
703 #endif /* NPROBE */
704 	if (t->t_cldata) {
705 		CL_EXITCLASS(t->t_cid, (caddr_t *)t->t_cldata);
706 	}
707 	if (t->t_rprof != NULL) {
708 		kmem_free(t->t_rprof, sizeof (*t->t_rprof));
709 		t->t_rprof = NULL;
710 	}
711 	t->t_lockp = NULL;	/* nothing should try to lock this thread now */
712 	if (t->t_lwp)
713 		lwp_freeregs(t->t_lwp, 0);
714 	if (t->t_ctx)
715 		freectx(t, 0);
716 	t->t_stk = NULL;
717 	if (t->t_lwp)
718 		lwp_stk_fini(t->t_lwp);
719 	lock_clear(&t->t_lock);
720 
721 	if (t->t_ts->ts_waiters > 0)
722 		panic("thread_free: turnstile still active");
723 
724 	kmem_cache_free(turnstile_cache, t->t_ts);
725 
726 	free_afd(&t->t_activefd);
727 
728 	/*
729 	 * Barrier for clock thread.  The clock holds this lock to
730 	 * keep the thread from going away while it's looking at it.
731 	 */
732 	mutex_enter(&thread_free_lock);
733 	mutex_exit(&thread_free_lock);
734 
735 	ASSERT(ttoproj(t) == proj0p);
736 	project_rele(ttoproj(t));
737 
738 	lgrp_affinity_free(&t->t_lgrp_affinity);
739 
740 	/*
741 	 * Free thread struct and its stack.
742 	 */
743 	if (t->t_flag & T_TALLOCSTK) {
744 		/* thread struct is embedded in stack */
745 		segkp_release(segkp, t->t_swap);
746 		mutex_enter(&pidlock);
747 		nthread--;
748 		mutex_exit(&pidlock);
749 	} else {
750 		if (t->t_swap) {
751 			segkp_release(segkp, t->t_swap);
752 			t->t_swap = NULL;
753 		}
754 		if (t->t_lwp) {
755 			kmem_cache_free(lwp_cache, t->t_lwp);
756 			t->t_lwp = NULL;
757 		}
758 		mutex_enter(&pidlock);
759 		nthread--;
760 		mutex_exit(&pidlock);
761 		kmem_cache_free(thread_cache, t);
762 	}
763 }
764 
765 /*
766  * Removes threads associated with the given zone from a deathrow queue.
767  * tp is a pointer to the head of the deathrow queue, and countp is a
768  * pointer to the current deathrow count.  Returns a linked list of
769  * threads removed from the list.
770  */
771 static kthread_t *
772 thread_zone_cleanup(kthread_t **tp, int *countp, zoneid_t zoneid)
773 {
774 	kthread_t *tmp, *list = NULL;
775 	cred_t *cr;
776 
777 	ASSERT(MUTEX_HELD(&reaplock));
778 	while (*tp != NULL) {
779 		if ((cr = (*tp)->t_cred) != NULL && crgetzoneid(cr) == zoneid) {
780 			tmp = *tp;
781 			*tp = tmp->t_forw;
782 			tmp->t_forw = list;
783 			list = tmp;
784 			(*countp)--;
785 		} else {
786 			tp = &(*tp)->t_forw;
787 		}
788 	}
789 	return (list);
790 }
791 
792 static void
793 thread_reap_list(kthread_t *t)
794 {
795 	kthread_t *next;
796 
797 	while (t != NULL) {
798 		next = t->t_forw;
799 		thread_free(t);
800 		t = next;
801 	}
802 }
803 
804 /* ARGSUSED */
805 static void
806 thread_zone_destroy(zoneid_t zoneid, void *unused)
807 {
808 	kthread_t *t, *l;
809 
810 	mutex_enter(&reaplock);
811 	/*
812 	 * Pull threads and lwps associated with zone off deathrow lists.
813 	 */
814 	t = thread_zone_cleanup(&thread_deathrow, &thread_reapcnt, zoneid);
815 	l = thread_zone_cleanup(&lwp_deathrow, &lwp_reapcnt, zoneid);
816 	mutex_exit(&reaplock);
817 
818 	/*
819 	 * Reap threads
820 	 */
821 	thread_reap_list(t);
822 
823 	/*
824 	 * Reap lwps
825 	 */
826 	thread_reap_list(l);
827 }
828 
829 /*
830  * cleanup zombie threads that are on deathrow.
831  */
832 void
833 thread_reaper()
834 {
835 	kthread_t *t, *l;
836 	callb_cpr_t cprinfo;
837 
838 	/*
839 	 * Register callback to clean up threads when zone is destroyed.
840 	 */
841 	zone_key_create(&zone_thread_key, NULL, NULL, thread_zone_destroy);
842 
843 	CALLB_CPR_INIT(&cprinfo, &reaplock, callb_generic_cpr, "t_reaper");
844 	for (;;) {
845 		mutex_enter(&reaplock);
846 		while (thread_deathrow == NULL && lwp_deathrow == NULL) {
847 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
848 			cv_wait(&reaper_cv, &reaplock);
849 			CALLB_CPR_SAFE_END(&cprinfo, &reaplock);
850 		}
851 		t = thread_deathrow;
852 		l = lwp_deathrow;
853 		thread_deathrow = NULL;
854 		lwp_deathrow = NULL;
855 		thread_reapcnt = 0;
856 		lwp_reapcnt = 0;
857 		mutex_exit(&reaplock);
858 
859 		/*
860 		 * Reap threads
861 		 */
862 		thread_reap_list(t);
863 
864 		/*
865 		 * Reap lwps
866 		 */
867 		thread_reap_list(l);
868 	}
869 }
870 
871 /*
872  * This is called by resume() to put a zombie thread onto deathrow.
873  * The thread's state is changed to TS_FREE to indicate that is reapable.
874  * This is called from the idle thread so it must not block (just spin).
875  */
876 void
877 reapq_add(kthread_t *t)
878 {
879 	mutex_enter(&reaplock);
880 
881 	/*
882 	 * lwp_deathrow contains only threads with lwp linkage
883 	 * that are of the default stacksize. Anything else goes
884 	 * on thread_deathrow.
885 	 */
886 	if (ttolwp(t) && (t->t_flag & T_DFLTSTK)) {
887 		t->t_forw = lwp_deathrow;
888 		lwp_deathrow = t;
889 		lwp_reapcnt++;
890 	} else {
891 		t->t_forw = thread_deathrow;
892 		thread_deathrow = t;
893 		thread_reapcnt++;
894 	}
895 	if (lwp_reapcnt + thread_reapcnt > reaplimit)
896 		cv_signal(&reaper_cv);	/* wake the reaper */
897 	t->t_state = TS_FREE;
898 	lock_clear(&t->t_lock);
899 	mutex_exit(&reaplock);
900 }
901 
902 /*
903  * Install thread context ops for the current thread.
904  */
905 void
906 installctx(
907 	kthread_t *t,
908 	void	*arg,
909 	void	(*save)(void *),
910 	void	(*restore)(void *),
911 	void	(*fork)(void *, void *),
912 	void	(*lwp_create)(void *, void *),
913 	void	(*exit)(void *),
914 	void	(*free)(void *, int))
915 {
916 	struct ctxop *ctx;
917 
918 	ctx = kmem_alloc(sizeof (struct ctxop), KM_SLEEP);
919 	ctx->save_op = save;
920 	ctx->restore_op = restore;
921 	ctx->fork_op = fork;
922 	ctx->lwp_create_op = lwp_create;
923 	ctx->exit_op = exit;
924 	ctx->free_op = free;
925 	ctx->arg = arg;
926 	ctx->next = t->t_ctx;
927 	t->t_ctx = ctx;
928 }
929 
930 /*
931  * Remove the thread context ops from a thread.
932  */
933 int
934 removectx(
935 	kthread_t *t,
936 	void	*arg,
937 	void	(*save)(void *),
938 	void	(*restore)(void *),
939 	void	(*fork)(void *, void *),
940 	void	(*lwp_create)(void *, void *),
941 	void	(*exit)(void *),
942 	void	(*free)(void *, int))
943 {
944 	struct ctxop *ctx, *prev_ctx;
945 
946 	/*
947 	 * The incoming kthread_t (which is the thread for which the
948 	 * context ops will be removed) should be one of the following:
949 	 *
950 	 * a) the current thread,
951 	 *
952 	 * b) a thread of a process that's being forked (SIDL),
953 	 *
954 	 * c) a thread that belongs to the same process as the current
955 	 *    thread and for which the current thread is the agent thread,
956 	 *
957 	 * d) a thread that is TS_STOPPED which is indicative of it
958 	 *    being (if curthread is not an agent) a thread being created
959 	 *    as part of an lwp creation.
960 	 */
961 	ASSERT(t == curthread || ttoproc(t)->p_stat == SIDL ||
962 	    ttoproc(t)->p_agenttp == curthread || t->t_state == TS_STOPPED);
963 
964 	/*
965 	 * Serialize modifications to t->t_ctx to prevent the agent thread
966 	 * and the target thread from racing with each other during lwp exit.
967 	 */
968 	mutex_enter(&t->t_ctx_lock);
969 	prev_ctx = NULL;
970 	for (ctx = t->t_ctx; ctx != NULL; ctx = ctx->next) {
971 		if (ctx->save_op == save && ctx->restore_op == restore &&
972 		    ctx->fork_op == fork && ctx->lwp_create_op == lwp_create &&
973 		    ctx->exit_op == exit && ctx->free_op == free &&
974 		    ctx->arg == arg) {
975 			if (prev_ctx)
976 				prev_ctx->next = ctx->next;
977 			else
978 				t->t_ctx = ctx->next;
979 			mutex_exit(&t->t_ctx_lock);
980 			if (ctx->free_op != NULL)
981 				(ctx->free_op)(ctx->arg, 0);
982 			kmem_free(ctx, sizeof (struct ctxop));
983 			return (1);
984 		}
985 		prev_ctx = ctx;
986 	}
987 	mutex_exit(&t->t_ctx_lock);
988 
989 	return (0);
990 }
991 
992 void
993 savectx(kthread_t *t)
994 {
995 	struct ctxop *ctx;
996 
997 	ASSERT(t == curthread);
998 	for (ctx = t->t_ctx; ctx != 0; ctx = ctx->next)
999 		if (ctx->save_op != NULL)
1000 			(ctx->save_op)(ctx->arg);
1001 }
1002 
1003 void
1004 restorectx(kthread_t *t)
1005 {
1006 	struct ctxop *ctx;
1007 
1008 	ASSERT(t == curthread);
1009 	for (ctx = t->t_ctx; ctx != 0; ctx = ctx->next)
1010 		if (ctx->restore_op != NULL)
1011 			(ctx->restore_op)(ctx->arg);
1012 }
1013 
1014 void
1015 forkctx(kthread_t *t, kthread_t *ct)
1016 {
1017 	struct ctxop *ctx;
1018 
1019 	for (ctx = t->t_ctx; ctx != NULL; ctx = ctx->next)
1020 		if (ctx->fork_op != NULL)
1021 			(ctx->fork_op)(t, ct);
1022 }
1023 
1024 /*
1025  * Note that this operator is only invoked via the _lwp_create
1026  * system call.  The system may have other reasons to create lwps
1027  * e.g. the agent lwp or the doors unreferenced lwp.
1028  */
1029 void
1030 lwp_createctx(kthread_t *t, kthread_t *ct)
1031 {
1032 	struct ctxop *ctx;
1033 
1034 	for (ctx = t->t_ctx; ctx != NULL; ctx = ctx->next)
1035 		if (ctx->lwp_create_op != NULL)
1036 			(ctx->lwp_create_op)(t, ct);
1037 }
1038 
1039 /*
1040  * exitctx is called from thread_exit() and lwp_exit() to perform any actions
1041  * needed when the thread/LWP leaves the processor for the last time. This
1042  * routine is not intended to deal with freeing memory; freectx() is used for
1043  * that purpose during thread_free(). This routine is provided to allow for
1044  * clean-up that can't wait until thread_free().
1045  */
1046 void
1047 exitctx(kthread_t *t)
1048 {
1049 	struct ctxop *ctx;
1050 
1051 	for (ctx = t->t_ctx; ctx != NULL; ctx = ctx->next)
1052 		if (ctx->exit_op != NULL)
1053 			(ctx->exit_op)(t);
1054 }
1055 
1056 /*
1057  * freectx is called from thread_free() and exec() to get
1058  * rid of old thread context ops.
1059  */
1060 void
1061 freectx(kthread_t *t, int isexec)
1062 {
1063 	struct ctxop *ctx;
1064 
1065 	while ((ctx = t->t_ctx) != NULL) {
1066 		t->t_ctx = ctx->next;
1067 		if (ctx->free_op != NULL)
1068 			(ctx->free_op)(ctx->arg, isexec);
1069 		kmem_free(ctx, sizeof (struct ctxop));
1070 	}
1071 }
1072 
1073 /*
1074  * Set the thread running; arrange for it to be swapped in if necessary.
1075  */
1076 void
1077 setrun_locked(kthread_t *t)
1078 {
1079 	ASSERT(THREAD_LOCK_HELD(t));
1080 	if (t->t_state == TS_SLEEP) {
1081 		/*
1082 		 * Take off sleep queue.
1083 		 */
1084 		SOBJ_UNSLEEP(t->t_sobj_ops, t);
1085 	} else if (t->t_state & (TS_RUN | TS_ONPROC)) {
1086 		/*
1087 		 * Already on dispatcher queue.
1088 		 */
1089 		return;
1090 	} else if (t->t_state == TS_WAIT) {
1091 		waitq_setrun(t);
1092 	} else if (t->t_state == TS_STOPPED) {
1093 		/*
1094 		 * All of the sending of SIGCONT (TC_XSTART) and /proc
1095 		 * (TC_PSTART) and lwp_continue() (TC_CSTART) must have
1096 		 * requested that the thread be run.
1097 		 * Just calling setrun() is not sufficient to set a stopped
1098 		 * thread running.  TP_TXSTART is always set if the thread
1099 		 * is not stopped by a jobcontrol stop signal.
1100 		 * TP_TPSTART is always set if /proc is not controlling it.
1101 		 * TP_TCSTART is always set if lwp_suspend() didn't stop it.
1102 		 * The thread won't be stopped unless one of these
1103 		 * three mechanisms did it.
1104 		 *
1105 		 * These flags must be set before calling setrun_locked(t).
1106 		 * They can't be passed as arguments because the streams
1107 		 * code calls setrun() indirectly and the mechanism for
1108 		 * doing so admits only one argument.  Note that the
1109 		 * thread must be locked in order to change t_schedflags.
1110 		 */
1111 		if ((t->t_schedflag & TS_ALLSTART) != TS_ALLSTART)
1112 			return;
1113 		/*
1114 		 * Process is no longer stopped (a thread is running).
1115 		 */
1116 		t->t_whystop = 0;
1117 		t->t_whatstop = 0;
1118 		/*
1119 		 * Strictly speaking, we do not have to clear these
1120 		 * flags here; they are cleared on entry to stop().
1121 		 * However, they are confusing when doing kernel
1122 		 * debugging or when they are revealed by ps(1).
1123 		 */
1124 		t->t_schedflag &= ~TS_ALLSTART;
1125 		THREAD_TRANSITION(t);	/* drop stopped-thread lock */
1126 		ASSERT(t->t_lockp == &transition_lock);
1127 		ASSERT(t->t_wchan0 == NULL && t->t_wchan == NULL);
1128 		/*
1129 		 * Let the class put the process on the dispatcher queue.
1130 		 */
1131 		CL_SETRUN(t);
1132 	}
1133 }
1134 
1135 void
1136 setrun(kthread_t *t)
1137 {
1138 	thread_lock(t);
1139 	setrun_locked(t);
1140 	thread_unlock(t);
1141 }
1142 
1143 /*
1144  * Unpin an interrupted thread.
1145  *	When an interrupt occurs, the interrupt is handled on the stack
1146  *	of an interrupt thread, taken from a pool linked to the CPU structure.
1147  *
1148  *	When swtch() is switching away from an interrupt thread because it
1149  *	blocked or was preempted, this routine is called to complete the
1150  *	saving of the interrupted thread state, and returns the interrupted
1151  *	thread pointer so it may be resumed.
1152  *
1153  *	Called by swtch() only at high spl.
1154  */
1155 kthread_t *
1156 thread_unpin()
1157 {
1158 	kthread_t	*t = curthread;	/* current thread */
1159 	kthread_t	*itp;		/* interrupted thread */
1160 	int		i;		/* interrupt level */
1161 	extern int	intr_passivate();
1162 
1163 	ASSERT(t->t_intr != NULL);
1164 
1165 	itp = t->t_intr;		/* interrupted thread */
1166 	t->t_intr = NULL;		/* clear interrupt ptr */
1167 
1168 	/*
1169 	 * Get state from interrupt thread for the one
1170 	 * it interrupted.
1171 	 */
1172 
1173 	i = intr_passivate(t, itp);
1174 
1175 	TRACE_5(TR_FAC_INTR, TR_INTR_PASSIVATE,
1176 		"intr_passivate:level %d curthread %p (%T) ithread %p (%T)",
1177 		i, t, t, itp, itp);
1178 
1179 	/*
1180 	 * Dissociate the current thread from the interrupted thread's LWP.
1181 	 */
1182 	t->t_lwp = NULL;
1183 
1184 	/*
1185 	 * Interrupt handlers above the level that spinlocks block must
1186 	 * not block.
1187 	 */
1188 #if DEBUG
1189 	if (i < 0 || i > LOCK_LEVEL)
1190 		cmn_err(CE_PANIC, "thread_unpin: ipl out of range %x", i);
1191 #endif
1192 
1193 	/*
1194 	 * Compute the CPU's base interrupt level based on the active
1195 	 * interrupts.
1196 	 */
1197 	ASSERT(CPU->cpu_intr_actv & (1 << i));
1198 	set_base_spl();
1199 
1200 	return (itp);
1201 }
1202 
1203 /*
1204  * Create and initialize an interrupt thread.
1205  *	Returns non-zero on error.
1206  *	Called at spl7() or better.
1207  */
1208 void
1209 thread_create_intr(struct cpu *cp)
1210 {
1211 	kthread_t *tp;
1212 
1213 	tp = thread_create(NULL, 0,
1214 	    (void (*)())thread_create_intr, NULL, 0, &p0, TS_ONPROC, 0);
1215 
1216 	/*
1217 	 * Set the thread in the TS_FREE state.  The state will change
1218 	 * to TS_ONPROC only while the interrupt is active.  Think of these
1219 	 * as being on a private free list for the CPU.  Being TS_FREE keeps
1220 	 * inactive interrupt threads out of debugger thread lists.
1221 	 *
1222 	 * We cannot call thread_create with TS_FREE because of the current
1223 	 * checks there for ONPROC.  Fix this when thread_create takes flags.
1224 	 */
1225 	THREAD_FREEINTR(tp, cp);
1226 
1227 	/*
1228 	 * Nobody should ever reference the credentials of an interrupt
1229 	 * thread so make it NULL to catch any such references.
1230 	 */
1231 	tp->t_cred = NULL;
1232 	tp->t_flag |= T_INTR_THREAD;
1233 	tp->t_cpu = cp;
1234 	tp->t_bound_cpu = cp;
1235 	tp->t_disp_queue = cp->cpu_disp;
1236 	tp->t_affinitycnt = 1;
1237 	tp->t_preempt = 1;
1238 
1239 	/*
1240 	 * Don't make a user-requested binding on this thread so that
1241 	 * the processor can be offlined.
1242 	 */
1243 	tp->t_bind_cpu = PBIND_NONE;	/* no USER-requested binding */
1244 	tp->t_bind_pset = PS_NONE;
1245 
1246 #if defined(__i386) || defined(__amd64)
1247 	tp->t_stk -= STACK_ALIGN;
1248 	*(tp->t_stk) = 0;		/* terminate intr thread stack */
1249 #endif
1250 
1251 	/*
1252 	 * Link onto CPU's interrupt pool.
1253 	 */
1254 	tp->t_link = cp->cpu_intr_thread;
1255 	cp->cpu_intr_thread = tp;
1256 }
1257 
1258 /*
1259  * TSD -- THREAD SPECIFIC DATA
1260  */
1261 static kmutex_t		tsd_mutex;	 /* linked list spin lock */
1262 static uint_t		tsd_nkeys;	 /* size of destructor array */
1263 /* per-key destructor funcs */
1264 static void 		(**tsd_destructor)(void *);
1265 /* list of tsd_thread's */
1266 static struct tsd_thread	*tsd_list;
1267 
1268 /*
1269  * Default destructor
1270  *	Needed because NULL destructor means that the key is unused
1271  */
1272 /* ARGSUSED */
1273 void
1274 tsd_defaultdestructor(void *value)
1275 {}
1276 
1277 /*
1278  * Create a key (index into per thread array)
1279  *	Locks out tsd_create, tsd_destroy, and tsd_exit
1280  *	May allocate memory with lock held
1281  */
1282 void
1283 tsd_create(uint_t *keyp, void (*destructor)(void *))
1284 {
1285 	int	i;
1286 	uint_t	nkeys;
1287 
1288 	/*
1289 	 * if key is allocated, do nothing
1290 	 */
1291 	mutex_enter(&tsd_mutex);
1292 	if (*keyp) {
1293 		mutex_exit(&tsd_mutex);
1294 		return;
1295 	}
1296 	/*
1297 	 * find an unused key
1298 	 */
1299 	if (destructor == NULL)
1300 		destructor = tsd_defaultdestructor;
1301 
1302 	for (i = 0; i < tsd_nkeys; ++i)
1303 		if (tsd_destructor[i] == NULL)
1304 			break;
1305 
1306 	/*
1307 	 * if no unused keys, increase the size of the destructor array
1308 	 */
1309 	if (i == tsd_nkeys) {
1310 		if ((nkeys = (tsd_nkeys << 1)) == 0)
1311 			nkeys = 1;
1312 		tsd_destructor =
1313 		    (void (**)(void *))tsd_realloc((void *)tsd_destructor,
1314 		    (size_t)(tsd_nkeys * sizeof (void (*)(void *))),
1315 		    (size_t)(nkeys * sizeof (void (*)(void *))));
1316 		tsd_nkeys = nkeys;
1317 	}
1318 
1319 	/*
1320 	 * allocate the next available unused key
1321 	 */
1322 	tsd_destructor[i] = destructor;
1323 	*keyp = i + 1;
1324 	mutex_exit(&tsd_mutex);
1325 }
1326 
1327 /*
1328  * Destroy a key -- this is for unloadable modules
1329  *
1330  * Assumes that the caller is preventing tsd_set and tsd_get
1331  * Locks out tsd_create, tsd_destroy, and tsd_exit
1332  * May free memory with lock held
1333  */
1334 void
1335 tsd_destroy(uint_t *keyp)
1336 {
1337 	uint_t key;
1338 	struct tsd_thread *tsd;
1339 
1340 	/*
1341 	 * protect the key namespace and our destructor lists
1342 	 */
1343 	mutex_enter(&tsd_mutex);
1344 	key = *keyp;
1345 	*keyp = 0;
1346 
1347 	ASSERT(key <= tsd_nkeys);
1348 
1349 	/*
1350 	 * if the key is valid
1351 	 */
1352 	if (key != 0) {
1353 		uint_t k = key - 1;
1354 		/*
1355 		 * for every thread with TSD, call key's destructor
1356 		 */
1357 		for (tsd = tsd_list; tsd; tsd = tsd->ts_next) {
1358 			/*
1359 			 * no TSD for key in this thread
1360 			 */
1361 			if (key > tsd->ts_nkeys)
1362 				continue;
1363 			/*
1364 			 * call destructor for key
1365 			 */
1366 			if (tsd->ts_value[k] && tsd_destructor[k])
1367 				(*tsd_destructor[k])(tsd->ts_value[k]);
1368 			/*
1369 			 * reset value for key
1370 			 */
1371 			tsd->ts_value[k] = NULL;
1372 		}
1373 		/*
1374 		 * actually free the key (NULL destructor == unused)
1375 		 */
1376 		tsd_destructor[k] = NULL;
1377 	}
1378 
1379 	mutex_exit(&tsd_mutex);
1380 }
1381 
1382 /*
1383  * Quickly return the per thread value that was stored with the specified key
1384  * Assumes the caller is protecting key from tsd_create and tsd_destroy
1385  */
1386 void *
1387 tsd_get(uint_t key)
1388 {
1389 	return (tsd_agent_get(curthread, key));
1390 }
1391 
1392 /*
1393  * Set a per thread value indexed with the specified key
1394  */
1395 int
1396 tsd_set(uint_t key, void *value)
1397 {
1398 	return (tsd_agent_set(curthread, key, value));
1399 }
1400 
1401 /*
1402  * Like tsd_get(), except that the agent lwp can get the tsd of
1403  * another thread in the same process (the agent thread only runs when the
1404  * process is completely stopped by /proc), or syslwp is creating a new lwp.
1405  */
1406 void *
1407 tsd_agent_get(kthread_t *t, uint_t key)
1408 {
1409 	struct tsd_thread *tsd = t->t_tsd;
1410 
1411 	ASSERT(t == curthread ||
1412 	    ttoproc(t)->p_agenttp == curthread || t->t_state == TS_STOPPED);
1413 
1414 	if (key && tsd != NULL && key <= tsd->ts_nkeys)
1415 		return (tsd->ts_value[key - 1]);
1416 	return (NULL);
1417 }
1418 
1419 /*
1420  * Like tsd_set(), except that the agent lwp can set the tsd of
1421  * another thread in the same process, or syslwp can set the tsd
1422  * of a thread it's in the middle of creating.
1423  *
1424  * Assumes the caller is protecting key from tsd_create and tsd_destroy
1425  * May lock out tsd_destroy (and tsd_create), may allocate memory with
1426  * lock held
1427  */
1428 int
1429 tsd_agent_set(kthread_t *t, uint_t key, void *value)
1430 {
1431 	struct tsd_thread *tsd = t->t_tsd;
1432 
1433 	ASSERT(t == curthread ||
1434 	    ttoproc(t)->p_agenttp == curthread || t->t_state == TS_STOPPED);
1435 
1436 	if (key == 0)
1437 		return (EINVAL);
1438 	if (tsd == NULL)
1439 		tsd = t->t_tsd = kmem_zalloc(sizeof (*tsd), KM_SLEEP);
1440 	if (key <= tsd->ts_nkeys) {
1441 		tsd->ts_value[key - 1] = value;
1442 		return (0);
1443 	}
1444 
1445 	ASSERT(key <= tsd_nkeys);
1446 
1447 	/*
1448 	 * lock out tsd_destroy()
1449 	 */
1450 	mutex_enter(&tsd_mutex);
1451 	if (tsd->ts_nkeys == 0) {
1452 		/*
1453 		 * Link onto list of threads with TSD
1454 		 */
1455 		if ((tsd->ts_next = tsd_list) != NULL)
1456 			tsd_list->ts_prev = tsd;
1457 		tsd_list = tsd;
1458 	}
1459 
1460 	/*
1461 	 * Allocate thread local storage and set the value for key
1462 	 */
1463 	tsd->ts_value = tsd_realloc(tsd->ts_value,
1464 	    tsd->ts_nkeys * sizeof (void *),
1465 	    key * sizeof (void *));
1466 	tsd->ts_nkeys = key;
1467 	tsd->ts_value[key - 1] = value;
1468 	mutex_exit(&tsd_mutex);
1469 
1470 	return (0);
1471 }
1472 
1473 
1474 /*
1475  * Return the per thread value that was stored with the specified key
1476  *	If necessary, create the key and the value
1477  *	Assumes the caller is protecting *keyp from tsd_destroy
1478  */
1479 void *
1480 tsd_getcreate(uint_t *keyp, void (*destroy)(void *), void *(*allocate)(void))
1481 {
1482 	void *value;
1483 	uint_t key = *keyp;
1484 	struct tsd_thread *tsd = curthread->t_tsd;
1485 
1486 	if (tsd == NULL)
1487 		tsd = curthread->t_tsd = kmem_zalloc(sizeof (*tsd), KM_SLEEP);
1488 	if (key && key <= tsd->ts_nkeys && (value = tsd->ts_value[key - 1]))
1489 		return (value);
1490 	if (key == 0)
1491 		tsd_create(keyp, destroy);
1492 	(void) tsd_set(*keyp, value = (*allocate)());
1493 
1494 	return (value);
1495 }
1496 
1497 /*
1498  * Called from thread_exit() to run the destructor function for each tsd
1499  *	Locks out tsd_create and tsd_destroy
1500  *	Assumes that the destructor *DOES NOT* use tsd
1501  */
1502 void
1503 tsd_exit(void)
1504 {
1505 	int i;
1506 	struct tsd_thread *tsd = curthread->t_tsd;
1507 
1508 	if (tsd == NULL)
1509 		return;
1510 
1511 	if (tsd->ts_nkeys == 0) {
1512 		kmem_free(tsd, sizeof (*tsd));
1513 		curthread->t_tsd = NULL;
1514 		return;
1515 	}
1516 
1517 	/*
1518 	 * lock out tsd_create and tsd_destroy, call
1519 	 * the destructor, and mark the value as destroyed.
1520 	 */
1521 	mutex_enter(&tsd_mutex);
1522 
1523 	for (i = 0; i < tsd->ts_nkeys; i++) {
1524 		if (tsd->ts_value[i] && tsd_destructor[i])
1525 			(*tsd_destructor[i])(tsd->ts_value[i]);
1526 		tsd->ts_value[i] = NULL;
1527 	}
1528 
1529 	/*
1530 	 * remove from linked list of threads with TSD
1531 	 */
1532 	if (tsd->ts_next)
1533 		tsd->ts_next->ts_prev = tsd->ts_prev;
1534 	if (tsd->ts_prev)
1535 		tsd->ts_prev->ts_next = tsd->ts_next;
1536 	if (tsd_list == tsd)
1537 		tsd_list = tsd->ts_next;
1538 
1539 	mutex_exit(&tsd_mutex);
1540 
1541 	/*
1542 	 * free up the TSD
1543 	 */
1544 	kmem_free(tsd->ts_value, tsd->ts_nkeys * sizeof (void *));
1545 	kmem_free(tsd, sizeof (struct tsd_thread));
1546 	curthread->t_tsd = NULL;
1547 }
1548 
1549 /*
1550  * realloc
1551  */
1552 static void *
1553 tsd_realloc(void *old, size_t osize, size_t nsize)
1554 {
1555 	void *new;
1556 
1557 	new = kmem_zalloc(nsize, KM_SLEEP);
1558 	if (old) {
1559 		bcopy(old, new, osize);
1560 		kmem_free(old, osize);
1561 	}
1562 	return (new);
1563 }
1564 
1565 /*
1566  * Check to see if an interrupt thread might be active at a given ipl.
1567  * If so return true.
1568  * We must be conservative--it is ok to give a false yes, but a false no
1569  * will cause disaster.  (But if the situation changes after we check it is
1570  * ok--the caller is trying to ensure that an interrupt routine has been
1571  * exited).
1572  * This is used when trying to remove an interrupt handler from an autovector
1573  * list in avintr.c.
1574  */
1575 int
1576 intr_active(struct cpu *cp, int level)
1577 {
1578 	if (level <= LOCK_LEVEL)
1579 		return (cp->cpu_thread != cp->cpu_dispthread);
1580 	else
1581 		return (CPU_ON_INTR(cp));
1582 }
1583 
1584 /*
1585  * Return non-zero if an interrupt is being serviced.
1586  */
1587 int
1588 servicing_interrupt()
1589 {
1590 	int onintr = 0;
1591 
1592 	/* Are we an interrupt thread */
1593 	if (curthread->t_flag & T_INTR_THREAD)
1594 		return (1);
1595 	/* Are we servicing a high level interrupt? */
1596 	if (CPU_ON_INTR(CPU)) {
1597 		kpreempt_disable();
1598 		onintr = CPU_ON_INTR(CPU);
1599 		kpreempt_enable();
1600 	}
1601 	return (onintr);
1602 }
1603 
1604 
1605 /*
1606  * Change the dispatch priority of a thread in the system.
1607  * Used when raising or lowering a thread's priority.
1608  * (E.g., priority inheritance)
1609  *
1610  * Since threads are queued according to their priority, we
1611  * we must check the thread's state to determine whether it
1612  * is on a queue somewhere. If it is, we've got to:
1613  *
1614  *	o Dequeue the thread.
1615  *	o Change its effective priority.
1616  *	o Enqueue the thread.
1617  *
1618  * Assumptions: The thread whose priority we wish to change
1619  * must be locked before we call thread_change_(e)pri().
1620  * The thread_change(e)pri() function doesn't drop the thread
1621  * lock--that must be done by its caller.
1622  */
1623 void
1624 thread_change_epri(kthread_t *t, pri_t disp_pri)
1625 {
1626 	uint_t	state;
1627 
1628 	ASSERT(THREAD_LOCK_HELD(t));
1629 
1630 	/*
1631 	 * If the inherited priority hasn't actually changed,
1632 	 * just return.
1633 	 */
1634 	if (t->t_epri == disp_pri)
1635 		return;
1636 
1637 	state = t->t_state;
1638 
1639 	/*
1640 	 * If it's not on a queue, change the priority with
1641 	 * impunity.
1642 	 */
1643 	if ((state & (TS_SLEEP | TS_RUN | TS_WAIT)) == 0) {
1644 		t->t_epri = disp_pri;
1645 
1646 		if (state == TS_ONPROC) {
1647 			cpu_t *cp = t->t_disp_queue->disp_cpu;
1648 
1649 			if (t == cp->cpu_dispthread)
1650 				cp->cpu_dispatch_pri = DISP_PRIO(t);
1651 		}
1652 		return;
1653 	}
1654 
1655 	/*
1656 	 * It's either on a sleep queue or a run queue.
1657 	 */
1658 	if (state == TS_SLEEP) {
1659 		/*
1660 		 * Take the thread out of its sleep queue.
1661 		 * Change the inherited priority.
1662 		 * Re-enqueue the thread.
1663 		 * Each synchronization object exports a function
1664 		 * to do this in an appropriate manner.
1665 		 */
1666 		SOBJ_CHANGE_EPRI(t->t_sobj_ops, t, disp_pri);
1667 	} else if (state == TS_WAIT) {
1668 		/*
1669 		 * Re-enqueue a thread on the wait queue if its
1670 		 * effective priority needs to change.
1671 		 */
1672 		if (disp_pri != t->t_epri)
1673 			waitq_change_pri(t, disp_pri);
1674 	} else {
1675 		/*
1676 		 * The thread is on a run queue.
1677 		 * Note: setbackdq() may not put the thread
1678 		 * back on the same run queue where it originally
1679 		 * resided.
1680 		 */
1681 		(void) dispdeq(t);
1682 		t->t_epri = disp_pri;
1683 		setbackdq(t);
1684 	}
1685 }	/* end of thread_change_epri */
1686 
1687 /*
1688  * Function: Change the t_pri field of a thread.
1689  * Side Effects: Adjust the thread ordering on a run queue
1690  *		 or sleep queue, if necessary.
1691  * Returns: 1 if the thread was on a run queue, else 0.
1692  */
1693 int
1694 thread_change_pri(kthread_t *t, pri_t disp_pri, int front)
1695 {
1696 	uint_t	state;
1697 	int	on_rq = 0;
1698 
1699 	ASSERT(THREAD_LOCK_HELD(t));
1700 
1701 	state = t->t_state;
1702 	THREAD_WILLCHANGE_PRI(t, disp_pri);
1703 
1704 	/*
1705 	 * If it's not on a queue, change the priority with
1706 	 * impunity.
1707 	 */
1708 	if ((state & (TS_SLEEP | TS_RUN | TS_WAIT)) == 0) {
1709 		t->t_pri = disp_pri;
1710 
1711 		if (state == TS_ONPROC) {
1712 			cpu_t *cp = t->t_disp_queue->disp_cpu;
1713 
1714 			if (t == cp->cpu_dispthread)
1715 				cp->cpu_dispatch_pri = DISP_PRIO(t);
1716 		}
1717 		return (0);
1718 	}
1719 
1720 	/*
1721 	 * It's either on a sleep queue or a run queue.
1722 	 */
1723 	if (state == TS_SLEEP) {
1724 		/*
1725 		 * If the priority has changed, take the thread out of
1726 		 * its sleep queue and change the priority.
1727 		 * Re-enqueue the thread.
1728 		 * Each synchronization object exports a function
1729 		 * to do this in an appropriate manner.
1730 		 */
1731 		if (disp_pri != t->t_pri)
1732 			SOBJ_CHANGE_PRI(t->t_sobj_ops, t, disp_pri);
1733 	} else if (state == TS_WAIT) {
1734 		/*
1735 		 * Re-enqueue a thread on the wait queue if its
1736 		 * priority needs to change.
1737 		 */
1738 		if (disp_pri != t->t_pri)
1739 			waitq_change_pri(t, disp_pri);
1740 	} else {
1741 		/*
1742 		 * The thread is on a run queue.
1743 		 * Note: setbackdq() may not put the thread
1744 		 * back on the same run queue where it originally
1745 		 * resided.
1746 		 *
1747 		 * We still requeue the thread even if the priority
1748 		 * is unchanged to preserve round-robin (and other)
1749 		 * effects between threads of the same priority.
1750 		 */
1751 		on_rq = dispdeq(t);
1752 		ASSERT(on_rq);
1753 		t->t_pri = disp_pri;
1754 		if (front) {
1755 			setfrontdq(t);
1756 		} else {
1757 			setbackdq(t);
1758 		}
1759 	}
1760 	return (on_rq);
1761 }
1762