kern_synch.c revision 139315
1/*- 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. 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 * 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. 21 * 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 32 * SUCH DAMAGE. 33 * 34 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95 35 */ 36 37#include <sys/cdefs.h> 38__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 139315 2004-12-26 00:14:21Z jeff $"); 39 40#include "opt_ktrace.h" 41 42#include <sys/param.h> 43#include <sys/systm.h> 44#include <sys/condvar.h> 45#include <sys/kdb.h> 46#include <sys/kernel.h> 47#include <sys/ktr.h> 48#include <sys/lock.h> 49#include <sys/mutex.h> 50#include <sys/proc.h> 51#include <sys/resourcevar.h> 52#include <sys/sched.h> 53#include <sys/signalvar.h> 54#include <sys/sleepqueue.h> 55#include <sys/smp.h> 56#include <sys/sx.h> 57#include <sys/sysctl.h> 58#include <sys/sysproto.h> 59#include <sys/vmmeter.h> 60#ifdef KTRACE 61#include <sys/uio.h> 62#include <sys/ktrace.h> 63#endif 64 65#include <machine/cpu.h> 66 67static void synch_setup(void *dummy); 68SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL) 69 70int hogticks; 71int lbolt; 72 73static struct callout loadav_callout; 74static struct callout lbolt_callout; 75 76struct loadavg averunnable = 77 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 78/* 79 * Constants for averages over 1, 5, and 15 minutes 80 * when sampling at 5 second intervals. 81 */ 82static 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) */ 86}; 87 88/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */ 89static int fscale __unused = FSCALE; 90SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, ""); 91 92static void loadav(void *arg); 93static void lboltcb(void *arg); 94 95void 96sleepinit(void) 97{ 98 99 hogticks = (hz / 10) * 2; /* Default only. */ 100 init_sleepqueues(); 101} 102 103/* 104 * General sleep call. Suspends the current process until a wakeup is 105 * performed on the specified identifier. The process 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). 113 * 114 * The mutex argument is exited before the caller is suspended, and 115 * entered before msleep returns. If priority includes the PDROP 116 * flag the mutex is not entered before returning. 117 */ 118int 119msleep(ident, mtx, priority, wmesg, timo) 120 void *ident; 121 struct mtx *mtx; 122 int priority, timo; 123 const char *wmesg; 124{ 125 struct thread *td; 126 struct proc *p; 127 int catch, rval, sig, flags; 128 WITNESS_SAVE_DECL(mtx); 129 130 td = curthread; 131 p = td->td_proc; 132#ifdef KTRACE 133 if (KTRPOINT(td, KTR_CSW)) 134 ktrcsw(1, 0); 135#endif 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")); 142 143 if (cold) { 144 /* 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. 151 */ 152 if (mtx != NULL && priority & PDROP) 153 mtx_unlock(mtx); 154 return (0); 155 } 156 catch = priority & PCATCH; 157 rval = 0; 158 159 /* 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 162 * sleeps. 163 */ 164 if (TD_ON_SLEEPQ(td)) 165 sleepq_remove(td, td->td_wchan); 166 167 sleepq_lock(ident); 168 if (catch) { 169 /* 170 * Don't bother sleeping if we are exiting and not the exiting 171 * thread or if our thread is marked as interrupted. 172 */ 173 mtx_lock_spin(&sched_lock); 174 rval = thread_sleep_check(td); 175 mtx_unlock_spin(&sched_lock); 176 if (rval != 0) { 177 sleepq_release(ident); 178 if (mtx != NULL && priority & PDROP) 179 mtx_unlock(mtx); 180 return (rval); 181 } 182 } 183 CTR5(KTR_PROC, "msleep: thread %p (pid %ld, %s) on %s (%p)", 184 (void *)td, (long)p->p_pid, p->p_comm, wmesg, ident); 185 186 DROP_GIANT(); 187 if (mtx != NULL) { 188 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 189 WITNESS_SAVE(&mtx->mtx_object, mtx); 190 mtx_unlock(mtx); 191 } 192 193 /* 194 * We put ourselves on the sleep queue and start our timeout 195 * before calling thread_suspend_check, as we could stop there, 196 * and a wakeup or a SIGCONT (or both) could occur while we were 197 * stopped without resuming us. Thus, we must be ready for sleep 198 * when cursig() is called. If the wakeup happens while we're 199 * stopped, then td will no longer be on a sleep queue upon 200 * return from cursig(). 201 */ 202 flags = SLEEPQ_MSLEEP; 203 if (catch) 204 flags |= SLEEPQ_INTERRUPTIBLE; 205 sleepq_add(ident, mtx, wmesg, flags); 206 if (timo) 207 sleepq_set_timeout(ident, timo); 208 if (catch) { 209 sig = sleepq_catch_signals(ident); 210 } else 211 sig = 0; 212 213 /* 214 * Adjust this thread's priority. 215 * 216 * XXX: do we need to save priority in td_base_pri? 217 */ 218 mtx_lock_spin(&sched_lock); 219 sched_prio(td, priority & PRIMASK); 220 mtx_unlock_spin(&sched_lock); 221 222 if (timo && catch) 223 rval = sleepq_timedwait_sig(ident, sig != 0); 224 else if (timo) 225 rval = sleepq_timedwait(ident); 226 else if (catch) 227 rval = sleepq_wait_sig(ident); 228 else { 229 sleepq_wait(ident); 230 rval = 0; 231 } 232 if (rval == 0 && catch) 233 rval = sleepq_calc_signal_retval(sig); 234#ifdef KTRACE 235 if (KTRPOINT(td, KTR_CSW)) 236 ktrcsw(0, 0); 237#endif 238 PICKUP_GIANT(); 239 if (mtx != NULL && !(priority & PDROP)) { 240 mtx_lock(mtx); 241 WITNESS_RESTORE(&mtx->mtx_object, mtx); 242 } 243 return (rval); 244} 245 246/* 247 * Make all threads sleeping on the specified identifier runnable. 248 */ 249void 250wakeup(ident) 251 register void *ident; 252{ 253 254 sleepq_lock(ident); 255 sleepq_broadcast(ident, SLEEPQ_MSLEEP, -1); 256} 257 258/* 259 * Make a thread sleeping on the specified identifier runnable. 260 * May wake more than one thread if a target thread is currently 261 * swapped out. 262 */ 263void 264wakeup_one(ident) 265 register void *ident; 266{ 267 268 sleepq_lock(ident); 269 sleepq_signal(ident, SLEEPQ_MSLEEP, -1); 270} 271 272/* 273 * The machine independent parts of context switching. 274 */ 275void 276mi_switch(int flags, struct thread *newtd) 277{ 278 struct bintime new_switchtime; 279 struct thread *td; 280 struct proc *p; 281 282 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED); 283 td = curthread; /* XXX */ 284 p = td->td_proc; /* XXX */ 285 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 286#ifdef INVARIANTS 287 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 288 mtx_assert(&Giant, MA_NOTOWNED); 289#endif 290 KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 && 291 (td->td_pflags & TDP_OWEPREEMPT) != 0 && (flags & SW_INVOL) != 0 && 292 newtd == NULL), 293 ("mi_switch: switch in a critical section")); 294 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 295 ("mi_switch: switch must be voluntary or involuntary")); 296 KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself")); 297 298 if (flags & SW_VOL) 299 p->p_stats->p_ru.ru_nvcsw++; 300 else 301 p->p_stats->p_ru.ru_nivcsw++; 302 303 /* 304 * Compute the amount of time during which the current 305 * process was running, and add that to its total so far. 306 */ 307 binuptime(&new_switchtime); 308 bintime_add(&p->p_rux.rux_runtime, &new_switchtime); 309 bintime_sub(&p->p_rux.rux_runtime, PCPU_PTR(switchtime)); 310 311 td->td_generation++; /* bump preempt-detect counter */ 312 313 /* 314 * Don't perform context switches from the debugger. 315 */ 316 if (kdb_active) { 317 mtx_unlock_spin(&sched_lock); 318 kdb_backtrace(); 319 kdb_reenter(); 320 panic("%s: did not reenter debugger", __func__); 321 } 322 323 /* 324 * Check if the process exceeds its cpu resource allocation. If 325 * over max, arrange to kill the process in ast(). 326 */ 327 if (p->p_cpulimit != RLIM_INFINITY && 328 p->p_rux.rux_runtime.sec > p->p_cpulimit) { 329 p->p_sflag |= PS_XCPU; 330 td->td_flags |= TDF_ASTPENDING; 331 } 332 333 /* 334 * Finish up stats for outgoing thread. 335 */ 336 cnt.v_swtch++; 337 PCPU_SET(switchtime, new_switchtime); 338 PCPU_SET(switchticks, ticks); 339 CTR4(KTR_PROC, "mi_switch: old thread %p (kse %p, pid %ld, %s)", 340 (void *)td, td->td_sched, (long)p->p_pid, p->p_comm); 341 if ((flags & SW_VOL) && (td->td_proc->p_flag & P_SA)) 342 newtd = thread_switchout(td, flags, newtd); 343#if (KTR_COMPILE & KTR_SCHED) != 0 344 if (td == PCPU_GET(idlethread)) 345 CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle", 346 td, td->td_proc->p_comm, td->td_priority); 347 else if (newtd != NULL) 348 CTR5(KTR_SCHED, 349 "mi_switch: %p(%s) prio %d preempted by %p(%s)", 350 td, td->td_proc->p_comm, td->td_priority, newtd, 351 newtd->td_proc->p_comm); 352 else 353 CTR6(KTR_SCHED, 354 "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s", 355 td, td->td_proc->p_comm, td->td_priority, 356 td->td_inhibitors, td->td_wmesg, td->td_lockname); 357#endif 358 sched_switch(td, newtd, flags); 359 CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d", 360 td, td->td_proc->p_comm, td->td_priority); 361 362 CTR4(KTR_PROC, "mi_switch: new thread %p (kse %p, pid %ld, %s)", 363 (void *)td, td->td_sched, (long)p->p_pid, p->p_comm); 364 365 /* 366 * If the last thread was exiting, finish cleaning it up. 367 */ 368 if ((td = PCPU_GET(deadthread))) { 369 PCPU_SET(deadthread, NULL); 370 thread_stash(td); 371 } 372} 373 374/* 375 * Change process state to be runnable, 376 * placing it on the run queue if it is in memory, 377 * and awakening the swapper if it isn't in memory. 378 */ 379void 380setrunnable(struct thread *td) 381{ 382 struct proc *p; 383 384 p = td->td_proc; 385 mtx_assert(&sched_lock, MA_OWNED); 386 switch (p->p_state) { 387 case PRS_ZOMBIE: 388 panic("setrunnable(1)"); 389 default: 390 break; 391 } 392 switch (td->td_state) { 393 case TDS_RUNNING: 394 case TDS_RUNQ: 395 return; 396 case TDS_INHIBITED: 397 /* 398 * If we are only inhibited because we are swapped out 399 * then arange to swap in this process. Otherwise just return. 400 */ 401 if (td->td_inhibitors != TDI_SWAPPED) 402 return; 403 /* XXX: intentional fall-through ? */ 404 case TDS_CAN_RUN: 405 break; 406 default: 407 printf("state is 0x%x", td->td_state); 408 panic("setrunnable(2)"); 409 } 410 if ((p->p_sflag & PS_INMEM) == 0) { 411 if ((p->p_sflag & PS_SWAPPINGIN) == 0) { 412 p->p_sflag |= PS_SWAPINREQ; 413 /* 414 * due to a LOR between sched_lock and 415 * the sleepqueue chain locks, delay 416 * wakeup proc0 until thread leaves 417 * critical region. 418 */ 419 curthread->td_pflags |= TDP_WAKEPROC0; 420 } 421 } else 422 sched_wakeup(td); 423} 424 425/* 426 * Compute a tenex style load average of a quantity on 427 * 1, 5 and 15 minute intervals. 428 * XXXKSE Needs complete rewrite when correct info is available. 429 * Completely Bogus.. only works with 1:1 (but compiles ok now :-) 430 */ 431static void 432loadav(void *arg) 433{ 434 int i, nrun; 435 struct loadavg *avg; 436 437 nrun = sched_load(); 438 avg = &averunnable; 439 440 for (i = 0; i < 3; i++) 441 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 442 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 443 444 /* 445 * Schedule the next update to occur after 5 seconds, but add a 446 * random variation to avoid synchronisation with processes that 447 * run at regular intervals. 448 */ 449 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 450 loadav, NULL); 451} 452 453static void 454lboltcb(void *arg) 455{ 456 wakeup(&lbolt); 457 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 458} 459 460/* ARGSUSED */ 461static void 462synch_setup(dummy) 463 void *dummy; 464{ 465 callout_init(&loadav_callout, CALLOUT_MPSAFE); 466 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 467 468 /* Kick off timeout driven events by calling first time. */ 469 loadav(NULL); 470 lboltcb(NULL); 471} 472 473/* 474 * General purpose yield system call 475 */ 476int 477yield(struct thread *td, struct yield_args *uap) 478{ 479 struct ksegrp *kg; 480 481 kg = td->td_ksegrp; 482 mtx_assert(&Giant, MA_NOTOWNED); 483 mtx_lock_spin(&sched_lock); 484 sched_prio(td, PRI_MAX_TIMESHARE); 485 mi_switch(SW_VOL, NULL); 486 mtx_unlock_spin(&sched_lock); 487 td->td_retval[0] = 0; 488 return (0); 489} 490