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