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

55-freebsd-126-freebsd-12
Last change on this file since bcdce02 was bcdce02, checked in by Sebastian Huber <sebastian.huber@…>, on 08/21/18 at 11:47:02

Update to FreeBSD head 2018-06-01

Git mirror commit fb63610a69b0eb7f69a201ba05c4c1a7a2739cf9.

Update #3472.

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