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 * 4. 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"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/condvar.h>
46 #include <sys/kernel.h>
49 #include <sys/mutex.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
53 #include <sys/signalvar.h>
54 #include <sys/sleepqueue.h>
57 #include <sys/sysctl.h>
58 #include <sys/sysproto.h>
59 #include <sys/vmmeter.h>
62 #include <sys/ktrace.h>
65 #include <machine/cpu.h>
67 static void synch_setup(void *dummy);
68 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL)
73 static struct callout loadav_callout;
74 static struct callout lbolt_callout;
76 struct loadavg averunnable =
77 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
79 * Constants for averages over 1, 5, and 15 minutes
80 * when sampling at 5 second intervals.
82 static fixpt_t cexp[3] = {
83 0.9200444146293232 * FSCALE, /* exp(-1/12) */
84 0.9834714538216174 * FSCALE, /* exp(-1/60) */
85 0.9944598480048967 * FSCALE, /* exp(-1/180) */
88 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
89 static int fscale __unused = FSCALE;
90 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
92 static void loadav(void *arg);
93 static void lboltcb(void *arg);
99 hogticks = (hz / 10) * 2; /* Default only. */
104 * General sleep call. Suspends the current thread until a wakeup is
105 * performed on the specified identifier. The thread will then be made
106 * runnable with the specified priority. Sleeps at most timo/hz seconds
107 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
108 * before and after sleeping, else signals are not checked. Returns 0 if
109 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
110 * signal needs to be delivered, ERESTART is returned if the current system
111 * call should be restarted if possible, and EINTR is returned if the system
112 * call should be interrupted by the signal (return EINTR).
114 * The mutex argument is unlocked before the caller is suspended, and
115 * re-locked before msleep returns. If priority includes the PDROP
116 * flag the mutex is not re-locked before returning.
119 msleep(ident, mtx, priority, wmesg, timo)
127 int catch, rval, flags;
128 WITNESS_SAVE_DECL(mtx);
133 if (KTRPOINT(td, KTR_CSW))
136 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, mtx == NULL ? NULL :
137 &mtx->mtx_object, "Sleeping on \"%s\"", wmesg);
138 KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
139 ("sleeping without a mutex"));
140 KASSERT(p != NULL, ("msleep1"));
141 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
145 * During autoconfiguration, just return;
146 * don't run any other threads or panic below,
147 * in case this is the idle thread and already asleep.
148 * XXX: this used to do "s = splhigh(); splx(safepri);
149 * splx(s);" to give interrupts a chance, but there is
150 * no way to give interrupts a chance now.
152 if (mtx != NULL && priority & PDROP)
156 catch = priority & PCATCH;
160 * If we are already on a sleep queue, then remove us from that
161 * sleep queue first. We have to do this to handle recursive
164 if (TD_ON_SLEEPQ(td))
165 sleepq_remove(td, td->td_wchan);
167 flags = SLEEPQ_MSLEEP;
169 flags |= SLEEPQ_INTERRUPTIBLE;
172 CTR5(KTR_PROC, "msleep: thread %p (pid %ld, %s) on %s (%p)",
173 (void *)td, (long)p->p_pid, p->p_comm, wmesg, ident);
177 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
178 WITNESS_SAVE(&mtx->mtx_object, mtx);
183 * We put ourselves on the sleep queue and start our timeout
184 * before calling thread_suspend_check, as we could stop there,
185 * and a wakeup or a SIGCONT (or both) could occur while we were
186 * stopped without resuming us. Thus, we must be ready for sleep
187 * when cursig() is called. If the wakeup happens while we're
188 * stopped, then td will no longer be on a sleep queue upon
189 * return from cursig().
191 sleepq_add(ident, mtx, wmesg, flags);
193 sleepq_set_timeout(ident, timo);
196 * Adjust this thread's priority.
198 if ((priority & PRIMASK) != 0) {
199 mtx_lock_spin(&sched_lock);
200 sched_prio(td, priority & PRIMASK);
201 mtx_unlock_spin(&sched_lock);
205 rval = sleepq_timedwait_sig(ident);
207 rval = sleepq_timedwait(ident);
209 rval = sleepq_wait_sig(ident);
215 if (KTRPOINT(td, KTR_CSW))
219 if (mtx != NULL && !(priority & PDROP)) {
221 WITNESS_RESTORE(&mtx->mtx_object, mtx);
227 msleep_spin(ident, mtx, wmesg, timo)
236 WITNESS_SAVE_DECL(mtx);
240 KASSERT(mtx != NULL, ("sleeping without a mutex"));
241 KASSERT(p != NULL, ("msleep1"));
242 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
246 * During autoconfiguration, just return;
247 * don't run any other threads or panic below,
248 * in case this is the idle thread and already asleep.
249 * XXX: this used to do "s = splhigh(); splx(safepri);
250 * splx(s);" to give interrupts a chance, but there is
251 * no way to give interrupts a chance now.
257 CTR5(KTR_PROC, "msleep_spin: thread %p (pid %ld, %s) on %s (%p)",
258 (void *)td, (long)p->p_pid, p->p_comm, wmesg, ident);
261 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
262 WITNESS_SAVE(&mtx->mtx_object, mtx);
263 mtx_unlock_spin(mtx);
266 * We put ourselves on the sleep queue and start our timeout.
268 sleepq_add(ident, mtx, wmesg, SLEEPQ_MSLEEP);
270 sleepq_set_timeout(ident, timo);
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);
299 if (KTRPOINT(td, KTR_CSW))
304 WITNESS_RESTORE(&mtx->mtx_object, mtx);
309 * Make all threads sleeping on the specified identifier runnable.
313 register void *ident;
317 sleepq_broadcast(ident, SLEEPQ_MSLEEP, -1);
321 * Make a thread sleeping on the specified identifier runnable.
322 * May wake more than one thread if a target thread is currently
327 register void *ident;
331 sleepq_signal(ident, SLEEPQ_MSLEEP, -1);
335 * The machine independent parts of context switching.
338 mi_switch(int flags, struct thread *newtd)
340 uint64_t new_switchtime;
344 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
345 td = curthread; /* XXX */
346 p = td->td_proc; /* XXX */
347 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
349 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
350 mtx_assert(&Giant, MA_NOTOWNED);
352 KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 &&
353 (td->td_owepreempt) && (flags & SW_INVOL) != 0 &&
354 newtd == NULL) || panicstr,
355 ("mi_switch: switch in a critical section"));
356 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
357 ("mi_switch: switch must be voluntary or involuntary"));
358 KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
361 * Don't perform context switches from the debugger.
364 mtx_unlock_spin(&sched_lock);
367 panic("%s: did not reenter debugger", __func__);
371 p->p_stats->p_ru.ru_nvcsw++;
373 p->p_stats->p_ru.ru_nivcsw++;
376 * Compute the amount of time during which the current
377 * process was running, and add that to its total so far.
379 new_switchtime = cpu_ticks();
380 p->p_rux.rux_runtime += (new_switchtime - PCPU_GET(switchtime));
381 p->p_rux.rux_uticks += td->td_uticks;
383 p->p_rux.rux_iticks += td->td_iticks;
385 p->p_rux.rux_sticks += td->td_sticks;
388 td->td_generation++; /* bump preempt-detect counter */
391 * Check if the process exceeds its cpu resource allocation. If
392 * it reaches the max, arrange to kill the process in ast().
394 if (p->p_cpulimit != RLIM_INFINITY &&
395 p->p_rux.rux_runtime >= p->p_cpulimit * cpu_tickrate()) {
396 p->p_sflag |= PS_XCPU;
397 td->td_flags |= TDF_ASTPENDING;
401 * Finish up stats for outgoing thread.
404 PCPU_SET(switchtime, new_switchtime);
405 PCPU_SET(switchticks, ticks);
406 CTR4(KTR_PROC, "mi_switch: old thread %p (kse %p, pid %ld, %s)",
407 (void *)td, td->td_sched, (long)p->p_pid, p->p_comm);
408 if ((flags & SW_VOL) && (td->td_proc->p_flag & P_SA))
409 newtd = thread_switchout(td, flags, newtd);
410 #if (KTR_COMPILE & KTR_SCHED) != 0
411 if (td == PCPU_GET(idlethread))
412 CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle",
413 td, td->td_proc->p_comm, td->td_priority);
414 else if (newtd != NULL)
416 "mi_switch: %p(%s) prio %d preempted by %p(%s)",
417 td, td->td_proc->p_comm, td->td_priority, newtd,
418 newtd->td_proc->p_comm);
421 "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s",
422 td, td->td_proc->p_comm, td->td_priority,
423 td->td_inhibitors, td->td_wmesg, td->td_lockname);
425 sched_switch(td, newtd, flags);
426 CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d",
427 td, td->td_proc->p_comm, td->td_priority);
429 CTR4(KTR_PROC, "mi_switch: new thread %p (kse %p, pid %ld, %s)",
430 (void *)td, td->td_sched, (long)p->p_pid, p->p_comm);
433 * If the last thread was exiting, finish cleaning it up.
435 if ((td = PCPU_GET(deadthread))) {
436 PCPU_SET(deadthread, NULL);
442 * Change process state to be runnable,
443 * placing it on the run queue if it is in memory,
444 * and awakening the swapper if it isn't in memory.
447 setrunnable(struct thread *td)
452 mtx_assert(&sched_lock, MA_OWNED);
453 switch (p->p_state) {
455 panic("setrunnable(1)");
459 switch (td->td_state) {
465 * If we are only inhibited because we are swapped out
466 * then arange to swap in this process. Otherwise just return.
468 if (td->td_inhibitors != TDI_SWAPPED)
470 /* XXX: intentional fall-through ? */
474 printf("state is 0x%x", td->td_state);
475 panic("setrunnable(2)");
477 if ((p->p_sflag & PS_INMEM) == 0) {
478 if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
479 p->p_sflag |= PS_SWAPINREQ;
481 * due to a LOR between sched_lock and
482 * the sleepqueue chain locks, use
483 * lower level scheduling functions.
492 * Compute a tenex style load average of a quantity on
493 * 1, 5 and 15 minute intervals.
494 * XXXKSE Needs complete rewrite when correct info is available.
495 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
506 for (i = 0; i < 3; i++)
507 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
508 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
511 * Schedule the next update to occur after 5 seconds, but add a
512 * random variation to avoid synchronisation with processes that
513 * run at regular intervals.
515 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
523 callout_reset(&lbolt_callout, hz, lboltcb, NULL);
531 callout_init(&loadav_callout, CALLOUT_MPSAFE);
532 callout_init(&lbolt_callout, CALLOUT_MPSAFE);
534 /* Kick off timeout driven events by calling first time. */
540 * General purpose yield system call
543 yield(struct thread *td, struct yield_args *uap)
545 mtx_assert(&Giant, MA_NOTOWNED);
547 sched_relinquish(td);