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