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