2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2004 John Baldwin <jhb@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
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.
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
61 #include <sys/cdefs.h>
62 __FBSDID("$FreeBSD$");
64 #include "opt_sleepqueue_profiling.h"
66 #include "opt_sched.h"
67 #include "opt_stack.h"
69 #include <sys/param.h>
70 #include <sys/systm.h>
72 #include <sys/kernel.h>
74 #include <sys/mutex.h>
77 #include <sys/sched.h>
79 #include <sys/signalvar.h>
80 #include <sys/sleepqueue.h>
81 #include <sys/stack.h>
82 #include <sys/sysctl.h>
85 #include <machine/atomic.h>
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.
99 #define SC_TABLESIZE 256
101 CTASSERT(powerof2(SC_TABLESIZE));
102 #define SC_MASK (SC_TABLESIZE - 1)
104 #define SC_HASH(wc) ((((uintptr_t)(wc) >> SC_SHIFT) ^ (uintptr_t)(wc)) & \
106 #define SC_LOOKUP(wc) &sleepq_chains[SC_HASH(wc)]
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
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
124 * c - sleep queue chain lock
127 struct threadqueue 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. */
134 struct lock_object *sq_lock; /* (c) Associated lock. */
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. */
145 } __aligned(CACHE_LINE_SIZE);
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");
155 static void sleepq_profile(const char *wmesg);
156 static int prof_enabled;
158 static struct sleepqueue_chain sleepq_chains[SC_TABLESIZE];
159 static uma_zone_t sleepq_zone;
162 * Prototypes for non-exported routines.
164 static int sleepq_catch_signals(void *wchan, int pri);
165 static int sleepq_check_signals(void);
166 static int sleepq_check_timeout(void);
168 static void sleepq_dtor(void *mem, int size, void *arg);
170 static int sleepq_init(void *mem, int size, int flags);
171 static int sleepq_resume_thread(struct sleepqueue *sq, struct thread *td,
173 static void sleepq_switch(void *wchan, int pri);
174 static void sleepq_timeout(void *arg);
176 SDT_PROBE_DECLARE(sched, , , sleep);
177 SDT_PROBE_DECLARE(sched, , , wakeup);
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.
184 #ifdef SLEEPQUEUE_PROFILING
186 init_sleepqueue_profiling(void)
189 struct sysctl_oid *chain_oid;
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,
205 SYSINIT(sleepqueue_profiling, SI_SUB_LOCK, SI_ORDER_ANY,
206 init_sleepqueue_profiling, NULL);
210 * Early initialization of sleep queues that is called from the sleepinit()
214 init_sleepqueues(void)
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);
223 sleepq_zone = uma_zcreate("SLEEPQUEUE", sizeof(struct sleepqueue),
225 NULL, sleepq_dtor, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
227 NULL, NULL, sleepq_init, NULL, UMA_ALIGN_CACHE, 0);
230 thread0.td_sleepqueue = sleepq_alloc();
234 * Get a sleep queue for a new thread.
240 return (uma_zalloc(sleepq_zone, M_WAITOK));
244 * Free a sleep queue when a thread is destroyed.
247 sleepq_free(struct sleepqueue *sq)
250 uma_zfree(sleepq_zone, sq);
254 * Lock the sleep queue chain associated with the specified wait channel.
257 sleepq_lock(void *wchan)
259 struct sleepqueue_chain *sc;
261 sc = SC_LOOKUP(wchan);
262 mtx_lock_spin(&sc->sc_lock);
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.
271 sleepq_lookup(void *wchan)
273 struct sleepqueue_chain *sc;
274 struct sleepqueue *sq;
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)
286 * Unlock the sleep queue chain associated with a given wait channel.
289 sleepq_release(void *wchan)
291 struct sleepqueue_chain *sc;
293 sc = SC_LOOKUP(wchan);
294 mtx_unlock_spin(&sc->sc_lock);
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
304 sleepq_add(void *wchan, struct lock_object *lock, const char *wmesg, int flags,
307 struct sleepqueue_chain *sc;
308 struct sleepqueue *sq;
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));
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));
323 /* Look up the sleep queue associated with the wait channel 'wchan'. */
324 sq = sleepq_lookup(wchan);
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.
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));
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"));
347 #ifdef SLEEPQUEUE_PROFILING
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;
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;
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);
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;
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.
384 sleepq_set_timeout_sbt(void *wchan, sbintime_t sbt, sbintime_t pr,
387 struct sleepqueue_chain *sc __unused;
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));
402 callout_when(sbt, pr, flags, &td->td_sleeptimo, &pr1);
404 callout_reset_sbt_on(&td->td_slpcallout, td->td_sleeptimo, pr1,
405 sleepq_timeout, td, PCPU_GET(cpuid), flags | C_PRECALC |
410 * Return the number of actual sleepers for the specified queue.
413 sleepq_sleepcnt(void *wchan, int queue)
415 struct sleepqueue *sq;
417 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
418 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
419 sq = sleepq_lookup(wchan);
422 return (sq->sq_blockedcnt[queue]);
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.
432 sleepq_catch_signals(void *wchan, int pri)
434 struct sleepqueue_chain *sc;
435 struct sleepqueue *sq;
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;
455 * See if there are any pending signals or suspension requests for this
456 * thread. If not, we can switch immediately.
459 if ((td->td_flags & (TDF_NEEDSIGCHK | TDF_NEEDSUSPCHK)) != 0) {
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);
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 if ((td->td_flags & TDF_NEEDSUSPCHK) != 0) {
471 ret = thread_suspend_check(1);
472 MPASS(ret == 0 || ret == EINTR || ret == ERESTART);
475 mtx_lock_spin(&sc->sc_lock);
480 if ((td->td_flags & TDF_NEEDSIGCHK) != 0) {
482 mtx_lock(&ps->ps_mtx);
485 mtx_unlock(&ps->ps_mtx);
486 KASSERT((td->td_flags & TDF_SBDRY) != 0,
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) ?
498 mtx_unlock(&ps->ps_mtx);
500 mtx_unlock(&ps->ps_mtx);
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.
510 if ((td->td_dbgflags & TDB_FSTP) != 0) {
513 td->td_dbgflags &= ~TDB_FSTP;
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().
522 mtx_lock_spin(&sc->sc_lock);
528 sleepq_switch(wchan, pri);
533 * There were pending signals and this thread is still
534 * on the sleep queue, remove it from the sleep queue.
536 if (TD_ON_SLEEPQ(td)) {
537 sq = sleepq_lookup(wchan);
538 if (sleepq_resume_thread(sq, td, 0)) {
541 * This thread hasn't gone to sleep yet, so it
542 * should not be swapped out.
544 panic("not waking up swapper");
548 mtx_unlock_spin(&sc->sc_lock);
549 MPASS(td->td_lock != &sc->sc_lock);
554 * Switches to another thread if we are still asleep on a sleep queue.
555 * Returns with thread lock.
558 sleepq_switch(void *wchan, int pri)
560 struct sleepqueue_chain *sc;
561 struct sleepqueue *sq;
566 sc = SC_LOOKUP(wchan);
567 mtx_assert(&sc->sc_lock, MA_OWNED);
568 THREAD_LOCK_ASSERT(td, MA_OWNED);
571 * If we have a sleep queue, then we've already been woken up, so
574 if (td->td_sleepqueue != NULL) {
575 mtx_unlock_spin(&sc->sc_lock);
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
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.)
598 rtc_changed = td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation;
599 if ((td->td_flags & TDF_TIMEOUT) || rtc_changed) {
603 MPASS(TD_ON_SLEEPQ(td));
604 sq = sleepq_lookup(wchan);
605 if (sleepq_resume_thread(sq, td, 0)) {
608 * This thread hasn't gone to sleep yet, so it
609 * should not be swapped out.
611 panic("not waking up swapper");
614 mtx_unlock_spin(&sc->sc_lock);
617 #ifdef SLEEPQUEUE_PROFILING
619 sleepq_profile(td->td_wmesg);
621 MPASS(td->td_sleepqueue == NULL);
622 sched_sleep(td, pri);
623 thread_lock_set(td, &sc->sc_lock);
624 SDT_PROBE0(sched, , , sleep);
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);
633 * Check to see if we timed out.
636 sleepq_check_timeout(void)
642 THREAD_LOCK_ASSERT(td, MA_OWNED);
645 * If TDF_TIMEOUT is set, we timed out. But recheck
646 * td_sleeptimo anyway.
649 if (td->td_sleeptimo != 0) {
650 if (td->td_sleeptimo <= sbinuptime())
652 td->td_sleeptimo = 0;
654 if (td->td_flags & TDF_TIMEOUT)
655 td->td_flags &= ~TDF_TIMEOUT;
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
667 callout_stop(&td->td_slpcallout);
672 * Check to see if we were awoken by a signal.
675 sleepq_check_signals(void)
680 THREAD_LOCK_ASSERT(td, MA_OWNED);
682 /* We are no longer in an interruptible sleep. */
683 if (td->td_flags & TDF_SINTR)
684 td->td_flags &= ~TDF_SINTR;
686 if (td->td_flags & TDF_SLEEPABORT) {
687 td->td_flags &= ~TDF_SLEEPABORT;
688 return (td->td_intrval);
695 * Block the current thread until it is awakened from its sleep queue.
698 sleepq_wait(void *wchan, int pri)
703 MPASS(!(td->td_flags & TDF_SINTR));
705 sleepq_switch(wchan, pri);
710 * Block the current thread until it is awakened from its sleep queue
711 * or it is interrupted by a signal.
714 sleepq_wait_sig(void *wchan, int pri)
719 rcatch = sleepq_catch_signals(wchan, pri);
720 rval = sleepq_check_signals();
721 thread_unlock(curthread);
728 * Block the current thread until it is awakened from its sleep queue
729 * or it times out while waiting.
732 sleepq_timedwait(void *wchan, int pri)
738 MPASS(!(td->td_flags & TDF_SINTR));
740 sleepq_switch(wchan, pri);
741 rval = sleepq_check_timeout();
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.
752 sleepq_timedwait_sig(void *wchan, int pri)
754 int rcatch, rvalt, rvals;
756 rcatch = sleepq_catch_signals(wchan, pri);
757 rvalt = sleepq_check_timeout();
758 rvals = sleepq_check_signals();
759 thread_unlock(curthread);
768 * Returns the type of sleepqueue given a waitchannel.
771 sleepq_type(void *wchan)
773 struct sleepqueue *sq;
776 MPASS(wchan != NULL);
779 sq = sleepq_lookup(wchan);
781 sleepq_release(wchan);
785 sleepq_release(wchan);
790 * Removes a thread from a sleep queue and makes it
794 sleepq_resume_thread(struct sleepqueue *sq, struct thread *td, int pri)
796 struct sleepqueue_chain *sc __unused;
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);
806 SDT_PROBE2(sched, , , wakeup, td, td->td_proc);
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);
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.
817 if (LIST_EMPTY(&sq->sq_free)) {
818 td->td_sleepqueue = sq;
822 #ifdef SLEEPQUEUE_PROFILING
826 td->td_sleepqueue = LIST_FIRST(&sq->sq_free);
827 LIST_REMOVE(td->td_sleepqueue, sq_hash);
831 td->td_flags &= ~TDF_SINTR;
833 CTR3(KTR_PROC, "sleepq_wakeup: thread %p (pid %ld, %s)",
834 (void *)td, (long)td->td_proc->p_pid, td->td_name);
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)
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.
848 if (TD_IS_SLEEPING(td)) {
850 return (setrunnable(td));
857 * UMA zone item deallocator.
860 sleepq_dtor(void *mem, int size, void *arg)
862 struct sleepqueue *sq;
866 for (i = 0; i < NR_SLEEPQS; i++) {
867 MPASS(TAILQ_EMPTY(&sq->sq_blocked[i]));
868 MPASS(sq->sq_blockedcnt[i] == 0);
874 * UMA zone item initializer.
877 sleepq_init(void *mem, int size, int flags)
879 struct sleepqueue *sq;
884 for (i = 0; i < NR_SLEEPQS; i++) {
885 TAILQ_INIT(&sq->sq_blocked[i]);
886 sq->sq_blockedcnt[i] = 0;
888 LIST_INIT(&sq->sq_free);
893 * Find thread sleeping on a wait channel and resume it.
896 sleepq_signal(void *wchan, int flags, int pri, int queue)
898 struct sleepqueue_chain *sc;
899 struct sleepqueue *sq;
900 struct threadqueue *head;
901 struct thread *td, *besttd;
904 CTR2(KTR_PROC, "sleepq_signal(%p, %d)", wchan, flags);
905 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
906 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
907 sq = sleepq_lookup(wchan);
910 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
911 ("%s: mismatch between sleep/wakeup and cv_*", __func__));
913 head = &sq->sq_blocked[queue];
914 if (flags & SLEEPQ_UNFAIR) {
916 * Find the most recently sleeping thread, but try to
917 * skip threads still in process of context switch to
918 * avoid spinning on the thread lock.
920 sc = SC_LOOKUP(wchan);
921 besttd = TAILQ_LAST_FAST(head, thread, td_slpq);
922 while (besttd->td_lock != &sc->sc_lock) {
923 td = TAILQ_PREV_FAST(besttd, head, thread, td_slpq);
930 * Find the highest priority thread on the queue. If there
931 * is a tie, use the thread that first appears in the queue
932 * as it has been sleeping the longest since threads are
933 * always added to the tail of sleep queues.
935 besttd = td = TAILQ_FIRST(head);
936 while ((td = TAILQ_NEXT(td, td_slpq)) != NULL) {
937 if (td->td_priority < besttd->td_priority)
941 MPASS(besttd != NULL);
943 wakeup_swapper = sleepq_resume_thread(sq, besttd, pri);
944 thread_unlock(besttd);
945 return (wakeup_swapper);
949 match_any(struct thread *td __unused)
956 * Resume all threads sleeping on a specified wait channel.
959 sleepq_broadcast(void *wchan, int flags, int pri, int queue)
961 struct sleepqueue *sq;
963 CTR2(KTR_PROC, "sleepq_broadcast(%p, %d)", wchan, flags);
964 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
965 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
966 sq = sleepq_lookup(wchan);
969 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE),
970 ("%s: mismatch between sleep/wakeup and cv_*", __func__));
972 return (sleepq_remove_matching(sq, queue, match_any, pri));
976 * Resume threads on the sleep queue that match the given predicate.
979 sleepq_remove_matching(struct sleepqueue *sq, int queue,
980 bool (*matches)(struct thread *), int pri)
982 struct thread *td, *tdn;
986 * The last thread will be given ownership of sq and may
987 * re-enqueue itself before sleepq_resume_thread() returns,
988 * so we must cache the "next" queue item at the beginning
989 * of the final iteration.
992 TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq, tdn) {
995 wakeup_swapper |= sleepq_resume_thread(sq, td, pri);
999 return (wakeup_swapper);
1003 * Time sleeping threads out. When the timeout expires, the thread is
1004 * removed from the sleep queue and made runnable if it is still asleep.
1007 sleepq_timeout(void *arg)
1009 struct sleepqueue_chain *sc __unused;
1010 struct sleepqueue *sq;
1017 CTR3(KTR_PROC, "sleepq_timeout: thread %p (pid %ld, %s)",
1018 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
1022 if (td->td_sleeptimo > sbinuptime() || td->td_sleeptimo == 0) {
1024 * The thread does not want a timeout (yet).
1026 } else if (TD_IS_SLEEPING(td) && TD_ON_SLEEPQ(td)) {
1028 * See if the thread is asleep and get the wait
1031 wchan = td->td_wchan;
1032 sc = SC_LOOKUP(wchan);
1033 THREAD_LOCKPTR_ASSERT(td, &sc->sc_lock);
1034 sq = sleepq_lookup(wchan);
1036 td->td_flags |= TDF_TIMEOUT;
1037 wakeup_swapper = sleepq_resume_thread(sq, td, 0);
1038 } else if (TD_ON_SLEEPQ(td)) {
1040 * If the thread is on the SLEEPQ but isn't sleeping
1041 * yet, it can either be on another CPU in between
1042 * sleepq_add() and one of the sleepq_*wait*()
1043 * routines or it can be in sleepq_catch_signals().
1045 td->td_flags |= TDF_TIMEOUT;
1054 * Resumes a specific thread from the sleep queue associated with a specific
1055 * wait channel if it is on that queue.
1058 sleepq_remove(struct thread *td, void *wchan)
1060 struct sleepqueue *sq;
1064 * Look up the sleep queue for this wait channel, then re-check
1065 * that the thread is asleep on that channel, if it is not, then
1068 MPASS(wchan != NULL);
1070 sq = sleepq_lookup(wchan);
1072 * We can not lock the thread here as it may be sleeping on a
1073 * different sleepq. However, holding the sleepq lock for this
1074 * wchan can guarantee that we do not miss a wakeup for this
1075 * channel. The asserts below will catch any false positives.
1077 if (!TD_ON_SLEEPQ(td) || td->td_wchan != wchan) {
1078 sleepq_release(wchan);
1081 /* Thread is asleep on sleep queue sq, so wake it up. */
1084 MPASS(td->td_wchan == wchan);
1085 wakeup_swapper = sleepq_resume_thread(sq, td, 0);
1087 sleepq_release(wchan);
1093 * Abort a thread as if an interrupt had occurred. Only abort
1094 * interruptible waits (unfortunately it isn't safe to abort others).
1097 sleepq_abort(struct thread *td, int intrval)
1099 struct sleepqueue *sq;
1102 THREAD_LOCK_ASSERT(td, MA_OWNED);
1103 MPASS(TD_ON_SLEEPQ(td));
1104 MPASS(td->td_flags & TDF_SINTR);
1105 MPASS(intrval == EINTR || intrval == ERESTART);
1108 * If the TDF_TIMEOUT flag is set, just leave. A
1109 * timeout is scheduled anyhow.
1111 if (td->td_flags & TDF_TIMEOUT)
1114 CTR3(KTR_PROC, "sleepq_abort: thread %p (pid %ld, %s)",
1115 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name);
1116 td->td_intrval = intrval;
1117 td->td_flags |= TDF_SLEEPABORT;
1119 * If the thread has not slept yet it will find the signal in
1120 * sleepq_catch_signals() and call sleepq_resume_thread. Otherwise
1121 * we have to do it here.
1123 if (!TD_IS_SLEEPING(td))
1125 wchan = td->td_wchan;
1126 MPASS(wchan != NULL);
1127 sq = sleepq_lookup(wchan);
1130 /* Thread is asleep on sleep queue sq, so wake it up. */
1131 return (sleepq_resume_thread(sq, td, 0));
1135 sleepq_chains_remove_matching(bool (*matches)(struct thread *))
1137 struct sleepqueue_chain *sc;
1138 struct sleepqueue *sq, *sq1;
1139 int i, wakeup_swapper;
1142 for (sc = &sleepq_chains[0]; sc < sleepq_chains + SC_TABLESIZE; ++sc) {
1143 if (LIST_EMPTY(&sc->sc_queues)) {
1146 mtx_lock_spin(&sc->sc_lock);
1147 LIST_FOREACH_SAFE(sq, &sc->sc_queues, sq_hash, sq1) {
1148 for (i = 0; i < NR_SLEEPQS; ++i) {
1149 wakeup_swapper |= sleepq_remove_matching(sq, i,
1153 mtx_unlock_spin(&sc->sc_lock);
1155 if (wakeup_swapper) {
1161 * Prints the stacks of all threads presently sleeping on wchan/queue to
1162 * the sbuf sb. Sets count_stacks_printed to the number of stacks actually
1163 * printed. Typically, this will equal the number of threads sleeping on the
1164 * queue, but may be less if sb overflowed before all stacks were printed.
1168 sleepq_sbuf_print_stacks(struct sbuf *sb, void *wchan, int queue,
1169 int *count_stacks_printed)
1171 struct thread *td, *td_next;
1172 struct sleepqueue *sq;
1174 struct sbuf **td_infos;
1175 int i, stack_idx, error, stacks_to_allocate;
1181 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__));
1182 MPASS((queue >= 0) && (queue < NR_SLEEPQS));
1184 stacks_to_allocate = 10;
1185 for (i = 0; i < 3 && !finished ; i++) {
1186 /* We cannot malloc while holding the queue's spinlock, so
1187 * we do our mallocs now, and hope it is enough. If it
1188 * isn't, we will free these, drop the lock, malloc more,
1189 * and try again, up to a point. After that point we will
1190 * give up and report ENOMEM. We also cannot write to sb
1191 * during this time since the client may have set the
1192 * SBUF_AUTOEXTEND flag on their sbuf, which could cause a
1193 * malloc as we print to it. So we defer actually printing
1194 * to sb until after we drop the spinlock.
1197 /* Where we will store the stacks. */
1198 st = malloc(sizeof(struct stack *) * stacks_to_allocate,
1200 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1202 st[stack_idx] = stack_create(M_WAITOK);
1204 /* Where we will store the td name, tid, etc. */
1205 td_infos = malloc(sizeof(struct sbuf *) * stacks_to_allocate,
1207 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1209 td_infos[stack_idx] = sbuf_new(NULL, NULL,
1210 MAXCOMLEN + sizeof(struct thread *) * 2 + 40,
1214 sq = sleepq_lookup(wchan);
1216 /* This sleepq does not exist; exit and return ENOENT. */
1219 sleepq_release(wchan);
1224 /* Save thread info */
1225 TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq,
1227 if (stack_idx >= stacks_to_allocate)
1230 /* Note the td_lock is equal to the sleepq_lock here. */
1231 stack_save_td(st[stack_idx], td);
1233 sbuf_printf(td_infos[stack_idx], "%d: %s %p",
1234 td->td_tid, td->td_name, td);
1240 sleepq_release(wchan);
1242 /* Print the stacks */
1243 for (i = 0; i < stack_idx; i++) {
1244 sbuf_finish(td_infos[i]);
1245 sbuf_printf(sb, "--- thread %s: ---\n", sbuf_data(td_infos[i]));
1246 stack_sbuf_print(sb, st[i]);
1247 sbuf_printf(sb, "\n");
1249 error = sbuf_error(sb);
1251 *count_stacks_printed = stack_idx;
1256 sleepq_release(wchan);
1257 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1259 stack_destroy(st[stack_idx]);
1260 for (stack_idx = 0; stack_idx < stacks_to_allocate;
1262 sbuf_delete(td_infos[stack_idx]);
1264 free(td_infos, M_TEMP);
1265 stacks_to_allocate *= 10;
1268 if (!finished && error == 0)
1275 #ifdef SLEEPQUEUE_PROFILING
1276 #define SLEEPQ_PROF_LOCATIONS 1024
1277 #define SLEEPQ_SBUFSIZE 512
1278 struct sleepq_prof {
1279 LIST_ENTRY(sleepq_prof) sp_link;
1280 const char *sp_wmesg;
1284 LIST_HEAD(sqphead, sleepq_prof);
1286 struct sqphead sleepq_prof_free;
1287 struct sqphead sleepq_hash[SC_TABLESIZE];
1288 static struct sleepq_prof sleepq_profent[SLEEPQ_PROF_LOCATIONS];
1289 static struct mtx sleepq_prof_lock;
1290 MTX_SYSINIT(sleepq_prof_lock, &sleepq_prof_lock, "sleepq_prof", MTX_SPIN);
1293 sleepq_profile(const char *wmesg)
1295 struct sleepq_prof *sp;
1297 mtx_lock_spin(&sleepq_prof_lock);
1298 if (prof_enabled == 0)
1300 LIST_FOREACH(sp, &sleepq_hash[SC_HASH(wmesg)], sp_link)
1301 if (sp->sp_wmesg == wmesg)
1303 sp = LIST_FIRST(&sleepq_prof_free);
1306 sp->sp_wmesg = wmesg;
1307 LIST_REMOVE(sp, sp_link);
1308 LIST_INSERT_HEAD(&sleepq_hash[SC_HASH(wmesg)], sp, sp_link);
1312 mtx_unlock_spin(&sleepq_prof_lock);
1317 sleepq_prof_reset(void)
1319 struct sleepq_prof *sp;
1323 mtx_lock_spin(&sleepq_prof_lock);
1324 enabled = prof_enabled;
1326 for (i = 0; i < SC_TABLESIZE; i++)
1327 LIST_INIT(&sleepq_hash[i]);
1328 LIST_INIT(&sleepq_prof_free);
1329 for (i = 0; i < SLEEPQ_PROF_LOCATIONS; i++) {
1330 sp = &sleepq_profent[i];
1331 sp->sp_wmesg = NULL;
1333 LIST_INSERT_HEAD(&sleepq_prof_free, sp, sp_link);
1335 prof_enabled = enabled;
1336 mtx_unlock_spin(&sleepq_prof_lock);
1340 enable_sleepq_prof(SYSCTL_HANDLER_ARGS)
1345 error = sysctl_handle_int(oidp, &v, v, req);
1348 if (req->newptr == NULL)
1350 if (v == prof_enabled)
1353 sleepq_prof_reset();
1354 mtx_lock_spin(&sleepq_prof_lock);
1356 mtx_unlock_spin(&sleepq_prof_lock);
1362 reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1367 error = sysctl_handle_int(oidp, &v, 0, req);
1370 if (req->newptr == NULL)
1374 sleepq_prof_reset();
1380 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
1382 struct sleepq_prof *sp;
1388 error = sysctl_wire_old_buffer(req, 0);
1391 sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
1392 sbuf_printf(sb, "\nwmesg\tcount\n");
1393 enabled = prof_enabled;
1394 mtx_lock_spin(&sleepq_prof_lock);
1396 mtx_unlock_spin(&sleepq_prof_lock);
1397 for (i = 0; i < SC_TABLESIZE; i++) {
1398 LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
1399 sbuf_printf(sb, "%s\t%ld\n",
1400 sp->sp_wmesg, sp->sp_count);
1403 mtx_lock_spin(&sleepq_prof_lock);
1404 prof_enabled = enabled;
1405 mtx_unlock_spin(&sleepq_prof_lock);
1407 error = sbuf_finish(sb);
1412 SYSCTL_PROC(_debug_sleepq, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
1413 NULL, 0, dump_sleepq_prof_stats, "A", "Sleepqueue profiling statistics");
1414 SYSCTL_PROC(_debug_sleepq, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
1415 NULL, 0, reset_sleepq_prof_stats, "I",
1416 "Reset sleepqueue profiling statistics");
1417 SYSCTL_PROC(_debug_sleepq, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
1418 NULL, 0, enable_sleepq_prof, "I", "Enable sleepqueue profiling");
1422 DB_SHOW_COMMAND(sleepq, db_show_sleepqueue)
1424 struct sleepqueue_chain *sc;
1425 struct sleepqueue *sq;
1427 struct lock_object *lock;
1437 * First, see if there is an active sleep queue for the wait channel
1438 * indicated by the address.
1440 wchan = (void *)addr;
1441 sc = SC_LOOKUP(wchan);
1442 LIST_FOREACH(sq, &sc->sc_queues, sq_hash)
1443 if (sq->sq_wchan == wchan)
1447 * Second, see if there is an active sleep queue at the address
1450 for (i = 0; i < SC_TABLESIZE; i++)
1451 LIST_FOREACH(sq, &sleepq_chains[i].sc_queues, sq_hash) {
1452 if (sq == (struct sleepqueue *)addr)
1456 db_printf("Unable to locate a sleep queue via %p\n", (void *)addr);
1459 db_printf("Wait channel: %p\n", sq->sq_wchan);
1460 db_printf("Queue type: %d\n", sq->sq_type);
1464 db_printf("Associated Interlock: %p - (%s) %s\n", lock,
1465 LOCK_CLASS(lock)->lc_name, lock->lo_name);
1468 db_printf("Blocked threads:\n");
1469 for (i = 0; i < NR_SLEEPQS; i++) {
1470 db_printf("\nQueue[%d]:\n", i);
1471 if (TAILQ_EMPTY(&sq->sq_blocked[i]))
1472 db_printf("\tempty\n");
1474 TAILQ_FOREACH(td, &sq->sq_blocked[i],
1476 db_printf("\t%p (tid %d, pid %d, \"%s\")\n", td,
1477 td->td_tid, td->td_proc->p_pid,
1480 db_printf("(expected: %u)\n", sq->sq_blockedcnt[i]);
1484 /* Alias 'show sleepqueue' to 'show sleepq'. */
1485 DB_SHOW_ALIAS(sleepqueue, db_show_sleepqueue);