2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2004 John Baldwin <jhb@FreeBSD.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
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.
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
60 #include <sys/cdefs.h>
61 #include "opt_sleepqueue_profiling.h"
63 #include "opt_sched.h"
64 #include "opt_stack.h"
66 #include <sys/param.h>
67 #include <sys/systm.h>
69 #include <sys/kernel.h>
71 #include <sys/mutex.h>
74 #include <sys/sched.h>
76 #include <sys/signalvar.h>
77 #include <sys/sleepqueue.h>
78 #include <sys/stack.h>
79 #include <sys/sysctl.h>
82 #include <sys/epoch.h>
85 #include <machine/atomic.h>
94 * Constants for the hash table of sleep queue chains.
95 * SC_TABLESIZE must be a power of two for SC_MASK to work properly.
98 #define SC_TABLESIZE 256
100 CTASSERT(powerof2(SC_TABLESIZE));
101 #define SC_MASK (SC_TABLESIZE - 1)
103 #define SC_HASH(wc) ((((uintptr_t)(wc) >> SC_SHIFT) ^ (uintptr_t)(wc)) & \
105 #define SC_LOOKUP(wc) &sleepq_chains[SC_HASH(wc)]
108 * There are two different lists of sleep queues. Both lists are connected
109 * via the sq_hash entries. The first list is the sleep queue chain list
110 * that a sleep queue is on when it is attached to a wait channel. The
111 * second list is the free list hung off of a sleep queue that is attached
114 * Each sleep queue also contains the wait channel it is attached to, the
115 * list of threads blocked on that wait channel, flags specific to the
116 * wait channel, and the lock used to synchronize with a wait channel.
117 * The flags are used to catch mismatches between the various consumers
118 * of the sleep queue API (e.g. sleep/wakeup and condition variables).
119 * The lock pointer is only used when invariants are enabled for various
123 * c - sleep queue chain lock
126 struct threadqueue sq_blocked[NR_SLEEPQS]; /* (c) Blocked threads. */
127 u_int sq_blockedcnt[NR_SLEEPQS]; /* (c) N. of blocked threads. */
128 LIST_ENTRY(sleepqueue) sq_hash; /* (c) Chain and free list. */
129 LIST_HEAD(, sleepqueue) sq_free; /* (c) Free queues. */
130 const void *sq_wchan; /* (c) Wait channel. */
131 int sq_type; /* (c) Queue type. */
133 struct lock_object *sq_lock; /* (c) Associated lock. */
137 struct sleepqueue_chain {
138 LIST_HEAD(, sleepqueue) sc_queues; /* List of sleep queues. */
139 struct mtx sc_lock; /* Spin lock for this chain. */
140 #ifdef SLEEPQUEUE_PROFILING
141 u_int sc_depth; /* Length of sc_queues. */
142 u_int sc_max_depth; /* Max length of sc_queues. */
144 } __aligned(CACHE_LINE_SIZE);
146 #ifdef SLEEPQUEUE_PROFILING
147 static SYSCTL_NODE(_debug, OID_AUTO, sleepq, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
149 static SYSCTL_NODE(_debug_sleepq, OID_AUTO, chains,
150 CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
151 "sleepq chain stats");
152 static u_int sleepq_max_depth;
153 SYSCTL_UINT(_debug_sleepq, OID_AUTO, max_depth, CTLFLAG_RD, &sleepq_max_depth,
154 0, "maxmimum depth achieved of a single chain");
156 static void sleepq_profile(const char *wmesg);
157 static int prof_enabled;
159 static struct sleepqueue_chain sleepq_chains[SC_TABLESIZE];
160 static uma_zone_t sleepq_zone;
163 * Prototypes for non-exported routines.
165 static int sleepq_catch_signals(const void *wchan, int pri);
166 static inline int sleepq_check_signals(void);
167 static inline int sleepq_check_timeout(void);
169 static void sleepq_dtor(void *mem, int size, void *arg);
171 static int sleepq_init(void *mem, int size, int flags);
172 static int sleepq_resume_thread(struct sleepqueue *sq, struct thread *td,
173 int pri, int srqflags);
174 static void sleepq_remove_thread(struct sleepqueue *sq, struct thread *td);
175 static void sleepq_switch(const void *wchan, int pri);
176 static void sleepq_timeout(void *arg);
178 SDT_PROBE_DECLARE(sched, , , sleep);
179 SDT_PROBE_DECLARE(sched, , , wakeup);
182 * Initialize SLEEPQUEUE_PROFILING specific sysctl nodes.
183 * Note that it must happen after sleepinit() has been fully executed, so
184 * it must happen after SI_SUB_KMEM SYSINIT() subsystem setup.
186 #ifdef SLEEPQUEUE_PROFILING
188 init_sleepqueue_profiling(void)
191 struct sysctl_oid *chain_oid;
194 for (i = 0; i < SC_TABLESIZE; i++) {
195 snprintf(chain_name, sizeof(chain_name), "%u", i);
196 chain_oid = SYSCTL_ADD_NODE(NULL,
197 SYSCTL_STATIC_CHILDREN(_debug_sleepq_chains), OID_AUTO,
198 chain_name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
199 "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,
208 SYSINIT(sleepqueue_profiling, SI_SUB_LOCK, SI_ORDER_ANY,
209 init_sleepqueue_profiling, NULL);
213 * Early initialization of sleep queues that is called from the sleepinit()
217 init_sleepqueues(void)
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,
226 sleepq_zone = uma_zcreate("SLEEPQUEUE", sizeof(struct sleepqueue),
228 NULL, sleepq_dtor, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
230 NULL, NULL, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
233 thread0.td_sleepqueue = sleepq_alloc();
237 * Get a sleep queue for a new thread.
243 return (uma_zalloc(sleepq_zone, M_WAITOK));
247 * Free a sleep queue when a thread is destroyed.
250 sleepq_free(struct sleepqueue *sq)
253 uma_zfree(sleepq_zone, sq);
257 * Lock the sleep queue chain associated with the specified wait channel.
260 sleepq_lock(const void *wchan)
262 struct sleepqueue_chain *sc;
264 sc = SC_LOOKUP(wchan);
265 mtx_lock_spin(&sc->sc_lock);
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.
274 sleepq_lookup(const void *wchan)
276 struct sleepqueue_chain *sc;
277 struct sleepqueue *sq;
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)
289 * Unlock the sleep queue chain associated with a given wait channel.
292 sleepq_release(const void *wchan)
294 struct sleepqueue_chain *sc;
296 sc = SC_LOOKUP(wchan);
297 mtx_unlock_spin(&sc->sc_lock);
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
307 sleepq_add(const void *wchan, struct lock_object *lock, const char *wmesg,
308 int flags, int queue)
310 struct sleepqueue_chain *sc;
311 struct sleepqueue *sq;
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));
321 /* If this thread is not allowed to sleep, die a horrible death. */
322 if (__predict_false(!THREAD_CAN_SLEEP())) {
324 epoch_trace_list(curthread);
327 ("%s: td %p to sleep on wchan %p with sleeping prohibited",
328 __func__, td, wchan));
331 /* Look up the sleep queue associated with the wait channel 'wchan'. */
332 sq = sleepq_lookup(wchan);
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.
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));
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"));
355 #ifdef SLEEPQUEUE_PROFILING
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;
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;
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);
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) {
382 td->td_flags |= TDF_SINTR;
384 td->td_flags &= ~TDF_TIMEOUT;
389 * Sets a timeout that will remove the current thread from the
390 * specified sleep queue at the specified time if the thread has not
391 * already been awakened. Flags are from C_* (callout) namespace.
394 sleepq_set_timeout_sbt(const void *wchan, sbintime_t sbt, sbintime_t pr,
397 struct sleepqueue_chain *sc __unused;
402 sc = SC_LOOKUP(wchan);
403 mtx_assert(&sc->sc_lock, MA_OWNED);
404 MPASS(TD_ON_SLEEPQ(td));
405 MPASS(td->td_sleepqueue == NULL);
406 MPASS(wchan != NULL);
407 if (cold && td == &thread0)
408 panic("timed sleep before timers are working");
409 KASSERT(td->td_sleeptimo == 0, ("td %d %p td_sleeptimo %jx",
410 td->td_tid, td, (uintmax_t)td->td_sleeptimo));
412 callout_when(sbt, pr, flags, &td->td_sleeptimo, &pr1);
414 callout_reset_sbt_on(&td->td_slpcallout, td->td_sleeptimo, pr1,
415 sleepq_timeout, td, PCPU_GET(cpuid), flags | C_PRECALC |
420 * Return the number of actual sleepers for the specified queue.
423 sleepq_sleepcnt(const void *wchan, int queue)
425 struct sleepqueue *sq;
427 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
428 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
429 sq = sleepq_lookup(wchan);
432 return (sq->sq_blockedcnt[queue]);
436 sleepq_check_ast_sc_locked(struct thread *td, struct sleepqueue_chain *sc)
441 mtx_assert(&sc->sc_lock, MA_OWNED);
443 if ((td->td_pflags & TDP_WAKEUP) != 0) {
444 td->td_pflags &= ~TDP_WAKEUP;
450 * See if there are any pending signals or suspension requests for this
451 * thread. If not, we can switch immediately.
454 if ((td->td_flags & (TDF_NEEDSIGCHK | TDF_NEEDSUSPCHK)) == 0)
458 mtx_unlock_spin(&sc->sc_lock);
461 CTR3(KTR_PROC, "sleepq catching signals: thread %p (pid %ld, %s)",
462 (void *)td, (long)p->p_pid, td->td_name);
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.
470 ret = sig_ast_checksusp(td);
473 mtx_lock_spin(&sc->sc_lock);
478 ret = sig_ast_needsigchk(td);
481 * Lock the per-process spinlock prior to dropping the
482 * PROC_LOCK to avoid a signal delivery race.
483 * PROC_LOCK, PROC_SLOCK, and thread_lock() are
484 * currently held in tdsendsignal() and thread_single().
487 mtx_lock_spin(&sc->sc_lock);
496 * Marks the pending sleep of the current thread as interruptible and
497 * makes an initial check for pending signals before putting a thread
498 * to sleep. Enters and exits with the thread lock held. Thread lock
499 * may have transitioned from the sleepq lock to a run lock.
502 sleepq_catch_signals(const void *wchan, int pri)
505 struct sleepqueue_chain *sc;
506 struct sleepqueue *sq;
509 sc = SC_LOOKUP(wchan);
510 mtx_assert(&sc->sc_lock, MA_OWNED);
511 MPASS(wchan != NULL);
514 ret = sleepq_check_ast_sc_locked(td, sc);
515 THREAD_LOCK_ASSERT(td, MA_OWNED);
516 mtx_assert(&sc->sc_lock, MA_OWNED);
520 * No pending signals and no suspension requests found.
521 * Switch the thread off the cpu.
523 sleepq_switch(wchan, pri);
526 * There were pending signals and this thread is still
527 * on the sleep queue, remove it from the sleep queue.
529 if (TD_ON_SLEEPQ(td)) {
530 sq = sleepq_lookup(wchan);
531 sleepq_remove_thread(sq, td);
533 MPASS(td->td_lock != &sc->sc_lock);
534 mtx_unlock_spin(&sc->sc_lock);
541 * Switches to another thread if we are still asleep on a sleep queue.
542 * Returns with thread lock.
545 sleepq_switch(const void *wchan, int pri)
547 struct sleepqueue_chain *sc;
548 struct sleepqueue *sq;
553 sc = SC_LOOKUP(wchan);
554 mtx_assert(&sc->sc_lock, MA_OWNED);
555 THREAD_LOCK_ASSERT(td, MA_OWNED);
558 * If we have a sleep queue, then we've already been woken up, so
561 if (td->td_sleepqueue != NULL) {
562 mtx_unlock_spin(&sc->sc_lock);
568 * If TDF_TIMEOUT is set, then our sleep has been timed out
569 * already but we are still on the sleep queue, so dequeue the
572 * Do the same if the real-time clock has been adjusted since this
573 * thread calculated its timeout based on that clock. This handles
574 * the following race:
575 * - The Ts thread needs to sleep until an absolute real-clock time.
576 * It copies the global rtc_generation into curthread->td_rtcgen,
577 * reads the RTC, and calculates a sleep duration based on that time.
578 * See umtxq_sleep() for an example.
579 * - The Tc thread adjusts the RTC, bumps rtc_generation, and wakes
580 * threads that are sleeping until an absolute real-clock time.
581 * See tc_setclock() and the POSIX specification of clock_settime().
582 * - Ts reaches the code below. It holds the sleepqueue chain lock,
583 * so Tc has finished waking, so this thread must test td_rtcgen.
584 * (The declaration of td_rtcgen refers to this comment.)
586 rtc_changed = td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation;
587 if ((td->td_flags & TDF_TIMEOUT) || rtc_changed) {
591 MPASS(TD_ON_SLEEPQ(td));
592 sq = sleepq_lookup(wchan);
593 sleepq_remove_thread(sq, td);
594 mtx_unlock_spin(&sc->sc_lock);
598 #ifdef SLEEPQUEUE_PROFILING
600 sleepq_profile(td->td_wmesg);
602 MPASS(td->td_sleepqueue == NULL);
603 sched_sleep(td, pri);
604 thread_lock_set(td, &sc->sc_lock);
605 SDT_PROBE0(sched, , , sleep);
607 mi_switch(SW_VOL | SWT_SLEEPQ);
608 KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING"));
609 CTR3(KTR_PROC, "sleepq resume: thread %p (pid %ld, %s)",
610 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
614 * Check to see if we timed out.
617 sleepq_check_timeout(void)
624 if (td->td_sleeptimo != 0) {
625 if (td->td_sleeptimo <= sbinuptime())
627 td->td_sleeptimo = 0;
633 * Check to see if we were awoken by a signal.
636 sleepq_check_signals(void)
641 KASSERT((td->td_flags & TDF_SINTR) == 0,
642 ("thread %p still in interruptible sleep?", td));
644 return (td->td_intrval);
648 * Block the current thread until it is awakened from its sleep queue.
651 sleepq_wait(const void *wchan, int pri)
656 MPASS(!(td->td_flags & TDF_SINTR));
658 sleepq_switch(wchan, pri);
662 * Block the current thread until it is awakened from its sleep queue
663 * or it is interrupted by a signal.
666 sleepq_wait_sig(const void *wchan, int pri)
670 rcatch = sleepq_catch_signals(wchan, pri);
673 return (sleepq_check_signals());
677 * Block the current thread until it is awakened from its sleep queue
678 * or it times out while waiting.
681 sleepq_timedwait(const void *wchan, int pri)
686 MPASS(!(td->td_flags & TDF_SINTR));
689 sleepq_switch(wchan, pri);
691 return (sleepq_check_timeout());
695 * Block the current thread until it is awakened from its sleep queue,
696 * it is interrupted by a signal, or it times out waiting to be awakened.
699 sleepq_timedwait_sig(const void *wchan, int pri)
701 int rcatch, rvalt, rvals;
703 rcatch = sleepq_catch_signals(wchan, pri);
704 /* We must always call check_timeout() to clear sleeptimo. */
705 rvalt = sleepq_check_timeout();
706 rvals = sleepq_check_signals();
715 * Returns the type of sleepqueue given a waitchannel.
718 sleepq_type(const void *wchan)
720 struct sleepqueue *sq;
723 MPASS(wchan != NULL);
725 sq = sleepq_lookup(wchan);
734 * Removes a thread from a sleep queue and makes it
737 * Requires the sc chain locked on entry. If SRQ_HOLD is specified it will
738 * be locked on return. Returns without the thread lock held.
741 sleepq_resume_thread(struct sleepqueue *sq, struct thread *td, int pri,
744 struct sleepqueue_chain *sc;
748 MPASS(sq->sq_wchan != NULL);
749 MPASS(td->td_wchan == sq->sq_wchan);
751 sc = SC_LOOKUP(sq->sq_wchan);
752 mtx_assert(&sc->sc_lock, MA_OWNED);
755 * Avoid recursing on the chain lock. If the locks don't match we
756 * need to acquire the thread lock which setrunnable will drop for
757 * us. In this case we need to drop the chain lock afterwards.
759 * There is no race that will make td_lock equal to sc_lock because
763 if (!TD_IS_SLEEPING(td)) {
767 thread_lock_block_wait(td);
769 /* Remove thread from the sleepq. */
770 sleepq_remove_thread(sq, td);
772 /* If we're done with the sleepqueue release it. */
773 if ((srqflags & SRQ_HOLD) == 0 && drop)
774 mtx_unlock_spin(&sc->sc_lock);
776 /* Adjust priority if requested. */
777 MPASS(pri == 0 || (pri >= PRI_MIN && pri <= PRI_MAX));
778 if (pri != 0 && td->td_priority > pri &&
779 PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
783 * Note that thread td might not be sleeping if it is running
784 * sleepq_catch_signals() on another CPU or is blocked on its
785 * proc lock to check signals. There's no need to mark the
786 * thread runnable in that case.
788 if (TD_IS_SLEEPING(td)) {
791 return (setrunnable(td, srqflags));
800 sleepq_remove_thread(struct sleepqueue *sq, struct thread *td)
802 struct sleepqueue_chain *sc __unused;
805 MPASS(sq->sq_wchan != NULL);
806 MPASS(td->td_wchan == sq->sq_wchan);
807 MPASS(td->td_sqqueue < NR_SLEEPQS && td->td_sqqueue >= 0);
808 THREAD_LOCK_ASSERT(td, MA_OWNED);
809 sc = SC_LOOKUP(sq->sq_wchan);
810 mtx_assert(&sc->sc_lock, MA_OWNED);
812 SDT_PROBE2(sched, , , wakeup, td, td->td_proc);
814 /* Remove the thread from the queue. */
815 sq->sq_blockedcnt[td->td_sqqueue]--;
816 TAILQ_REMOVE(&sq->sq_blocked[td->td_sqqueue], td, td_slpq);
819 * Get a sleep queue for this thread. If this is the last waiter,
820 * use the queue itself and take it out of the chain, otherwise,
821 * remove a queue from the free list.
823 if (LIST_EMPTY(&sq->sq_free)) {
824 td->td_sleepqueue = sq;
828 #ifdef SLEEPQUEUE_PROFILING
832 td->td_sleepqueue = LIST_FIRST(&sq->sq_free);
833 LIST_REMOVE(td->td_sleepqueue, sq_hash);
835 if ((td->td_flags & TDF_TIMEOUT) == 0 && td->td_sleeptimo != 0)
837 * We ignore the situation where timeout subsystem was
838 * unable to stop our callout. The struct thread is
839 * type-stable, the callout will use the correct
840 * memory when running. The checks of the
841 * td_sleeptimo value in this function and in
842 * sleepq_timeout() ensure that the thread does not
843 * get spurious wakeups, even if the callout was reset
846 callout_stop(&td->td_slpcallout);
850 td->td_flags &= ~(TDF_SINTR | TDF_TIMEOUT);
852 CTR3(KTR_PROC, "sleepq_wakeup: thread %p (pid %ld, %s)",
853 (void *)td, (long)td->td_proc->p_pid, td->td_name);
857 sleepq_remove_nested(struct thread *td)
859 struct sleepqueue_chain *sc;
860 struct sleepqueue *sq;
863 MPASS(TD_ON_SLEEPQ(td));
865 wchan = td->td_wchan;
866 sc = SC_LOOKUP(wchan);
867 mtx_lock_spin(&sc->sc_lock);
868 sq = sleepq_lookup(wchan);
871 sleepq_remove_thread(sq, td);
872 mtx_unlock_spin(&sc->sc_lock);
873 /* Returns with the thread lock owned. */
878 * UMA zone item deallocator.
881 sleepq_dtor(void *mem, int size, void *arg)
883 struct sleepqueue *sq;
887 for (i = 0; i < NR_SLEEPQS; i++) {
888 MPASS(TAILQ_EMPTY(&sq->sq_blocked[i]));
889 MPASS(sq->sq_blockedcnt[i] == 0);
895 * UMA zone item initializer.
898 sleepq_init(void *mem, int size, int flags)
900 struct sleepqueue *sq;
905 for (i = 0; i < NR_SLEEPQS; i++) {
906 TAILQ_INIT(&sq->sq_blocked[i]);
907 sq->sq_blockedcnt[i] = 0;
909 LIST_INIT(&sq->sq_free);
914 * Find thread sleeping on a wait channel and resume it.
917 sleepq_signal(const void *wchan, int flags, int pri, int queue)
919 struct sleepqueue_chain *sc;
920 struct sleepqueue *sq;
921 struct threadqueue *head;
922 struct thread *td, *besttd;
925 CTR2(KTR_PROC, "sleepq_signal(%p, %d)", wchan, flags);
926 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
927 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
928 sq = sleepq_lookup(wchan);
930 if (flags & SLEEPQ_DROP)
931 sleepq_release(wchan);
934 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
935 ("%s: mismatch between sleep/wakeup and cv_*", __func__));
937 head = &sq->sq_blocked[queue];
938 if (flags & SLEEPQ_UNFAIR) {
940 * Find the most recently sleeping thread, but try to
941 * skip threads still in process of context switch to
942 * avoid spinning on the thread lock.
944 sc = SC_LOOKUP(wchan);
945 besttd = TAILQ_LAST_FAST(head, thread, td_slpq);
946 while (besttd->td_lock != &sc->sc_lock) {
947 td = TAILQ_PREV_FAST(besttd, head, thread, td_slpq);
954 * Find the highest priority thread on the queue. If there
955 * is a tie, use the thread that first appears in the queue
956 * as it has been sleeping the longest since threads are
957 * always added to the tail of sleep queues.
959 besttd = td = TAILQ_FIRST(head);
960 while ((td = TAILQ_NEXT(td, td_slpq)) != NULL) {
961 if (td->td_priority < besttd->td_priority)
965 MPASS(besttd != NULL);
966 wakeup_swapper = sleepq_resume_thread(sq, besttd, pri,
967 (flags & SLEEPQ_DROP) ? 0 : SRQ_HOLD);
968 return (wakeup_swapper);
972 match_any(struct thread *td __unused)
979 * Resume all threads sleeping on a specified wait channel.
982 sleepq_broadcast(const void *wchan, int flags, int pri, int queue)
984 struct sleepqueue *sq;
986 CTR2(KTR_PROC, "sleepq_broadcast(%p, %d)", wchan, flags);
987 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
988 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
989 sq = sleepq_lookup(wchan);
992 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
993 ("%s: mismatch between sleep/wakeup and cv_*", __func__));
995 return (sleepq_remove_matching(sq, queue, match_any, pri));
999 * Resume threads on the sleep queue that match the given predicate.
1002 sleepq_remove_matching(struct sleepqueue *sq, int queue,
1003 bool (*matches)(struct thread *), int pri)
1005 struct thread *td, *tdn;
1009 * The last thread will be given ownership of sq and may
1010 * re-enqueue itself before sleepq_resume_thread() returns,
1011 * so we must cache the "next" queue item at the beginning
1012 * of the final iteration.
1015 TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq, tdn) {
1017 wakeup_swapper |= sleepq_resume_thread(sq, td, pri,
1021 return (wakeup_swapper);
1025 * Time sleeping threads out. When the timeout expires, the thread is
1026 * removed from the sleep queue and made runnable if it is still asleep.
1029 sleepq_timeout(void *arg)
1031 struct sleepqueue_chain *sc __unused;
1032 struct sleepqueue *sq;
1038 CTR3(KTR_PROC, "sleepq_timeout: thread %p (pid %ld, %s)",
1039 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
1042 if (td->td_sleeptimo == 0 ||
1043 td->td_sleeptimo > td->td_slpcallout.c_time) {
1045 * The thread does not want a timeout (yet).
1047 } else if (TD_IS_SLEEPING(td) && TD_ON_SLEEPQ(td)) {
1049 * See if the thread is asleep and get the wait
1052 wchan = td->td_wchan;
1053 sc = SC_LOOKUP(wchan);
1054 THREAD_LOCKPTR_ASSERT(td, &sc->sc_lock);
1055 sq = sleepq_lookup(wchan);
1057 td->td_flags |= TDF_TIMEOUT;
1058 wakeup_swapper = sleepq_resume_thread(sq, td, 0, 0);
1062 } else if (TD_ON_SLEEPQ(td)) {
1064 * If the thread is on the SLEEPQ but isn't sleeping
1065 * yet, it can either be on another CPU in between
1066 * sleepq_add() and one of the sleepq_*wait*()
1067 * routines or it can be in sleepq_catch_signals().
1069 td->td_flags |= TDF_TIMEOUT;
1075 * Resumes a specific thread from the sleep queue associated with a specific
1076 * wait channel if it is on that queue.
1079 sleepq_remove(struct thread *td, const void *wchan)
1081 struct sleepqueue_chain *sc;
1082 struct sleepqueue *sq;
1086 * Look up the sleep queue for this wait channel, then re-check
1087 * that the thread is asleep on that channel, if it is not, then
1090 MPASS(wchan != NULL);
1091 sc = SC_LOOKUP(wchan);
1092 mtx_lock_spin(&sc->sc_lock);
1094 * We can not lock the thread here as it may be sleeping on a
1095 * different sleepq. However, holding the sleepq lock for this
1096 * wchan can guarantee that we do not miss a wakeup for this
1097 * channel. The asserts below will catch any false positives.
1099 if (!TD_ON_SLEEPQ(td) || td->td_wchan != wchan) {
1100 mtx_unlock_spin(&sc->sc_lock);
1104 /* Thread is asleep on sleep queue sq, so wake it up. */
1105 sq = sleepq_lookup(wchan);
1107 MPASS(td->td_wchan == wchan);
1108 wakeup_swapper = sleepq_resume_thread(sq, td, 0, 0);
1114 * Abort a thread as if an interrupt had occurred. Only abort
1115 * interruptible waits (unfortunately it isn't safe to abort others).
1117 * Requires thread lock on entry, releases on return.
1120 sleepq_abort(struct thread *td, int intrval)
1122 struct sleepqueue *sq;
1125 THREAD_LOCK_ASSERT(td, MA_OWNED);
1126 MPASS(TD_ON_SLEEPQ(td));
1127 MPASS(td->td_flags & TDF_SINTR);
1128 MPASS((intrval == 0 && (td->td_flags & TDF_SIGWAIT) != 0) ||
1129 intrval == EINTR || intrval == ERESTART);
1132 * If the TDF_TIMEOUT flag is set, just leave. A
1133 * timeout is scheduled anyhow.
1135 if (td->td_flags & TDF_TIMEOUT) {
1140 CTR3(KTR_PROC, "sleepq_abort: thread %p (pid %ld, %s)",
1141 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
1142 td->td_intrval = intrval;
1145 * If the thread has not slept yet it will find the signal in
1146 * sleepq_catch_signals() and call sleepq_resume_thread. Otherwise
1147 * we have to do it here.
1149 if (!TD_IS_SLEEPING(td)) {
1153 wchan = td->td_wchan;
1154 MPASS(wchan != NULL);
1155 sq = sleepq_lookup(wchan);
1158 /* Thread is asleep on sleep queue sq, so wake it up. */
1159 return (sleepq_resume_thread(sq, td, 0, 0));
1163 sleepq_chains_remove_matching(bool (*matches)(struct thread *))
1165 struct sleepqueue_chain *sc;
1166 struct sleepqueue *sq, *sq1;
1167 int i, wakeup_swapper;
1170 for (sc = &sleepq_chains[0]; sc < sleepq_chains + SC_TABLESIZE; ++sc) {
1171 if (LIST_EMPTY(&sc->sc_queues)) {
1174 mtx_lock_spin(&sc->sc_lock);
1175 LIST_FOREACH_SAFE(sq, &sc->sc_queues, sq_hash, sq1) {
1176 for (i = 0; i < NR_SLEEPQS; ++i) {
1177 wakeup_swapper |= sleepq_remove_matching(sq, i,
1181 mtx_unlock_spin(&sc->sc_lock);
1183 if (wakeup_swapper) {
1189 * Prints the stacks of all threads presently sleeping on wchan/queue to
1190 * the sbuf sb. Sets count_stacks_printed to the number of stacks actually
1191 * printed. Typically, this will equal the number of threads sleeping on the
1192 * queue, but may be less if sb overflowed before all stacks were printed.
1196 sleepq_sbuf_print_stacks(struct sbuf *sb, const void *wchan, int queue,
1197 int *count_stacks_printed)
1199 struct thread *td, *td_next;
1200 struct sleepqueue *sq;
1202 struct sbuf **td_infos;
1203 int i, stack_idx, error, stacks_to_allocate;
1209 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
1210 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
1212 stacks_to_allocate = 10;
1213 for (i = 0; i < 3 && !finished ; i++) {
1214 /* We cannot malloc while holding the queue's spinlock, so
1215 * we do our mallocs now, and hope it is enough. If it
1216 * isn't, we will free these, drop the lock, malloc more,
1217 * and try again, up to a point. After that point we will
1218 * give up and report ENOMEM. We also cannot write to sb
1219 * during this time since the client may have set the
1220 * SBUF_AUTOEXTEND flag on their sbuf, which could cause a
1221 * malloc as we print to it. So we defer actually printing
1222 * to sb until after we drop the spinlock.
1225 /* Where we will store the stacks. */
1226 st = malloc(sizeof(struct stack *) * stacks_to_allocate,
1228 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1230 st[stack_idx] = stack_create(M_WAITOK);
1232 /* Where we will store the td name, tid, etc. */
1233 td_infos = malloc(sizeof(struct sbuf *) * stacks_to_allocate,
1235 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1237 td_infos[stack_idx] = sbuf_new(NULL, NULL,
1238 MAXCOMLEN + sizeof(struct thread *) * 2 + 40,
1242 sq = sleepq_lookup(wchan);
1244 /* This sleepq does not exist; exit and return ENOENT. */
1247 sleepq_release(wchan);
1252 /* Save thread info */
1253 TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq,
1255 if (stack_idx >= stacks_to_allocate)
1258 /* Note the td_lock is equal to the sleepq_lock here. */
1259 (void)stack_save_td(st[stack_idx], td);
1261 sbuf_printf(td_infos[stack_idx], "%d: %s %p",
1262 td->td_tid, td->td_name, td);
1268 sleepq_release(wchan);
1270 /* Print the stacks */
1271 for (i = 0; i < stack_idx; i++) {
1272 sbuf_finish(td_infos[i]);
1273 sbuf_printf(sb, "--- thread %s: ---\n", sbuf_data(td_infos[i]));
1274 stack_sbuf_print(sb, st[i]);
1275 sbuf_printf(sb, "\n");
1277 error = sbuf_error(sb);
1279 *count_stacks_printed = stack_idx;
1284 sleepq_release(wchan);
1285 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1287 stack_destroy(st[stack_idx]);
1288 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1290 sbuf_delete(td_infos[stack_idx]);
1292 free(td_infos, M_TEMP);
1293 stacks_to_allocate *= 10;
1296 if (!finished && error == 0)
1303 #ifdef SLEEPQUEUE_PROFILING
1304 #define SLEEPQ_PROF_LOCATIONS 1024
1305 #define SLEEPQ_SBUFSIZE 512
1306 struct sleepq_prof {
1307 LIST_ENTRY(sleepq_prof) sp_link;
1308 const char *sp_wmesg;
1312 LIST_HEAD(sqphead, sleepq_prof);
1314 struct sqphead sleepq_prof_free;
1315 struct sqphead sleepq_hash[SC_TABLESIZE];
1316 static struct sleepq_prof sleepq_profent[SLEEPQ_PROF_LOCATIONS];
1317 static struct mtx sleepq_prof_lock;
1318 MTX_SYSINIT(sleepq_prof_lock, &sleepq_prof_lock, "sleepq_prof", MTX_SPIN);
1321 sleepq_profile(const char *wmesg)
1323 struct sleepq_prof *sp;
1325 mtx_lock_spin(&sleepq_prof_lock);
1326 if (prof_enabled == 0)
1328 LIST_FOREACH(sp, &sleepq_hash[SC_HASH(wmesg)], sp_link)
1329 if (sp->sp_wmesg == wmesg)
1331 sp = LIST_FIRST(&sleepq_prof_free);
1334 sp->sp_wmesg = wmesg;
1335 LIST_REMOVE(sp, sp_link);
1336 LIST_INSERT_HEAD(&sleepq_hash[SC_HASH(wmesg)], sp, sp_link);
1340 mtx_unlock_spin(&sleepq_prof_lock);
1345 sleepq_prof_reset(void)
1347 struct sleepq_prof *sp;
1351 mtx_lock_spin(&sleepq_prof_lock);
1352 enabled = prof_enabled;
1354 for (i = 0; i < SC_TABLESIZE; i++)
1355 LIST_INIT(&sleepq_hash[i]);
1356 LIST_INIT(&sleepq_prof_free);
1357 for (i = 0; i < SLEEPQ_PROF_LOCATIONS; i++) {
1358 sp = &sleepq_profent[i];
1359 sp->sp_wmesg = NULL;
1361 LIST_INSERT_HEAD(&sleepq_prof_free, sp, sp_link);
1363 prof_enabled = enabled;
1364 mtx_unlock_spin(&sleepq_prof_lock);
1368 enable_sleepq_prof(SYSCTL_HANDLER_ARGS)
1373 error = sysctl_handle_int(oidp, &v, v, req);
1376 if (req->newptr == NULL)
1378 if (v == prof_enabled)
1381 sleepq_prof_reset();
1382 mtx_lock_spin(&sleepq_prof_lock);
1384 mtx_unlock_spin(&sleepq_prof_lock);
1390 reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1395 error = sysctl_handle_int(oidp, &v, 0, req);
1398 if (req->newptr == NULL)
1402 sleepq_prof_reset();
1408 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1410 struct sleepq_prof *sp;
1416 error = sysctl_wire_old_buffer(req, 0);
1419 sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
1420 sbuf_printf(sb, "\nwmesg\tcount\n");
1421 enabled = prof_enabled;
1422 mtx_lock_spin(&sleepq_prof_lock);
1424 mtx_unlock_spin(&sleepq_prof_lock);
1425 for (i = 0; i < SC_TABLESIZE; i++) {
1426 LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
1427 sbuf_printf(sb, "%s\t%ld\n",
1428 sp->sp_wmesg, sp->sp_count);
1431 mtx_lock_spin(&sleepq_prof_lock);
1432 prof_enabled = enabled;
1433 mtx_unlock_spin(&sleepq_prof_lock);
1435 error = sbuf_finish(sb);
1440 SYSCTL_PROC(_debug_sleepq, OID_AUTO, stats,
1441 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1442 dump_sleepq_prof_stats, "A",
1443 "Sleepqueue profiling statistics");
1444 SYSCTL_PROC(_debug_sleepq, OID_AUTO, reset,
1445 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
1446 reset_sleepq_prof_stats, "I",
1447 "Reset sleepqueue profiling statistics");
1448 SYSCTL_PROC(_debug_sleepq, OID_AUTO, enable,
1449 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
1450 enable_sleepq_prof, "I",
1451 "Enable sleepqueue profiling");
1455 DB_SHOW_COMMAND(sleepq, db_show_sleepqueue)
1457 struct sleepqueue_chain *sc;
1458 struct sleepqueue *sq;
1460 struct lock_object *lock;
1470 * First, see if there is an active sleep queue for the wait channel
1471 * indicated by the address.
1473 wchan = (void *)addr;
1474 sc = SC_LOOKUP(wchan);
1475 LIST_FOREACH(sq, &sc->sc_queues, sq_hash)
1476 if (sq->sq_wchan == wchan)
1480 * Second, see if there is an active sleep queue at the address
1483 for (i = 0; i < SC_TABLESIZE; i++)
1484 LIST_FOREACH(sq, &sleepq_chains[i].sc_queues, sq_hash) {
1485 if (sq == (struct sleepqueue *)addr)
1489 db_printf("Unable to locate a sleep queue via %p\n", (void *)addr);
1492 db_printf("Wait channel: %p\n", sq->sq_wchan);
1493 db_printf("Queue type: %d\n", sq->sq_type);
1497 db_printf("Associated Interlock: %p - (%s) %s\n", lock,
1498 LOCK_CLASS(lock)->lc_name, lock->lo_name);
1501 db_printf("Blocked threads:\n");
1502 for (i = 0; i < NR_SLEEPQS; i++) {
1503 db_printf("\nQueue[%d]:\n", i);
1504 if (TAILQ_EMPTY(&sq->sq_blocked[i]))
1505 db_printf("\tempty\n");
1507 TAILQ_FOREACH(td, &sq->sq_blocked[i],
1509 db_printf("\t%p (tid %d, pid %d, \"%s\")\n", td,
1510 td->td_tid, td->td_proc->p_pid,
1513 db_printf("(expected: %u)\n", sq->sq_blockedcnt[i]);
1517 /* Alias 'show sleepqueue' to 'show sleepq'. */
1518 DB_SHOW_ALIAS(sleepqueue, db_show_sleepqueue);