2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_ktrace.h"
41 #include "opt_sched.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/condvar.h>
47 #include <sys/kernel.h>
50 #include <sys/mutex.h>
52 #include <sys/resourcevar.h>
53 #include <sys/sched.h>
55 #include <sys/signalvar.h>
56 #include <sys/sleepqueue.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysproto.h>
61 #include <sys/vmmeter.h>
64 #include <sys/ktrace.h>
67 #include <machine/cpu.h>
69 #define KTDSTATE(td) \
70 (((td)->td_inhibitors & TDI_SLEEPING) != 0 ? "sleep" : \
71 ((td)->td_inhibitors & TDI_SUSPENDED) != 0 ? "suspended" : \
72 ((td)->td_inhibitors & TDI_SWAPPED) != 0 ? "swapped" : \
73 ((td)->td_inhibitors & TDI_LOCK) != 0 ? "blocked" : \
74 ((td)->td_inhibitors & TDI_IWAIT) != 0 ? "iwait" : "yielding")
76 static void synch_setup(void *dummy);
77 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup,
81 static uint8_t pause_wchan[MAXCPU];
83 static struct callout loadav_callout;
85 struct loadavg averunnable =
86 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
88 * Constants for averages over 1, 5, and 15 minutes
89 * when sampling at 5 second intervals.
91 static fixpt_t cexp[3] = {
92 0.9200444146293232 * FSCALE, /* exp(-1/12) */
93 0.9834714538216174 * FSCALE, /* exp(-1/60) */
94 0.9944598480048967 * FSCALE, /* exp(-1/180) */
97 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
98 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, FSCALE, "");
100 static void loadav(void *arg);
102 SDT_PROVIDER_DECLARE(sched);
103 SDT_PROBE_DEFINE(sched, , , preempt);
106 sleepinit(void *unused)
109 hogticks = (hz / 10) * 2; /* Default only. */
114 * vmem tries to lock the sleepq mutexes when free'ing kva, so make sure
117 SYSINIT(sleepinit, SI_SUB_KMEM, SI_ORDER_ANY, sleepinit, 0);
120 * General sleep call. Suspends the current thread until a wakeup is
121 * performed on the specified identifier. The thread will then be made
122 * runnable with the specified priority. Sleeps at most sbt units of time
123 * (0 means no timeout). If pri includes the PCATCH flag, let signals
124 * interrupt the sleep, otherwise ignore them while sleeping. Returns 0 if
125 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
126 * signal becomes pending, ERESTART is returned if the current system
127 * call should be restarted if possible, and EINTR is returned if the system
128 * call should be interrupted by the signal (return EINTR).
130 * The lock argument is unlocked before the caller is suspended, and
131 * re-locked before _sleep() returns. If priority includes the PDROP
132 * flag the lock is not re-locked before returning.
135 _sleep(void *ident, struct lock_object *lock, int priority,
136 const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
140 struct lock_class *class;
141 uintptr_t lock_state;
142 int catch, pri, rval, sleepq_flags;
143 WITNESS_SAVE_DECL(lock_witness);
148 if (KTRPOINT(td, KTR_CSW))
151 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock,
152 "Sleeping on \"%s\"", wmesg);
153 KASSERT(sbt != 0 || mtx_owned(&Giant) || lock != NULL,
154 ("sleeping without a lock"));
155 KASSERT(ident != NULL, ("_sleep: NULL ident"));
156 KASSERT(TD_IS_RUNNING(td), ("_sleep: curthread not running"));
157 if (priority & PDROP)
158 KASSERT(lock != NULL && lock != &Giant.lock_object,
159 ("PDROP requires a non-Giant lock"));
161 class = LOCK_CLASS(lock);
165 if (SCHEDULER_STOPPED_TD(td)) {
166 if (lock != NULL && priority & PDROP)
167 class->lc_unlock(lock);
170 catch = priority & PCATCH;
171 pri = priority & PRIMASK;
173 KASSERT(!TD_ON_SLEEPQ(td), ("recursive sleep"));
175 if ((uint8_t *)ident >= &pause_wchan[0] &&
176 (uint8_t *)ident <= &pause_wchan[MAXCPU - 1])
177 sleepq_flags = SLEEPQ_PAUSE;
179 sleepq_flags = SLEEPQ_SLEEP;
181 sleepq_flags |= SLEEPQ_INTERRUPTIBLE;
184 CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)",
185 td->td_tid, p->p_pid, td->td_name, wmesg, ident);
187 if (lock == &Giant.lock_object)
188 mtx_assert(&Giant, MA_OWNED);
190 if (lock != NULL && lock != &Giant.lock_object &&
191 !(class->lc_flags & LC_SLEEPABLE)) {
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);
239 msleep_spin_sbt(void *ident, struct mtx *mtx, const char *wmesg,
240 sbintime_t sbt, sbintime_t pr, int flags)
245 WITNESS_SAVE_DECL(mtx);
249 KASSERT(mtx != NULL, ("sleeping without a mutex"));
250 KASSERT(ident != NULL, ("msleep_spin_sbt: NULL ident"));
251 KASSERT(TD_IS_RUNNING(td), ("msleep_spin_sbt: curthread not running"));
253 if (SCHEDULER_STOPPED_TD(td))
257 CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)",
258 td->td_tid, p->p_pid, td->td_name, wmesg, ident);
261 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
262 WITNESS_SAVE(&mtx->lock_object, mtx);
263 mtx_unlock_spin(mtx);
266 * We put ourselves on the sleep queue and start our timeout.
268 sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0);
270 sleepq_set_timeout_sbt(ident, sbt, pr, flags);
273 * Can't call ktrace with any spin locks held so it can lock the
274 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold
275 * any spin lock. Thus, we have to drop the sleepq spin lock while
276 * we handle those requests. This is safe since we have placed our
277 * thread on the sleep queue already.
280 if (KTRPOINT(td, KTR_CSW)) {
281 sleepq_release(ident);
287 sleepq_release(ident);
288 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"",
293 rval = sleepq_timedwait(ident, 0);
295 sleepq_wait(ident, 0);
299 if (KTRPOINT(td, KTR_CSW))
304 WITNESS_RESTORE(&mtx->lock_object, mtx);
309 * pause() delays the calling thread by the given number of system ticks.
310 * During cold bootup, pause() uses the DELAY() function instead of
311 * the tsleep() function to do the waiting. The "timo" argument must be
312 * greater than or equal to zero. A "timo" value of zero is equivalent
313 * to a "timo" value of one.
316 pause_sbt(const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
318 KASSERT(sbt >= 0, ("pause: timeout must be >= 0"));
320 /* silently convert invalid timeouts */
324 if ((cold && curthread == &thread0) || kdb_active ||
325 SCHEDULER_STOPPED()) {
327 * We delay one second at a time to avoid overflowing the
328 * system specific DELAY() function(s):
330 while (sbt >= SBT_1S) {
334 /* Do the delay remainder, if any */
335 sbt = howmany(sbt, SBT_1US);
340 return (_sleep(&pause_wchan[curcpu], NULL, 0, wmesg, sbt, pr, flags));
344 * Make all threads sleeping on the specified identifier runnable.
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(void *ident)
372 wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP, 0, 0);
373 sleepq_release(ident);
381 thread_unlock(curthread);
384 panic("%s: did not reenter debugger", __func__);
388 * The machine independent parts of context switching.
391 mi_switch(int flags, struct thread *newtd)
393 uint64_t runtime, new_switchtime;
396 td = curthread; /* XXX */
397 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
398 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
400 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
401 mtx_assert(&Giant, MA_NOTOWNED);
403 KASSERT(td->td_critnest == 1 || panicstr,
404 ("mi_switch: switch in a critical section"));
405 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
406 ("mi_switch: switch must be voluntary or involuntary"));
407 KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
410 * Don't perform context switches from the debugger.
414 if (SCHEDULER_STOPPED_TD(td))
416 if (flags & SW_VOL) {
417 td->td_ru.ru_nvcsw++;
418 td->td_swvoltick = ticks;
420 td->td_ru.ru_nivcsw++;
421 td->td_swinvoltick = ticks;
424 SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]);
427 * Compute the amount of time during which the current
428 * thread was running, and add that to its total so far.
430 new_switchtime = cpu_ticks();
431 runtime = new_switchtime - PCPU_GET(switchtime);
432 td->td_runtime += runtime;
433 td->td_incruntime += runtime;
434 PCPU_SET(switchtime, new_switchtime);
435 td->td_generation++; /* bump preempt-detect counter */
436 PCPU_INC(cnt.v_swtch);
437 PCPU_SET(switchticks, ticks);
438 CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)",
439 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
440 #if (KTR_COMPILE & KTR_SCHED) != 0
441 if (TD_IS_IDLETHREAD(td))
442 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
443 "prio:%d", td->td_priority);
445 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
446 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
447 "lockname:\"%s\"", td->td_lockname);
449 SDT_PROBE0(sched, , , preempt);
450 sched_switch(td, newtd, flags);
451 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
452 "prio:%d", td->td_priority);
454 CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)",
455 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
458 * If the last thread was exiting, finish cleaning it up.
460 if ((td = PCPU_GET(deadthread))) {
461 PCPU_SET(deadthread, NULL);
467 * Change thread state to be runnable, placing it on the run queue if
468 * it is in memory. If it is swapped out, return true so our caller
469 * will know to awaken the swapper.
472 setrunnable(struct thread *td)
475 THREAD_LOCK_ASSERT(td, MA_OWNED);
476 KASSERT(td->td_proc->p_state != PRS_ZOMBIE,
477 ("setrunnable: pid %d is a zombie", td->td_proc->p_pid));
478 switch (td->td_state) {
484 * If we are only inhibited because we are swapped out
485 * then arange to swap in this process. Otherwise just return.
487 if (td->td_inhibitors != TDI_SWAPPED)
493 printf("state is 0x%x", td->td_state);
494 panic("setrunnable(2)");
496 if ((td->td_flags & TDF_INMEM) == 0) {
497 if ((td->td_flags & TDF_SWAPINREQ) == 0) {
498 td->td_flags |= TDF_SWAPINREQ;
507 * Compute a tenex style load average of a quantity on
508 * 1, 5 and 15 minute intervals.
519 for (i = 0; i < 3; i++)
520 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
521 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
524 * Schedule the next update to occur after 5 seconds, but add a
525 * random variation to avoid synchronisation with processes that
526 * run at regular intervals.
528 callout_reset_sbt(&loadav_callout,
529 SBT_1US * (4000000 + (int)(random() % 2000001)), SBT_1US,
530 loadav, NULL, C_DIRECT_EXEC | C_PREL(32));
535 synch_setup(void *dummy)
537 callout_init(&loadav_callout, 1);
539 /* Kick off timeout driven events by calling first time. */
547 return ((u_int)ticks - (u_int)curthread->td_swvoltick >= hogticks);
555 kern_yield(PRI_USER);
566 if (prio == PRI_USER)
567 prio = td->td_user_pri;
569 sched_prio(td, prio);
570 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
576 * General purpose yield system call.
579 sys_yield(struct thread *td, struct yield_args *uap)
583 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
584 sched_prio(td, PRI_MAX_TIMESHARE);
585 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
587 td->td_retval[0] = 0;