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