kern_synch.c revision 124944
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 * 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. 25 * 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 36 * SUCH DAMAGE. 37 * 38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95 39 */ 40 41#include <sys/cdefs.h> 42__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 124944 2004-01-25 03:54:52Z jeff $"); 43 44#include "opt_ddb.h" 45#include "opt_ktrace.h" 46 47#include <sys/param.h> 48#include <sys/systm.h> 49#include <sys/condvar.h> 50#include <sys/kernel.h> 51#include <sys/ktr.h> 52#include <sys/lock.h> 53#include <sys/mutex.h> 54#include <sys/proc.h> 55#include <sys/resourcevar.h> 56#include <sys/sched.h> 57#include <sys/signalvar.h> 58#include <sys/smp.h> 59#include <sys/sx.h> 60#include <sys/sysctl.h> 61#include <sys/sysproto.h> 62#include <sys/vmmeter.h> 63#ifdef DDB 64#include <ddb/ddb.h> 65#endif 66#ifdef KTRACE 67#include <sys/uio.h> 68#include <sys/ktrace.h> 69#endif 70 71#include <machine/cpu.h> 72 73static void sched_setup(void *dummy); 74SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL) 75 76int hogticks; 77int lbolt; 78 79static struct callout loadav_callout; 80static struct callout lbolt_callout; 81 82struct loadavg averunnable = 83 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 84/* 85 * Constants for averages over 1, 5, and 15 minutes 86 * when sampling at 5 second intervals. 87 */ 88static 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) */ 92}; 93 94/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */ 95static int fscale __unused = FSCALE; 96SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, ""); 97 98static void endtsleep(void *); 99static void loadav(void *arg); 100static void lboltcb(void *arg); 101 102/* 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. 106 */ 107#define TABLESIZE 128 108static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE]; 109#define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1)) 110 111void 112sleepinit(void) 113{ 114 int i; 115 116 hogticks = (hz / 10) * 2; /* Default only. */ 117 for (i = 0; i < TABLESIZE; i++) 118 TAILQ_INIT(&slpque[i]); 119} 120 121/* 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). 131 * 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. 135 */ 136 137int 138msleep(ident, mtx, priority, wmesg, timo) 139 void *ident; 140 struct mtx *mtx; 141 int priority, timo; 142 const char *wmesg; 143{ 144 struct thread *td = curthread; 145 struct proc *p = td->td_proc; 146 int sig, catch = priority & PCATCH; 147 int rval = 0; 148 WITNESS_SAVE_DECL(mtx); 149 150#ifdef KTRACE 151 if (KTRPOINT(td, KTR_CSW)) 152 ktrcsw(1, 0); 153#endif 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")); 159 /* 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). 165 */ 166 mtx_lock_spin(&sched_lock); 167 if (p->p_flag & P_SA || p->p_numthreads > 1) { 168 /* 169 * Just don't bother if we are exiting 170 * and not the exiting thread or thread was marked as 171 * interrupted. 172 */ 173 if (catch) { 174 if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) { 175 mtx_unlock_spin(&sched_lock); 176 return (EINTR); 177 } 178 if (td->td_flags & TDF_INTERRUPT) { 179 mtx_unlock_spin(&sched_lock); 180 return (td->td_intrval); 181 } 182 } 183 } 184 if (cold ) { 185 /* 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. 192 */ 193 if (mtx != NULL && priority & PDROP) 194 mtx_unlock(mtx); 195 mtx_unlock_spin(&sched_lock); 196 return (0); 197 } 198 DROP_GIANT(); 199 if (mtx != NULL) { 200 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 201 WITNESS_SAVE(&mtx->mtx_object, mtx); 202 mtx_unlock(mtx); 203 if (priority & PDROP) 204 mtx = NULL; 205 } 206 KASSERT(p != NULL, ("msleep1")); 207 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 208 209 CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)", 210 td, p->p_pid, p->p_comm, wmesg, ident); 211 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); 216 if (timo) 217 callout_reset(&td->td_slpcallout, timo, endtsleep, td); 218 /* 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. 225 */ 226 if (catch) { 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); 231 PROC_LOCK(p); 232 mtx_lock(&p->p_sigacts->ps_mtx); 233 sig = cursig(td); 234 mtx_unlock(&p->p_sigacts->ps_mtx); 235 if (sig == 0 && thread_suspend_check(1)) 236 sig = SIGSTOP; 237 mtx_lock_spin(&sched_lock); 238 PROC_UNLOCK(p); 239 if (sig != 0) { 240 if (TD_ON_SLEEPQ(td)) 241 unsleep(td); 242 } else if (!TD_ON_SLEEPQ(td)) 243 catch = 0; 244 } else 245 sig = 0; 246 247 /* 248 * Let the scheduler know we're about to voluntarily go to sleep. 249 */ 250 sched_sleep(td, priority & PRIMASK); 251 252 if (TD_ON_SLEEPQ(td)) { 253 TD_SET_SLEEPING(td); 254 mi_switch(SW_VOL); 255 } 256 /* 257 * We're awake from voluntary sleep. 258 */ 259 CTR3(KTR_PROC, "msleep resume: thread %p (pid %d, %s)", td, p->p_pid, 260 p->p_comm); 261 KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING")); 262 td->td_flags &= ~TDF_SINTR; 263 if (td->td_flags & TDF_TIMEOUT) { 264 td->td_flags &= ~TDF_TIMEOUT; 265 if (sig == 0) 266 rval = EWOULDBLOCK; 267 } else if (td->td_flags & TDF_TIMOFAIL) { 268 td->td_flags &= ~TDF_TIMOFAIL; 269 } else if (timo && callout_stop(&td->td_slpcallout) == 0) { 270 /* 271 * This isn't supposed to be pretty. If we are here, then 272 * the endtsleep() callout is currently executing on another 273 * CPU and is either spinning on the sched_lock or will be 274 * soon. If we don't synchronize here, there is a chance 275 * that this process may msleep() again before the callout 276 * has a chance to run and the callout may end up waking up 277 * the wrong msleep(). Yuck. 278 */ 279 TD_SET_SLEEPING(td); 280 mi_switch(SW_INVOL); 281 td->td_flags &= ~TDF_TIMOFAIL; 282 } 283 if ((td->td_flags & TDF_INTERRUPT) && (priority & PCATCH) && 284 (rval == 0)) { 285 rval = td->td_intrval; 286 } 287 mtx_unlock_spin(&sched_lock); 288 if (rval == 0 && catch) { 289 PROC_LOCK(p); 290 /* XXX: shouldn't we always be calling cursig()? */ 291 mtx_lock(&p->p_sigacts->ps_mtx); 292 if (sig != 0 || (sig = cursig(td))) { 293 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig)) 294 rval = EINTR; 295 else 296 rval = ERESTART; 297 } 298 mtx_unlock(&p->p_sigacts->ps_mtx); 299 PROC_UNLOCK(p); 300 } 301#ifdef KTRACE 302 if (KTRPOINT(td, KTR_CSW)) 303 ktrcsw(0, 0); 304#endif 305 PICKUP_GIANT(); 306 if (mtx != NULL) { 307 mtx_lock(mtx); 308 WITNESS_RESTORE(&mtx->mtx_object, mtx); 309 } 310 return (rval); 311} 312 313/* 314 * Implement timeout for msleep(). 315 * 316 * If process hasn't been awakened (wchan non-zero), 317 * set timeout flag and undo the sleep. If proc 318 * is stopped, just unsleep so it will remain stopped. 319 * MP-safe, called without the Giant mutex. 320 */ 321static void 322endtsleep(arg) 323 void *arg; 324{ 325 register struct thread *td; 326 327 td = (struct thread *)arg; 328 CTR3(KTR_PROC, "endtsleep: thread %p (pid %d, %s)", 329 td, td->td_proc->p_pid, td->td_proc->p_comm); 330 mtx_lock_spin(&sched_lock); 331 /* 332 * This is the other half of the synchronization with msleep() 333 * described above. If the TDS_TIMEOUT flag is set, we lost the 334 * race and just need to put the process back on the runqueue. 335 */ 336 if (TD_ON_SLEEPQ(td)) { 337 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq); 338 TD_CLR_ON_SLEEPQ(td); 339 td->td_flags |= TDF_TIMEOUT; 340 td->td_wmesg = NULL; 341 } else 342 td->td_flags |= TDF_TIMOFAIL; 343 TD_CLR_SLEEPING(td); 344 setrunnable(td); 345 mtx_unlock_spin(&sched_lock); 346} 347 348/* 349 * Abort a thread, as if an interrupt had occured. Only abort 350 * interruptable waits (unfortunatly it isn't only safe to abort others). 351 * This is about identical to cv_abort(). 352 * Think about merging them? 353 * Also, whatever the signal code does... 354 */ 355void 356abortsleep(struct thread *td) 357{ 358 359 mtx_assert(&sched_lock, MA_OWNED); 360 /* 361 * If the TDF_TIMEOUT flag is set, just leave. A 362 * timeout is scheduled anyhow. 363 */ 364 if ((td->td_flags & (TDF_TIMEOUT | TDF_SINTR)) == TDF_SINTR) { 365 if (TD_ON_SLEEPQ(td)) { 366 unsleep(td); 367 TD_CLR_SLEEPING(td); 368 setrunnable(td); 369 } 370 } 371} 372 373/* 374 * Remove a process from its wait queue 375 */ 376void 377unsleep(struct thread *td) 378{ 379 380 mtx_lock_spin(&sched_lock); 381 if (TD_ON_SLEEPQ(td)) { 382 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq); 383 TD_CLR_ON_SLEEPQ(td); 384 td->td_wmesg = NULL; 385 } 386 mtx_unlock_spin(&sched_lock); 387} 388 389/* 390 * Make all processes sleeping on the specified identifier runnable. 391 */ 392void 393wakeup(ident) 394 register void *ident; 395{ 396 register struct slpquehead *qp; 397 register struct thread *td; 398 struct thread *ntd; 399 struct proc *p; 400 401 mtx_lock_spin(&sched_lock); 402 qp = &slpque[LOOKUP(ident)]; 403restart: 404 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) { 405 ntd = TAILQ_NEXT(td, td_slpq); 406 if (td->td_wchan == ident) { 407 unsleep(td); 408 TD_CLR_SLEEPING(td); 409 setrunnable(td); 410 p = td->td_proc; 411 CTR3(KTR_PROC,"wakeup: thread %p (pid %d, %s)", 412 td, p->p_pid, p->p_comm); 413 goto restart; 414 } 415 } 416 mtx_unlock_spin(&sched_lock); 417} 418 419/* 420 * Make a process sleeping on the specified identifier runnable. 421 * May wake more than one process if a target process is currently 422 * swapped out. 423 */ 424void 425wakeup_one(ident) 426 register void *ident; 427{ 428 register struct proc *p; 429 register struct slpquehead *qp; 430 register struct thread *td; 431 struct thread *ntd; 432 433 mtx_lock_spin(&sched_lock); 434 qp = &slpque[LOOKUP(ident)]; 435 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) { 436 ntd = TAILQ_NEXT(td, td_slpq); 437 if (td->td_wchan == ident) { 438 unsleep(td); 439 TD_CLR_SLEEPING(td); 440 setrunnable(td); 441 p = td->td_proc; 442 CTR3(KTR_PROC,"wakeup1: thread %p (pid %d, %s)", 443 td, p->p_pid, p->p_comm); 444 break; 445 } 446 } 447 mtx_unlock_spin(&sched_lock); 448} 449 450/* 451 * The machine independent parts of mi_switch(). 452 */ 453void 454mi_switch(int flags) 455{ 456 struct bintime new_switchtime; 457 struct thread *td; 458 struct proc *p; 459 460 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED); 461 td = curthread; /* XXX */ 462 p = td->td_proc; /* XXX */ 463 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 464#ifdef INVARIANTS 465 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 466 mtx_assert(&Giant, MA_NOTOWNED); 467#endif 468 KASSERT(td->td_critnest == 1, 469 ("mi_switch: switch in a critical section")); 470 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 471 ("mi_switch: switch must be voluntary or involuntary")); 472 473 if (flags & SW_VOL) 474 p->p_stats->p_ru.ru_nvcsw++; 475 else 476 p->p_stats->p_ru.ru_nivcsw++; 477 /* 478 * Compute the amount of time during which the current 479 * process was running, and add that to its total so far. 480 */ 481 binuptime(&new_switchtime); 482 bintime_add(&p->p_runtime, &new_switchtime); 483 bintime_sub(&p->p_runtime, PCPU_PTR(switchtime)); 484 485 td->td_generation++; /* bump preempt-detect counter */ 486 487#ifdef DDB 488 /* 489 * Don't perform context switches from the debugger. 490 */ 491 if (db_active) { 492 mtx_unlock_spin(&sched_lock); 493 db_print_backtrace(); 494 db_error("Context switches not allowed in the debugger"); 495 } 496#endif 497 498 /* 499 * Check if the process exceeds its cpu resource allocation. If 500 * over max, arrange to kill the process in ast(). 501 */ 502 if (p->p_cpulimit != RLIM_INFINITY && 503 p->p_runtime.sec > p->p_cpulimit) { 504 p->p_sflag |= PS_XCPU; 505 td->td_flags |= TDF_ASTPENDING; 506 } 507 508 /* 509 * Finish up stats for outgoing thread. 510 */ 511 cnt.v_swtch++; 512 PCPU_SET(switchtime, new_switchtime); 513 PCPU_SET(switchticks, ticks); 514 CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid, 515 p->p_comm); 516 if (td->td_proc->p_flag & P_SA) 517 thread_switchout(td); 518 sched_switch(td); 519 520 CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid, 521 p->p_comm); 522 523 /* 524 * If the last thread was exiting, finish cleaning it up. 525 */ 526 if ((td = PCPU_GET(deadthread))) { 527 PCPU_SET(deadthread, NULL); 528 thread_stash(td); 529 } 530} 531 532/* 533 * Change process state to be runnable, 534 * placing it on the run queue if it is in memory, 535 * and awakening the swapper if it isn't in memory. 536 */ 537void 538setrunnable(struct thread *td) 539{ 540 struct proc *p; 541 542 p = td->td_proc; 543 mtx_assert(&sched_lock, MA_OWNED); 544 switch (p->p_state) { 545 case PRS_ZOMBIE: 546 panic("setrunnable(1)"); 547 default: 548 break; 549 } 550 switch (td->td_state) { 551 case TDS_RUNNING: 552 case TDS_RUNQ: 553 return; 554 case TDS_INHIBITED: 555 /* 556 * If we are only inhibited because we are swapped out 557 * then arange to swap in this process. Otherwise just return. 558 */ 559 if (td->td_inhibitors != TDI_SWAPPED) 560 return; 561 /* XXX: intentional fall-through ? */ 562 case TDS_CAN_RUN: 563 break; 564 default: 565 printf("state is 0x%x", td->td_state); 566 panic("setrunnable(2)"); 567 } 568 if ((p->p_sflag & PS_INMEM) == 0) { 569 if ((p->p_sflag & PS_SWAPPINGIN) == 0) { 570 p->p_sflag |= PS_SWAPINREQ; 571 wakeup(&proc0); 572 } 573 } else 574 sched_wakeup(td); 575} 576 577/* 578 * Compute a tenex style load average of a quantity on 579 * 1, 5 and 15 minute intervals. 580 * XXXKSE Needs complete rewrite when correct info is available. 581 * Completely Bogus.. only works with 1:1 (but compiles ok now :-) 582 */ 583static void 584loadav(void *arg) 585{ 586 int i, nrun; 587 struct loadavg *avg; 588 struct proc *p; 589 struct thread *td; 590 591 avg = &averunnable; 592 sx_slock(&allproc_lock); 593 nrun = 0; 594 FOREACH_PROC_IN_SYSTEM(p) { 595 FOREACH_THREAD_IN_PROC(p, td) { 596 switch (td->td_state) { 597 case TDS_RUNQ: 598 case TDS_RUNNING: 599 if ((p->p_flag & P_NOLOAD) != 0) 600 goto nextproc; 601 nrun++; /* XXXKSE */ 602 default: 603 break; 604 } 605nextproc: 606 continue; 607 } 608 } 609 sx_sunlock(&allproc_lock); 610 for (i = 0; i < 3; i++) 611 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 612 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 613 614 /* 615 * Schedule the next update to occur after 5 seconds, but add a 616 * random variation to avoid synchronisation with processes that 617 * run at regular intervals. 618 */ 619 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 620 loadav, NULL); 621} 622 623static void 624lboltcb(void *arg) 625{ 626 wakeup(&lbolt); 627 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 628} 629 630/* ARGSUSED */ 631static void 632sched_setup(dummy) 633 void *dummy; 634{ 635 callout_init(&loadav_callout, 0); 636 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 637 638 /* Kick off timeout driven events by calling first time. */ 639 loadav(NULL); 640 lboltcb(NULL); 641} 642 643/* 644 * General purpose yield system call 645 */ 646int 647yield(struct thread *td, struct yield_args *uap) 648{ 649 struct ksegrp *kg; 650 651 kg = td->td_ksegrp; 652 mtx_assert(&Giant, MA_NOTOWNED); 653 mtx_lock_spin(&sched_lock); 654 sched_prio(td, PRI_MAX_TIMESHARE); 655 mi_switch(SW_VOL); 656 mtx_unlock_spin(&sched_lock); 657 td->td_retval[0] = 0; 658 return (0); 659} 660