1 /* $OpenBSD: sched_bsd.c,v 1.16 2008/05/22 14:07:14 thib Exp $ */ 2 /* $NetBSD: kern_synch.c,v 1.37 1996/04/22 01:38:37 christos Exp $ */ 3 4 /*- 5 * Copyright (c) 1982, 1986, 1990, 1991, 1993 6 * The Regents of the University of California. All rights reserved. 7 * (c) UNIX System Laboratories, Inc. 8 * All or some portions of this file are derived from material licensed 9 * to the University of California by American Telephone and Telegraph 10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 11 * the permission of UNIX System Laboratories, Inc. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. Neither the name of the University nor the names of its contributors 22 * may be used to endorse or promote products derived from this software 23 * without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 * 37 * @(#)kern_synch.c 8.6 (Berkeley) 1/21/94 38 */ 39 40 #include <sys/param.h> 41 #include <sys/systm.h> 42 #include <sys/proc.h> 43 #include <sys/kernel.h> 44 #include <sys/buf.h> 45 #include <sys/signalvar.h> 46 #include <sys/resourcevar.h> 47 #include <uvm/uvm_extern.h> 48 #include <sys/sched.h> 49 #include <sys/timeout.h> 50 51 #ifdef KTRACE 52 #include <sys/ktrace.h> 53 #endif 54 55 #include <machine/cpu.h> 56 57 int lbolt; /* once a second sleep address */ 58 int rrticks_init; /* # of hardclock ticks per roundrobin() */ 59 60 #ifdef MULTIPROCESSOR 61 struct __mp_lock sched_lock; 62 #endif 63 64 void scheduler_start(void); 65 66 void roundrobin(struct cpu_info *); 67 void schedcpu(void *); 68 void updatepri(struct proc *); 69 void endtsleep(void *); 70 71 void 72 scheduler_start(void) 73 { 74 static struct timeout schedcpu_to; 75 76 /* 77 * We avoid polluting the global namespace by keeping the scheduler 78 * timeouts static in this function. 79 * We setup the timeouts here and kick schedcpu and roundrobin once to 80 * make them do their job. 81 */ 82 83 timeout_set(&schedcpu_to, schedcpu, &schedcpu_to); 84 85 rrticks_init = hz / 10; 86 schedcpu(&schedcpu_to); 87 } 88 89 /* 90 * Force switch among equal priority processes every 100ms. 91 */ 92 void 93 roundrobin(struct cpu_info *ci) 94 { 95 struct schedstate_percpu *spc = &ci->ci_schedstate; 96 int s; 97 98 spc->spc_rrticks = rrticks_init; 99 100 if (curproc != NULL) { 101 s = splstatclock(); 102 if (spc->spc_schedflags & SPCF_SEENRR) { 103 /* 104 * The process has already been through a roundrobin 105 * without switching and may be hogging the CPU. 106 * Indicate that the process should yield. 107 */ 108 spc->spc_schedflags |= SPCF_SHOULDYIELD; 109 } else { 110 spc->spc_schedflags |= SPCF_SEENRR; 111 } 112 splx(s); 113 } 114 115 need_resched(curcpu()); 116 } 117 118 /* 119 * Constants for digital decay and forget: 120 * 90% of (p_estcpu) usage in 5 * loadav time 121 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive) 122 * Note that, as ps(1) mentions, this can let percentages 123 * total over 100% (I've seen 137.9% for 3 processes). 124 * 125 * Note that hardclock updates p_estcpu and p_cpticks independently. 126 * 127 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds. 128 * That is, the system wants to compute a value of decay such 129 * that the following for loop: 130 * for (i = 0; i < (5 * loadavg); i++) 131 * p_estcpu *= decay; 132 * will compute 133 * p_estcpu *= 0.1; 134 * for all values of loadavg: 135 * 136 * Mathematically this loop can be expressed by saying: 137 * decay ** (5 * loadavg) ~= .1 138 * 139 * The system computes decay as: 140 * decay = (2 * loadavg) / (2 * loadavg + 1) 141 * 142 * We wish to prove that the system's computation of decay 143 * will always fulfill the equation: 144 * decay ** (5 * loadavg) ~= .1 145 * 146 * If we compute b as: 147 * b = 2 * loadavg 148 * then 149 * decay = b / (b + 1) 150 * 151 * We now need to prove two things: 152 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1) 153 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg) 154 * 155 * Facts: 156 * For x close to zero, exp(x) =~ 1 + x, since 157 * exp(x) = 0! + x**1/1! + x**2/2! + ... . 158 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b. 159 * For x close to zero, ln(1+x) =~ x, since 160 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1 161 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1). 162 * ln(.1) =~ -2.30 163 * 164 * Proof of (1): 165 * Solve (factor)**(power) =~ .1 given power (5*loadav): 166 * solving for factor, 167 * ln(factor) =~ (-2.30/5*loadav), or 168 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) = 169 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED 170 * 171 * Proof of (2): 172 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)): 173 * solving for power, 174 * power*ln(b/(b+1)) =~ -2.30, or 175 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED 176 * 177 * Actual power values for the implemented algorithm are as follows: 178 * loadav: 1 2 3 4 179 * power: 5.68 10.32 14.94 19.55 180 */ 181 182 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */ 183 #define loadfactor(loadav) (2 * (loadav)) 184 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE)) 185 186 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */ 187 fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */ 188 189 /* 190 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the 191 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below 192 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT). 193 * 194 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used: 195 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits). 196 * 197 * If you don't want to bother with the faster/more-accurate formula, you 198 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate 199 * (more general) method of calculating the %age of CPU used by a process. 200 */ 201 #define CCPU_SHIFT 11 202 203 /* 204 * Recompute process priorities, every hz ticks. 205 */ 206 void 207 schedcpu(void *arg) 208 { 209 struct timeout *to = (struct timeout *)arg; 210 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]); 211 struct proc *p; 212 int s; 213 unsigned int newcpu; 214 int phz; 215 216 /* 217 * If we have a statistics clock, use that to calculate CPU 218 * time, otherwise revert to using the profiling clock (which, 219 * in turn, defaults to hz if there is no separate profiling 220 * clock available) 221 */ 222 phz = stathz ? stathz : profhz; 223 KASSERT(phz); 224 225 LIST_FOREACH(p, &allproc, p_list) { 226 /* 227 * Increment time in/out of memory and sleep time 228 * (if sleeping). We ignore overflow; with 16-bit int's 229 * (remember them?) overflow takes 45 days. 230 */ 231 p->p_swtime++; 232 if (p->p_stat == SSLEEP || p->p_stat == SSTOP) 233 p->p_slptime++; 234 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT; 235 /* 236 * If the process has slept the entire second, 237 * stop recalculating its priority until it wakes up. 238 */ 239 if (p->p_slptime > 1) 240 continue; 241 SCHED_LOCK(s); 242 /* 243 * p_pctcpu is only for ps. 244 */ 245 #if (FSHIFT >= CCPU_SHIFT) 246 p->p_pctcpu += (phz == 100)? 247 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT): 248 100 * (((fixpt_t) p->p_cpticks) 249 << (FSHIFT - CCPU_SHIFT)) / phz; 250 #else 251 p->p_pctcpu += ((FSCALE - ccpu) * 252 (p->p_cpticks * FSCALE / phz)) >> FSHIFT; 253 #endif 254 p->p_cpticks = 0; 255 newcpu = (u_int) decay_cpu(loadfac, p->p_estcpu); 256 p->p_estcpu = newcpu; 257 resetpriority(p); 258 if (p->p_priority >= PUSER) { 259 if ((p != curproc) && 260 p->p_stat == SRUN && 261 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) { 262 remrunqueue(p); 263 p->p_priority = p->p_usrpri; 264 setrunqueue(p); 265 } else 266 p->p_priority = p->p_usrpri; 267 } 268 SCHED_UNLOCK(s); 269 } 270 uvm_meter(); 271 wakeup(&lbolt); 272 timeout_add(to, hz); 273 } 274 275 /* 276 * Recalculate the priority of a process after it has slept for a while. 277 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at 278 * least six times the loadfactor will decay p_estcpu to zero. 279 */ 280 void 281 updatepri(struct proc *p) 282 { 283 unsigned int newcpu = p->p_estcpu; 284 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]); 285 286 SCHED_ASSERT_LOCKED(); 287 288 if (p->p_slptime > 5 * loadfac) 289 p->p_estcpu = 0; 290 else { 291 p->p_slptime--; /* the first time was done in schedcpu */ 292 while (newcpu && --p->p_slptime) 293 newcpu = (int) decay_cpu(loadfac, newcpu); 294 p->p_estcpu = newcpu; 295 } 296 resetpriority(p); 297 } 298 299 /* 300 * General yield call. Puts the current process back on its run queue and 301 * performs a voluntary context switch. 302 */ 303 void 304 yield(void) 305 { 306 struct proc *p = curproc; 307 int s; 308 309 SCHED_LOCK(s); 310 p->p_priority = p->p_usrpri; 311 p->p_stat = SRUN; 312 setrunqueue(p); 313 p->p_stats->p_ru.ru_nvcsw++; 314 mi_switch(); 315 SCHED_UNLOCK(s); 316 } 317 318 /* 319 * General preemption call. Puts the current process back on its run queue 320 * and performs an involuntary context switch. If a process is supplied, 321 * we switch to that process. Otherwise, we use the normal process selection 322 * criteria. 323 */ 324 void 325 preempt(struct proc *newp) 326 { 327 struct proc *p = curproc; 328 int s; 329 330 /* 331 * XXX Switching to a specific process is not supported yet. 332 */ 333 if (newp != NULL) 334 panic("preempt: cpu_preempt not yet implemented"); 335 336 SCHED_LOCK(s); 337 p->p_priority = p->p_usrpri; 338 p->p_stat = SRUN; 339 setrunqueue(p); 340 p->p_stats->p_ru.ru_nivcsw++; 341 mi_switch(); 342 SCHED_UNLOCK(s); 343 } 344 345 void 346 mi_switch(void) 347 { 348 struct schedstate_percpu *spc = &curcpu()->ci_schedstate; 349 struct proc *p = curproc; 350 struct proc *nextproc; 351 struct rlimit *rlim; 352 struct timeval tv; 353 #ifdef MULTIPROCESSOR 354 int hold_count; 355 int sched_count; 356 #endif 357 358 KASSERT(p->p_stat != SONPROC); 359 360 SCHED_ASSERT_LOCKED(); 361 362 #ifdef MULTIPROCESSOR 363 /* 364 * Release the kernel_lock, as we are about to yield the CPU. 365 */ 366 sched_count = __mp_release_all_but_one(&sched_lock); 367 if (p->p_flag & P_BIGLOCK) 368 hold_count = __mp_release_all(&kernel_lock); 369 #endif 370 371 /* 372 * Compute the amount of time during which the current 373 * process was running, and add that to its total so far. 374 */ 375 microuptime(&tv); 376 if (timercmp(&tv, &spc->spc_runtime, <)) { 377 #if 0 378 printf("uptime is not monotonic! " 379 "tv=%lu.%06lu, runtime=%lu.%06lu\n", 380 tv.tv_sec, tv.tv_usec, spc->spc_runtime.tv_sec, 381 spc->spc_runtime.tv_usec); 382 #endif 383 } else { 384 timersub(&tv, &spc->spc_runtime, &tv); 385 timeradd(&p->p_rtime, &tv, &p->p_rtime); 386 } 387 388 /* 389 * Check if the process exceeds its cpu resource allocation. 390 * If over max, kill it. 391 */ 392 rlim = &p->p_rlimit[RLIMIT_CPU]; 393 if ((rlim_t)p->p_rtime.tv_sec >= rlim->rlim_cur) { 394 if ((rlim_t)p->p_rtime.tv_sec >= rlim->rlim_max) { 395 psignal(p, SIGKILL); 396 } else { 397 psignal(p, SIGXCPU); 398 if (rlim->rlim_cur < rlim->rlim_max) 399 rlim->rlim_cur += 5; 400 } 401 } 402 403 /* 404 * Process is about to yield the CPU; clear the appropriate 405 * scheduling flags. 406 */ 407 spc->spc_schedflags &= ~SPCF_SWITCHCLEAR; 408 409 nextproc = sched_chooseproc(); 410 411 if (p != nextproc) { 412 uvmexp.swtch++; 413 cpu_switchto(p, nextproc); 414 } else { 415 p->p_stat = SONPROC; 416 } 417 418 SCHED_ASSERT_LOCKED(); 419 420 /* 421 * To preserve lock ordering, we need to release the sched lock 422 * and grab it after we grab the big lock. 423 * In the future, when the sched lock isn't recursive, we'll 424 * just release it here. 425 */ 426 #ifdef MULTIPROCESSOR 427 __mp_unlock(&sched_lock); 428 #endif 429 430 SCHED_ASSERT_UNLOCKED(); 431 432 /* 433 * We're running again; record our new start time. We might 434 * be running on a new CPU now, so don't use the cache'd 435 * schedstate_percpu pointer. 436 */ 437 KASSERT(p->p_cpu == curcpu()); 438 439 microuptime(&p->p_cpu->ci_schedstate.spc_runtime); 440 441 #ifdef MULTIPROCESSOR 442 /* 443 * Reacquire the kernel_lock now. We do this after we've 444 * released the scheduler lock to avoid deadlock, and before 445 * we reacquire the interlock and the scheduler lock. 446 */ 447 if (p->p_flag & P_BIGLOCK) 448 __mp_acquire_count(&kernel_lock, hold_count); 449 __mp_acquire_count(&sched_lock, sched_count + 1); 450 #endif 451 } 452 453 static __inline void 454 resched_proc(struct proc *p, u_char pri) 455 { 456 struct cpu_info *ci; 457 458 /* 459 * XXXSMP 460 * Since p->p_cpu persists across a context switch, 461 * this gives us *very weak* processor affinity, in 462 * that we notify the CPU on which the process last 463 * ran that it should try to switch. 464 * 465 * This does not guarantee that the process will run on 466 * that processor next, because another processor might 467 * grab it the next time it performs a context switch. 468 * 469 * This also does not handle the case where its last 470 * CPU is running a higher-priority process, but every 471 * other CPU is running a lower-priority process. There 472 * are ways to handle this situation, but they're not 473 * currently very pretty, and we also need to weigh the 474 * cost of moving a process from one CPU to another. 475 * 476 * XXXSMP 477 * There is also the issue of locking the other CPU's 478 * sched state, which we currently do not do. 479 */ 480 ci = (p->p_cpu != NULL) ? p->p_cpu : curcpu(); 481 if (pri < ci->ci_schedstate.spc_curpriority) 482 need_resched(ci); 483 } 484 485 /* 486 * Change process state to be runnable, 487 * placing it on the run queue if it is in memory, 488 * and awakening the swapper if it isn't in memory. 489 */ 490 void 491 setrunnable(struct proc *p) 492 { 493 SCHED_ASSERT_LOCKED(); 494 495 switch (p->p_stat) { 496 case 0: 497 case SRUN: 498 case SONPROC: 499 case SZOMB: 500 case SDEAD: 501 default: 502 panic("setrunnable"); 503 case SSTOP: 504 /* 505 * If we're being traced (possibly because someone attached us 506 * while we were stopped), check for a signal from the debugger. 507 */ 508 if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) 509 atomic_setbits_int(&p->p_siglist, sigmask(p->p_xstat)); 510 case SSLEEP: 511 unsleep(p); /* e.g. when sending signals */ 512 break; 513 case SIDL: 514 break; 515 } 516 p->p_stat = SRUN; 517 setrunqueue(p); 518 if (p->p_slptime > 1) 519 updatepri(p); 520 p->p_slptime = 0; 521 resched_proc(p, p->p_priority); 522 } 523 524 /* 525 * Compute the priority of a process when running in user mode. 526 * Arrange to reschedule if the resulting priority is better 527 * than that of the current process. 528 */ 529 void 530 resetpriority(struct proc *p) 531 { 532 unsigned int newpriority; 533 534 SCHED_ASSERT_LOCKED(); 535 536 newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO); 537 newpriority = min(newpriority, MAXPRI); 538 p->p_usrpri = newpriority; 539 resched_proc(p, p->p_usrpri); 540 } 541 542 /* 543 * We adjust the priority of the current process. The priority of a process 544 * gets worse as it accumulates CPU time. The cpu usage estimator (p_estcpu) 545 * is increased here. The formula for computing priorities (in kern_synch.c) 546 * will compute a different value each time p_estcpu increases. This can 547 * cause a switch, but unless the priority crosses a PPQ boundary the actual 548 * queue will not change. The cpu usage estimator ramps up quite quickly 549 * when the process is running (linearly), and decays away exponentially, at 550 * a rate which is proportionally slower when the system is busy. The basic 551 * principle is that the system will 90% forget that the process used a lot 552 * of CPU time in 5 * loadav seconds. This causes the system to favor 553 * processes which haven't run much recently, and to round-robin among other 554 * processes. 555 */ 556 557 void 558 schedclock(struct proc *p) 559 { 560 int s; 561 562 SCHED_LOCK(s); 563 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1); 564 resetpriority(p); 565 if (p->p_priority >= PUSER) 566 p->p_priority = p->p_usrpri; 567 SCHED_UNLOCK(s); 568 } 569