source: rtems-libbsd/freebsd/sys/kern/subr_sleepqueue.c @ 5e093a5

55-freebsd-126-freebsd-12
Last change on this file since 5e093a5 was 5e093a5, checked in by Sebastian Huber <sebastian.huber@…>, on 02/22/17 at 10:49:33

SLEEPQUEUE(9): Fix absolute timeouts

The FreeBSD kernel timeouts are always based on the uptime. Thus, we
have to use the relative watchdog. C_ABSOLUTE just means that the
timeout value is already an uptime value.

https://lists.freebsd.org/pipermail/freebsd-hackers/2017-February/050572.html

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