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