source: rtems-libbsd/freebsd/sys/kern/subr_sleepqueue.c @ 8b722db

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 8b722db was 8b722db, checked in by Sebastian Huber <sebastian.huber@…>, on 04/08/15 at 05:22:01

SLEEPQUEUE(9): Include missing header file

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