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