2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
39 #include <sys/cdefs.h>
40 #include "opt_ktrace.h"
41 #include "opt_sched.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/blockcount.h>
46 #include <sys/condvar.h>
48 #include <sys/kernel.h>
51 #include <sys/mutex.h>
53 #include <sys/resourcevar.h>
54 #include <sys/sched.h>
56 #include <sys/signalvar.h>
57 #include <sys/sleepqueue.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysproto.h>
62 #include <sys/vmmeter.h>
65 #include <sys/ktrace.h>
68 #include <sys/epoch.h>
71 #include <machine/cpu.h>
73 static void synch_setup(void *dummy);
74 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup,
78 static const char pause_wchan[MAXCPU];
80 static struct callout loadav_callout;
82 struct loadavg averunnable =
83 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
85 * Constants for averages over 1, 5, and 15 minutes
86 * when sampling at 5 second intervals.
88 static uint64_t cexp[3] = {
89 0.9200444146293232 * FSCALE, /* exp(-1/12) */
90 0.9834714538216174 * FSCALE, /* exp(-1/60) */
91 0.9944598480048967 * FSCALE, /* exp(-1/180) */
94 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
95 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, FSCALE,
96 "Fixed-point scale factor used for calculating load average values");
98 static void loadav(void *arg);
100 SDT_PROVIDER_DECLARE(sched);
101 SDT_PROBE_DEFINE(sched, , , preempt);
104 sleepinit(void *unused)
107 hogticks = (hz / 10) * 2; /* Default only. */
112 * vmem tries to lock the sleepq mutexes when free'ing kva, so make sure
115 SYSINIT(sleepinit, SI_SUB_KMEM, SI_ORDER_ANY, sleepinit, NULL);
118 * General sleep call. Suspends the current thread until a wakeup is
119 * performed on the specified identifier. The thread will then be made
120 * runnable with the specified priority. Sleeps at most sbt units of time
121 * (0 means no timeout). If pri includes the PCATCH flag, let signals
122 * interrupt the sleep, otherwise ignore them while sleeping. Returns 0 if
123 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
124 * signal becomes pending, ERESTART is returned if the current system
125 * call should be restarted if possible, and EINTR is returned if the system
126 * call should be interrupted by the signal (return EINTR).
128 * The lock argument is unlocked before the caller is suspended, and
129 * re-locked before _sleep() returns. If priority includes the PDROP
130 * flag the lock is not re-locked before returning.
133 _sleep(const void *ident, struct lock_object *lock, int priority,
134 const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
137 struct lock_class *class;
138 uintptr_t lock_state;
139 int catch, pri, rval, sleepq_flags;
140 WITNESS_SAVE_DECL(lock_witness);
145 if (KTRPOINT(td, KTR_CSW))
148 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock,
149 "Sleeping on \"%s\"", wmesg);
150 KASSERT(sbt != 0 || mtx_owned(&Giant) || lock != NULL ||
151 (priority & PNOLOCK) != 0,
152 ("sleeping without a lock"));
153 KASSERT(ident != NULL, ("_sleep: NULL ident"));
154 KASSERT(TD_IS_RUNNING(td), ("_sleep: curthread not running"));
155 if (priority & PDROP)
156 KASSERT(lock != NULL && lock != &Giant.lock_object,
157 ("PDROP requires a non-Giant lock"));
159 class = LOCK_CLASS(lock);
163 if (SCHEDULER_STOPPED_TD(td)) {
164 if (lock != NULL && priority & PDROP)
165 class->lc_unlock(lock);
168 catch = priority & PCATCH;
169 pri = priority & PRIMASK;
171 KASSERT(!TD_ON_SLEEPQ(td), ("recursive sleep"));
173 if ((uintptr_t)ident >= (uintptr_t)&pause_wchan[0] &&
174 (uintptr_t)ident <= (uintptr_t)&pause_wchan[MAXCPU - 1])
175 sleepq_flags = SLEEPQ_PAUSE;
177 sleepq_flags = SLEEPQ_SLEEP;
179 sleepq_flags |= SLEEPQ_INTERRUPTIBLE;
182 CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)",
183 td->td_tid, td->td_proc->p_pid, td->td_name, wmesg, ident);
185 if (lock == &Giant.lock_object)
186 mtx_assert(&Giant, MA_OWNED);
188 if (lock != NULL && lock != &Giant.lock_object &&
189 !(class->lc_flags & LC_SLEEPABLE)) {
190 KASSERT(!(class->lc_flags & LC_SPINLOCK),
191 ("spin locks can only use msleep_spin"));
192 WITNESS_SAVE(lock, lock_witness);
193 lock_state = class->lc_unlock(lock);
195 /* GCC needs to follow the Yellow Brick Road */
199 * We put ourselves on the sleep queue and start our timeout
200 * before calling thread_suspend_check, as we could stop there,
201 * and a wakeup or a SIGCONT (or both) could occur while we were
202 * stopped without resuming us. Thus, we must be ready for sleep
203 * when cursig() is called. If the wakeup happens while we're
204 * stopped, then td will no longer be on a sleep queue upon
205 * return from cursig().
207 sleepq_add(ident, lock, wmesg, sleepq_flags, 0);
209 sleepq_set_timeout_sbt(ident, sbt, pr, flags);
210 if (lock != NULL && class->lc_flags & LC_SLEEPABLE) {
211 sleepq_release(ident);
212 WITNESS_SAVE(lock, lock_witness);
213 lock_state = class->lc_unlock(lock);
216 if (sbt != 0 && catch)
217 rval = sleepq_timedwait_sig(ident, pri);
219 rval = sleepq_timedwait(ident, pri);
221 rval = sleepq_wait_sig(ident, pri);
223 sleepq_wait(ident, pri);
227 if (KTRPOINT(td, KTR_CSW))
231 if (lock != NULL && lock != &Giant.lock_object && !(priority & PDROP)) {
232 class->lc_lock(lock, lock_state);
233 WITNESS_RESTORE(lock, lock_witness);
240 msleep_spin_sbt(const void *ident, struct mtx *mtx, const char *wmesg,
241 sbintime_t sbt, sbintime_t pr, int flags)
245 WITNESS_SAVE_DECL(mtx);
248 KASSERT(mtx != NULL, ("sleeping without a mutex"));
249 KASSERT(ident != NULL, ("msleep_spin_sbt: NULL ident"));
250 KASSERT(TD_IS_RUNNING(td), ("msleep_spin_sbt: curthread not running"));
252 if (SCHEDULER_STOPPED_TD(td))
256 CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)",
257 td->td_tid, td->td_proc->p_pid, td->td_name, wmesg, ident);
260 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
261 WITNESS_SAVE(&mtx->lock_object, mtx);
262 mtx_unlock_spin(mtx);
265 * We put ourselves on the sleep queue and start our timeout.
267 sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0);
269 sleepq_set_timeout_sbt(ident, sbt, pr, flags);
272 * Can't call ktrace with any spin locks held so it can lock the
273 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold
274 * any spin lock. Thus, we have to drop the sleepq spin lock while
275 * we handle those requests. This is safe since we have placed our
276 * thread on the sleep queue already.
279 if (KTRPOINT(td, KTR_CSW)) {
280 sleepq_release(ident);
286 sleepq_release(ident);
287 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"",
292 rval = sleepq_timedwait(ident, 0);
294 sleepq_wait(ident, 0);
298 if (KTRPOINT(td, KTR_CSW))
303 WITNESS_RESTORE(&mtx->lock_object, mtx);
308 * pause_sbt() delays the calling thread by the given signed binary
309 * time. During cold bootup, pause_sbt() uses the DELAY() function
310 * instead of the _sleep() function to do the waiting. The "sbt"
311 * argument must be greater than or equal to zero. A "sbt" value of
312 * zero is equivalent to a "sbt" value of one tick.
315 pause_sbt(const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
317 KASSERT(sbt >= 0, ("pause_sbt: timeout must be >= 0"));
319 /* silently convert invalid timeouts */
323 if ((cold && curthread == &thread0) || kdb_active ||
324 SCHEDULER_STOPPED()) {
326 * We delay one second at a time to avoid overflowing the
327 * system specific DELAY() function(s):
329 while (sbt >= SBT_1S) {
333 /* Do the delay remainder, if any */
334 sbt = howmany(sbt, SBT_1US);
337 return (EWOULDBLOCK);
339 return (_sleep(&pause_wchan[curcpu], NULL,
340 (flags & C_CATCH) ? PCATCH : 0, wmesg, sbt, pr, flags));
344 * Make all threads sleeping on the specified identifier runnable.
347 wakeup(const void *ident)
352 wakeup_swapper = sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0);
353 sleepq_release(ident);
354 if (wakeup_swapper) {
355 KASSERT(ident != &proc0,
356 ("wakeup and wakeup_swapper and proc0"));
362 * Make a thread sleeping on the specified identifier runnable.
363 * May wake more than one thread if a target thread is currently
367 wakeup_one(const void *ident)
372 wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP | SLEEPQ_DROP, 0, 0);
378 wakeup_any(const void *ident)
383 wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP | SLEEPQ_UNFAIR |
390 * Signal sleeping waiters after the counter has reached zero.
393 _blockcount_wakeup(blockcount_t *bc, u_int old)
396 KASSERT(_BLOCKCOUNT_WAITERS(old),
397 ("%s: no waiters on %p", __func__, bc));
399 if (atomic_cmpset_int(&bc->__count, _BLOCKCOUNT_WAITERS_FLAG, 0))
404 * Wait for a wakeup or a signal. This does not guarantee that the count is
405 * still zero on return. Callers wanting a precise answer should use
406 * blockcount_wait() with an interlock.
408 * If there is no work to wait for, return 0. If the sleep was interrupted by a
409 * signal, return EINTR or ERESTART, and return EAGAIN otherwise.
412 _blockcount_sleep(blockcount_t *bc, struct lock_object *lock, const char *wmesg,
416 uintptr_t lock_state;
421 KASSERT(lock != &Giant.lock_object,
422 ("%s: cannot use Giant as the interlock", __func__));
424 catch = (prio & PCATCH) != 0;
425 drop = (prio & PDROP) != 0;
429 * Synchronize with the fence in blockcount_release(). If we end up
430 * waiting, the sleepqueue lock acquisition will provide the required
433 * If there is no work to wait for, but waiters are present, try to put
434 * ourselves to sleep to avoid jumping ahead.
436 if (atomic_load_acq_int(&bc->__count) == 0) {
437 if (lock != NULL && drop)
438 LOCK_CLASS(lock)->lc_unlock(lock);
446 lock_state = LOCK_CLASS(lock)->lc_unlock(lock);
447 old = blockcount_read(bc);
450 if (_BLOCKCOUNT_COUNT(old) == 0) {
451 sleepq_release(wchan);
454 if (_BLOCKCOUNT_WAITERS(old))
456 } while (!atomic_fcmpset_int(&bc->__count, &old,
457 old | _BLOCKCOUNT_WAITERS_FLAG));
458 sleepq_add(wchan, NULL, wmesg, catch ? SLEEPQ_INTERRUPTIBLE : 0, 0);
460 ret = sleepq_wait_sig(wchan, prio);
462 sleepq_wait(wchan, prio);
468 if (lock != NULL && !drop)
469 LOCK_CLASS(lock)->lc_lock(lock, lock_state);
477 thread_unlock(curthread);
480 panic("%s: did not reenter debugger", __func__);
484 * mi_switch(9): The machine-independent parts of context switching.
486 * The thread lock is required on entry and is no longer held on return.
491 uint64_t runtime, new_switchtime;
494 td = curthread; /* XXX */
495 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
496 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
498 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
499 mtx_assert(&Giant, MA_NOTOWNED);
501 /* thread_lock() performs spinlock_enter(). */
502 KASSERT(td->td_critnest == 1 || KERNEL_PANICKED(),
503 ("mi_switch: switch in a critical section"));
504 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
505 ("mi_switch: switch must be voluntary or involuntary"));
506 KASSERT((flags & SW_TYPE_MASK) != 0,
507 ("mi_switch: a switch reason (type) must be specified"));
508 KASSERT((flags & SW_TYPE_MASK) < SWT_COUNT,
509 ("mi_switch: invalid switch reason %d", (flags & SW_TYPE_MASK)));
512 * Don't perform context switches from the debugger.
516 if (SCHEDULER_STOPPED_TD(td))
518 if (flags & SW_VOL) {
519 td->td_ru.ru_nvcsw++;
520 td->td_swvoltick = ticks;
522 td->td_ru.ru_nivcsw++;
523 td->td_swinvoltick = ticks;
526 SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]);
529 * Compute the amount of time during which the current
530 * thread was running, and add that to its total so far.
532 new_switchtime = cpu_ticks();
533 runtime = new_switchtime - PCPU_GET(switchtime);
534 td->td_runtime += runtime;
535 td->td_incruntime += runtime;
536 PCPU_SET(switchtime, new_switchtime);
537 td->td_generation++; /* bump preempt-detect counter */
539 PCPU_SET(switchticks, ticks);
540 CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)",
541 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
543 if (SDT_PROBES_ENABLED() &&
544 ((flags & SW_PREEMPT) != 0 || ((flags & SW_INVOL) != 0 &&
545 (flags & SW_TYPE_MASK) == SWT_NEEDRESCHED)))
546 SDT_PROBE0(sched, , , preempt);
548 sched_switch(td, flags);
549 CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)",
550 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
553 * If the last thread was exiting, finish cleaning it up.
555 if ((td = PCPU_GET(deadthread))) {
556 PCPU_SET(deadthread, NULL);
563 * Change thread state to be runnable, placing it on the run queue if
564 * it is in memory. If it is swapped out, return true so our caller
565 * will know to awaken the swapper.
567 * Requires the thread lock on entry, drops on exit.
570 setrunnable(struct thread *td, int srqflags)
574 THREAD_LOCK_ASSERT(td, MA_OWNED);
575 KASSERT(td->td_proc->p_state != PRS_ZOMBIE,
576 ("setrunnable: pid %d is a zombie", td->td_proc->p_pid));
579 switch (TD_GET_STATE(td)) {
584 KASSERT((td->td_flags & TDF_INMEM) != 0,
585 ("setrunnable: td %p not in mem, flags 0x%X inhibit 0x%X",
586 td, td->td_flags, td->td_inhibitors));
587 /* unlocks thread lock according to flags */
588 sched_wakeup(td, srqflags);
592 * If we are only inhibited because we are swapped out
593 * arrange to swap in this process.
595 if (td->td_inhibitors == TDI_SWAPPED &&
596 (td->td_flags & TDF_SWAPINREQ) == 0) {
597 td->td_flags |= TDF_SWAPINREQ;
602 panic("setrunnable: state 0x%x", TD_GET_STATE(td));
604 if ((srqflags & (SRQ_HOLD | SRQ_HOLDTD)) == 0)
611 * Compute a tenex style load average of a quantity on
612 * 1, 5 and 15 minute intervals.
621 nrun = (uint64_t)sched_load();
624 for (i = 0; i < 3; i++)
625 avg->ldavg[i] = (cexp[i] * (uint64_t)avg->ldavg[i] +
626 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
629 * Schedule the next update to occur after 5 seconds, but add a
630 * random variation to avoid synchronisation with processes that
631 * run at regular intervals.
633 callout_reset_sbt(&loadav_callout,
634 SBT_1US * (4000000 + (int)(random() % 2000001)), SBT_1US,
635 loadav, NULL, C_DIRECT_EXEC | C_PREL(32));
639 ast_scheduler(struct thread *td, int tda __unused)
642 if (KTRPOINT(td, KTR_CSW))
643 ktrcsw(1, 1, __func__);
646 sched_prio(td, td->td_user_pri);
647 mi_switch(SW_INVOL | SWT_NEEDRESCHED);
649 if (KTRPOINT(td, KTR_CSW))
650 ktrcsw(0, 1, __func__);
655 synch_setup(void *dummy __unused)
657 callout_init(&loadav_callout, 1);
658 ast_register(TDA_SCHED, ASTR_ASTF_REQUIRED, 0, ast_scheduler);
660 /* Kick off timeout driven events by calling first time. */
668 return ((u_int)ticks - (u_int)curthread->td_swvoltick >= hogticks);
676 kern_yield(PRI_USER);
687 if (prio == PRI_USER)
688 prio = td->td_user_pri;
690 sched_prio(td, prio);
691 mi_switch(SW_VOL | SWT_RELINQUISH);
696 * General purpose yield system call.
699 sys_yield(struct thread *td, struct yield_args *uap)
703 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
704 sched_prio(td, PRI_MAX_TIMESHARE);
705 mi_switch(SW_VOL | SWT_RELINQUISH);
706 td->td_retval[0] = 0;
711 sys_sched_getcpu(struct thread *td, struct sched_getcpu_args *uap)
713 td->td_retval[0] = td->td_oncpu;