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