kern_synch.c revision 177253
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 177253 2008-03-16 10:58:09Z rwatson $"); 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, 69 NULL); 70 71int hogticks; 72int lbolt; 73static int pause_wchan; 74 75static struct callout loadav_callout; 76static struct callout lbolt_callout; 77 78struct loadavg averunnable = 79 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 80/* 81 * Constants for averages over 1, 5, and 15 minutes 82 * when sampling at 5 second intervals. 83 */ 84static fixpt_t cexp[3] = { 85 0.9200444146293232 * FSCALE, /* exp(-1/12) */ 86 0.9834714538216174 * FSCALE, /* exp(-1/60) */ 87 0.9944598480048967 * FSCALE, /* exp(-1/180) */ 88}; 89 90/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */ 91static int fscale __unused = FSCALE; 92SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, ""); 93 94static void loadav(void *arg); 95static void lboltcb(void *arg); 96 97void 98sleepinit(void) 99{ 100 101 hogticks = (hz / 10) * 2; /* Default only. */ 102 init_sleepqueues(); 103} 104 105/* 106 * General sleep call. Suspends the current thread until a wakeup is 107 * performed on the specified identifier. The thread will then be made 108 * runnable with the specified priority. Sleeps at most timo/hz seconds 109 * (0 means no timeout). If pri includes PCATCH flag, signals are checked 110 * before and after sleeping, else signals are not checked. Returns 0 if 111 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 112 * signal needs to be delivered, ERESTART is returned if the current system 113 * call should be restarted if possible, and EINTR is returned if the system 114 * call should be interrupted by the signal (return EINTR). 115 * 116 * The lock argument is unlocked before the caller is suspended, and 117 * re-locked before _sleep() returns. If priority includes the PDROP 118 * flag the lock is not re-locked before returning. 119 */ 120int 121_sleep(ident, lock, priority, wmesg, timo) 122 void *ident; 123 struct lock_object *lock; 124 int priority, timo; 125 const char *wmesg; 126{ 127 struct thread *td; 128 struct proc *p; 129 struct lock_class *class; 130 int catch, flags, lock_state, pri, rval; 131 WITNESS_SAVE_DECL(lock_witness); 132 133 td = curthread; 134 p = td->td_proc; 135#ifdef KTRACE 136 if (KTRPOINT(td, KTR_CSW)) 137 ktrcsw(1, 0); 138#endif 139 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock, 140 "Sleeping on \"%s\"", wmesg); 141 KASSERT(timo != 0 || mtx_owned(&Giant) || lock != NULL || 142 ident == &lbolt, ("sleeping without a lock")); 143 KASSERT(p != NULL, ("msleep1")); 144 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 145 if (lock != NULL) 146 class = LOCK_CLASS(lock); 147 else 148 class = NULL; 149 150 if (cold) { 151 /* 152 * During autoconfiguration, just return; 153 * don't run any other threads or panic below, 154 * in case this is the idle thread and already asleep. 155 * XXX: this used to do "s = splhigh(); splx(safepri); 156 * splx(s);" to give interrupts a chance, but there is 157 * no way to give interrupts a chance now. 158 */ 159 if (lock != NULL && priority & PDROP) 160 class->lc_unlock(lock); 161 return (0); 162 } 163 catch = priority & PCATCH; 164 pri = priority & PRIMASK; 165 rval = 0; 166 167 /* 168 * If we are already on a sleep queue, then remove us from that 169 * sleep queue first. We have to do this to handle recursive 170 * sleeps. 171 */ 172 if (TD_ON_SLEEPQ(td)) 173 sleepq_remove(td, td->td_wchan); 174 175 if (ident == &pause_wchan) 176 flags = SLEEPQ_PAUSE; 177 else 178 flags = SLEEPQ_SLEEP; 179 if (catch) 180 flags |= SLEEPQ_INTERRUPTIBLE; 181 182 sleepq_lock(ident); 183 CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)", 184 td->td_tid, p->p_pid, td->td_name, wmesg, ident); 185 186 DROP_GIANT(); 187 if (lock != NULL && !(class->lc_flags & LC_SLEEPABLE)) { 188 WITNESS_SAVE(lock, lock_witness); 189 lock_state = class->lc_unlock(lock); 190 } else 191 /* GCC needs to follow the Yellow Brick Road */ 192 lock_state = -1; 193 194 /* 195 * We put ourselves on the sleep queue and start our timeout 196 * before calling thread_suspend_check, as we could stop there, 197 * and a wakeup or a SIGCONT (or both) could occur while we were 198 * stopped without resuming us. Thus, we must be ready for sleep 199 * when cursig() is called. If the wakeup happens while we're 200 * stopped, then td will no longer be on a sleep queue upon 201 * return from cursig(). 202 */ 203 sleepq_add(ident, ident == &lbolt ? NULL : lock, wmesg, flags, 0); 204 if (timo) 205 sleepq_set_timeout(ident, timo); 206 if (lock != NULL && class->lc_flags & LC_SLEEPABLE) { 207 sleepq_release(ident); 208 WITNESS_SAVE(lock, lock_witness); 209 lock_state = class->lc_unlock(lock); 210 sleepq_lock(ident); 211 } 212 if (timo && catch) 213 rval = sleepq_timedwait_sig(ident, pri); 214 else if (timo) 215 rval = sleepq_timedwait(ident, pri); 216 else if (catch) 217 rval = sleepq_wait_sig(ident, pri); 218 else { 219 sleepq_wait(ident, pri); 220 rval = 0; 221 } 222#ifdef KTRACE 223 if (KTRPOINT(td, KTR_CSW)) 224 ktrcsw(0, 0); 225#endif 226 PICKUP_GIANT(); 227 if (lock != NULL && !(priority & PDROP)) { 228 class->lc_lock(lock, lock_state); 229 WITNESS_RESTORE(lock, lock_witness); 230 } 231 return (rval); 232} 233 234int 235msleep_spin(ident, mtx, wmesg, timo) 236 void *ident; 237 struct mtx *mtx; 238 const char *wmesg; 239 int timo; 240{ 241 struct thread *td; 242 struct proc *p; 243 int rval; 244 WITNESS_SAVE_DECL(mtx); 245 246 td = curthread; 247 p = td->td_proc; 248 KASSERT(mtx != NULL, ("sleeping without a mutex")); 249 KASSERT(p != NULL, ("msleep1")); 250 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 251 252 if (cold) { 253 /* 254 * During autoconfiguration, just return; 255 * don't run any other threads or panic below, 256 * in case this is the idle thread and already asleep. 257 * XXX: this used to do "s = splhigh(); splx(safepri); 258 * splx(s);" to give interrupts a chance, but there is 259 * no way to give interrupts a chance now. 260 */ 261 return (0); 262 } 263 264 sleepq_lock(ident); 265 CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)", 266 td->td_tid, p->p_pid, td->td_name, wmesg, ident); 267 268 DROP_GIANT(); 269 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 270 WITNESS_SAVE(&mtx->lock_object, mtx); 271 mtx_unlock_spin(mtx); 272 273 /* 274 * We put ourselves on the sleep queue and start our timeout. 275 */ 276 sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0); 277 if (timo) 278 sleepq_set_timeout(ident, timo); 279 280 /* 281 * Can't call ktrace with any spin locks held so it can lock the 282 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold 283 * any spin lock. Thus, we have to drop the sleepq spin lock while 284 * we handle those requests. This is safe since we have placed our 285 * thread on the sleep queue already. 286 */ 287#ifdef KTRACE 288 if (KTRPOINT(td, KTR_CSW)) { 289 sleepq_release(ident); 290 ktrcsw(1, 0); 291 sleepq_lock(ident); 292 } 293#endif 294#ifdef WITNESS 295 sleepq_release(ident); 296 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"", 297 wmesg); 298 sleepq_lock(ident); 299#endif 300 if (timo) 301 rval = sleepq_timedwait(ident, 0); 302 else { 303 sleepq_wait(ident, 0); 304 rval = 0; 305 } 306#ifdef KTRACE 307 if (KTRPOINT(td, KTR_CSW)) 308 ktrcsw(0, 0); 309#endif 310 PICKUP_GIANT(); 311 mtx_lock_spin(mtx); 312 WITNESS_RESTORE(&mtx->lock_object, mtx); 313 return (rval); 314} 315 316/* 317 * pause() is like tsleep() except that the intention is to not be 318 * explicitly woken up by another thread. Instead, the current thread 319 * simply wishes to sleep until the timeout expires. It is 320 * implemented using a dummy wait channel. 321 */ 322int 323pause(wmesg, timo) 324 const char *wmesg; 325 int timo; 326{ 327 328 KASSERT(timo != 0, ("pause: timeout required")); 329 return (tsleep(&pause_wchan, 0, wmesg, timo)); 330} 331 332/* 333 * Make all threads sleeping on the specified identifier runnable. 334 */ 335void 336wakeup(ident) 337 register void *ident; 338{ 339 340 sleepq_lock(ident); 341 sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0); 342 sleepq_release(ident); 343} 344 345/* 346 * Make a thread sleeping on the specified identifier runnable. 347 * May wake more than one thread if a target thread is currently 348 * swapped out. 349 */ 350void 351wakeup_one(ident) 352 register void *ident; 353{ 354 355 sleepq_lock(ident); 356 sleepq_signal(ident, SLEEPQ_SLEEP, 0, 0); 357 sleepq_release(ident); 358} 359 360static void 361kdb_switch(void) 362{ 363 thread_unlock(curthread); 364 kdb_backtrace(); 365 kdb_reenter(); 366 panic("%s: did not reenter debugger", __func__); 367} 368 369/* 370 * The machine independent parts of context switching. 371 */ 372void 373mi_switch(int flags, struct thread *newtd) 374{ 375 uint64_t runtime, new_switchtime; 376 struct thread *td; 377 struct proc *p; 378 379 td = curthread; /* XXX */ 380 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED); 381 p = td->td_proc; /* XXX */ 382 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 383#ifdef INVARIANTS 384 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 385 mtx_assert(&Giant, MA_NOTOWNED); 386#endif 387 KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 && 388 (td->td_owepreempt) && (flags & SW_INVOL) != 0 && 389 newtd == NULL) || panicstr, 390 ("mi_switch: switch in a critical section")); 391 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 392 ("mi_switch: switch must be voluntary or involuntary")); 393 KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself")); 394 395 /* 396 * Don't perform context switches from the debugger. 397 */ 398 if (kdb_active) 399 kdb_switch(); 400 if (flags & SW_VOL) 401 td->td_ru.ru_nvcsw++; 402 else 403 td->td_ru.ru_nivcsw++; 404 /* 405 * Compute the amount of time during which the current 406 * thread was running, and add that to its total so far. 407 */ 408 new_switchtime = cpu_ticks(); 409 runtime = new_switchtime - PCPU_GET(switchtime); 410 td->td_runtime += runtime; 411 td->td_incruntime += runtime; 412 PCPU_SET(switchtime, new_switchtime); 413 td->td_generation++; /* bump preempt-detect counter */ 414 PCPU_INC(cnt.v_swtch); 415 PCPU_SET(switchticks, ticks); 416 CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)", 417 td->td_tid, td->td_sched, p->p_pid, td->td_name); 418#if (KTR_COMPILE & KTR_SCHED) != 0 419 if (TD_IS_IDLETHREAD(td)) 420 CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle", 421 td, td->td_name, td->td_priority); 422 else if (newtd != NULL) 423 CTR5(KTR_SCHED, 424 "mi_switch: %p(%s) prio %d preempted by %p(%s)", 425 td, td->td_name, td->td_priority, newtd, 426 newtd->td_name); 427 else 428 CTR6(KTR_SCHED, 429 "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s", 430 td, td->td_name, td->td_priority, 431 td->td_inhibitors, td->td_wmesg, td->td_lockname); 432#endif 433 sched_switch(td, newtd, flags); 434 CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d", 435 td, td->td_name, td->td_priority); 436 437 CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)", 438 td->td_tid, td->td_sched, p->p_pid, td->td_name); 439 440 /* 441 * If the last thread was exiting, finish cleaning it up. 442 */ 443 if ((td = PCPU_GET(deadthread))) { 444 PCPU_SET(deadthread, NULL); 445 thread_stash(td); 446 } 447} 448 449/* 450 * Change process state to be runnable, 451 * placing it on the run queue if it is in memory, 452 * and awakening the swapper if it isn't in memory. 453 */ 454void 455setrunnable(struct thread *td) 456{ 457 458 THREAD_LOCK_ASSERT(td, MA_OWNED); 459 KASSERT(td->td_proc->p_state != PRS_ZOMBIE, 460 ("setrunnable: pid %d is a zombie", td->td_proc->p_pid)); 461 switch (td->td_state) { 462 case TDS_RUNNING: 463 case TDS_RUNQ: 464 return; 465 case TDS_INHIBITED: 466 /* 467 * If we are only inhibited because we are swapped out 468 * then arange to swap in this process. Otherwise just return. 469 */ 470 if (td->td_inhibitors != TDI_SWAPPED) 471 return; 472 /* XXX: intentional fall-through ? */ 473 case TDS_CAN_RUN: 474 break; 475 default: 476 printf("state is 0x%x", td->td_state); 477 panic("setrunnable(2)"); 478 } 479 if ((td->td_flags & TDF_INMEM) == 0) { 480 if ((td->td_flags & TDF_SWAPINREQ) == 0) { 481 td->td_flags |= TDF_SWAPINREQ; 482 /* 483 * due to a LOR between the thread lock and 484 * the sleepqueue chain locks, use 485 * lower level scheduling functions. 486 */ 487 kick_proc0(); 488 } 489 } else 490 sched_wakeup(td); 491} 492 493/* 494 * Compute a tenex style load average of a quantity on 495 * 1, 5 and 15 minute intervals. 496 */ 497static void 498loadav(void *arg) 499{ 500 int i, nrun; 501 struct loadavg *avg; 502 503 nrun = sched_load(); 504 avg = &averunnable; 505 506 for (i = 0; i < 3; i++) 507 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 508 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 509 510 /* 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. 514 */ 515 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 516 loadav, NULL); 517} 518 519static void 520lboltcb(void *arg) 521{ 522 wakeup(&lbolt); 523 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 524} 525 526/* ARGSUSED */ 527static void 528synch_setup(dummy) 529 void *dummy; 530{ 531 callout_init(&loadav_callout, CALLOUT_MPSAFE); 532 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 533 534 /* Kick off timeout driven events by calling first time. */ 535 loadav(NULL); 536 lboltcb(NULL); 537} 538 539/* 540 * General purpose yield system call. 541 */ 542int 543yield(struct thread *td, struct yield_args *uap) 544{ 545 546 thread_lock(td); 547 sched_prio(td, PRI_MAX_TIMESHARE); 548 mi_switch(SW_VOL, NULL); 549 thread_unlock(td); 550 td->td_retval[0] = 0; 551 return (0); 552} 553