kern_synch.c revision 163709
1325618Ssbruno/*- 2325618Ssbruno * Copyright (c) 1982, 1986, 1990, 1991, 1993 3325618Ssbruno * The Regents of the University of California. All rights reserved. 4325618Ssbruno * (c) UNIX System Laboratories, Inc. 5325618Ssbruno * All or some portions of this file are derived from material licensed 6325618Ssbruno * to the University of California by American Telephone and Telegraph 7325618Ssbruno * Co. or Unix System Laboratories, Inc. and are reproduced herein with 8325618Ssbruno * the permission of UNIX System Laboratories, Inc. 9325618Ssbruno * 10325618Ssbruno * Redistribution and use in source and binary forms, with or without 11325618Ssbruno * modification, are permitted provided that the following conditions 12325618Ssbruno * are met: 13325618Ssbruno * 1. Redistributions of source code must retain the above copyright 14325618Ssbruno * notice, this list of conditions and the following disclaimer. 15325618Ssbruno * 2. Redistributions in binary form must reproduce the above copyright 16325618Ssbruno * notice, this list of conditions and the following disclaimer in the 17325618Ssbruno * documentation and/or other materials provided with the distribution. 18325618Ssbruno * 4. Neither the name of the University nor the names of its contributors 19325618Ssbruno * may be used to endorse or promote products derived from this software 20325618Ssbruno * without specific prior written permission. 21325618Ssbruno * 22325618Ssbruno * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23325618Ssbruno * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24325618Ssbruno * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25325618Ssbruno * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26325618Ssbruno * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27325618Ssbruno * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28325618Ssbruno * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29325618Ssbruno * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30325618Ssbruno * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31325618Ssbruno * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32325618Ssbruno * SUCH DAMAGE. 33325618Ssbruno * 34325618Ssbruno * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95 35325618Ssbruno */ 36325618Ssbruno 37325618Ssbruno#include <sys/cdefs.h> 38325618Ssbruno__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 163709 2006-10-26 21:42:22Z jb $"); 39325618Ssbruno 40325618Ssbruno#include "opt_ktrace.h" 41325618Ssbruno 42325618Ssbruno#include <sys/param.h> 43325618Ssbruno#include <sys/systm.h> 44325618Ssbruno#include <sys/condvar.h> 45325618Ssbruno#include <sys/kdb.h> 46325618Ssbruno#include <sys/kernel.h> 47325618Ssbruno#include <sys/ktr.h> 48325618Ssbruno#include <sys/lock.h> 49325618Ssbruno#include <sys/mutex.h> 50325618Ssbruno#include <sys/proc.h> 51325618Ssbruno#include <sys/resourcevar.h> 52325618Ssbruno#include <sys/sched.h> 53325618Ssbruno#include <sys/signalvar.h> 54325618Ssbruno#include <sys/sleepqueue.h> 55325618Ssbruno#include <sys/smp.h> 56325618Ssbruno#include <sys/sx.h> 57325618Ssbruno#include <sys/sysctl.h> 58325618Ssbruno#include <sys/sysproto.h> 59325618Ssbruno#include <sys/vmmeter.h> 60325618Ssbruno#ifdef KTRACE 61325618Ssbruno#include <sys/uio.h> 62325618Ssbruno#include <sys/ktrace.h> 63325618Ssbruno#endif 64325618Ssbruno 65325618Ssbruno#include <machine/cpu.h> 66325618Ssbruno 67325618Ssbrunostatic void synch_setup(void *dummy); 68325618SsbrunoSYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL) 69325618Ssbruno 70325618Ssbrunoint hogticks; 71325618Ssbrunoint lbolt; 72325618Ssbruno 73325618Ssbrunostatic struct callout loadav_callout; 74325618Ssbrunostatic struct callout lbolt_callout; 75325618Ssbruno 76325618Ssbrunostruct loadavg averunnable = 77325618Ssbruno { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 78325618Ssbruno/* 79325618Ssbruno * Constants for averages over 1, 5, and 15 minutes 80325618Ssbruno * when sampling at 5 second intervals. 81325618Ssbruno */ 82325618Ssbrunostatic fixpt_t cexp[3] = { 83325618Ssbruno 0.9200444146293232 * FSCALE, /* exp(-1/12) */ 84325618Ssbruno 0.9834714538216174 * FSCALE, /* exp(-1/60) */ 85325618Ssbruno 0.9944598480048967 * FSCALE, /* exp(-1/180) */ 86325618Ssbruno}; 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 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). 113 * 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. 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, 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 flags = SLEEPQ_MSLEEP; 168 if (catch) 169 flags |= SLEEPQ_INTERRUPTIBLE; 170 171 sleepq_lock(ident); 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); 174 175 DROP_GIANT(); 176 if (mtx != NULL) { 177 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 178 WITNESS_SAVE(&mtx->mtx_object, mtx); 179 mtx_unlock(mtx); 180 } 181 182 /* 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(). 190 */ 191 sleepq_add(ident, mtx, wmesg, flags); 192 if (timo) 193 sleepq_set_timeout(ident, timo); 194 195 /* 196 * Adjust this thread's priority. 197 */ 198 if ((priority & PRIMASK) != 0) { 199 mtx_lock_spin(&sched_lock); 200 sched_prio(td, priority & PRIMASK); 201 mtx_unlock_spin(&sched_lock); 202 } 203 204 if (timo && catch) 205 rval = sleepq_timedwait_sig(ident); 206 else if (timo) 207 rval = sleepq_timedwait(ident); 208 else if (catch) 209 rval = sleepq_wait_sig(ident); 210 else { 211 sleepq_wait(ident); 212 rval = 0; 213 } 214#ifdef KTRACE 215 if (KTRPOINT(td, KTR_CSW)) 216 ktrcsw(0, 0); 217#endif 218 PICKUP_GIANT(); 219 if (mtx != NULL && !(priority & PDROP)) { 220 mtx_lock(mtx); 221 WITNESS_RESTORE(&mtx->mtx_object, mtx); 222 } 223 return (rval); 224} 225 226int 227msleep_spin(ident, mtx, wmesg, timo) 228 void *ident; 229 struct mtx *mtx; 230 const char *wmesg; 231 int timo; 232{ 233 struct thread *td; 234 struct proc *p; 235 int rval; 236 WITNESS_SAVE_DECL(mtx); 237 238 td = curthread; 239 p = td->td_proc; 240 KASSERT(mtx != NULL, ("sleeping without a mutex")); 241 KASSERT(p != NULL, ("msleep1")); 242 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 243 244 if (cold) { 245 /* 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. 252 */ 253 return (0); 254 } 255 256 sleepq_lock(ident); 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); 259 260 DROP_GIANT(); 261 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 262 WITNESS_SAVE(&mtx->mtx_object, mtx); 263 mtx_unlock_spin(mtx); 264 265 /* 266 * We put ourselves on the sleep queue and start our timeout. 267 */ 268 sleepq_add(ident, mtx, wmesg, SLEEPQ_MSLEEP); 269 if (timo) 270 sleepq_set_timeout(ident, timo); 271 272 /* 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. 278 */ 279#ifdef KTRACE 280 if (KTRPOINT(td, KTR_CSW)) { 281 sleepq_release(ident); 282 ktrcsw(1, 0); 283 sleepq_lock(ident); 284 } 285#endif 286#ifdef WITNESS 287 sleepq_release(ident); 288 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"", 289 wmesg); 290 sleepq_lock(ident); 291#endif 292 if (timo) 293 rval = sleepq_timedwait(ident); 294 else { 295 sleepq_wait(ident); 296 rval = 0; 297 } 298#ifdef KTRACE 299 if (KTRPOINT(td, KTR_CSW)) 300 ktrcsw(0, 0); 301#endif 302 PICKUP_GIANT(); 303 mtx_lock_spin(mtx); 304 WITNESS_RESTORE(&mtx->mtx_object, mtx); 305 return (rval); 306} 307 308/* 309 * Make all threads sleeping on the specified identifier runnable. 310 */ 311void 312wakeup(ident) 313 register void *ident; 314{ 315 316 sleepq_lock(ident); 317 sleepq_broadcast(ident, SLEEPQ_MSLEEP, -1); 318} 319 320/* 321 * Make a thread sleeping on the specified identifier runnable. 322 * May wake more than one thread if a target thread is currently 323 * swapped out. 324 */ 325void 326wakeup_one(ident) 327 register void *ident; 328{ 329 330 sleepq_lock(ident); 331 sleepq_signal(ident, SLEEPQ_MSLEEP, -1); 332} 333 334/* 335 * The machine independent parts of context switching. 336 */ 337void 338mi_switch(int flags, struct thread *newtd) 339{ 340 uint64_t new_switchtime; 341 struct thread *td; 342 struct proc *p; 343 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")); 348#ifdef INVARIANTS 349 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 350 mtx_assert(&Giant, MA_NOTOWNED); 351#endif 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")); 359 360 /* 361 * Don't perform context switches from the debugger. 362 */ 363 if (kdb_active) { 364 mtx_unlock_spin(&sched_lock); 365 kdb_backtrace(); 366 kdb_reenter(); 367 panic("%s: did not reenter debugger", __func__); 368 } 369 370 if (flags & SW_VOL) 371 p->p_stats->p_ru.ru_nvcsw++; 372 else 373 p->p_stats->p_ru.ru_nivcsw++; 374 375 /* 376 * Compute the amount of time during which the current 377 * process was running, and add that to its total so far. 378 */ 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; 382 td->td_uticks = 0; 383 p->p_rux.rux_iticks += td->td_iticks; 384 td->td_iticks = 0; 385 p->p_rux.rux_sticks += td->td_sticks; 386 td->td_sticks = 0; 387 388 td->td_generation++; /* bump preempt-detect counter */ 389 390 /* 391 * Check if the process exceeds its cpu resource allocation. If 392 * it reaches the max, arrange to kill the process in ast(). 393 */ 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; 398 } 399 400 /* 401 * Finish up stats for outgoing thread. 402 */ 403 cnt.v_swtch++; 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#ifdef KSE 409 if ((flags & SW_VOL) && (td->td_proc->p_flag & P_SA)) 410 newtd = thread_switchout(td, flags, newtd); 411#endif 412#if (KTR_COMPILE & KTR_SCHED) != 0 413 if (td == PCPU_GET(idlethread)) 414 CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle", 415 td, td->td_proc->p_comm, td->td_priority); 416 else if (newtd != NULL) 417 CTR5(KTR_SCHED, 418 "mi_switch: %p(%s) prio %d preempted by %p(%s)", 419 td, td->td_proc->p_comm, td->td_priority, newtd, 420 newtd->td_proc->p_comm); 421 else 422 CTR6(KTR_SCHED, 423 "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s", 424 td, td->td_proc->p_comm, td->td_priority, 425 td->td_inhibitors, td->td_wmesg, td->td_lockname); 426#endif 427 sched_switch(td, newtd, flags); 428 CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d", 429 td, td->td_proc->p_comm, td->td_priority); 430 431 CTR4(KTR_PROC, "mi_switch: new thread %p (kse %p, pid %ld, %s)", 432 (void *)td, td->td_sched, (long)p->p_pid, p->p_comm); 433 434 /* 435 * If the last thread was exiting, finish cleaning it up. 436 */ 437 if ((td = PCPU_GET(deadthread))) { 438 PCPU_SET(deadthread, NULL); 439 thread_stash(td); 440 } 441} 442 443/* 444 * Change process state to be runnable, 445 * placing it on the run queue if it is in memory, 446 * and awakening the swapper if it isn't in memory. 447 */ 448void 449setrunnable(struct thread *td) 450{ 451 struct proc *p; 452 453 p = td->td_proc; 454 mtx_assert(&sched_lock, MA_OWNED); 455 switch (p->p_state) { 456 case PRS_ZOMBIE: 457 panic("setrunnable(1)"); 458 default: 459 break; 460 } 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 ((p->p_sflag & PS_INMEM) == 0) { 480 if ((p->p_sflag & PS_SWAPPINGIN) == 0) { 481 p->p_sflag |= PS_SWAPINREQ; 482 /* 483 * due to a LOR between sched_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 * XXXKSE Needs complete rewrite when correct info is available. 497 * Completely Bogus.. only works with 1:1 (but compiles ok now :-) 498 */ 499static void 500loadav(void *arg) 501{ 502 int i, nrun; 503 struct loadavg *avg; 504 505 nrun = sched_load(); 506 avg = &averunnable; 507 508 for (i = 0; i < 3; i++) 509 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 510 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 511 512 /* 513 * Schedule the next update to occur after 5 seconds, but add a 514 * random variation to avoid synchronisation with processes that 515 * run at regular intervals. 516 */ 517 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 518 loadav, NULL); 519} 520 521static void 522lboltcb(void *arg) 523{ 524 wakeup(&lbolt); 525 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 526} 527 528/* ARGSUSED */ 529static void 530synch_setup(dummy) 531 void *dummy; 532{ 533 callout_init(&loadav_callout, CALLOUT_MPSAFE); 534 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 535 536 /* Kick off timeout driven events by calling first time. */ 537 loadav(NULL); 538 lboltcb(NULL); 539} 540 541/* 542 * General purpose yield system call 543 */ 544int 545yield(struct thread *td, struct yield_args *uap) 546{ 547 mtx_assert(&Giant, MA_NOTOWNED); 548 (void)uap; 549 sched_relinquish(td); 550 return (0); 551} 552