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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
45 #include "opt_ktrace.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/condvar.h>
50 #include <sys/kernel.h>
53 #include <sys/mutex.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sched.h>
57 #include <sys/signalvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysproto.h>
62 #include <sys/vmmeter.h>
68 #include <sys/ktrace.h>
71 #include <machine/cpu.h>
73 static void sched_setup(void *dummy);
74 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
79 static struct callout loadav_callout;
80 static struct callout lbolt_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 fixpt_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 static int fscale __unused = FSCALE;
96 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
98 static void endtsleep(void *);
99 static void loadav(void *arg);
100 static void lboltcb(void *arg);
103 * We're only looking at 7 bits of the address; everything is
104 * aligned to 4, lots of things are aligned to greater powers
105 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
107 #define TABLESIZE 128
108 static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
109 #define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
116 hogticks = (hz / 10) * 2; /* Default only. */
117 for (i = 0; i < TABLESIZE; i++)
118 TAILQ_INIT(&slpque[i]);
122 * General sleep call. Suspends the current process until a wakeup is
123 * performed on the specified identifier. The process will then be made
124 * runnable with the specified priority. Sleeps at most timo/hz seconds
125 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
126 * before and after sleeping, else signals are not checked. Returns 0 if
127 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
128 * signal needs to be delivered, ERESTART is returned if the current system
129 * call should be restarted if possible, and EINTR is returned if the system
130 * call should be interrupted by the signal (return EINTR).
132 * The mutex argument is exited before the caller is suspended, and
133 * entered before msleep returns. If priority includes the PDROP
134 * flag the mutex is not entered before returning.
138 msleep(ident, mtx, priority, wmesg, timo)
144 struct thread *td = curthread;
145 struct proc *p = td->td_proc;
146 int sig, catch = priority & PCATCH;
148 WITNESS_SAVE_DECL(mtx);
151 if (KTRPOINT(td, KTR_CSW))
154 /* XXX: mtx == NULL ?? */
155 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, &mtx->mtx_object,
156 "Sleeping on \"%s\"", wmesg);
157 KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
158 ("sleeping without a mutex"));
160 * If we are capable of async syscalls and there isn't already
161 * another one ready to return, start a new thread
162 * and queue it as ready to run. Note that there is danger here
163 * because we need to make sure that we don't sleep allocating
164 * the thread (recursion here might be bad).
166 mtx_lock_spin(&sched_lock);
167 if (p->p_flag & P_SA || p->p_numthreads > 1) {
169 * Just don't bother if we are exiting
170 * and not the exiting thread or thread was marked as
174 if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) {
175 mtx_unlock_spin(&sched_lock);
178 if (td->td_flags & TDF_INTERRUPT) {
179 mtx_unlock_spin(&sched_lock);
180 return (td->td_intrval);
186 * During autoconfiguration, just return;
187 * don't run any other procs or panic below,
188 * in case this is the idle process and already asleep.
189 * XXX: this used to do "s = splhigh(); splx(safepri);
190 * splx(s);" to give interrupts a chance, but there is
191 * no way to give interrupts a chance now.
193 if (mtx != NULL && priority & PDROP)
195 mtx_unlock_spin(&sched_lock);
200 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
201 WITNESS_SAVE(&mtx->mtx_object, mtx);
203 if (priority & PDROP)
206 KASSERT(p != NULL, ("msleep1"));
207 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
209 CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)",
210 td, p->p_pid, p->p_comm, wmesg, ident);
212 td->td_wchan = ident;
213 td->td_wmesg = wmesg;
214 TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], td, td_slpq);
215 TD_SET_ON_SLEEPQ(td);
217 callout_reset(&td->td_slpcallout, timo, endtsleep, td);
219 * We put ourselves on the sleep queue and start our timeout
220 * before calling thread_suspend_check, as we could stop there, and
221 * a wakeup or a SIGCONT (or both) could occur while we were stopped.
222 * without resuming us, thus we must be ready for sleep
223 * when cursig is called. If the wakeup happens while we're
224 * stopped, td->td_wchan will be 0 upon return from cursig.
227 CTR3(KTR_PROC, "msleep caught: thread %p (pid %d, %s)", td,
228 p->p_pid, p->p_comm);
229 td->td_flags |= TDF_SINTR;
230 mtx_unlock_spin(&sched_lock);
232 mtx_lock(&p->p_sigacts->ps_mtx);
234 mtx_unlock(&p->p_sigacts->ps_mtx);
235 if (sig == 0 && thread_suspend_check(1))
237 mtx_lock_spin(&sched_lock);
240 if (TD_ON_SLEEPQ(td))
242 } else if (!TD_ON_SLEEPQ(td))
248 * Let the scheduler know we're about to voluntarily go to sleep.
250 sched_sleep(td, priority & PRIMASK);
252 if (TD_ON_SLEEPQ(td)) {
253 p->p_stats->p_ru.ru_nvcsw++;
258 * We're awake from voluntary sleep.
260 CTR3(KTR_PROC, "msleep resume: thread %p (pid %d, %s)", td, p->p_pid,
262 KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING"));
263 td->td_flags &= ~TDF_SINTR;
264 if (td->td_flags & TDF_TIMEOUT) {
265 td->td_flags &= ~TDF_TIMEOUT;
268 } else if (td->td_flags & TDF_TIMOFAIL) {
269 td->td_flags &= ~TDF_TIMOFAIL;
270 } else if (timo && callout_stop(&td->td_slpcallout) == 0) {
272 * This isn't supposed to be pretty. If we are here, then
273 * the endtsleep() callout is currently executing on another
274 * CPU and is either spinning on the sched_lock or will be
275 * soon. If we don't synchronize here, there is a chance
276 * that this process may msleep() again before the callout
277 * has a chance to run and the callout may end up waking up
278 * the wrong msleep(). Yuck.
281 p->p_stats->p_ru.ru_nivcsw++;
283 td->td_flags &= ~TDF_TIMOFAIL;
285 if ((td->td_flags & TDF_INTERRUPT) && (priority & PCATCH) &&
287 rval = td->td_intrval;
289 mtx_unlock_spin(&sched_lock);
290 if (rval == 0 && catch) {
292 /* XXX: shouldn't we always be calling cursig()? */
293 mtx_lock(&p->p_sigacts->ps_mtx);
294 if (sig != 0 || (sig = cursig(td))) {
295 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
300 mtx_unlock(&p->p_sigacts->ps_mtx);
304 if (KTRPOINT(td, KTR_CSW))
310 WITNESS_RESTORE(&mtx->mtx_object, mtx);
316 * Implement timeout for msleep().
318 * If process hasn't been awakened (wchan non-zero),
319 * set timeout flag and undo the sleep. If proc
320 * is stopped, just unsleep so it will remain stopped.
321 * MP-safe, called without the Giant mutex.
327 register struct thread *td;
329 td = (struct thread *)arg;
330 CTR3(KTR_PROC, "endtsleep: thread %p (pid %d, %s)",
331 td, td->td_proc->p_pid, td->td_proc->p_comm);
332 mtx_lock_spin(&sched_lock);
334 * This is the other half of the synchronization with msleep()
335 * described above. If the TDS_TIMEOUT flag is set, we lost the
336 * race and just need to put the process back on the runqueue.
338 if (TD_ON_SLEEPQ(td)) {
339 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
340 TD_CLR_ON_SLEEPQ(td);
341 td->td_flags |= TDF_TIMEOUT;
344 td->td_flags |= TDF_TIMOFAIL;
347 mtx_unlock_spin(&sched_lock);
351 * Abort a thread, as if an interrupt had occured. Only abort
352 * interruptable waits (unfortunatly it isn't only safe to abort others).
353 * This is about identical to cv_abort().
354 * Think about merging them?
355 * Also, whatever the signal code does...
358 abortsleep(struct thread *td)
361 mtx_assert(&sched_lock, MA_OWNED);
363 * If the TDF_TIMEOUT flag is set, just leave. A
364 * timeout is scheduled anyhow.
366 if ((td->td_flags & (TDF_TIMEOUT | TDF_SINTR)) == TDF_SINTR) {
367 if (TD_ON_SLEEPQ(td)) {
376 * Remove a process from its wait queue
379 unsleep(struct thread *td)
382 mtx_lock_spin(&sched_lock);
383 if (TD_ON_SLEEPQ(td)) {
384 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
385 TD_CLR_ON_SLEEPQ(td);
388 mtx_unlock_spin(&sched_lock);
392 * Make all processes sleeping on the specified identifier runnable.
396 register void *ident;
398 register struct slpquehead *qp;
399 register struct thread *td;
403 mtx_lock_spin(&sched_lock);
404 qp = &slpque[LOOKUP(ident)];
406 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
407 ntd = TAILQ_NEXT(td, td_slpq);
408 if (td->td_wchan == ident) {
413 CTR3(KTR_PROC,"wakeup: thread %p (pid %d, %s)",
414 td, p->p_pid, p->p_comm);
418 mtx_unlock_spin(&sched_lock);
422 * Make a process sleeping on the specified identifier runnable.
423 * May wake more than one process if a target process is currently
428 register void *ident;
430 register struct proc *p;
431 register struct slpquehead *qp;
432 register struct thread *td;
435 mtx_lock_spin(&sched_lock);
436 qp = &slpque[LOOKUP(ident)];
437 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
438 ntd = TAILQ_NEXT(td, td_slpq);
439 if (td->td_wchan == ident) {
444 CTR3(KTR_PROC,"wakeup1: thread %p (pid %d, %s)",
445 td, p->p_pid, p->p_comm);
449 mtx_unlock_spin(&sched_lock);
453 * The machine independent parts of mi_switch().
458 struct bintime new_switchtime;
460 struct thread *newtd;
464 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
465 td = curthread; /* XXX */
466 p = td->td_proc; /* XXX */
467 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
469 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
470 mtx_assert(&Giant, MA_NOTOWNED);
472 KASSERT(td->td_critnest == 1,
473 ("mi_switch: switch in a critical section"));
476 * Compute the amount of time during which the current
477 * process was running, and add that to its total so far.
479 binuptime(&new_switchtime);
480 bintime_add(&p->p_runtime, &new_switchtime);
481 bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
483 td->td_generation++; /* bump preempt-detect counter */
487 * Don't perform context switches from the debugger.
490 mtx_unlock_spin(&sched_lock);
491 db_print_backtrace();
492 db_error("Context switches not allowed in the debugger");
497 * Check if the process exceeds its cpu resource allocation. If
498 * over max, arrange to kill the process in ast().
500 if (p->p_cpulimit != RLIM_INFINITY &&
501 p->p_runtime.sec > p->p_cpulimit) {
502 p->p_sflag |= PS_XCPU;
503 td->td_flags |= TDF_ASTPENDING;
507 * Finish up stats for outgoing thread.
510 PCPU_SET(switchtime, new_switchtime);
511 CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid,
513 sched_nest = sched_lock.mtx_recurse;
514 if (td->td_proc->p_flag & P_SA)
515 thread_switchout(td);
518 newtd = choosethread();
520 cpu_switch(td, newtd); /* SHAZAM!! */
522 sched_lock.mtx_recurse = sched_nest;
523 sched_lock.mtx_lock = (uintptr_t)td;
527 * Start setting up stats etc. for the incoming thread.
528 * Similar code in fork_exit() is returned to by cpu_switch()
529 * in the case of a new thread/process.
531 CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid,
533 if (PCPU_GET(switchtime.sec) == 0)
534 binuptime(PCPU_PTR(switchtime));
535 PCPU_SET(switchticks, ticks);
537 * If the last thread was exiting, finish cleaning it up.
539 if ((td = PCPU_GET(deadthread))) {
540 PCPU_SET(deadthread, NULL);
546 * Change process state to be runnable,
547 * placing it on the run queue if it is in memory,
548 * and awakening the swapper if it isn't in memory.
551 setrunnable(struct thread *td)
556 mtx_assert(&sched_lock, MA_OWNED);
557 switch (p->p_state) {
559 panic("setrunnable(1)");
563 switch (td->td_state) {
569 * If we are only inhibited because we are swapped out
570 * then arange to swap in this process. Otherwise just return.
572 if (td->td_inhibitors != TDI_SWAPPED)
574 /* XXX: intentional fall-through ? */
578 printf("state is 0x%x", td->td_state);
579 panic("setrunnable(2)");
581 if ((p->p_sflag & PS_INMEM) == 0) {
582 if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
583 p->p_sflag |= PS_SWAPINREQ;
591 * Compute a tenex style load average of a quantity on
592 * 1, 5 and 15 minute intervals.
593 * XXXKSE Needs complete rewrite when correct info is available.
594 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
605 sx_slock(&allproc_lock);
607 FOREACH_PROC_IN_SYSTEM(p) {
608 FOREACH_THREAD_IN_PROC(p, td) {
609 switch (td->td_state) {
612 if ((p->p_flag & P_NOLOAD) != 0)
622 sx_sunlock(&allproc_lock);
623 for (i = 0; i < 3; i++)
624 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
625 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
628 * Schedule the next update to occur after 5 seconds, but add a
629 * random variation to avoid synchronisation with processes that
630 * run at regular intervals.
632 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
640 callout_reset(&lbolt_callout, hz, lboltcb, NULL);
648 callout_init(&loadav_callout, 0);
649 callout_init(&lbolt_callout, CALLOUT_MPSAFE);
651 /* Kick off timeout driven events by calling first time. */
657 * General purpose yield system call
660 yield(struct thread *td, struct yield_args *uap)
665 mtx_assert(&Giant, MA_NOTOWNED);
666 mtx_lock_spin(&sched_lock);
667 kg->kg_proc->p_stats->p_ru.ru_nvcsw++;
668 sched_prio(td, PRI_MAX_TIMESHARE);
670 mtx_unlock_spin(&sched_lock);
671 td->td_retval[0] = 0;