kern_synch.c revision 12569
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.6 (Berkeley) 1/21/94 39 * $Id: kern_synch.c,v 1.13 1995/09/09 18:10:04 davidg Exp $ 40 */ 41 42#include <sys/param.h> 43#include <sys/systm.h> 44#include <sys/proc.h> 45#include <sys/kernel.h> 46#include <sys/buf.h> 47#include <sys/signalvar.h> 48#include <sys/resourcevar.h> 49#include <sys/signalvar.h> 50#include <vm/vm.h> 51#ifdef KTRACE 52#include <sys/ktrace.h> 53#endif 54 55#include <machine/cpu.h> 56 57static void rqinit __P((void *)); 58SYSINIT(runqueue, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, rqinit, NULL) 59 60u_char curpriority; /* usrpri of curproc */ 61int lbolt; /* once a second sleep address */ 62 63void endtsleep __P((void *)); 64 65/* 66 * Force switch among equal priority processes every 100ms. 67 */ 68/* ARGSUSED */ 69void 70roundrobin(arg) 71 void *arg; 72{ 73 74 need_resched(); 75 timeout(roundrobin, NULL, hz / 10); 76} 77 78/* 79 * Constants for digital decay and forget: 80 * 90% of (p_estcpu) usage in 5 * loadav time 81 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive) 82 * Note that, as ps(1) mentions, this can let percentages 83 * total over 100% (I've seen 137.9% for 3 processes). 84 * 85 * Note that hardclock updates p_estcpu and p_cpticks independently. 86 * 87 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds. 88 * That is, the system wants to compute a value of decay such 89 * that the following for loop: 90 * for (i = 0; i < (5 * loadavg); i++) 91 * p_estcpu *= decay; 92 * will compute 93 * p_estcpu *= 0.1; 94 * for all values of loadavg: 95 * 96 * Mathematically this loop can be expressed by saying: 97 * decay ** (5 * loadavg) ~= .1 98 * 99 * The system computes decay as: 100 * decay = (2 * loadavg) / (2 * loadavg + 1) 101 * 102 * We wish to prove that the system's computation of decay 103 * will always fulfill the equation: 104 * decay ** (5 * loadavg) ~= .1 105 * 106 * If we compute b as: 107 * b = 2 * loadavg 108 * then 109 * decay = b / (b + 1) 110 * 111 * We now need to prove two things: 112 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1) 113 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg) 114 * 115 * Facts: 116 * For x close to zero, exp(x) =~ 1 + x, since 117 * exp(x) = 0! + x**1/1! + x**2/2! + ... . 118 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b. 119 * For x close to zero, ln(1+x) =~ x, since 120 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1 121 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1). 122 * ln(.1) =~ -2.30 123 * 124 * Proof of (1): 125 * Solve (factor)**(power) =~ .1 given power (5*loadav): 126 * solving for factor, 127 * ln(factor) =~ (-2.30/5*loadav), or 128 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) = 129 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED 130 * 131 * Proof of (2): 132 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)): 133 * solving for power, 134 * power*ln(b/(b+1)) =~ -2.30, or 135 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED 136 * 137 * Actual power values for the implemented algorithm are as follows: 138 * loadav: 1 2 3 4 139 * power: 5.68 10.32 14.94 19.55 140 */ 141 142/* calculations for digital decay to forget 90% of usage in 5*loadav sec */ 143#define loadfactor(loadav) (2 * (loadav)) 144#define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE)) 145 146/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */ 147fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */ 148 149/* 150 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the 151 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below 152 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT). 153 * 154 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used: 155 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits). 156 * 157 * If you dont want to bother with the faster/more-accurate formula, you 158 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate 159 * (more general) method of calculating the %age of CPU used by a process. 160 */ 161#define CCPU_SHIFT 11 162 163/* 164 * Recompute process priorities, every hz ticks. 165 */ 166/* ARGSUSED */ 167void 168schedcpu(arg) 169 void *arg; 170{ 171 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]); 172 register struct proc *p; 173 register int s; 174 register unsigned int newcpu; 175 176 wakeup((caddr_t)&lbolt); 177 for (p = (struct proc *)allproc; p != NULL; p = p->p_next) { 178 /* 179 * Increment time in/out of memory and sleep time 180 * (if sleeping). We ignore overflow; with 16-bit int's 181 * (remember them?) overflow takes 45 days. 182 */ 183 p->p_swtime++; 184 if (p->p_stat == SSLEEP || p->p_stat == SSTOP) 185 p->p_slptime++; 186 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT; 187 /* 188 * If the process has slept the entire second, 189 * stop recalculating its priority until it wakes up. 190 */ 191 if (p->p_slptime > 1) 192 continue; 193 s = splstatclock(); /* prevent state changes */ 194 /* 195 * p_pctcpu is only for ps. 196 */ 197#if (FSHIFT >= CCPU_SHIFT) 198 p->p_pctcpu += (hz == 100)? 199 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT): 200 100 * (((fixpt_t) p->p_cpticks) 201 << (FSHIFT - CCPU_SHIFT)) / hz; 202#else 203 p->p_pctcpu += ((FSCALE - ccpu) * 204 (p->p_cpticks * FSCALE / hz)) >> FSHIFT; 205#endif 206 p->p_cpticks = 0; 207 newcpu = (u_int) decay_cpu(loadfac, p->p_estcpu) + p->p_nice; 208 p->p_estcpu = min(newcpu, UCHAR_MAX); 209 resetpriority(p); 210 if (p->p_priority >= PUSER) { 211#define PPQ (128 / NQS) /* priorities per queue */ 212 if ((p != curproc) && 213 p->p_stat == SRUN && 214 (p->p_flag & P_INMEM) && 215 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) { 216 remrq(p); 217 p->p_priority = p->p_usrpri; 218 setrunqueue(p); 219 } else 220 p->p_priority = p->p_usrpri; 221 } 222 splx(s); 223 } 224 vmmeter(); 225 timeout(schedcpu, (void *)0, hz); 226} 227 228/* 229 * Recalculate the priority of a process after it has slept for a while. 230 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at 231 * least six times the loadfactor will decay p_estcpu to zero. 232 */ 233void 234updatepri(p) 235 register struct proc *p; 236{ 237 register unsigned int newcpu = p->p_estcpu; 238 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]); 239 240 if (p->p_slptime > 5 * loadfac) 241 p->p_estcpu = 0; 242 else { 243 p->p_slptime--; /* the first time was done in schedcpu */ 244 while (newcpu && --p->p_slptime) 245 newcpu = (int) decay_cpu(loadfac, newcpu); 246 p->p_estcpu = min(newcpu, UCHAR_MAX); 247 } 248 resetpriority(p); 249} 250 251/* 252 * We're only looking at 7 bits of the address; everything is 253 * aligned to 4, lots of things are aligned to greater powers 254 * of 2. Shift right by 8, i.e. drop the bottom 256 worth. 255 */ 256#define TABLESIZE 128 257#define LOOKUP(x) (((int)(x) >> 8) & (TABLESIZE - 1)) 258struct slpque { 259 struct proc *sq_head; 260 struct proc **sq_tailp; 261} slpque[TABLESIZE]; 262 263/* 264 * During autoconfiguration or after a panic, a sleep will simply 265 * lower the priority briefly to allow interrupts, then return. 266 * The priority to be used (safepri) is machine-dependent, thus this 267 * value is initialized and maintained in the machine-dependent layers. 268 * This priority will typically be 0, or the lowest priority 269 * that is safe for use on the interrupt stack; it can be made 270 * higher to block network software interrupts after panics. 271 */ 272int safepri; 273 274/* 275 * General sleep call. Suspends the current process until a wakeup is 276 * performed on the specified identifier. The process will then be made 277 * runnable with the specified priority. Sleeps at most timo/hz seconds 278 * (0 means no timeout). If pri includes PCATCH flag, signals are checked 279 * before and after sleeping, else signals are not checked. Returns 0 if 280 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 281 * signal needs to be delivered, ERESTART is returned if the current system 282 * call should be restarted if possible, and EINTR is returned if the system 283 * call should be interrupted by the signal (return EINTR). 284 */ 285int 286tsleep(ident, priority, wmesg, timo) 287 void *ident; 288 int priority, timo; 289 char *wmesg; 290{ 291 register struct proc *p = curproc; 292 register struct slpque *qp; 293 register s; 294 int sig, catch = priority & PCATCH; 295 296#ifdef KTRACE 297 if (KTRPOINT(p, KTR_CSW)) 298 ktrcsw(p->p_tracep, 1, 0); 299#endif 300 s = splhigh(); 301 if (cold || panicstr) { 302 /* 303 * After a panic, or during autoconfiguration, 304 * just give interrupts a chance, then just return; 305 * don't run any other procs or panic below, 306 * in case this is the idle process and already asleep. 307 */ 308 splx(safepri); 309 splx(s); 310 return (0); 311 } 312#ifdef DIAGNOSTIC 313 if (ident == NULL || p->p_stat != SRUN || p->p_back) 314 panic("tsleep"); 315#endif 316 p->p_wchan = ident; 317 p->p_wmesg = wmesg; 318 p->p_slptime = 0; 319 p->p_priority = priority & PRIMASK; 320 qp = &slpque[LOOKUP(ident)]; 321 if (qp->sq_head == 0) 322 qp->sq_head = p; 323 else 324 *qp->sq_tailp = p; 325 *(qp->sq_tailp = &p->p_forw) = 0; 326 if (timo) 327 timeout(endtsleep, (void *)p, timo); 328 /* 329 * We put ourselves on the sleep queue and start our timeout 330 * before calling CURSIG, as we could stop there, and a wakeup 331 * or a SIGCONT (or both) could occur while we were stopped. 332 * A SIGCONT would cause us to be marked as SSLEEP 333 * without resuming us, thus we must be ready for sleep 334 * when CURSIG is called. If the wakeup happens while we're 335 * stopped, p->p_wchan will be 0 upon return from CURSIG. 336 */ 337 if (catch) { 338 p->p_flag |= P_SINTR; 339 if ((sig = CURSIG(p))) { 340 if (p->p_wchan) 341 unsleep(p); 342 p->p_stat = SRUN; 343 goto resume; 344 } 345 if (p->p_wchan == 0) { 346 catch = 0; 347 goto resume; 348 } 349 } else 350 sig = 0; 351 p->p_stat = SSLEEP; 352 p->p_stats->p_ru.ru_nvcsw++; 353 mi_switch(); 354resume: 355 curpriority = p->p_usrpri; 356 splx(s); 357 p->p_flag &= ~P_SINTR; 358 if (p->p_flag & P_TIMEOUT) { 359 p->p_flag &= ~P_TIMEOUT; 360 if (sig == 0) { 361#ifdef KTRACE 362 if (KTRPOINT(p, KTR_CSW)) 363 ktrcsw(p->p_tracep, 0, 0); 364#endif 365 return (EWOULDBLOCK); 366 } 367 } else if (timo) 368 untimeout(endtsleep, (void *)p); 369 if (catch && (sig != 0 || (sig = CURSIG(p)))) { 370#ifdef KTRACE 371 if (KTRPOINT(p, KTR_CSW)) 372 ktrcsw(p->p_tracep, 0, 0); 373#endif 374 if (p->p_sigacts->ps_sigintr & sigmask(sig)) 375 return (EINTR); 376 return (ERESTART); 377 } 378#ifdef KTRACE 379 if (KTRPOINT(p, KTR_CSW)) 380 ktrcsw(p->p_tracep, 0, 0); 381#endif 382 return (0); 383} 384 385/* 386 * Implement timeout for tsleep. 387 * If process hasn't been awakened (wchan non-zero), 388 * set timeout flag and undo the sleep. If proc 389 * is stopped, just unsleep so it will remain stopped. 390 */ 391void 392endtsleep(arg) 393 void *arg; 394{ 395 register struct proc *p; 396 int s; 397 398 p = (struct proc *)arg; 399 s = splhigh(); 400 if (p->p_wchan) { 401 if (p->p_stat == SSLEEP) 402 setrunnable(p); 403 else 404 unsleep(p); 405 p->p_flag |= P_TIMEOUT; 406 } 407 splx(s); 408} 409 410/* 411 * Short-term, non-interruptable sleep. 412 */ 413void 414sleep(ident, priority) 415 void *ident; 416 int priority; 417{ 418 register struct proc *p = curproc; 419 register struct slpque *qp; 420 register s; 421 422#ifdef DIAGNOSTIC 423 if (priority > PZERO) { 424 printf("sleep called with priority %d > PZERO, wchan: %p\n", 425 priority, ident); 426 panic("old sleep"); 427 } 428#endif 429 s = splhigh(); 430 if (cold || panicstr) { 431 /* 432 * After a panic, or during autoconfiguration, 433 * just give interrupts a chance, then just return; 434 * don't run any other procs or panic below, 435 * in case this is the idle process and already asleep. 436 */ 437 splx(safepri); 438 splx(s); 439 return; 440 } 441#ifdef DIAGNOSTIC 442 if (ident == NULL || p->p_stat != SRUN || p->p_back) 443 panic("sleep"); 444#endif 445 p->p_wchan = ident; 446 p->p_wmesg = NULL; 447 p->p_slptime = 0; 448 p->p_priority = priority; 449 qp = &slpque[LOOKUP(ident)]; 450 if (qp->sq_head == 0) 451 qp->sq_head = p; 452 else 453 *qp->sq_tailp = p; 454 *(qp->sq_tailp = &p->p_forw) = 0; 455 p->p_stat = SSLEEP; 456 p->p_stats->p_ru.ru_nvcsw++; 457#ifdef KTRACE 458 if (KTRPOINT(p, KTR_CSW)) 459 ktrcsw(p->p_tracep, 1, 0); 460#endif 461 mi_switch(); 462#ifdef KTRACE 463 if (KTRPOINT(p, KTR_CSW)) 464 ktrcsw(p->p_tracep, 0, 0); 465#endif 466 curpriority = p->p_usrpri; 467 splx(s); 468} 469 470/* 471 * Remove a process from its wait queue 472 */ 473void 474unsleep(p) 475 register struct proc *p; 476{ 477 register struct slpque *qp; 478 register struct proc **hp; 479 int s; 480 481 s = splhigh(); 482 if (p->p_wchan) { 483 hp = &(qp = &slpque[LOOKUP(p->p_wchan)])->sq_head; 484 while (*hp != p) 485 hp = &(*hp)->p_forw; 486 *hp = p->p_forw; 487 if (qp->sq_tailp == &p->p_forw) 488 qp->sq_tailp = hp; 489 p->p_wchan = 0; 490 } 491 splx(s); 492} 493 494/* 495 * Make all processes sleeping on the specified identifier runnable. 496 */ 497void 498wakeup(ident) 499 register void *ident; 500{ 501 register struct slpque *qp; 502 register struct proc *p, **q; 503 int s; 504 505 s = splhigh(); 506 qp = &slpque[LOOKUP(ident)]; 507restart: 508 for (q = &qp->sq_head; *q; ) { 509 p = *q; 510#ifdef DIAGNOSTIC 511 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP)) 512 panic("wakeup"); 513#endif 514 if (p->p_wchan == ident) { 515 p->p_wchan = 0; 516 *q = p->p_forw; 517 if (qp->sq_tailp == &p->p_forw) 518 qp->sq_tailp = q; 519 if (p->p_stat == SSLEEP) { 520 /* OPTIMIZED EXPANSION OF setrunnable(p); */ 521 if (p->p_slptime > 1) 522 updatepri(p); 523 p->p_slptime = 0; 524 p->p_stat = SRUN; 525 if (p->p_flag & P_INMEM) 526 setrunqueue(p); 527 /* 528 * Since curpriority is a user priority, 529 * p->p_priority is always better than 530 * curpriority. 531 */ 532 if ((p->p_flag & P_INMEM) == 0) 533 wakeup((caddr_t)&proc0); 534 else 535 need_resched(); 536 /* END INLINE EXPANSION */ 537 goto restart; 538 } 539 } else 540 q = &p->p_forw; 541 } 542 splx(s); 543} 544 545/* 546 * The machine independent parts of mi_switch(). 547 * Must be called at splstatclock() or higher. 548 */ 549void 550mi_switch() 551{ 552 register struct proc *p = curproc; /* XXX */ 553 register struct rlimit *rlim; 554 register long s, u; 555 struct timeval tv; 556 557 /* 558 * Compute the amount of time during which the current 559 * process was running, and add that to its total so far. 560 */ 561 microtime(&tv); 562 u = p->p_rtime.tv_usec + (tv.tv_usec - runtime.tv_usec); 563 s = p->p_rtime.tv_sec + (tv.tv_sec - runtime.tv_sec); 564 if (u < 0) { 565 u += 1000000; 566 s--; 567 } else if (u >= 1000000) { 568 u -= 1000000; 569 s++; 570 } 571 p->p_rtime.tv_usec = u; 572 p->p_rtime.tv_sec = s; 573 574 /* 575 * Check if the process exceeds its cpu resource allocation. 576 * If over max, kill it. In any case, if it has run for more 577 * than 10 minutes, reduce priority to give others a chance. 578 */ 579 if (p->p_stat != SZOMB) { 580 rlim = &p->p_rlimit[RLIMIT_CPU]; 581 if (s >= rlim->rlim_cur) { 582 if (s >= rlim->rlim_max) 583 psignal(p, SIGKILL); 584 else { 585 psignal(p, SIGXCPU); 586 if (rlim->rlim_cur < rlim->rlim_max) 587 rlim->rlim_cur += 5; 588 } 589 } 590 if (s > 10 * 60 && p->p_ucred->cr_uid && p->p_nice == NZERO) { 591 p->p_nice = NZERO + 4; 592 resetpriority(p); 593 } 594 } 595 596 /* 597 * Pick a new current process and record its start time. 598 */ 599 cnt.v_swtch++; 600 cpu_switch(p); 601 microtime(&runtime); 602} 603 604/* 605 * Initialize the (doubly-linked) run queues 606 * to be empty. 607 */ 608/* ARGSUSED*/ 609static void 610rqinit(dummy) 611 void *dummy; 612{ 613 register int i; 614 615 for (i = 0; i < NQS; i++) { 616 qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i]; 617 rtqs[i].ph_link = rtqs[i].ph_rlink = (struct proc *)&rtqs[i]; 618 idqs[i].ph_link = idqs[i].ph_rlink = (struct proc *)&idqs[i]; 619 } 620} 621 622/* 623 * Change process state to be runnable, 624 * placing it on the run queue if it is in memory, 625 * and awakening the swapper if it isn't in memory. 626 */ 627void 628setrunnable(p) 629 register struct proc *p; 630{ 631 register int s; 632 633 s = splhigh(); 634 switch (p->p_stat) { 635 case 0: 636 case SRUN: 637 case SZOMB: 638 default: 639 panic("setrunnable"); 640 case SSTOP: 641 case SSLEEP: 642 unsleep(p); /* e.g. when sending signals */ 643 break; 644 645 case SIDL: 646 break; 647 } 648 p->p_stat = SRUN; 649 if (p->p_flag & P_INMEM) 650 setrunqueue(p); 651 splx(s); 652 if (p->p_slptime > 1) 653 updatepri(p); 654 p->p_slptime = 0; 655 if ((p->p_flag & P_INMEM) == 0) 656 wakeup((caddr_t)&proc0); 657 else if (p->p_priority < curpriority) 658 need_resched(); 659} 660 661/* 662 * Compute the priority of a process when running in user mode. 663 * Arrange to reschedule if the resulting priority is better 664 * than that of the current process. 665 */ 666void 667resetpriority(p) 668 register struct proc *p; 669{ 670 register unsigned int newpriority; 671 672 if (p->p_rtprio.type == RTP_PRIO_NORMAL) { 673 newpriority = PUSER + p->p_estcpu / 4 + 2 * p->p_nice; 674 newpriority = min(newpriority, MAXPRI); 675 p->p_usrpri = newpriority; 676 if (newpriority < curpriority) 677 need_resched(); 678 } else { 679 need_resched(); 680 } 681} 682