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