source: rtems-libbsd/freebsd/sys/kern/subr_sleepqueue.c @ 1b47c61

55-freebsd-12
Last change on this file since 1b47c61 was 1b47c61, checked in by Sebastian Huber <sebastian.huber@…>, on Dec 14, 2018 at 9:36:10 AM

SLEEPQUEUE(9): SMP only cache line alignment

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