1 /* $OpenBSD: kern_clock.c,v 1.70 2010/01/14 23:12:11 schwarze Exp $ */ 2 /* $NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $ */ 3 4 /*- 5 * Copyright (c) 1982, 1986, 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_clock.c 8.5 (Berkeley) 1/21/94 38 */ 39 40 #include <sys/param.h> 41 #include <sys/systm.h> 42 #include <sys/dkstat.h> 43 #include <sys/timeout.h> 44 #include <sys/kernel.h> 45 #include <sys/limits.h> 46 #include <sys/proc.h> 47 #include <sys/user.h> 48 #include <sys/resourcevar.h> 49 #include <sys/signalvar.h> 50 #include <uvm/uvm_extern.h> 51 #include <sys/sysctl.h> 52 #include <sys/sched.h> 53 #ifdef __HAVE_TIMECOUNTER 54 #include <sys/timetc.h> 55 #endif 56 57 #include <machine/cpu.h> 58 59 #ifdef GPROF 60 #include <sys/gmon.h> 61 #endif 62 63 /* 64 * Clock handling routines. 65 * 66 * This code is written to operate with two timers that run independently of 67 * each other. The main clock, running hz times per second, is used to keep 68 * track of real time. The second timer handles kernel and user profiling, 69 * and does resource use estimation. If the second timer is programmable, 70 * it is randomized to avoid aliasing between the two clocks. For example, 71 * the randomization prevents an adversary from always giving up the cpu 72 * just before its quantum expires. Otherwise, it would never accumulate 73 * cpu ticks. The mean frequency of the second timer is stathz. 74 * 75 * If no second timer exists, stathz will be zero; in this case we drive 76 * profiling and statistics off the main clock. This WILL NOT be accurate; 77 * do not do it unless absolutely necessary. 78 * 79 * The statistics clock may (or may not) be run at a higher rate while 80 * profiling. This profile clock runs at profhz. We require that profhz 81 * be an integral multiple of stathz. 82 * 83 * If the statistics clock is running fast, it must be divided by the ratio 84 * profhz/stathz for statistics. (For profiling, every tick counts.) 85 */ 86 87 /* 88 * Bump a timeval by a small number of usec's. 89 */ 90 #define BUMPTIME(t, usec) { \ 91 volatile struct timeval *tp = (t); \ 92 long us; \ 93 \ 94 tp->tv_usec = us = tp->tv_usec + (usec); \ 95 if (us >= 1000000) { \ 96 tp->tv_usec = us - 1000000; \ 97 tp->tv_sec++; \ 98 } \ 99 } 100 101 int stathz; 102 int schedhz; 103 int profhz; 104 int profprocs; 105 int ticks; 106 static int psdiv, pscnt; /* prof => stat divider */ 107 int psratio; /* ratio: prof / stat */ 108 109 long cp_time[CPUSTATES]; 110 111 #ifndef __HAVE_TIMECOUNTER 112 int tickfix, tickfixinterval; /* used if tick not really integral */ 113 static int tickfixcnt; /* accumulated fractional error */ 114 115 volatile time_t time_second; 116 volatile time_t time_uptime; 117 118 volatile struct timeval time 119 __attribute__((__aligned__(__alignof__(quad_t)))); 120 volatile struct timeval mono_time; 121 #endif 122 123 void *softclock_si; 124 125 /* 126 * Initialize clock frequencies and start both clocks running. 127 */ 128 void 129 initclocks(void) 130 { 131 int i; 132 #ifdef __HAVE_TIMECOUNTER 133 extern void inittimecounter(void); 134 #endif 135 136 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL); 137 if (softclock_si == NULL) 138 panic("initclocks: unable to register softclock intr"); 139 140 /* 141 * Set divisors to 1 (normal case) and let the machine-specific 142 * code do its bit. 143 */ 144 psdiv = pscnt = 1; 145 cpu_initclocks(); 146 147 /* 148 * Compute profhz/stathz, and fix profhz if needed. 149 */ 150 i = stathz ? stathz : hz; 151 if (profhz == 0) 152 profhz = i; 153 psratio = profhz / i; 154 155 /* For very large HZ, ensure that division by 0 does not occur later */ 156 if (tickadj == 0) 157 tickadj = 1; 158 159 #ifdef __HAVE_TIMECOUNTER 160 inittimecounter(); 161 #endif 162 } 163 164 /* 165 * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL. 166 * We don't want to send signals with psignal from hardclock because it makes 167 * MULTIPROCESSOR locking very complicated. Instead we use a small trick 168 * to send the signals safely and without blocking too many interrupts 169 * while doing that (signal handling can be heavy). 170 * 171 * hardclock detects that the itimer has expired, and schedules a timeout 172 * to deliver the signal. This works because of the following reasons: 173 * - The timeout structures can be in struct pstats because the timers 174 * can be only activated on curproc (never swapped). Swapout can 175 * only happen from a kernel thread and softclock runs before threads 176 * are scheduled. 177 * - The timeout can be scheduled with a 1 tick time because we're 178 * doing it before the timeout processing in hardclock. So it will 179 * be scheduled to run as soon as possible. 180 * - The timeout will be run in softclock which will run before we 181 * return to userland and process pending signals. 182 * - If the system is so busy that several VIRTUAL/PROF ticks are 183 * sent before softclock processing, we'll send only one signal. 184 * But if we'd send the signal from hardclock only one signal would 185 * be delivered to the user process. So userland will only see one 186 * signal anyway. 187 */ 188 189 void 190 virttimer_trampoline(void *v) 191 { 192 struct proc *p = v; 193 194 psignal(p, SIGVTALRM); 195 } 196 197 void 198 proftimer_trampoline(void *v) 199 { 200 struct proc *p = v; 201 202 psignal(p, SIGPROF); 203 } 204 205 /* 206 * The real-time timer, interrupting hz times per second. 207 */ 208 void 209 hardclock(struct clockframe *frame) 210 { 211 struct proc *p; 212 #ifndef __HAVE_TIMECOUNTER 213 int delta; 214 extern int tickdelta; 215 extern long timedelta; 216 extern int64_t ntp_tick_permanent; 217 extern int64_t ntp_tick_acc; 218 #endif 219 struct cpu_info *ci = curcpu(); 220 221 p = curproc; 222 if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) { 223 struct pstats *pstats; 224 225 /* 226 * Run current process's virtual and profile time, as needed. 227 */ 228 pstats = p->p_stats; 229 if (CLKF_USERMODE(frame) && 230 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 231 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 232 timeout_add(&pstats->p_virt_to, 1); 233 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 234 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 235 timeout_add(&pstats->p_prof_to, 1); 236 } 237 238 /* 239 * If no separate statistics clock is available, run it from here. 240 */ 241 if (stathz == 0) 242 statclock(frame); 243 244 if (--ci->ci_schedstate.spc_rrticks <= 0) 245 roundrobin(ci); 246 247 /* 248 * If we are not the primary CPU, we're not allowed to do 249 * any more work. 250 */ 251 if (CPU_IS_PRIMARY(ci) == 0) 252 return; 253 254 #ifndef __HAVE_TIMECOUNTER 255 /* 256 * Increment the time-of-day. The increment is normally just 257 * ``tick''. If the machine is one which has a clock frequency 258 * such that ``hz'' would not divide the second evenly into 259 * milliseconds, a periodic adjustment must be applied. Finally, 260 * if we are still adjusting the time (see adjtime()), 261 * ``tickdelta'' may also be added in. 262 */ 263 264 delta = tick; 265 266 if (tickfix) { 267 tickfixcnt += tickfix; 268 if (tickfixcnt >= tickfixinterval) { 269 delta++; 270 tickfixcnt -= tickfixinterval; 271 } 272 } 273 /* Imprecise 4bsd adjtime() handling */ 274 if (timedelta != 0) { 275 delta += tickdelta; 276 timedelta -= tickdelta; 277 } 278 279 /* 280 * ntp_tick_permanent accumulates the clock correction each 281 * tick. The unit is ns per tick shifted left 32 bits. If we have 282 * accumulated more than 1us, we bump delta in the right 283 * direction. Use a loop to avoid long long div; typically 284 * the loops will be executed 0 or 1 iteration. 285 */ 286 if (ntp_tick_permanent != 0) { 287 ntp_tick_acc += ntp_tick_permanent; 288 while (ntp_tick_acc >= (1000LL << 32)) { 289 delta++; 290 ntp_tick_acc -= (1000LL << 32); 291 } 292 while (ntp_tick_acc <= -(1000LL << 32)) { 293 delta--; 294 ntp_tick_acc += (1000LL << 32); 295 } 296 } 297 298 BUMPTIME(&time, delta); 299 BUMPTIME(&mono_time, delta); 300 time_second = time.tv_sec; 301 time_uptime = mono_time.tv_sec; 302 #else 303 tc_ticktock(); 304 #endif 305 306 /* 307 * Update real-time timeout queue. 308 * Process callouts at a very low cpu priority, so we don't keep the 309 * relatively high clock interrupt priority any longer than necessary. 310 */ 311 if (timeout_hardclock_update()) 312 softintr_schedule(softclock_si); 313 } 314 315 /* 316 * Compute number of hz until specified time. Used to 317 * compute the second argument to timeout_add() from an absolute time. 318 */ 319 int 320 hzto(struct timeval *tv) 321 { 322 struct timeval now; 323 unsigned long ticks; 324 long sec, usec; 325 326 /* 327 * If the number of usecs in the whole seconds part of the time 328 * difference fits in a long, then the total number of usecs will 329 * fit in an unsigned long. Compute the total and convert it to 330 * ticks, rounding up and adding 1 to allow for the current tick 331 * to expire. Rounding also depends on unsigned long arithmetic 332 * to avoid overflow. 333 * 334 * Otherwise, if the number of ticks in the whole seconds part of 335 * the time difference fits in a long, then convert the parts to 336 * ticks separately and add, using similar rounding methods and 337 * overflow avoidance. This method would work in the previous 338 * case but it is slightly slower and assumes that hz is integral. 339 * 340 * Otherwise, round the time difference down to the maximum 341 * representable value. 342 * 343 * If ints have 32 bits, then the maximum value for any timeout in 344 * 10ms ticks is 248 days. 345 */ 346 getmicrotime(&now); 347 sec = tv->tv_sec - now.tv_sec; 348 usec = tv->tv_usec - now.tv_usec; 349 if (usec < 0) { 350 sec--; 351 usec += 1000000; 352 } 353 if (sec < 0 || (sec == 0 && usec <= 0)) { 354 ticks = 0; 355 } else if (sec <= LONG_MAX / 1000000) 356 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 357 / tick + 1; 358 else if (sec <= LONG_MAX / hz) 359 ticks = sec * hz 360 + ((unsigned long)usec + (tick - 1)) / tick + 1; 361 else 362 ticks = LONG_MAX; 363 if (ticks > INT_MAX) 364 ticks = INT_MAX; 365 return ((int)ticks); 366 } 367 368 /* 369 * Compute number of hz in the specified amount of time. 370 */ 371 int 372 tvtohz(struct timeval *tv) 373 { 374 unsigned long ticks; 375 long sec, usec; 376 377 /* 378 * If the number of usecs in the whole seconds part of the time 379 * fits in a long, then the total number of usecs will 380 * fit in an unsigned long. Compute the total and convert it to 381 * ticks, rounding up and adding 1 to allow for the current tick 382 * to expire. Rounding also depends on unsigned long arithmetic 383 * to avoid overflow. 384 * 385 * Otherwise, if the number of ticks in the whole seconds part of 386 * the time fits in a long, then convert the parts to 387 * ticks separately and add, using similar rounding methods and 388 * overflow avoidance. This method would work in the previous 389 * case but it is slightly slower and assumes that hz is integral. 390 * 391 * Otherwise, round the time down to the maximum 392 * representable value. 393 * 394 * If ints have 32 bits, then the maximum value for any timeout in 395 * 10ms ticks is 248 days. 396 */ 397 sec = tv->tv_sec; 398 usec = tv->tv_usec; 399 if (sec < 0 || (sec == 0 && usec <= 0)) 400 ticks = 0; 401 else if (sec <= LONG_MAX / 1000000) 402 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 403 / tick + 1; 404 else if (sec <= LONG_MAX / hz) 405 ticks = sec * hz 406 + ((unsigned long)usec + (tick - 1)) / tick + 1; 407 else 408 ticks = LONG_MAX; 409 if (ticks > INT_MAX) 410 ticks = INT_MAX; 411 return ((int)ticks); 412 } 413 414 /* 415 * Start profiling on a process. 416 * 417 * Kernel profiling passes proc0 which never exits and hence 418 * keeps the profile clock running constantly. 419 */ 420 void 421 startprofclock(struct proc *p) 422 { 423 int s; 424 425 if ((p->p_flag & P_PROFIL) == 0) { 426 atomic_setbits_int(&p->p_flag, P_PROFIL); 427 if (++profprocs == 1 && stathz != 0) { 428 s = splstatclock(); 429 psdiv = pscnt = psratio; 430 setstatclockrate(profhz); 431 splx(s); 432 } 433 } 434 } 435 436 /* 437 * Stop profiling on a process. 438 */ 439 void 440 stopprofclock(struct proc *p) 441 { 442 int s; 443 444 if (p->p_flag & P_PROFIL) { 445 atomic_clearbits_int(&p->p_flag, P_PROFIL); 446 if (--profprocs == 0 && stathz != 0) { 447 s = splstatclock(); 448 psdiv = pscnt = 1; 449 setstatclockrate(stathz); 450 splx(s); 451 } 452 } 453 } 454 455 /* 456 * Statistics clock. Grab profile sample, and if divider reaches 0, 457 * do process and kernel statistics. 458 */ 459 void 460 statclock(struct clockframe *frame) 461 { 462 #ifdef GPROF 463 struct gmonparam *g; 464 u_long i; 465 #endif 466 struct cpu_info *ci = curcpu(); 467 struct schedstate_percpu *spc = &ci->ci_schedstate; 468 struct proc *p = curproc; 469 470 /* 471 * Notice changes in divisor frequency, and adjust clock 472 * frequency accordingly. 473 */ 474 if (spc->spc_psdiv != psdiv) { 475 spc->spc_psdiv = psdiv; 476 spc->spc_pscnt = psdiv; 477 if (psdiv == 1) { 478 setstatclockrate(stathz); 479 } else { 480 setstatclockrate(profhz); 481 } 482 } 483 484 if (CLKF_USERMODE(frame)) { 485 if (p->p_flag & P_PROFIL) 486 addupc_intr(p, CLKF_PC(frame)); 487 if (--spc->spc_pscnt > 0) 488 return; 489 /* 490 * Came from user mode; CPU was in user state. 491 * If this process is being profiled record the tick. 492 */ 493 p->p_uticks++; 494 if (p->p_nice > NZERO) 495 spc->spc_cp_time[CP_NICE]++; 496 else 497 spc->spc_cp_time[CP_USER]++; 498 } else { 499 #ifdef GPROF 500 /* 501 * Kernel statistics are just like addupc_intr, only easier. 502 */ 503 g = &_gmonparam; 504 if (g->state == GMON_PROF_ON) { 505 i = CLKF_PC(frame) - g->lowpc; 506 if (i < g->textsize) { 507 i /= HISTFRACTION * sizeof(*g->kcount); 508 g->kcount[i]++; 509 } 510 } 511 #endif 512 #if defined(PROC_PC) 513 if (p != NULL && p->p_flag & P_PROFIL) 514 addupc_intr(p, PROC_PC(p)); 515 #endif 516 if (--spc->spc_pscnt > 0) 517 return; 518 /* 519 * Came from kernel mode, so we were: 520 * - handling an interrupt, 521 * - doing syscall or trap work on behalf of the current 522 * user process, or 523 * - spinning in the idle loop. 524 * Whichever it is, charge the time as appropriate. 525 * Note that we charge interrupts to the current process, 526 * regardless of whether they are ``for'' that process, 527 * so that we know how much of its real time was spent 528 * in ``non-process'' (i.e., interrupt) work. 529 */ 530 if (CLKF_INTR(frame)) { 531 if (p != NULL) 532 p->p_iticks++; 533 spc->spc_cp_time[CP_INTR]++; 534 } else if (p != NULL && p != spc->spc_idleproc) { 535 p->p_sticks++; 536 spc->spc_cp_time[CP_SYS]++; 537 } else 538 spc->spc_cp_time[CP_IDLE]++; 539 } 540 spc->spc_pscnt = psdiv; 541 542 if (p != NULL) { 543 p->p_cpticks++; 544 /* 545 * If no schedclock is provided, call it here at ~~12-25 Hz; 546 * ~~16 Hz is best 547 */ 548 if (schedhz == 0) { 549 if ((++curcpu()->ci_schedstate.spc_schedticks & 3) == 550 0) 551 schedclock(p); 552 } 553 } 554 } 555 556 /* 557 * Return information about system clocks. 558 */ 559 int 560 sysctl_clockrate(char *where, size_t *sizep, void *newp) 561 { 562 struct clockinfo clkinfo; 563 564 /* 565 * Construct clockinfo structure. 566 */ 567 clkinfo.tick = tick; 568 clkinfo.tickadj = tickadj; 569 clkinfo.hz = hz; 570 clkinfo.profhz = profhz; 571 clkinfo.stathz = stathz ? stathz : hz; 572 return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo))); 573 } 574 575 #ifndef __HAVE_TIMECOUNTER 576 /* 577 * Placeholders until everyone uses the timecounters code. 578 * Won't improve anything except maybe removing a bunch of bugs in fixed code. 579 */ 580 581 void 582 getmicrotime(struct timeval *tvp) 583 { 584 int s; 585 586 s = splhigh(); 587 *tvp = time; 588 splx(s); 589 } 590 591 void 592 nanotime(struct timespec *tsp) 593 { 594 struct timeval tv; 595 596 microtime(&tv); 597 TIMEVAL_TO_TIMESPEC(&tv, tsp); 598 } 599 600 void 601 getnanotime(struct timespec *tsp) 602 { 603 struct timeval tv; 604 605 getmicrotime(&tv); 606 TIMEVAL_TO_TIMESPEC(&tv, tsp); 607 } 608 609 void 610 nanouptime(struct timespec *tsp) 611 { 612 struct timeval tv; 613 614 microuptime(&tv); 615 TIMEVAL_TO_TIMESPEC(&tv, tsp); 616 } 617 618 619 void 620 getnanouptime(struct timespec *tsp) 621 { 622 struct timeval tv; 623 624 getmicrouptime(&tv); 625 TIMEVAL_TO_TIMESPEC(&tv, tsp); 626 } 627 628 void 629 microuptime(struct timeval *tvp) 630 { 631 struct timeval tv; 632 633 microtime(&tv); 634 timersub(&tv, &boottime, tvp); 635 } 636 637 void 638 getmicrouptime(struct timeval *tvp) 639 { 640 int s; 641 642 s = splhigh(); 643 *tvp = mono_time; 644 splx(s); 645 } 646 #endif /* __HAVE_TIMECOUNTER */ 647