xref: /freebsd/sys/kern/subr_sleepqueue.c (revision 193d9e768ba63fcfb187cfd17f461f7d41345048)
1 /*-
2  * Copyright (c) 2004 John Baldwin <jhb@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * Implementation of sleep queues used to hold queue of threads blocked on
29  * a wait channel.  Sleep queues are different from turnstiles in that wait
30  * channels are not owned by anyone, so there is no priority propagation.
31  * Sleep queues can also provide a timeout and can also be interrupted by
32  * signals.  That said, there are several similarities between the turnstile
33  * and sleep queue implementations.  (Note: turnstiles were implemented
34  * first.)  For example, both use a hash table of the same size where each
35  * bucket is referred to as a "chain" that contains both a spin lock and
36  * a linked list of queues.  An individual queue is located by using a hash
37  * to pick a chain, locking the chain, and then walking the chain searching
38  * for the queue.  This means that a wait channel object does not need to
39  * embed its queue head just as locks do not embed their turnstile queue
40  * head.  Threads also carry around a sleep queue that they lend to the
41  * wait channel when blocking.  Just as in turnstiles, the queue includes
42  * a free list of the sleep queues of other threads blocked on the same
43  * wait channel in the case of multiple waiters.
44  *
45  * Some additional functionality provided by sleep queues include the
46  * ability to set a timeout.  The timeout is managed using a per-thread
47  * callout that resumes a thread if it is asleep.  A thread may also
48  * catch signals while it is asleep (aka an interruptible sleep).  The
49  * signal code uses sleepq_abort() to interrupt a sleeping thread.  Finally,
50  * sleep queues also provide some extra assertions.  One is not allowed to
51  * mix the sleep/wakeup and cv APIs for a given wait channel.  Also, one
52  * must consistently use the same lock to synchronize with a wait channel,
53  * though this check is currently only a warning for sleep/wakeup due to
54  * pre-existing abuse of that API.  The same lock must also be held when
55  * awakening threads, though that is currently only enforced for condition
56  * variables.
57  */
58 
59 #include <sys/cdefs.h>
60 __FBSDID("$FreeBSD$");
61 
62 #include "opt_sleepqueue_profiling.h"
63 #include "opt_ddb.h"
64 #include "opt_sched.h"
65 #include "opt_stack.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/lock.h>
70 #include <sys/kernel.h>
71 #include <sys/ktr.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/sbuf.h>
75 #include <sys/sched.h>
76 #include <sys/sdt.h>
77 #include <sys/signalvar.h>
78 #include <sys/sleepqueue.h>
79 #include <sys/stack.h>
80 #include <sys/sysctl.h>
81 
82 #include <vm/uma.h>
83 
84 #ifdef DDB
85 #include <ddb/ddb.h>
86 #endif
87 
88 
89 /*
90  * Constants for the hash table of sleep queue chains.
91  * SC_TABLESIZE must be a power of two for SC_MASK to work properly.
92  */
93 #define	SC_TABLESIZE	256			/* Must be power of 2. */
94 #define	SC_MASK		(SC_TABLESIZE - 1)
95 #define	SC_SHIFT	8
96 #define	SC_HASH(wc)	((((uintptr_t)(wc) >> SC_SHIFT) ^ (uintptr_t)(wc)) & \
97 			    SC_MASK)
98 #define	SC_LOOKUP(wc)	&sleepq_chains[SC_HASH(wc)]
99 #define NR_SLEEPQS      2
100 /*
101  * There are two different lists of sleep queues.  Both lists are connected
102  * via the sq_hash entries.  The first list is the sleep queue chain list
103  * that a sleep queue is on when it is attached to a wait channel.  The
104  * second list is the free list hung off of a sleep queue that is attached
105  * to a wait channel.
106  *
107  * Each sleep queue also contains the wait channel it is attached to, the
108  * list of threads blocked on that wait channel, flags specific to the
109  * wait channel, and the lock used to synchronize with a wait channel.
110  * The flags are used to catch mismatches between the various consumers
111  * of the sleep queue API (e.g. sleep/wakeup and condition variables).
112  * The lock pointer is only used when invariants are enabled for various
113  * debugging checks.
114  *
115  * Locking key:
116  *  c - sleep queue chain lock
117  */
118 struct sleepqueue {
119 	TAILQ_HEAD(, thread) sq_blocked[NR_SLEEPQS];	/* (c) Blocked threads. */
120 	u_int sq_blockedcnt[NR_SLEEPQS];	/* (c) N. of blocked threads. */
121 	LIST_ENTRY(sleepqueue) sq_hash;		/* (c) Chain and free list. */
122 	LIST_HEAD(, sleepqueue) sq_free;	/* (c) Free queues. */
123 	void	*sq_wchan;			/* (c) Wait channel. */
124 	int	sq_type;			/* (c) Queue type. */
125 #ifdef INVARIANTS
126 	struct lock_object *sq_lock;		/* (c) Associated lock. */
127 #endif
128 };
129 
130 struct sleepqueue_chain {
131 	LIST_HEAD(, sleepqueue) sc_queues;	/* List of sleep queues. */
132 	struct mtx sc_lock;			/* Spin lock for this chain. */
133 #ifdef SLEEPQUEUE_PROFILING
134 	u_int	sc_depth;			/* Length of sc_queues. */
135 	u_int	sc_max_depth;			/* Max length of sc_queues. */
136 #endif
137 };
138 
139 #ifdef SLEEPQUEUE_PROFILING
140 u_int sleepq_max_depth;
141 static SYSCTL_NODE(_debug, OID_AUTO, sleepq, CTLFLAG_RD, 0, "sleepq profiling");
142 static SYSCTL_NODE(_debug_sleepq, OID_AUTO, chains, CTLFLAG_RD, 0,
143     "sleepq chain stats");
144 SYSCTL_UINT(_debug_sleepq, OID_AUTO, max_depth, CTLFLAG_RD, &sleepq_max_depth,
145     0, "maxmimum depth achieved of a single chain");
146 
147 static void	sleepq_profile(const char *wmesg);
148 static int	prof_enabled;
149 #endif
150 static struct sleepqueue_chain sleepq_chains[SC_TABLESIZE];
151 static uma_zone_t sleepq_zone;
152 
153 /*
154  * Prototypes for non-exported routines.
155  */
156 static int	sleepq_catch_signals(void *wchan, int pri);
157 static int	sleepq_check_signals(void);
158 static int	sleepq_check_timeout(void);
159 #ifdef INVARIANTS
160 static void	sleepq_dtor(void *mem, int size, void *arg);
161 #endif
162 static int	sleepq_init(void *mem, int size, int flags);
163 static int	sleepq_resume_thread(struct sleepqueue *sq, struct thread *td,
164 		    int pri);
165 static void	sleepq_switch(void *wchan, int pri);
166 static void	sleepq_timeout(void *arg);
167 
168 SDT_PROBE_DECLARE(sched, , , sleep);
169 SDT_PROBE_DECLARE(sched, , , wakeup);
170 
171 /*
172  * Initialize SLEEPQUEUE_PROFILING specific sysctl nodes.
173  * Note that it must happen after sleepinit() has been fully executed, so
174  * it must happen after SI_SUB_KMEM SYSINIT() subsystem setup.
175  */
176 #ifdef SLEEPQUEUE_PROFILING
177 static void
178 init_sleepqueue_profiling(void)
179 {
180 	char chain_name[10];
181 	struct sysctl_oid *chain_oid;
182 	u_int i;
183 
184 	for (i = 0; i < SC_TABLESIZE; i++) {
185 		snprintf(chain_name, sizeof(chain_name), "%u", i);
186 		chain_oid = SYSCTL_ADD_NODE(NULL,
187 		    SYSCTL_STATIC_CHILDREN(_debug_sleepq_chains), OID_AUTO,
188 		    chain_name, CTLFLAG_RD, NULL, "sleepq chain stats");
189 		SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
190 		    "depth", CTLFLAG_RD, &sleepq_chains[i].sc_depth, 0, NULL);
191 		SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
192 		    "max_depth", CTLFLAG_RD, &sleepq_chains[i].sc_max_depth, 0,
193 		    NULL);
194 	}
195 }
196 
197 SYSINIT(sleepqueue_profiling, SI_SUB_LOCK, SI_ORDER_ANY,
198     init_sleepqueue_profiling, NULL);
199 #endif
200 
201 /*
202  * Early initialization of sleep queues that is called from the sleepinit()
203  * SYSINIT.
204  */
205 void
206 init_sleepqueues(void)
207 {
208 	int i;
209 
210 	for (i = 0; i < SC_TABLESIZE; i++) {
211 		LIST_INIT(&sleepq_chains[i].sc_queues);
212 		mtx_init(&sleepq_chains[i].sc_lock, "sleepq chain", NULL,
213 		    MTX_SPIN | MTX_RECURSE);
214 	}
215 	sleepq_zone = uma_zcreate("SLEEPQUEUE", sizeof(struct sleepqueue),
216 #ifdef INVARIANTS
217 	    NULL, sleepq_dtor, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
218 #else
219 	    NULL, NULL, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
220 #endif
221 
222 	thread0.td_sleepqueue = sleepq_alloc();
223 }
224 
225 /*
226  * Get a sleep queue for a new thread.
227  */
228 struct sleepqueue *
229 sleepq_alloc(void)
230 {
231 
232 	return (uma_zalloc(sleepq_zone, M_WAITOK));
233 }
234 
235 /*
236  * Free a sleep queue when a thread is destroyed.
237  */
238 void
239 sleepq_free(struct sleepqueue *sq)
240 {
241 
242 	uma_zfree(sleepq_zone, sq);
243 }
244 
245 /*
246  * Lock the sleep queue chain associated with the specified wait channel.
247  */
248 void
249 sleepq_lock(void *wchan)
250 {
251 	struct sleepqueue_chain *sc;
252 
253 	sc = SC_LOOKUP(wchan);
254 	mtx_lock_spin(&sc->sc_lock);
255 }
256 
257 /*
258  * Look up the sleep queue associated with a given wait channel in the hash
259  * table locking the associated sleep queue chain.  If no queue is found in
260  * the table, NULL is returned.
261  */
262 struct sleepqueue *
263 sleepq_lookup(void *wchan)
264 {
265 	struct sleepqueue_chain *sc;
266 	struct sleepqueue *sq;
267 
268 	KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
269 	sc = SC_LOOKUP(wchan);
270 	mtx_assert(&sc->sc_lock, MA_OWNED);
271 	LIST_FOREACH(sq, &sc->sc_queues, sq_hash)
272 		if (sq->sq_wchan == wchan)
273 			return (sq);
274 	return (NULL);
275 }
276 
277 /*
278  * Unlock the sleep queue chain associated with a given wait channel.
279  */
280 void
281 sleepq_release(void *wchan)
282 {
283 	struct sleepqueue_chain *sc;
284 
285 	sc = SC_LOOKUP(wchan);
286 	mtx_unlock_spin(&sc->sc_lock);
287 }
288 
289 /*
290  * Places the current thread on the sleep queue for the specified wait
291  * channel.  If INVARIANTS is enabled, then it associates the passed in
292  * lock with the sleepq to make sure it is held when that sleep queue is
293  * woken up.
294  */
295 void
296 sleepq_add(void *wchan, struct lock_object *lock, const char *wmesg, int flags,
297     int queue)
298 {
299 	struct sleepqueue_chain *sc;
300 	struct sleepqueue *sq;
301 	struct thread *td;
302 
303 	td = curthread;
304 	sc = SC_LOOKUP(wchan);
305 	mtx_assert(&sc->sc_lock, MA_OWNED);
306 	MPASS(td->td_sleepqueue != NULL);
307 	MPASS(wchan != NULL);
308 	MPASS((queue >= 0) && (queue < NR_SLEEPQS));
309 
310 	/* If this thread is not allowed to sleep, die a horrible death. */
311 	KASSERT(td->td_no_sleeping == 0,
312 	    ("%s: td %p to sleep on wchan %p with sleeping prohibited",
313 	    __func__, td, wchan));
314 
315 	/* Look up the sleep queue associated with the wait channel 'wchan'. */
316 	sq = sleepq_lookup(wchan);
317 
318 	/*
319 	 * If the wait channel does not already have a sleep queue, use
320 	 * this thread's sleep queue.  Otherwise, insert the current thread
321 	 * into the sleep queue already in use by this wait channel.
322 	 */
323 	if (sq == NULL) {
324 #ifdef INVARIANTS
325 		int i;
326 
327 		sq = td->td_sleepqueue;
328 		for (i = 0; i < NR_SLEEPQS; i++) {
329 			KASSERT(TAILQ_EMPTY(&sq->sq_blocked[i]),
330 			    ("thread's sleep queue %d is not empty", i));
331 			KASSERT(sq->sq_blockedcnt[i] == 0,
332 			    ("thread's sleep queue %d count mismatches", i));
333 		}
334 		KASSERT(LIST_EMPTY(&sq->sq_free),
335 		    ("thread's sleep queue has a non-empty free list"));
336 		KASSERT(sq->sq_wchan == NULL, ("stale sq_wchan pointer"));
337 		sq->sq_lock = lock;
338 #endif
339 #ifdef SLEEPQUEUE_PROFILING
340 		sc->sc_depth++;
341 		if (sc->sc_depth > sc->sc_max_depth) {
342 			sc->sc_max_depth = sc->sc_depth;
343 			if (sc->sc_max_depth > sleepq_max_depth)
344 				sleepq_max_depth = sc->sc_max_depth;
345 		}
346 #endif
347 		sq = td->td_sleepqueue;
348 		LIST_INSERT_HEAD(&sc->sc_queues, sq, sq_hash);
349 		sq->sq_wchan = wchan;
350 		sq->sq_type = flags & SLEEPQ_TYPE;
351 	} else {
352 		MPASS(wchan == sq->sq_wchan);
353 		MPASS(lock == sq->sq_lock);
354 		MPASS((flags & SLEEPQ_TYPE) == sq->sq_type);
355 		LIST_INSERT_HEAD(&sq->sq_free, td->td_sleepqueue, sq_hash);
356 	}
357 	thread_lock(td);
358 	TAILQ_INSERT_TAIL(&sq->sq_blocked[queue], td, td_slpq);
359 	sq->sq_blockedcnt[queue]++;
360 	td->td_sleepqueue = NULL;
361 	td->td_sqqueue = queue;
362 	td->td_wchan = wchan;
363 	td->td_wmesg = wmesg;
364 	if (flags & SLEEPQ_INTERRUPTIBLE) {
365 		td->td_flags |= TDF_SINTR;
366 		td->td_flags &= ~TDF_SLEEPABORT;
367 	}
368 	thread_unlock(td);
369 }
370 
371 /*
372  * Sets a timeout that will remove the current thread from the specified
373  * sleep queue after timo ticks if the thread has not already been awakened.
374  */
375 void
376 sleepq_set_timeout_sbt(void *wchan, sbintime_t sbt, sbintime_t pr,
377     int flags)
378 {
379 	struct sleepqueue_chain *sc;
380 	struct thread *td;
381 	sbintime_t pr1;
382 
383 	td = curthread;
384 	sc = SC_LOOKUP(wchan);
385 	mtx_assert(&sc->sc_lock, MA_OWNED);
386 	MPASS(TD_ON_SLEEPQ(td));
387 	MPASS(td->td_sleepqueue == NULL);
388 	MPASS(wchan != NULL);
389 	if (cold && td == &thread0)
390 		panic("timed sleep before timers are working");
391 	KASSERT(td->td_sleeptimo == 0, ("td %d %p td_sleeptimo %jx",
392 	    td->td_tid, td, (uintmax_t)td->td_sleeptimo));
393 	thread_lock(td);
394 	callout_when(sbt, pr, flags, &td->td_sleeptimo, &pr1);
395 	thread_unlock(td);
396 	callout_reset_sbt_on(&td->td_slpcallout, td->td_sleeptimo, pr1,
397 	    sleepq_timeout, td, PCPU_GET(cpuid), flags | C_PRECALC |
398 	    C_DIRECT_EXEC);
399 }
400 
401 /*
402  * Return the number of actual sleepers for the specified queue.
403  */
404 u_int
405 sleepq_sleepcnt(void *wchan, int queue)
406 {
407 	struct sleepqueue *sq;
408 
409 	KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
410 	MPASS((queue >= 0) && (queue < NR_SLEEPQS));
411 	sq = sleepq_lookup(wchan);
412 	if (sq == NULL)
413 		return (0);
414 	return (sq->sq_blockedcnt[queue]);
415 }
416 
417 /*
418  * Marks the pending sleep of the current thread as interruptible and
419  * makes an initial check for pending signals before putting a thread
420  * to sleep. Enters and exits with the thread lock held.  Thread lock
421  * may have transitioned from the sleepq lock to a run lock.
422  */
423 static int
424 sleepq_catch_signals(void *wchan, int pri)
425 {
426 	struct sleepqueue_chain *sc;
427 	struct sleepqueue *sq;
428 	struct thread *td;
429 	struct proc *p;
430 	struct sigacts *ps;
431 	int sig, ret;
432 
433 	ret = 0;
434 	td = curthread;
435 	p = curproc;
436 	sc = SC_LOOKUP(wchan);
437 	mtx_assert(&sc->sc_lock, MA_OWNED);
438 	MPASS(wchan != NULL);
439 	if ((td->td_pflags & TDP_WAKEUP) != 0) {
440 		td->td_pflags &= ~TDP_WAKEUP;
441 		ret = EINTR;
442 		thread_lock(td);
443 		goto out;
444 	}
445 
446 	/*
447 	 * See if there are any pending signals or suspension requests for this
448 	 * thread.  If not, we can switch immediately.
449 	 */
450 	thread_lock(td);
451 	if ((td->td_flags & (TDF_NEEDSIGCHK | TDF_NEEDSUSPCHK)) != 0) {
452 		thread_unlock(td);
453 		mtx_unlock_spin(&sc->sc_lock);
454 		CTR3(KTR_PROC, "sleepq catching signals: thread %p (pid %ld, %s)",
455 			(void *)td, (long)p->p_pid, td->td_name);
456 		PROC_LOCK(p);
457 		/*
458 		 * Check for suspension first. Checking for signals and then
459 		 * suspending could result in a missed signal, since a signal
460 		 * can be delivered while this thread is suspended.
461 		 */
462 		if ((td->td_flags & TDF_NEEDSUSPCHK) != 0) {
463 			ret = thread_suspend_check(1);
464 			MPASS(ret == 0 || ret == EINTR || ret == ERESTART);
465 			if (ret != 0) {
466 				PROC_UNLOCK(p);
467 				mtx_lock_spin(&sc->sc_lock);
468 				thread_lock(td);
469 				goto out;
470 			}
471 		}
472 		if ((td->td_flags & TDF_NEEDSIGCHK) != 0) {
473 			ps = p->p_sigacts;
474 			mtx_lock(&ps->ps_mtx);
475 			sig = cursig(td);
476 			if (sig == -1) {
477 				mtx_unlock(&ps->ps_mtx);
478 				KASSERT((td->td_flags & TDF_SBDRY) != 0,
479 				    ("lost TDF_SBDRY"));
480 				KASSERT(TD_SBDRY_INTR(td),
481 				    ("lost TDF_SERESTART of TDF_SEINTR"));
482 				KASSERT((td->td_flags &
483 				    (TDF_SEINTR | TDF_SERESTART)) !=
484 				    (TDF_SEINTR | TDF_SERESTART),
485 				    ("both TDF_SEINTR and TDF_SERESTART"));
486 				ret = TD_SBDRY_ERRNO(td);
487 			} else if (sig != 0) {
488 				ret = SIGISMEMBER(ps->ps_sigintr, sig) ?
489 				    EINTR : ERESTART;
490 				mtx_unlock(&ps->ps_mtx);
491 			} else {
492 				mtx_unlock(&ps->ps_mtx);
493 			}
494 		}
495 		/*
496 		 * Lock the per-process spinlock prior to dropping the PROC_LOCK
497 		 * to avoid a signal delivery race.  PROC_LOCK, PROC_SLOCK, and
498 		 * thread_lock() are currently held in tdsendsignal().
499 		 */
500 		PROC_SLOCK(p);
501 		mtx_lock_spin(&sc->sc_lock);
502 		PROC_UNLOCK(p);
503 		thread_lock(td);
504 		PROC_SUNLOCK(p);
505 	}
506 	if (ret == 0) {
507 		sleepq_switch(wchan, pri);
508 		return (0);
509 	}
510 out:
511 	/*
512 	 * There were pending signals and this thread is still
513 	 * on the sleep queue, remove it from the sleep queue.
514 	 */
515 	if (TD_ON_SLEEPQ(td)) {
516 		sq = sleepq_lookup(wchan);
517 		if (sleepq_resume_thread(sq, td, 0)) {
518 #ifdef INVARIANTS
519 			/*
520 			 * This thread hasn't gone to sleep yet, so it
521 			 * should not be swapped out.
522 			 */
523 			panic("not waking up swapper");
524 #endif
525 		}
526 	}
527 	mtx_unlock_spin(&sc->sc_lock);
528 	MPASS(td->td_lock != &sc->sc_lock);
529 	return (ret);
530 }
531 
532 /*
533  * Switches to another thread if we are still asleep on a sleep queue.
534  * Returns with thread lock.
535  */
536 static void
537 sleepq_switch(void *wchan, int pri)
538 {
539 	struct sleepqueue_chain *sc;
540 	struct sleepqueue *sq;
541 	struct thread *td;
542 
543 	td = curthread;
544 	sc = SC_LOOKUP(wchan);
545 	mtx_assert(&sc->sc_lock, MA_OWNED);
546 	THREAD_LOCK_ASSERT(td, MA_OWNED);
547 
548 	/*
549 	 * If we have a sleep queue, then we've already been woken up, so
550 	 * just return.
551 	 */
552 	if (td->td_sleepqueue != NULL) {
553 		mtx_unlock_spin(&sc->sc_lock);
554 		return;
555 	}
556 
557 	/*
558 	 * If TDF_TIMEOUT is set, then our sleep has been timed out
559 	 * already but we are still on the sleep queue, so dequeue the
560 	 * thread and return.
561 	 */
562 	if (td->td_flags & TDF_TIMEOUT) {
563 		MPASS(TD_ON_SLEEPQ(td));
564 		sq = sleepq_lookup(wchan);
565 		if (sleepq_resume_thread(sq, td, 0)) {
566 #ifdef INVARIANTS
567 			/*
568 			 * This thread hasn't gone to sleep yet, so it
569 			 * should not be swapped out.
570 			 */
571 			panic("not waking up swapper");
572 #endif
573 		}
574 		mtx_unlock_spin(&sc->sc_lock);
575 		return;
576 	}
577 #ifdef SLEEPQUEUE_PROFILING
578 	if (prof_enabled)
579 		sleepq_profile(td->td_wmesg);
580 #endif
581 	MPASS(td->td_sleepqueue == NULL);
582 	sched_sleep(td, pri);
583 	thread_lock_set(td, &sc->sc_lock);
584 	SDT_PROBE0(sched, , , sleep);
585 	TD_SET_SLEEPING(td);
586 	mi_switch(SW_VOL | SWT_SLEEPQ, NULL);
587 	KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING"));
588 	CTR3(KTR_PROC, "sleepq resume: thread %p (pid %ld, %s)",
589 	    (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
590 }
591 
592 /*
593  * Check to see if we timed out.
594  */
595 static int
596 sleepq_check_timeout(void)
597 {
598 	struct thread *td;
599 	int res;
600 
601 	td = curthread;
602 	THREAD_LOCK_ASSERT(td, MA_OWNED);
603 
604 	/*
605 	 * If TDF_TIMEOUT is set, we timed out.  But recheck
606 	 * td_sleeptimo anyway.
607 	 */
608 	res = 0;
609 	if (td->td_sleeptimo != 0) {
610 		if (td->td_sleeptimo <= sbinuptime())
611 			res = EWOULDBLOCK;
612 		td->td_sleeptimo = 0;
613 	}
614 	if (td->td_flags & TDF_TIMEOUT)
615 		td->td_flags &= ~TDF_TIMEOUT;
616 	else
617 		/*
618 		 * We ignore the situation where timeout subsystem was
619 		 * unable to stop our callout.  The struct thread is
620 		 * type-stable, the callout will use the correct
621 		 * memory when running.  The checks of the
622 		 * td_sleeptimo value in this function and in
623 		 * sleepq_timeout() ensure that the thread does not
624 		 * get spurious wakeups, even if the callout was reset
625 		 * or thread reused.
626 		 */
627 		callout_stop(&td->td_slpcallout);
628 	return (res);
629 }
630 
631 /*
632  * Check to see if we were awoken by a signal.
633  */
634 static int
635 sleepq_check_signals(void)
636 {
637 	struct thread *td;
638 
639 	td = curthread;
640 	THREAD_LOCK_ASSERT(td, MA_OWNED);
641 
642 	/* We are no longer in an interruptible sleep. */
643 	if (td->td_flags & TDF_SINTR)
644 		td->td_flags &= ~TDF_SINTR;
645 
646 	if (td->td_flags & TDF_SLEEPABORT) {
647 		td->td_flags &= ~TDF_SLEEPABORT;
648 		return (td->td_intrval);
649 	}
650 
651 	return (0);
652 }
653 
654 /*
655  * Block the current thread until it is awakened from its sleep queue.
656  */
657 void
658 sleepq_wait(void *wchan, int pri)
659 {
660 	struct thread *td;
661 
662 	td = curthread;
663 	MPASS(!(td->td_flags & TDF_SINTR));
664 	thread_lock(td);
665 	sleepq_switch(wchan, pri);
666 	thread_unlock(td);
667 }
668 
669 /*
670  * Block the current thread until it is awakened from its sleep queue
671  * or it is interrupted by a signal.
672  */
673 int
674 sleepq_wait_sig(void *wchan, int pri)
675 {
676 	int rcatch;
677 	int rval;
678 
679 	rcatch = sleepq_catch_signals(wchan, pri);
680 	rval = sleepq_check_signals();
681 	thread_unlock(curthread);
682 	if (rcatch)
683 		return (rcatch);
684 	return (rval);
685 }
686 
687 /*
688  * Block the current thread until it is awakened from its sleep queue
689  * or it times out while waiting.
690  */
691 int
692 sleepq_timedwait(void *wchan, int pri)
693 {
694 	struct thread *td;
695 	int rval;
696 
697 	td = curthread;
698 	MPASS(!(td->td_flags & TDF_SINTR));
699 	thread_lock(td);
700 	sleepq_switch(wchan, pri);
701 	rval = sleepq_check_timeout();
702 	thread_unlock(td);
703 
704 	return (rval);
705 }
706 
707 /*
708  * Block the current thread until it is awakened from its sleep queue,
709  * it is interrupted by a signal, or it times out waiting to be awakened.
710  */
711 int
712 sleepq_timedwait_sig(void *wchan, int pri)
713 {
714 	int rcatch, rvalt, rvals;
715 
716 	rcatch = sleepq_catch_signals(wchan, pri);
717 	rvalt = sleepq_check_timeout();
718 	rvals = sleepq_check_signals();
719 	thread_unlock(curthread);
720 	if (rcatch)
721 		return (rcatch);
722 	if (rvals)
723 		return (rvals);
724 	return (rvalt);
725 }
726 
727 /*
728  * Returns the type of sleepqueue given a waitchannel.
729  */
730 int
731 sleepq_type(void *wchan)
732 {
733 	struct sleepqueue *sq;
734 	int type;
735 
736 	MPASS(wchan != NULL);
737 
738 	sleepq_lock(wchan);
739 	sq = sleepq_lookup(wchan);
740 	if (sq == NULL) {
741 		sleepq_release(wchan);
742 		return (-1);
743 	}
744 	type = sq->sq_type;
745 	sleepq_release(wchan);
746 	return (type);
747 }
748 
749 /*
750  * Removes a thread from a sleep queue and makes it
751  * runnable.
752  */
753 static int
754 sleepq_resume_thread(struct sleepqueue *sq, struct thread *td, int pri)
755 {
756 	struct sleepqueue_chain *sc;
757 
758 	MPASS(td != NULL);
759 	MPASS(sq->sq_wchan != NULL);
760 	MPASS(td->td_wchan == sq->sq_wchan);
761 	MPASS(td->td_sqqueue < NR_SLEEPQS && td->td_sqqueue >= 0);
762 	THREAD_LOCK_ASSERT(td, MA_OWNED);
763 	sc = SC_LOOKUP(sq->sq_wchan);
764 	mtx_assert(&sc->sc_lock, MA_OWNED);
765 
766 	SDT_PROBE2(sched, , , wakeup, td, td->td_proc);
767 
768 	/* Remove the thread from the queue. */
769 	sq->sq_blockedcnt[td->td_sqqueue]--;
770 	TAILQ_REMOVE(&sq->sq_blocked[td->td_sqqueue], td, td_slpq);
771 
772 	/*
773 	 * Get a sleep queue for this thread.  If this is the last waiter,
774 	 * use the queue itself and take it out of the chain, otherwise,
775 	 * remove a queue from the free list.
776 	 */
777 	if (LIST_EMPTY(&sq->sq_free)) {
778 		td->td_sleepqueue = sq;
779 #ifdef INVARIANTS
780 		sq->sq_wchan = NULL;
781 #endif
782 #ifdef SLEEPQUEUE_PROFILING
783 		sc->sc_depth--;
784 #endif
785 	} else
786 		td->td_sleepqueue = LIST_FIRST(&sq->sq_free);
787 	LIST_REMOVE(td->td_sleepqueue, sq_hash);
788 
789 	td->td_wmesg = NULL;
790 	td->td_wchan = NULL;
791 	td->td_flags &= ~TDF_SINTR;
792 
793 	CTR3(KTR_PROC, "sleepq_wakeup: thread %p (pid %ld, %s)",
794 	    (void *)td, (long)td->td_proc->p_pid, td->td_name);
795 
796 	/* Adjust priority if requested. */
797 	MPASS(pri == 0 || (pri >= PRI_MIN && pri <= PRI_MAX));
798 	if (pri != 0 && td->td_priority > pri &&
799 	    PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
800 		sched_prio(td, pri);
801 
802 	/*
803 	 * Note that thread td might not be sleeping if it is running
804 	 * sleepq_catch_signals() on another CPU or is blocked on its
805 	 * proc lock to check signals.  There's no need to mark the
806 	 * thread runnable in that case.
807 	 */
808 	if (TD_IS_SLEEPING(td)) {
809 		TD_CLR_SLEEPING(td);
810 		return (setrunnable(td));
811 	}
812 	return (0);
813 }
814 
815 #ifdef INVARIANTS
816 /*
817  * UMA zone item deallocator.
818  */
819 static void
820 sleepq_dtor(void *mem, int size, void *arg)
821 {
822 	struct sleepqueue *sq;
823 	int i;
824 
825 	sq = mem;
826 	for (i = 0; i < NR_SLEEPQS; i++) {
827 		MPASS(TAILQ_EMPTY(&sq->sq_blocked[i]));
828 		MPASS(sq->sq_blockedcnt[i] == 0);
829 	}
830 }
831 #endif
832 
833 /*
834  * UMA zone item initializer.
835  */
836 static int
837 sleepq_init(void *mem, int size, int flags)
838 {
839 	struct sleepqueue *sq;
840 	int i;
841 
842 	bzero(mem, size);
843 	sq = mem;
844 	for (i = 0; i < NR_SLEEPQS; i++) {
845 		TAILQ_INIT(&sq->sq_blocked[i]);
846 		sq->sq_blockedcnt[i] = 0;
847 	}
848 	LIST_INIT(&sq->sq_free);
849 	return (0);
850 }
851 
852 /*
853  * Find the highest priority thread sleeping on a wait channel and resume it.
854  */
855 int
856 sleepq_signal(void *wchan, int flags, int pri, int queue)
857 {
858 	struct sleepqueue *sq;
859 	struct thread *td, *besttd;
860 	int wakeup_swapper;
861 
862 	CTR2(KTR_PROC, "sleepq_signal(%p, %d)", wchan, flags);
863 	KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
864 	MPASS((queue >= 0) && (queue < NR_SLEEPQS));
865 	sq = sleepq_lookup(wchan);
866 	if (sq == NULL)
867 		return (0);
868 	KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
869 	    ("%s: mismatch between sleep/wakeup and cv_*", __func__));
870 
871 	/*
872 	 * Find the highest priority thread on the queue.  If there is a
873 	 * tie, use the thread that first appears in the queue as it has
874 	 * been sleeping the longest since threads are always added to
875 	 * the tail of sleep queues.
876 	 */
877 	besttd = TAILQ_FIRST(&sq->sq_blocked[queue]);
878 	TAILQ_FOREACH(td, &sq->sq_blocked[queue], td_slpq) {
879 		if (td->td_priority < besttd->td_priority)
880 			besttd = td;
881 	}
882 	MPASS(besttd != NULL);
883 	thread_lock(besttd);
884 	wakeup_swapper = sleepq_resume_thread(sq, besttd, pri);
885 	thread_unlock(besttd);
886 	return (wakeup_swapper);
887 }
888 
889 /*
890  * Resume all threads sleeping on a specified wait channel.
891  */
892 int
893 sleepq_broadcast(void *wchan, int flags, int pri, int queue)
894 {
895 	struct sleepqueue *sq;
896 	struct thread *td, *tdn;
897 	int wakeup_swapper;
898 
899 	CTR2(KTR_PROC, "sleepq_broadcast(%p, %d)", wchan, flags);
900 	KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
901 	MPASS((queue >= 0) && (queue < NR_SLEEPQS));
902 	sq = sleepq_lookup(wchan);
903 	if (sq == NULL)
904 		return (0);
905 	KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
906 	    ("%s: mismatch between sleep/wakeup and cv_*", __func__));
907 
908 	/*
909 	 * Resume all blocked threads on the sleep queue.  The last thread will
910 	 * be given ownership of sq and may re-enqueue itself before
911 	 * sleepq_resume_thread() returns, so we must cache the "next" queue
912 	 * item at the beginning of the final iteration.
913 	 */
914 	wakeup_swapper = 0;
915 	TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq, tdn) {
916 		thread_lock(td);
917 		wakeup_swapper |= sleepq_resume_thread(sq, td, pri);
918 		thread_unlock(td);
919 	}
920 	return (wakeup_swapper);
921 }
922 
923 /*
924  * Time sleeping threads out.  When the timeout expires, the thread is
925  * removed from the sleep queue and made runnable if it is still asleep.
926  */
927 static void
928 sleepq_timeout(void *arg)
929 {
930 	struct sleepqueue_chain *sc;
931 	struct sleepqueue *sq;
932 	struct thread *td;
933 	void *wchan;
934 	int wakeup_swapper;
935 
936 	td = arg;
937 	wakeup_swapper = 0;
938 	CTR3(KTR_PROC, "sleepq_timeout: thread %p (pid %ld, %s)",
939 	    (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
940 
941 	thread_lock(td);
942 
943 	if (td->td_sleeptimo > sbinuptime() || td->td_sleeptimo == 0) {
944 		/*
945 		 * The thread does not want a timeout (yet).
946 		 */
947 	} else if (TD_IS_SLEEPING(td) && TD_ON_SLEEPQ(td)) {
948 		/*
949 		 * See if the thread is asleep and get the wait
950 		 * channel if it is.
951 		 */
952 		wchan = td->td_wchan;
953 		sc = SC_LOOKUP(wchan);
954 		THREAD_LOCKPTR_ASSERT(td, &sc->sc_lock);
955 		sq = sleepq_lookup(wchan);
956 		MPASS(sq != NULL);
957 		td->td_flags |= TDF_TIMEOUT;
958 		wakeup_swapper = sleepq_resume_thread(sq, td, 0);
959 	} else if (TD_ON_SLEEPQ(td)) {
960 		/*
961 		 * If the thread is on the SLEEPQ but isn't sleeping
962 		 * yet, it can either be on another CPU in between
963 		 * sleepq_add() and one of the sleepq_*wait*()
964 		 * routines or it can be in sleepq_catch_signals().
965 		 */
966 		td->td_flags |= TDF_TIMEOUT;
967 	}
968 
969 	thread_unlock(td);
970 	if (wakeup_swapper)
971 		kick_proc0();
972 }
973 
974 /*
975  * Resumes a specific thread from the sleep queue associated with a specific
976  * wait channel if it is on that queue.
977  */
978 void
979 sleepq_remove(struct thread *td, void *wchan)
980 {
981 	struct sleepqueue *sq;
982 	int wakeup_swapper;
983 
984 	/*
985 	 * Look up the sleep queue for this wait channel, then re-check
986 	 * that the thread is asleep on that channel, if it is not, then
987 	 * bail.
988 	 */
989 	MPASS(wchan != NULL);
990 	sleepq_lock(wchan);
991 	sq = sleepq_lookup(wchan);
992 	/*
993 	 * We can not lock the thread here as it may be sleeping on a
994 	 * different sleepq.  However, holding the sleepq lock for this
995 	 * wchan can guarantee that we do not miss a wakeup for this
996 	 * channel.  The asserts below will catch any false positives.
997 	 */
998 	if (!TD_ON_SLEEPQ(td) || td->td_wchan != wchan) {
999 		sleepq_release(wchan);
1000 		return;
1001 	}
1002 	/* Thread is asleep on sleep queue sq, so wake it up. */
1003 	thread_lock(td);
1004 	MPASS(sq != NULL);
1005 	MPASS(td->td_wchan == wchan);
1006 	wakeup_swapper = sleepq_resume_thread(sq, td, 0);
1007 	thread_unlock(td);
1008 	sleepq_release(wchan);
1009 	if (wakeup_swapper)
1010 		kick_proc0();
1011 }
1012 
1013 /*
1014  * Abort a thread as if an interrupt had occurred.  Only abort
1015  * interruptible waits (unfortunately it isn't safe to abort others).
1016  */
1017 int
1018 sleepq_abort(struct thread *td, int intrval)
1019 {
1020 	struct sleepqueue *sq;
1021 	void *wchan;
1022 
1023 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1024 	MPASS(TD_ON_SLEEPQ(td));
1025 	MPASS(td->td_flags & TDF_SINTR);
1026 	MPASS(intrval == EINTR || intrval == ERESTART);
1027 
1028 	/*
1029 	 * If the TDF_TIMEOUT flag is set, just leave. A
1030 	 * timeout is scheduled anyhow.
1031 	 */
1032 	if (td->td_flags & TDF_TIMEOUT)
1033 		return (0);
1034 
1035 	CTR3(KTR_PROC, "sleepq_abort: thread %p (pid %ld, %s)",
1036 	    (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
1037 	td->td_intrval = intrval;
1038 	td->td_flags |= TDF_SLEEPABORT;
1039 	/*
1040 	 * If the thread has not slept yet it will find the signal in
1041 	 * sleepq_catch_signals() and call sleepq_resume_thread.  Otherwise
1042 	 * we have to do it here.
1043 	 */
1044 	if (!TD_IS_SLEEPING(td))
1045 		return (0);
1046 	wchan = td->td_wchan;
1047 	MPASS(wchan != NULL);
1048 	sq = sleepq_lookup(wchan);
1049 	MPASS(sq != NULL);
1050 
1051 	/* Thread is asleep on sleep queue sq, so wake it up. */
1052 	return (sleepq_resume_thread(sq, td, 0));
1053 }
1054 
1055 /*
1056  * Prints the stacks of all threads presently sleeping on wchan/queue to
1057  * the sbuf sb.  Sets count_stacks_printed to the number of stacks actually
1058  * printed.  Typically, this will equal the number of threads sleeping on the
1059  * queue, but may be less if sb overflowed before all stacks were printed.
1060  */
1061 #ifdef STACK
1062 int
1063 sleepq_sbuf_print_stacks(struct sbuf *sb, void *wchan, int queue,
1064     int *count_stacks_printed)
1065 {
1066 	struct thread *td, *td_next;
1067 	struct sleepqueue *sq;
1068 	struct stack **st;
1069 	struct sbuf **td_infos;
1070 	int i, stack_idx, error, stacks_to_allocate;
1071 	bool finished, partial_print;
1072 
1073 	error = 0;
1074 	finished = false;
1075 	partial_print = false;
1076 
1077 	KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
1078 	MPASS((queue >= 0) && (queue < NR_SLEEPQS));
1079 
1080 	stacks_to_allocate = 10;
1081 	for (i = 0; i < 3 && !finished ; i++) {
1082 		/* We cannot malloc while holding the queue's spinlock, so
1083 		 * we do our mallocs now, and hope it is enough.  If it
1084 		 * isn't, we will free these, drop the lock, malloc more,
1085 		 * and try again, up to a point.  After that point we will
1086 		 * give up and report ENOMEM. We also cannot write to sb
1087 		 * during this time since the client may have set the
1088 		 * SBUF_AUTOEXTEND flag on their sbuf, which could cause a
1089 		 * malloc as we print to it.  So we defer actually printing
1090 		 * to sb until after we drop the spinlock.
1091 		 */
1092 
1093 		/* Where we will store the stacks. */
1094 		st = malloc(sizeof(struct stack *) * stacks_to_allocate,
1095 		    M_TEMP, M_WAITOK);
1096 		for (stack_idx = 0; stack_idx < stacks_to_allocate;
1097 		    stack_idx++)
1098 			st[stack_idx] = stack_create();
1099 
1100 		/* Where we will store the td name, tid, etc. */
1101 		td_infos = malloc(sizeof(struct sbuf *) * stacks_to_allocate,
1102 		    M_TEMP, M_WAITOK);
1103 		for (stack_idx = 0; stack_idx < stacks_to_allocate;
1104 		    stack_idx++)
1105 			td_infos[stack_idx] = sbuf_new(NULL, NULL,
1106 			    MAXCOMLEN + sizeof(struct thread *) * 2 + 40,
1107 			    SBUF_FIXEDLEN);
1108 
1109 		sleepq_lock(wchan);
1110 		sq = sleepq_lookup(wchan);
1111 		if (sq == NULL) {
1112 			/* This sleepq does not exist; exit and return ENOENT. */
1113 			error = ENOENT;
1114 			finished = true;
1115 			sleepq_release(wchan);
1116 			goto loop_end;
1117 		}
1118 
1119 		stack_idx = 0;
1120 		/* Save thread info */
1121 		TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq,
1122 		    td_next) {
1123 			if (stack_idx >= stacks_to_allocate)
1124 				goto loop_end;
1125 
1126 			/* Note the td_lock is equal to the sleepq_lock here. */
1127 			stack_save_td(st[stack_idx], td);
1128 
1129 			sbuf_printf(td_infos[stack_idx], "%d: %s %p",
1130 			    td->td_tid, td->td_name, td);
1131 
1132 			++stack_idx;
1133 		}
1134 
1135 		finished = true;
1136 		sleepq_release(wchan);
1137 
1138 		/* Print the stacks */
1139 		for (i = 0; i < stack_idx; i++) {
1140 			sbuf_finish(td_infos[i]);
1141 			sbuf_printf(sb, "--- thread %s: ---\n", sbuf_data(td_infos[i]));
1142 			stack_sbuf_print(sb, st[i]);
1143 			sbuf_printf(sb, "\n");
1144 
1145 			error = sbuf_error(sb);
1146 			if (error == 0)
1147 				*count_stacks_printed = stack_idx;
1148 		}
1149 
1150 loop_end:
1151 		if (!finished)
1152 			sleepq_release(wchan);
1153 		for (stack_idx = 0; stack_idx < stacks_to_allocate;
1154 		    stack_idx++)
1155 			stack_destroy(st[stack_idx]);
1156 		for (stack_idx = 0; stack_idx < stacks_to_allocate;
1157 		    stack_idx++)
1158 			sbuf_delete(td_infos[stack_idx]);
1159 		free(st, M_TEMP);
1160 		free(td_infos, M_TEMP);
1161 		stacks_to_allocate *= 10;
1162 	}
1163 
1164 	if (!finished && error == 0)
1165 		error = ENOMEM;
1166 
1167 	return (error);
1168 }
1169 #endif
1170 
1171 #ifdef SLEEPQUEUE_PROFILING
1172 #define	SLEEPQ_PROF_LOCATIONS	1024
1173 #define	SLEEPQ_SBUFSIZE		512
1174 struct sleepq_prof {
1175 	LIST_ENTRY(sleepq_prof) sp_link;
1176 	const char	*sp_wmesg;
1177 	long		sp_count;
1178 };
1179 
1180 LIST_HEAD(sqphead, sleepq_prof);
1181 
1182 struct sqphead sleepq_prof_free;
1183 struct sqphead sleepq_hash[SC_TABLESIZE];
1184 static struct sleepq_prof sleepq_profent[SLEEPQ_PROF_LOCATIONS];
1185 static struct mtx sleepq_prof_lock;
1186 MTX_SYSINIT(sleepq_prof_lock, &sleepq_prof_lock, "sleepq_prof", MTX_SPIN);
1187 
1188 static void
1189 sleepq_profile(const char *wmesg)
1190 {
1191 	struct sleepq_prof *sp;
1192 
1193 	mtx_lock_spin(&sleepq_prof_lock);
1194 	if (prof_enabled == 0)
1195 		goto unlock;
1196 	LIST_FOREACH(sp, &sleepq_hash[SC_HASH(wmesg)], sp_link)
1197 		if (sp->sp_wmesg == wmesg)
1198 			goto done;
1199 	sp = LIST_FIRST(&sleepq_prof_free);
1200 	if (sp == NULL)
1201 		goto unlock;
1202 	sp->sp_wmesg = wmesg;
1203 	LIST_REMOVE(sp, sp_link);
1204 	LIST_INSERT_HEAD(&sleepq_hash[SC_HASH(wmesg)], sp, sp_link);
1205 done:
1206 	sp->sp_count++;
1207 unlock:
1208 	mtx_unlock_spin(&sleepq_prof_lock);
1209 	return;
1210 }
1211 
1212 static void
1213 sleepq_prof_reset(void)
1214 {
1215 	struct sleepq_prof *sp;
1216 	int enabled;
1217 	int i;
1218 
1219 	mtx_lock_spin(&sleepq_prof_lock);
1220 	enabled = prof_enabled;
1221 	prof_enabled = 0;
1222 	for (i = 0; i < SC_TABLESIZE; i++)
1223 		LIST_INIT(&sleepq_hash[i]);
1224 	LIST_INIT(&sleepq_prof_free);
1225 	for (i = 0; i < SLEEPQ_PROF_LOCATIONS; i++) {
1226 		sp = &sleepq_profent[i];
1227 		sp->sp_wmesg = NULL;
1228 		sp->sp_count = 0;
1229 		LIST_INSERT_HEAD(&sleepq_prof_free, sp, sp_link);
1230 	}
1231 	prof_enabled = enabled;
1232 	mtx_unlock_spin(&sleepq_prof_lock);
1233 }
1234 
1235 static int
1236 enable_sleepq_prof(SYSCTL_HANDLER_ARGS)
1237 {
1238 	int error, v;
1239 
1240 	v = prof_enabled;
1241 	error = sysctl_handle_int(oidp, &v, v, req);
1242 	if (error)
1243 		return (error);
1244 	if (req->newptr == NULL)
1245 		return (error);
1246 	if (v == prof_enabled)
1247 		return (0);
1248 	if (v == 1)
1249 		sleepq_prof_reset();
1250 	mtx_lock_spin(&sleepq_prof_lock);
1251 	prof_enabled = !!v;
1252 	mtx_unlock_spin(&sleepq_prof_lock);
1253 
1254 	return (0);
1255 }
1256 
1257 static int
1258 reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1259 {
1260 	int error, v;
1261 
1262 	v = 0;
1263 	error = sysctl_handle_int(oidp, &v, 0, req);
1264 	if (error)
1265 		return (error);
1266 	if (req->newptr == NULL)
1267 		return (error);
1268 	if (v == 0)
1269 		return (0);
1270 	sleepq_prof_reset();
1271 
1272 	return (0);
1273 }
1274 
1275 static int
1276 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1277 {
1278 	struct sleepq_prof *sp;
1279 	struct sbuf *sb;
1280 	int enabled;
1281 	int error;
1282 	int i;
1283 
1284 	error = sysctl_wire_old_buffer(req, 0);
1285 	if (error != 0)
1286 		return (error);
1287 	sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
1288 	sbuf_printf(sb, "\nwmesg\tcount\n");
1289 	enabled = prof_enabled;
1290 	mtx_lock_spin(&sleepq_prof_lock);
1291 	prof_enabled = 0;
1292 	mtx_unlock_spin(&sleepq_prof_lock);
1293 	for (i = 0; i < SC_TABLESIZE; i++) {
1294 		LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
1295 			sbuf_printf(sb, "%s\t%ld\n",
1296 			    sp->sp_wmesg, sp->sp_count);
1297 		}
1298 	}
1299 	mtx_lock_spin(&sleepq_prof_lock);
1300 	prof_enabled = enabled;
1301 	mtx_unlock_spin(&sleepq_prof_lock);
1302 
1303 	error = sbuf_finish(sb);
1304 	sbuf_delete(sb);
1305 	return (error);
1306 }
1307 
1308 SYSCTL_PROC(_debug_sleepq, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
1309     NULL, 0, dump_sleepq_prof_stats, "A", "Sleepqueue profiling statistics");
1310 SYSCTL_PROC(_debug_sleepq, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
1311     NULL, 0, reset_sleepq_prof_stats, "I",
1312     "Reset sleepqueue profiling statistics");
1313 SYSCTL_PROC(_debug_sleepq, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
1314     NULL, 0, enable_sleepq_prof, "I", "Enable sleepqueue profiling");
1315 #endif
1316 
1317 #ifdef DDB
1318 DB_SHOW_COMMAND(sleepq, db_show_sleepqueue)
1319 {
1320 	struct sleepqueue_chain *sc;
1321 	struct sleepqueue *sq;
1322 #ifdef INVARIANTS
1323 	struct lock_object *lock;
1324 #endif
1325 	struct thread *td;
1326 	void *wchan;
1327 	int i;
1328 
1329 	if (!have_addr)
1330 		return;
1331 
1332 	/*
1333 	 * First, see if there is an active sleep queue for the wait channel
1334 	 * indicated by the address.
1335 	 */
1336 	wchan = (void *)addr;
1337 	sc = SC_LOOKUP(wchan);
1338 	LIST_FOREACH(sq, &sc->sc_queues, sq_hash)
1339 		if (sq->sq_wchan == wchan)
1340 			goto found;
1341 
1342 	/*
1343 	 * Second, see if there is an active sleep queue at the address
1344 	 * indicated.
1345 	 */
1346 	for (i = 0; i < SC_TABLESIZE; i++)
1347 		LIST_FOREACH(sq, &sleepq_chains[i].sc_queues, sq_hash) {
1348 			if (sq == (struct sleepqueue *)addr)
1349 				goto found;
1350 		}
1351 
1352 	db_printf("Unable to locate a sleep queue via %p\n", (void *)addr);
1353 	return;
1354 found:
1355 	db_printf("Wait channel: %p\n", sq->sq_wchan);
1356 	db_printf("Queue type: %d\n", sq->sq_type);
1357 #ifdef INVARIANTS
1358 	if (sq->sq_lock) {
1359 		lock = sq->sq_lock;
1360 		db_printf("Associated Interlock: %p - (%s) %s\n", lock,
1361 		    LOCK_CLASS(lock)->lc_name, lock->lo_name);
1362 	}
1363 #endif
1364 	db_printf("Blocked threads:\n");
1365 	for (i = 0; i < NR_SLEEPQS; i++) {
1366 		db_printf("\nQueue[%d]:\n", i);
1367 		if (TAILQ_EMPTY(&sq->sq_blocked[i]))
1368 			db_printf("\tempty\n");
1369 		else
1370 			TAILQ_FOREACH(td, &sq->sq_blocked[0],
1371 				      td_slpq) {
1372 				db_printf("\t%p (tid %d, pid %d, \"%s\")\n", td,
1373 					  td->td_tid, td->td_proc->p_pid,
1374 					  td->td_name);
1375 			}
1376 		db_printf("(expected: %u)\n", sq->sq_blockedcnt[i]);
1377 	}
1378 }
1379 
1380 /* Alias 'show sleepqueue' to 'show sleepq'. */
1381 DB_SHOW_ALIAS(sleepqueue, db_show_sleepqueue);
1382 #endif
1383