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