1 /* $OpenBSD: kern_clock.c,v 1.60 2006/12/24 20:29:45 miod 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 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 124 void *softclock_si; 125 void generic_softclock(void *); 126 127 void 128 generic_softclock(void *ignore) 129 { 130 /* 131 * XXX - don't commit, just a dummy wrapper until we learn everyone 132 * deal with a changed proto for softclock(). 133 */ 134 softclock(); 135 } 136 #endif 137 138 /* 139 * Initialize clock frequencies and start both clocks running. 140 */ 141 void 142 initclocks(void) 143 { 144 int i; 145 #ifdef __HAVE_TIMECOUNTER 146 extern void inittimecounter(void); 147 #endif 148 149 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 150 softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL); 151 if (softclock_si == NULL) 152 panic("initclocks: unable to register softclock intr"); 153 #endif 154 155 /* 156 * Set divisors to 1 (normal case) and let the machine-specific 157 * code do its bit. 158 */ 159 psdiv = pscnt = 1; 160 cpu_initclocks(); 161 162 /* 163 * Compute profhz/stathz, and fix profhz if needed. 164 */ 165 i = stathz ? stathz : hz; 166 if (profhz == 0) 167 profhz = i; 168 psratio = profhz / i; 169 #ifdef __HAVE_TIMECOUNTER 170 inittimecounter(); 171 #endif 172 } 173 174 /* 175 * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL. 176 * We don't want to send signals with psignal from hardclock because it makes 177 * MULTIPROCESSOR locking very complicated. Instead we use a small trick 178 * to send the signals safely and without blocking too many interrupts 179 * while doing that (signal handling can be heavy). 180 * 181 * hardclock detects that the itimer has expired, and schedules a timeout 182 * to deliver the signal. This works because of the following reasons: 183 * - The timeout structures can be in struct pstats because the timers 184 * can be only activated on curproc (never swapped). Swapout can 185 * only happen from a kernel thread and softclock runs before threads 186 * are scheduled. 187 * - The timeout can be scheduled with a 1 tick time because we're 188 * doing it before the timeout processing in hardclock. So it will 189 * be scheduled to run as soon as possible. 190 * - The timeout will be run in softclock which will run before we 191 * return to userland and process pending signals. 192 * - If the system is so busy that several VIRTUAL/PROF ticks are 193 * sent before softclock processing, we'll send only one signal. 194 * But if we'd send the signal from hardclock only one signal would 195 * be delivered to the user process. So userland will only see one 196 * signal anyway. 197 */ 198 199 void 200 virttimer_trampoline(void *v) 201 { 202 struct proc *p = v; 203 204 psignal(p, SIGVTALRM); 205 } 206 207 void 208 proftimer_trampoline(void *v) 209 { 210 struct proc *p = v; 211 212 psignal(p, SIGPROF); 213 } 214 215 /* 216 * The real-time timer, interrupting hz times per second. 217 */ 218 void 219 hardclock(struct clockframe *frame) 220 { 221 struct proc *p; 222 #ifndef __HAVE_TIMECOUNTER 223 int delta; 224 extern int tickdelta; 225 extern long timedelta; 226 extern int64_t ntp_tick_permanent; 227 extern int64_t ntp_tick_acc; 228 #endif 229 #ifdef __HAVE_CPUINFO 230 struct cpu_info *ci = curcpu(); 231 #endif 232 233 p = curproc; 234 if (p && ((p->p_flag & P_WEXIT) == 0)) { 235 struct pstats *pstats; 236 237 /* 238 * Run current process's virtual and profile time, as needed. 239 */ 240 pstats = p->p_stats; 241 if (CLKF_USERMODE(frame) && 242 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 243 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 244 timeout_add(&pstats->p_virt_to, 1); 245 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 246 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 247 timeout_add(&pstats->p_prof_to, 1); 248 } 249 250 /* 251 * If no separate statistics clock is available, run it from here. 252 */ 253 if (stathz == 0) 254 statclock(frame); 255 256 #if defined(__HAVE_CPUINFO) 257 if (--ci->ci_schedstate.spc_rrticks <= 0) 258 roundrobin(ci); 259 260 /* 261 * If we are not the primary CPU, we're not allowed to do 262 * any more work. 263 */ 264 if (CPU_IS_PRIMARY(ci) == 0) 265 return; 266 #endif 267 268 #ifndef __HAVE_TIMECOUNTER 269 /* 270 * Increment the time-of-day. The increment is normally just 271 * ``tick''. If the machine is one which has a clock frequency 272 * such that ``hz'' would not divide the second evenly into 273 * milliseconds, a periodic adjustment must be applied. Finally, 274 * if we are still adjusting the time (see adjtime()), 275 * ``tickdelta'' may also be added in. 276 */ 277 278 delta = tick; 279 280 if (tickfix) { 281 tickfixcnt += tickfix; 282 if (tickfixcnt >= tickfixinterval) { 283 delta++; 284 tickfixcnt -= tickfixinterval; 285 } 286 } 287 /* Imprecise 4bsd adjtime() handling */ 288 if (timedelta != 0) { 289 delta += tickdelta; 290 timedelta -= tickdelta; 291 } 292 293 /* 294 * ntp_tick_permanent accumulates the clock correction each 295 * tick. The unit is ns per tick shifted left 32 bits. If we have 296 * accumulated more than 1us, we bump delta in the right 297 * direction. Use a loop to avoid long long div; typicallly 298 * the loops will be executed 0 or 1 iteration. 299 */ 300 if (ntp_tick_permanent != 0) { 301 ntp_tick_acc += ntp_tick_permanent; 302 while (ntp_tick_acc >= (1000LL << 32)) { 303 delta++; 304 ntp_tick_acc -= (1000LL << 32); 305 } 306 while (ntp_tick_acc <= -(1000LL << 32)) { 307 delta--; 308 ntp_tick_acc += (1000LL << 32); 309 } 310 } 311 312 BUMPTIME(&time, delta); 313 BUMPTIME(&mono_time, delta); 314 time_second = time.tv_sec; 315 time_uptime = mono_time.tv_sec; 316 #else 317 tc_ticktock(); 318 #endif 319 320 #ifdef CPU_CLOCKUPDATE 321 CPU_CLOCKUPDATE(); 322 #endif 323 324 /* 325 * Update real-time timeout queue. 326 * Process callouts at a very low cpu priority, so we don't keep the 327 * relatively high clock interrupt priority any longer than necessary. 328 */ 329 if (timeout_hardclock_update()) { 330 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 331 softintr_schedule(softclock_si); 332 #else 333 setsoftclock(); 334 #endif 335 } 336 } 337 338 /* 339 * Compute number of hz until specified time. Used to 340 * compute the second argument to timeout_add() from an absolute time. 341 */ 342 int 343 hzto(struct timeval *tv) 344 { 345 struct timeval now; 346 unsigned long ticks; 347 long sec, usec; 348 349 /* 350 * If the number of usecs in the whole seconds part of the time 351 * difference fits in a long, then the total number of usecs will 352 * fit in an unsigned long. Compute the total and convert it to 353 * ticks, rounding up and adding 1 to allow for the current tick 354 * to expire. Rounding also depends on unsigned long arithmetic 355 * to avoid overflow. 356 * 357 * Otherwise, if the number of ticks in the whole seconds part of 358 * the time difference fits in a long, then convert the parts to 359 * ticks separately and add, using similar rounding methods and 360 * overflow avoidance. This method would work in the previous 361 * case but it is slightly slower and assumes that hz is integral. 362 * 363 * Otherwise, round the time difference down to the maximum 364 * representable value. 365 * 366 * If ints have 32 bits, then the maximum value for any timeout in 367 * 10ms ticks is 248 days. 368 */ 369 getmicrotime(&now); 370 sec = tv->tv_sec - now.tv_sec; 371 usec = tv->tv_usec - now.tv_usec; 372 if (usec < 0) { 373 sec--; 374 usec += 1000000; 375 } 376 if (sec < 0 || (sec == 0 && usec <= 0)) { 377 ticks = 0; 378 } else if (sec <= LONG_MAX / 1000000) 379 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 380 / tick + 1; 381 else if (sec <= LONG_MAX / hz) 382 ticks = sec * hz 383 + ((unsigned long)usec + (tick - 1)) / tick + 1; 384 else 385 ticks = LONG_MAX; 386 if (ticks > INT_MAX) 387 ticks = INT_MAX; 388 return ((int)ticks); 389 } 390 391 /* 392 * Compute number of hz in the specified amount of time. 393 */ 394 int 395 tvtohz(struct timeval *tv) 396 { 397 unsigned long ticks; 398 long sec, usec; 399 400 /* 401 * If the number of usecs in the whole seconds part of the time 402 * fits in a long, then the total number of usecs will 403 * fit in an unsigned long. Compute the total and convert it to 404 * ticks, rounding up and adding 1 to allow for the current tick 405 * to expire. Rounding also depends on unsigned long arithmetic 406 * to avoid overflow. 407 * 408 * Otherwise, if the number of ticks in the whole seconds part of 409 * the time fits in a long, then convert the parts to 410 * ticks separately and add, using similar rounding methods and 411 * overflow avoidance. This method would work in the previous 412 * case but it is slightly slower and assumes that hz is integral. 413 * 414 * Otherwise, round the time down to the maximum 415 * representable value. 416 * 417 * If ints have 32 bits, then the maximum value for any timeout in 418 * 10ms ticks is 248 days. 419 */ 420 sec = tv->tv_sec; 421 usec = tv->tv_usec; 422 if (sec < 0 || (sec == 0 && usec <= 0)) 423 ticks = 0; 424 else if (sec <= LONG_MAX / 1000000) 425 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 426 / tick + 1; 427 else if (sec <= LONG_MAX / hz) 428 ticks = sec * hz 429 + ((unsigned long)usec + (tick - 1)) / tick + 1; 430 else 431 ticks = LONG_MAX; 432 if (ticks > INT_MAX) 433 ticks = INT_MAX; 434 return ((int)ticks); 435 } 436 437 /* 438 * Start profiling on a process. 439 * 440 * Kernel profiling passes proc0 which never exits and hence 441 * keeps the profile clock running constantly. 442 */ 443 void 444 startprofclock(struct proc *p) 445 { 446 int s; 447 448 if ((p->p_flag & P_PROFIL) == 0) { 449 p->p_flag |= P_PROFIL; 450 if (++profprocs == 1 && stathz != 0) { 451 s = splstatclock(); 452 psdiv = pscnt = psratio; 453 setstatclockrate(profhz); 454 splx(s); 455 } 456 } 457 } 458 459 /* 460 * Stop profiling on a process. 461 */ 462 void 463 stopprofclock(struct proc *p) 464 { 465 int s; 466 467 if (p->p_flag & P_PROFIL) { 468 p->p_flag &= ~P_PROFIL; 469 if (--profprocs == 0 && stathz != 0) { 470 s = splstatclock(); 471 psdiv = pscnt = 1; 472 setstatclockrate(stathz); 473 splx(s); 474 } 475 } 476 } 477 478 /* 479 * Statistics clock. Grab profile sample, and if divider reaches 0, 480 * do process and kernel statistics. 481 */ 482 void 483 statclock(struct clockframe *frame) 484 { 485 #ifdef GPROF 486 struct gmonparam *g; 487 int i; 488 #endif 489 #ifdef __HAVE_CPUINFO 490 struct cpu_info *ci = curcpu(); 491 struct schedstate_percpu *spc = &ci->ci_schedstate; 492 #else 493 static int schedclk; 494 #endif 495 struct proc *p = curproc; 496 497 #ifdef __HAVE_CPUINFO 498 /* 499 * Notice changes in divisor frequency, and adjust clock 500 * frequency accordingly. 501 */ 502 if (spc->spc_psdiv != psdiv) { 503 spc->spc_psdiv = psdiv; 504 spc->spc_pscnt = psdiv; 505 if (psdiv == 1) { 506 setstatclockrate(stathz); 507 } else { 508 setstatclockrate(profhz); 509 } 510 } 511 512 /* XXX Kludgey */ 513 #define pscnt spc->spc_pscnt 514 #define cp_time spc->spc_cp_time 515 #endif 516 517 if (CLKF_USERMODE(frame)) { 518 if (p->p_flag & P_PROFIL) 519 addupc_intr(p, CLKF_PC(frame)); 520 if (--pscnt > 0) 521 return; 522 /* 523 * Came from user mode; CPU was in user state. 524 * If this process is being profiled record the tick. 525 */ 526 p->p_uticks++; 527 if (p->p_nice > NZERO) 528 cp_time[CP_NICE]++; 529 else 530 cp_time[CP_USER]++; 531 } else { 532 #ifdef GPROF 533 /* 534 * Kernel statistics are just like addupc_intr, only easier. 535 */ 536 g = &_gmonparam; 537 if (g->state == GMON_PROF_ON) { 538 i = CLKF_PC(frame) - g->lowpc; 539 if (i < g->textsize) { 540 i /= HISTFRACTION * sizeof(*g->kcount); 541 g->kcount[i]++; 542 } 543 } 544 #endif 545 #if defined(PROC_PC) 546 if (p != NULL && p->p_flag & P_PROFIL) 547 addupc_intr(p, PROC_PC(p)); 548 #endif 549 if (--pscnt > 0) 550 return; 551 /* 552 * Came from kernel mode, so we were: 553 * - handling an interrupt, 554 * - doing syscall or trap work on behalf of the current 555 * user process, or 556 * - spinning in the idle loop. 557 * Whichever it is, charge the time as appropriate. 558 * Note that we charge interrupts to the current process, 559 * regardless of whether they are ``for'' that process, 560 * so that we know how much of its real time was spent 561 * in ``non-process'' (i.e., interrupt) work. 562 */ 563 if (CLKF_INTR(frame)) { 564 if (p != NULL) 565 p->p_iticks++; 566 cp_time[CP_INTR]++; 567 } else if (p != NULL) { 568 p->p_sticks++; 569 cp_time[CP_SYS]++; 570 } else 571 cp_time[CP_IDLE]++; 572 } 573 pscnt = psdiv; 574 575 #ifdef __HAVE_CPUINFO 576 #undef pscnt 577 #undef cp_time 578 #endif 579 580 if (p != NULL) { 581 p->p_cpticks++; 582 /* 583 * If no schedclock is provided, call it here at ~~12-25 Hz; 584 * ~~16 Hz is best 585 */ 586 if (schedhz == 0) { 587 #ifdef __HAVE_CPUINFO 588 if ((++curcpu()->ci_schedstate.spc_schedticks & 3) == 589 0) 590 schedclock(p); 591 #else 592 if ((++schedclk & 3) == 0) 593 schedclock(p); 594 #endif 595 } 596 } 597 } 598 599 /* 600 * Return information about system clocks. 601 */ 602 int 603 sysctl_clockrate(char *where, size_t *sizep) 604 { 605 struct clockinfo clkinfo; 606 607 /* 608 * Construct clockinfo structure. 609 */ 610 clkinfo.tick = tick; 611 clkinfo.tickadj = tickadj; 612 clkinfo.hz = hz; 613 clkinfo.profhz = profhz; 614 clkinfo.stathz = stathz ? stathz : hz; 615 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo))); 616 } 617 618 #ifndef __HAVE_TIMECOUNTER 619 /* 620 * Placeholders until everyone uses the timecounters code. 621 * Won't improve anything except maybe removing a bunch of bugs in fixed code. 622 */ 623 624 void 625 getmicrotime(struct timeval *tvp) 626 { 627 int s; 628 629 s = splhigh(); 630 *tvp = time; 631 splx(s); 632 } 633 634 void 635 nanotime(struct timespec *tsp) 636 { 637 struct timeval tv; 638 639 microtime(&tv); 640 TIMEVAL_TO_TIMESPEC(&tv, tsp); 641 } 642 643 void 644 getnanotime(struct timespec *tsp) 645 { 646 struct timeval tv; 647 648 getmicrotime(&tv); 649 TIMEVAL_TO_TIMESPEC(&tv, tsp); 650 } 651 652 void 653 nanouptime(struct timespec *tsp) 654 { 655 struct timeval tv; 656 657 microuptime(&tv); 658 TIMEVAL_TO_TIMESPEC(&tv, tsp); 659 } 660 661 662 void 663 getnanouptime(struct timespec *tsp) 664 { 665 struct timeval tv; 666 667 getmicrouptime(&tv); 668 TIMEVAL_TO_TIMESPEC(&tv, tsp); 669 } 670 671 void 672 microuptime(struct timeval *tvp) 673 { 674 struct timeval tv; 675 676 microtime(&tv); 677 timersub(&tv, &boottime, tvp); 678 } 679 680 void 681 getmicrouptime(struct timeval *tvp) 682 { 683 int s; 684 685 s = splhigh(); 686 *tvp = mono_time; 687 splx(s); 688 } 689 #endif /* __HAVE_TIMECOUNTER */ 690