1 /* $OpenBSD: kern_clock.c,v 1.31 2002/01/02 06:07:41 nordin 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. All advertising materials mentioning features or use of this software 22 * must display the following acknowledgement: 23 * This product includes software developed by the University of 24 * California, Berkeley and its contributors. 25 * 4. Neither the name of the University nor the names of its contributors 26 * may be used to endorse or promote products derived from this software 27 * without specific prior written permission. 28 * 29 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 30 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 31 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 32 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 33 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 35 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 36 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 37 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 38 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 39 * SUCH DAMAGE. 40 * 41 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94 42 */ 43 44 #include <sys/param.h> 45 #include <sys/systm.h> 46 #include <sys/dkstat.h> 47 #include <sys/timeout.h> 48 #include <sys/kernel.h> 49 #include <sys/proc.h> 50 #include <sys/resourcevar.h> 51 #include <sys/signalvar.h> 52 #include <uvm/uvm_extern.h> 53 #include <sys/sysctl.h> 54 #include <sys/timex.h> 55 #include <sys/sched.h> 56 57 #include <machine/cpu.h> 58 #include <machine/limits.h> 59 60 #ifdef GPROF 61 #include <sys/gmon.h> 62 #endif 63 64 /* 65 * Clock handling routines. 66 * 67 * This code is written to operate with two timers that run independently of 68 * each other. The main clock, running hz times per second, is used to keep 69 * track of real time. The second timer handles kernel and user profiling, 70 * and does resource use estimation. If the second timer is programmable, 71 * it is randomized to avoid aliasing between the two clocks. For example, 72 * the randomization prevents an adversary from always giving up the cpu 73 * just before its quantum expires. Otherwise, it would never accumulate 74 * cpu ticks. The mean frequency of the second timer is stathz. 75 * 76 * If no second timer exists, stathz will be zero; in this case we drive 77 * profiling and statistics off the main clock. This WILL NOT be accurate; 78 * do not do it unless absolutely necessary. 79 * 80 * The statistics clock may (or may not) be run at a higher rate while 81 * profiling. This profile clock runs at profhz. We require that profhz 82 * be an integral multiple of stathz. 83 * 84 * If the statistics clock is running fast, it must be divided by the ratio 85 * profhz/stathz for statistics. (For profiling, every tick counts.) 86 */ 87 88 #ifdef NTP /* NTP phase-locked loop in kernel */ 89 /* 90 * Phase/frequency-lock loop (PLL/FLL) definitions 91 * 92 * The following variables are read and set by the ntp_adjtime() system 93 * call. 94 * 95 * time_state shows the state of the system clock, with values defined 96 * in the timex.h header file. 97 * 98 * time_status shows the status of the system clock, with bits defined 99 * in the timex.h header file. 100 * 101 * time_offset is used by the PLL/FLL to adjust the system time in small 102 * increments. 103 * 104 * time_constant determines the bandwidth or "stiffness" of the PLL. 105 * 106 * time_tolerance determines maximum frequency error or tolerance of the 107 * CPU clock oscillator and is a property of the architecture; however, 108 * in principle it could change as result of the presence of external 109 * discipline signals, for instance. 110 * 111 * time_precision is usually equal to the kernel tick variable; however, 112 * in cases where a precision clock counter or external clock is 113 * available, the resolution can be much less than this and depend on 114 * whether the external clock is working or not. 115 * 116 * time_maxerror is initialized by a ntp_adjtime() call and increased by 117 * the kernel once each second to reflect the maximum error bound 118 * growth. 119 * 120 * time_esterror is set and read by the ntp_adjtime() call, but 121 * otherwise not used by the kernel. 122 */ 123 int time_state = TIME_OK; /* clock state */ 124 int time_status = STA_UNSYNC; /* clock status bits */ 125 long time_offset = 0; /* time offset (us) */ 126 long time_constant = 0; /* pll time constant */ 127 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */ 128 long time_precision; /* clock precision (us) */ 129 long time_maxerror = MAXPHASE; /* maximum error (us) */ 130 long time_esterror = MAXPHASE; /* estimated error (us) */ 131 132 /* 133 * The following variables establish the state of the PLL/FLL and the 134 * residual time and frequency offset of the local clock. The scale 135 * factors are defined in the timex.h header file. 136 * 137 * time_phase and time_freq are the phase increment and the frequency 138 * increment, respectively, of the kernel time variable. 139 * 140 * time_freq is set via ntp_adjtime() from a value stored in a file when 141 * the synchronization daemon is first started. Its value is retrieved 142 * via ntp_adjtime() and written to the file about once per hour by the 143 * daemon. 144 * 145 * time_adj is the adjustment added to the value of tick at each timer 146 * interrupt and is recomputed from time_phase and time_freq at each 147 * seconds rollover. 148 * 149 * time_reftime is the second's portion of the system time at the last 150 * call to ntp_adjtime(). It is used to adjust the time_freq variable 151 * and to increase the time_maxerror as the time since last update 152 * increases. 153 */ 154 long time_phase = 0; /* phase offset (scaled us) */ 155 long time_freq = 0; /* frequency offset (scaled ppm) */ 156 long time_adj = 0; /* tick adjust (scaled 1 / hz) */ 157 long time_reftime = 0; /* time at last adjustment (s) */ 158 159 #ifdef PPS_SYNC 160 /* 161 * The following variables are used only if the kernel PPS discipline 162 * code is configured (PPS_SYNC). The scale factors are defined in the 163 * timex.h header file. 164 * 165 * pps_time contains the time at each calibration interval, as read by 166 * microtime(). pps_count counts the seconds of the calibration 167 * interval, the duration of which is nominally pps_shift in powers of 168 * two. 169 * 170 * pps_offset is the time offset produced by the time median filter 171 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by 172 * this filter. 173 * 174 * pps_freq is the frequency offset produced by the frequency median 175 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured 176 * by this filter. 177 * 178 * pps_usec is latched from a high resolution counter or external clock 179 * at pps_time. Here we want the hardware counter contents only, not the 180 * contents plus the time_tv.usec as usual. 181 * 182 * pps_valid counts the number of seconds since the last PPS update. It 183 * is used as a watchdog timer to disable the PPS discipline should the 184 * PPS signal be lost. 185 * 186 * pps_glitch counts the number of seconds since the beginning of an 187 * offset burst more than tick/2 from current nominal offset. It is used 188 * mainly to suppress error bursts due to priority conflicts between the 189 * PPS interrupt and timer interrupt. 190 * 191 * pps_intcnt counts the calibration intervals for use in the interval- 192 * adaptation algorithm. It's just too complicated for words. 193 */ 194 struct timeval pps_time; /* kernel time at last interval */ 195 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */ 196 long pps_offset = 0; /* pps time offset (us) */ 197 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */ 198 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */ 199 long pps_freq = 0; /* frequency offset (scaled ppm) */ 200 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */ 201 long pps_usec = 0; /* microsec counter at last interval */ 202 long pps_valid = PPS_VALID; /* pps signal watchdog counter */ 203 int pps_glitch = 0; /* pps signal glitch counter */ 204 int pps_count = 0; /* calibration interval counter (s) */ 205 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */ 206 int pps_intcnt = 0; /* intervals at current duration */ 207 208 /* 209 * PPS signal quality monitors 210 * 211 * pps_jitcnt counts the seconds that have been discarded because the 212 * jitter measured by the time median filter exceeds the limit MAXTIME 213 * (100 us). 214 * 215 * pps_calcnt counts the frequency calibration intervals, which are 216 * variable from 4 s to 256 s. 217 * 218 * pps_errcnt counts the calibration intervals which have been discarded 219 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the 220 * calibration interval jitter exceeds two ticks. 221 * 222 * pps_stbcnt counts the calibration intervals that have been discarded 223 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us). 224 */ 225 long pps_jitcnt = 0; /* jitter limit exceeded */ 226 long pps_calcnt = 0; /* calibration intervals */ 227 long pps_errcnt = 0; /* calibration errors */ 228 long pps_stbcnt = 0; /* stability limit exceeded */ 229 #endif /* PPS_SYNC */ 230 231 #ifdef EXT_CLOCK 232 /* 233 * External clock definitions 234 * 235 * The following definitions and declarations are used only if an 236 * external clock is configured on the system. 237 */ 238 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */ 239 240 /* 241 * The clock_count variable is set to CLOCK_INTERVAL at each PPS 242 * interrupt and decremented once each second. 243 */ 244 int clock_count = 0; /* CPU clock counter */ 245 246 #ifdef HIGHBALL 247 /* 248 * The clock_offset and clock_cpu variables are used by the HIGHBALL 249 * interface. The clock_offset variable defines the offset between 250 * system time and the HIGBALL counters. The clock_cpu variable contains 251 * the offset between the system clock and the HIGHBALL clock for use in 252 * disciplining the kernel time variable. 253 */ 254 extern struct timeval clock_offset; /* Highball clock offset */ 255 long clock_cpu = 0; /* CPU clock adjust */ 256 #endif /* HIGHBALL */ 257 #endif /* EXT_CLOCK */ 258 #endif /* NTP */ 259 260 261 /* 262 * Bump a timeval by a small number of usec's. 263 */ 264 #define BUMPTIME(t, usec) { \ 265 register volatile struct timeval *tp = (t); \ 266 register long us; \ 267 \ 268 tp->tv_usec = us = tp->tv_usec + (usec); \ 269 if (us >= 1000000) { \ 270 tp->tv_usec = us - 1000000; \ 271 tp->tv_sec++; \ 272 } \ 273 } 274 275 int stathz; 276 int schedhz; 277 int profhz; 278 int profprocs; 279 int ticks; 280 static int psdiv, pscnt; /* prof => stat divider */ 281 int psratio; /* ratio: prof / stat */ 282 int tickfix, tickfixinterval; /* used if tick not really integral */ 283 #ifndef NTP 284 static int tickfixcnt; /* accumulated fractional error */ 285 #else 286 int fixtick; /* used by NTP for same */ 287 int shifthz; 288 #endif 289 290 volatile struct timeval time; 291 volatile struct timeval mono_time; 292 293 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 294 void *softclock_si; 295 void generic_softclock(void *); 296 297 void 298 generic_softclock(void *ignore) 299 { 300 /* 301 * XXX - dont' commit, just a dummy wrapper until we learn everyone 302 * deal with a changed proto for softclock(). 303 */ 304 softclock(); 305 } 306 #endif 307 308 /* 309 * Initialize clock frequencies and start both clocks running. 310 */ 311 void 312 initclocks() 313 { 314 int i; 315 316 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 317 softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL); 318 if (softclock_si == NULL) 319 panic("initclocks: unable to register softclock intr"); 320 #endif 321 322 /* 323 * Set divisors to 1 (normal case) and let the machine-specific 324 * code do its bit. 325 */ 326 psdiv = pscnt = 1; 327 cpu_initclocks(); 328 329 /* 330 * Compute profhz/stathz, and fix profhz if needed. 331 */ 332 i = stathz ? stathz : hz; 333 if (profhz == 0) 334 profhz = i; 335 psratio = profhz / i; 336 337 #ifdef NTP 338 if (time_precision == 0) 339 time_precision = tick; 340 341 switch (hz) { 342 case 60: 343 case 64: 344 shifthz = SHIFT_SCALE - 6; 345 break; 346 case 96: 347 case 100: 348 case 128: 349 shifthz = SHIFT_SCALE - 7; 350 break; 351 case 256: 352 shifthz = SHIFT_SCALE - 8; 353 break; 354 case 1024: 355 shifthz = SHIFT_SCALE - 10; 356 break; 357 case 1200: 358 shifthz = SHIFT_SCALE - 11; 359 break; 360 default: 361 panic("weird hz"); 362 } 363 #endif 364 } 365 366 /* 367 * The real-time timer, interrupting hz times per second. 368 */ 369 void 370 hardclock(frame) 371 register struct clockframe *frame; 372 { 373 register struct proc *p; 374 register int delta; 375 extern int tickdelta; 376 extern long timedelta; 377 #ifdef NTP 378 register int time_update; 379 struct timeval newtime; 380 register int ltemp; 381 #endif 382 383 p = curproc; 384 if (p) { 385 register struct pstats *pstats; 386 387 /* 388 * Run current process's virtual and profile time, as needed. 389 */ 390 pstats = p->p_stats; 391 if (CLKF_USERMODE(frame) && 392 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 393 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 394 psignal(p, SIGVTALRM); 395 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 396 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 397 psignal(p, SIGPROF); 398 } 399 400 /* 401 * If no separate statistics clock is available, run it from here. 402 */ 403 if (stathz == 0) 404 statclock(frame); 405 406 /* 407 * Increment the time-of-day. The increment is normally just 408 * ``tick''. If the machine is one which has a clock frequency 409 * such that ``hz'' would not divide the second evenly into 410 * milliseconds, a periodic adjustment must be applied. Finally, 411 * if we are still adjusting the time (see adjtime()), 412 * ``tickdelta'' may also be added in. 413 */ 414 ticks++; 415 delta = tick; 416 417 #ifndef NTP 418 if (tickfix) { 419 tickfixcnt += tickfix; 420 if (tickfixcnt >= tickfixinterval) { 421 delta++; 422 tickfixcnt -= tickfixinterval; 423 } 424 } 425 #else 426 newtime = time; 427 #endif /* !NTP */ 428 /* Imprecise 4bsd adjtime() handling */ 429 if (timedelta != 0) { 430 delta += tickdelta; 431 timedelta -= tickdelta; 432 } 433 434 #ifdef notyet 435 microset(); 436 #endif 437 438 #ifndef NTP 439 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */ 440 #endif 441 BUMPTIME(&mono_time, delta); 442 443 #ifdef NTP 444 time_update = delta; 445 446 /* 447 * Compute the phase adjustment. If the low-order bits 448 * (time_phase) of the update overflow, bump the high-order bits 449 * (time_update). 450 */ 451 time_phase += time_adj; 452 if (time_phase <= -FINEUSEC) { 453 ltemp = -time_phase >> SHIFT_SCALE; 454 time_phase += ltemp << SHIFT_SCALE; 455 time_update -= ltemp; 456 } else if (time_phase >= FINEUSEC) { 457 ltemp = time_phase >> SHIFT_SCALE; 458 time_phase -= ltemp << SHIFT_SCALE; 459 time_update += ltemp; 460 } 461 462 #ifdef HIGHBALL 463 /* 464 * If the HIGHBALL board is installed, we need to adjust the 465 * external clock offset in order to close the hardware feedback 466 * loop. This will adjust the external clock phase and frequency 467 * in small amounts. The additional phase noise and frequency 468 * wander this causes should be minimal. We also need to 469 * discipline the kernel time variable, since the PLL is used to 470 * discipline the external clock. If the Highball board is not 471 * present, we discipline kernel time with the PLL as usual. We 472 * assume that the external clock phase adjustment (time_update) 473 * and kernel phase adjustment (clock_cpu) are less than the 474 * value of tick. 475 */ 476 clock_offset.tv_usec += time_update; 477 if (clock_offset.tv_usec >= 1000000) { 478 clock_offset.tv_sec++; 479 clock_offset.tv_usec -= 1000000; 480 } 481 if (clock_offset.tv_usec < 0) { 482 clock_offset.tv_sec--; 483 clock_offset.tv_usec += 1000000; 484 } 485 newtime.tv_usec += clock_cpu; 486 clock_cpu = 0; 487 #else 488 newtime.tv_usec += time_update; 489 #endif /* HIGHBALL */ 490 491 /* 492 * On rollover of the second the phase adjustment to be used for 493 * the next second is calculated. Also, the maximum error is 494 * increased by the tolerance. If the PPS frequency discipline 495 * code is present, the phase is increased to compensate for the 496 * CPU clock oscillator frequency error. 497 * 498 * On a 32-bit machine and given parameters in the timex.h 499 * header file, the maximum phase adjustment is +-512 ms and 500 * maximum frequency offset is a tad less than) +-512 ppm. On a 501 * 64-bit machine, you shouldn't need to ask. 502 */ 503 if (newtime.tv_usec >= 1000000) { 504 newtime.tv_usec -= 1000000; 505 newtime.tv_sec++; 506 time_maxerror += time_tolerance >> SHIFT_USEC; 507 508 /* 509 * Leap second processing. If in leap-insert state at 510 * the end of the day, the system clock is set back one 511 * second; if in leap-delete state, the system clock is 512 * set ahead one second. The microtime() routine or 513 * external clock driver will insure that reported time 514 * is always monotonic. The ugly divides should be 515 * replaced. 516 */ 517 switch (time_state) { 518 case TIME_OK: 519 if (time_status & STA_INS) 520 time_state = TIME_INS; 521 else if (time_status & STA_DEL) 522 time_state = TIME_DEL; 523 break; 524 525 case TIME_INS: 526 if (newtime.tv_sec % 86400 == 0) { 527 newtime.tv_sec--; 528 time_state = TIME_OOP; 529 } 530 break; 531 532 case TIME_DEL: 533 if ((newtime.tv_sec + 1) % 86400 == 0) { 534 newtime.tv_sec++; 535 time_state = TIME_WAIT; 536 } 537 break; 538 539 case TIME_OOP: 540 time_state = TIME_WAIT; 541 break; 542 543 case TIME_WAIT: 544 if (!(time_status & (STA_INS | STA_DEL))) 545 time_state = TIME_OK; 546 break; 547 } 548 549 /* 550 * Compute the phase adjustment for the next second. In 551 * PLL mode, the offset is reduced by a fixed factor 552 * times the time constant. In FLL mode the offset is 553 * used directly. In either mode, the maximum phase 554 * adjustment for each second is clamped so as to spread 555 * the adjustment over not more than the number of 556 * seconds between updates. 557 */ 558 if (time_offset < 0) { 559 ltemp = -time_offset; 560 if (!(time_status & STA_FLL)) 561 ltemp >>= SHIFT_KG + time_constant; 562 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE) 563 ltemp = (MAXPHASE / MINSEC) << 564 SHIFT_UPDATE; 565 time_offset += ltemp; 566 time_adj = -ltemp << (shifthz - SHIFT_UPDATE); 567 } else if (time_offset > 0) { 568 ltemp = time_offset; 569 if (!(time_status & STA_FLL)) 570 ltemp >>= SHIFT_KG + time_constant; 571 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE) 572 ltemp = (MAXPHASE / MINSEC) << 573 SHIFT_UPDATE; 574 time_offset -= ltemp; 575 time_adj = ltemp << (shifthz - SHIFT_UPDATE); 576 } else 577 time_adj = 0; 578 579 /* 580 * Compute the frequency estimate and additional phase 581 * adjustment due to frequency error for the next 582 * second. When the PPS signal is engaged, gnaw on the 583 * watchdog counter and update the frequency computed by 584 * the pll and the PPS signal. 585 */ 586 #ifdef PPS_SYNC 587 pps_valid++; 588 if (pps_valid >= PPS_VALID) { 589 pps_valid = PPS_VALID; /* Avoid possible overflow */ 590 pps_jitter = MAXTIME; 591 pps_stabil = MAXFREQ; 592 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER | 593 STA_PPSWANDER | STA_PPSERROR); 594 } 595 ltemp = time_freq + pps_freq; 596 #else 597 ltemp = time_freq; 598 #endif /* PPS_SYNC */ 599 600 if (ltemp < 0) 601 time_adj -= -ltemp >> (SHIFT_USEC - shifthz); 602 else 603 time_adj += ltemp >> (SHIFT_USEC - shifthz); 604 time_adj += (long)fixtick << shifthz; 605 606 /* 607 * When the CPU clock oscillator frequency is not a 608 * power of 2 in Hz, shifthz is only an approximate 609 * scale factor. 610 */ 611 switch (hz) { 612 case 96: 613 case 100: 614 /* 615 * In the following code the overall gain is increased 616 * by a factor of 1.25, which results in a residual 617 * error less than 3 percent. 618 */ 619 if (time_adj < 0) 620 time_adj -= -time_adj >> 2; 621 else 622 time_adj += time_adj >> 2; 623 break; 624 case 60: 625 /* 626 * 60 Hz m68k and vaxes have a PLL gain factor of of 627 * 60/64 (15/16) of what it should be. In the following code 628 * the overall gain is increased by a factor of 1.0625, 629 * (17/16) which results in a residual error of just less 630 * than 0.4 percent. 631 */ 632 if (time_adj < 0) 633 time_adj -= -time_adj >> 4; 634 else 635 time_adj += time_adj >> 4; 636 break; 637 } 638 639 #ifdef EXT_CLOCK 640 /* 641 * If an external clock is present, it is necessary to 642 * discipline the kernel time variable anyway, since not 643 * all system components use the microtime() interface. 644 * Here, the time offset between the external clock and 645 * kernel time variable is computed every so often. 646 */ 647 clock_count++; 648 if (clock_count > CLOCK_INTERVAL) { 649 clock_count = 0; 650 microtime(&clock_ext); 651 delta.tv_sec = clock_ext.tv_sec - newtime.tv_sec; 652 delta.tv_usec = clock_ext.tv_usec - newtime.tv_usec; 653 if (delta.tv_usec < 0) 654 delta.tv_sec--; 655 if (delta.tv_usec >= 500000) { 656 delta.tv_usec -= 1000000; 657 delta.tv_sec++; 658 } 659 if (delta.tv_usec < -500000) { 660 delta.tv_usec += 1000000; 661 delta.tv_sec--; 662 } 663 if (delta.tv_sec > 0 || (delta.tv_sec == 0 && 664 delta.tv_usec > MAXPHASE) || 665 delta.tv_sec < -1 || (delta.tv_sec == -1 && 666 delta.tv_usec < -MAXPHASE)) { 667 newtime = clock_ext; 668 delta.tv_sec = 0; 669 delta.tv_usec = 0; 670 } 671 #ifdef HIGHBALL 672 clock_cpu = delta.tv_usec; 673 #else /* HIGHBALL */ 674 hardupdate(delta.tv_usec); 675 #endif /* HIGHBALL */ 676 } 677 #endif /* EXT_CLOCK */ 678 } 679 680 #ifdef CPU_CLOCKUPDATE 681 CPU_CLOCKUPDATE(&time, &newtime); 682 #else 683 time = newtime; 684 #endif 685 686 #endif /* NTP */ 687 688 /* 689 * Update real-time timeout queue. 690 * Process callouts at a very low cpu priority, so we don't keep the 691 * relatively high clock interrupt priority any longer than necessary. 692 */ 693 if (timeout_hardclock_update()) { 694 if (CLKF_BASEPRI(frame)) { 695 /* 696 * Save the overhead of a software interrupt; 697 * it will happen as soon as we return, so do it now. 698 */ 699 spllowersoftclock(); 700 softclock(); 701 } else { 702 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 703 softintr_schedule(softclock_si); 704 #else 705 setsoftclock(); 706 #endif 707 } 708 } 709 } 710 711 /* 712 * Compute number of hz until specified time. Used to 713 * compute the second argument to timeout_add() from an absolute time. 714 */ 715 int 716 hzto(tv) 717 struct timeval *tv; 718 { 719 unsigned long ticks; 720 long sec, usec; 721 int s; 722 723 /* 724 * If the number of usecs in the whole seconds part of the time 725 * difference fits in a long, then the total number of usecs will 726 * fit in an unsigned long. Compute the total and convert it to 727 * ticks, rounding up and adding 1 to allow for the current tick 728 * to expire. Rounding also depends on unsigned long arithmetic 729 * to avoid overflow. 730 * 731 * Otherwise, if the number of ticks in the whole seconds part of 732 * the time difference fits in a long, then convert the parts to 733 * ticks separately and add, using similar rounding methods and 734 * overflow avoidance. This method would work in the previous 735 * case but it is slightly slower and assumes that hz is integral. 736 * 737 * Otherwise, round the time difference down to the maximum 738 * representable value. 739 * 740 * If ints have 32 bits, then the maximum value for any timeout in 741 * 10ms ticks is 248 days. 742 */ 743 s = splhigh(); 744 sec = tv->tv_sec - time.tv_sec; 745 usec = tv->tv_usec - time.tv_usec; 746 splx(s); 747 if (usec < 0) { 748 sec--; 749 usec += 1000000; 750 } 751 if (sec < 0 || (sec == 0 && usec <= 0)) { 752 ticks = 0; 753 } else if (sec <= LONG_MAX / 1000000) 754 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 755 / tick + 1; 756 else if (sec <= LONG_MAX / hz) 757 ticks = sec * hz 758 + ((unsigned long)usec + (tick - 1)) / tick + 1; 759 else 760 ticks = LONG_MAX; 761 if (ticks > INT_MAX) 762 ticks = INT_MAX; 763 return ((int)ticks); 764 } 765 766 /* 767 * Start profiling on a process. 768 * 769 * Kernel profiling passes proc0 which never exits and hence 770 * keeps the profile clock running constantly. 771 */ 772 void 773 startprofclock(p) 774 register struct proc *p; 775 { 776 int s; 777 778 if ((p->p_flag & P_PROFIL) == 0) { 779 p->p_flag |= P_PROFIL; 780 if (++profprocs == 1 && stathz != 0) { 781 s = splstatclock(); 782 psdiv = pscnt = psratio; 783 setstatclockrate(profhz); 784 splx(s); 785 } 786 } 787 } 788 789 /* 790 * Stop profiling on a process. 791 */ 792 void 793 stopprofclock(p) 794 register struct proc *p; 795 { 796 int s; 797 798 if (p->p_flag & P_PROFIL) { 799 p->p_flag &= ~P_PROFIL; 800 if (--profprocs == 0 && stathz != 0) { 801 s = splstatclock(); 802 psdiv = pscnt = 1; 803 setstatclockrate(stathz); 804 splx(s); 805 } 806 } 807 } 808 809 /* 810 * Statistics clock. Grab profile sample, and if divider reaches 0, 811 * do process and kernel statistics. 812 */ 813 void 814 statclock(frame) 815 register struct clockframe *frame; 816 { 817 #ifdef GPROF 818 register struct gmonparam *g; 819 register int i; 820 #endif 821 static int schedclk; 822 register struct proc *p; 823 824 if (CLKF_USERMODE(frame)) { 825 p = curproc; 826 if (p->p_flag & P_PROFIL) 827 addupc_intr(p, CLKF_PC(frame), 1); 828 if (--pscnt > 0) 829 return; 830 /* 831 * Came from user mode; CPU was in user state. 832 * If this process is being profiled record the tick. 833 */ 834 p->p_uticks++; 835 if (p->p_nice > NZERO) 836 cp_time[CP_NICE]++; 837 else 838 cp_time[CP_USER]++; 839 } else { 840 #ifdef GPROF 841 /* 842 * Kernel statistics are just like addupc_intr, only easier. 843 */ 844 g = &_gmonparam; 845 if (g->state == GMON_PROF_ON) { 846 i = CLKF_PC(frame) - g->lowpc; 847 if (i < g->textsize) { 848 i /= HISTFRACTION * sizeof(*g->kcount); 849 g->kcount[i]++; 850 } 851 } 852 #endif 853 if (--pscnt > 0) 854 return; 855 /* 856 * Came from kernel mode, so we were: 857 * - handling an interrupt, 858 * - doing syscall or trap work on behalf of the current 859 * user process, or 860 * - spinning in the idle loop. 861 * Whichever it is, charge the time as appropriate. 862 * Note that we charge interrupts to the current process, 863 * regardless of whether they are ``for'' that process, 864 * so that we know how much of its real time was spent 865 * in ``non-process'' (i.e., interrupt) work. 866 */ 867 p = curproc; 868 if (CLKF_INTR(frame)) { 869 if (p != NULL) 870 p->p_iticks++; 871 cp_time[CP_INTR]++; 872 } else if (p != NULL) { 873 p->p_sticks++; 874 cp_time[CP_SYS]++; 875 } else 876 cp_time[CP_IDLE]++; 877 } 878 pscnt = psdiv; 879 880 if (p != NULL) { 881 p->p_cpticks++; 882 /* 883 * If no schedclock is provided, call it here at ~~12-25 Hz; 884 * ~~16 Hz is best 885 */ 886 if (schedhz == 0) 887 if ((++schedclk & 3) == 0) 888 schedclock(p); 889 } 890 } 891 892 893 #ifdef NTP /* NTP phase-locked loop in kernel */ 894 895 /* 896 * hardupdate() - local clock update 897 * 898 * This routine is called by ntp_adjtime() to update the local clock 899 * phase and frequency. The implementation is of an adaptive-parameter, 900 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new 901 * time and frequency offset estimates for each call. If the kernel PPS 902 * discipline code is configured (PPS_SYNC), the PPS signal itself 903 * determines the new time offset, instead of the calling argument. 904 * Presumably, calls to ntp_adjtime() occur only when the caller 905 * believes the local clock is valid within some bound (+-128 ms with 906 * NTP). If the caller's time is far different than the PPS time, an 907 * argument will ensue, and it's not clear who will lose. 908 * 909 * For uncompensated quartz crystal oscillatores and nominal update 910 * intervals less than 1024 s, operation should be in phase-lock mode 911 * (STA_FLL = 0), where the loop is disciplined to phase. For update 912 * intervals greater than this, operation should be in frequency-lock 913 * mode (STA_FLL = 1), where the loop is disciplined to frequency. 914 * 915 * Note: splclock() is in effect. 916 */ 917 void 918 hardupdate(offset) 919 long offset; 920 { 921 long ltemp, mtemp; 922 923 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME)) 924 return; 925 ltemp = offset; 926 #ifdef PPS_SYNC 927 if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL)) 928 ltemp = pps_offset; 929 #endif /* PPS_SYNC */ 930 931 /* 932 * Scale the phase adjustment and clamp to the operating range. 933 */ 934 if (ltemp > MAXPHASE) 935 time_offset = MAXPHASE << SHIFT_UPDATE; 936 else if (ltemp < -MAXPHASE) 937 time_offset = -(MAXPHASE << SHIFT_UPDATE); 938 else 939 time_offset = ltemp << SHIFT_UPDATE; 940 941 /* 942 * Select whether the frequency is to be controlled and in which 943 * mode (PLL or FLL). Clamp to the operating range. Ugly 944 * multiply/divide should be replaced someday. 945 */ 946 if (time_status & STA_FREQHOLD || time_reftime == 0) 947 time_reftime = time.tv_sec; 948 mtemp = time.tv_sec - time_reftime; 949 time_reftime = time.tv_sec; 950 if (time_status & STA_FLL) { 951 if (mtemp >= MINSEC) { 952 ltemp = ((time_offset / mtemp) << (SHIFT_USEC - 953 SHIFT_UPDATE)); 954 if (ltemp < 0) 955 time_freq -= -ltemp >> SHIFT_KH; 956 else 957 time_freq += ltemp >> SHIFT_KH; 958 } 959 } else { 960 if (mtemp < MAXSEC) { 961 ltemp *= mtemp; 962 if (ltemp < 0) 963 time_freq -= -ltemp >> (time_constant + 964 time_constant + SHIFT_KF - 965 SHIFT_USEC); 966 else 967 time_freq += ltemp >> (time_constant + 968 time_constant + SHIFT_KF - 969 SHIFT_USEC); 970 } 971 } 972 if (time_freq > time_tolerance) 973 time_freq = time_tolerance; 974 else if (time_freq < -time_tolerance) 975 time_freq = -time_tolerance; 976 } 977 978 #ifdef PPS_SYNC 979 /* 980 * hardpps() - discipline CPU clock oscillator to external PPS signal 981 * 982 * This routine is called at each PPS interrupt in order to discipline 983 * the CPU clock oscillator to the PPS signal. It measures the PPS phase 984 * and leaves it in a handy spot for the hardclock() routine. It 985 * integrates successive PPS phase differences and calculates the 986 * frequency offset. This is used in hardclock() to discipline the CPU 987 * clock oscillator so that intrinsic frequency error is cancelled out. 988 * The code requires the caller to capture the time and hardware counter 989 * value at the on-time PPS signal transition. 990 * 991 * Note that, on some Unix systems, this routine runs at an interrupt 992 * priority level higher than the timer interrupt routine hardclock(). 993 * Therefore, the variables used are distinct from the hardclock() 994 * variables, except for certain exceptions: The PPS frequency pps_freq 995 * and phase pps_offset variables are determined by this routine and 996 * updated atomically. The time_tolerance variable can be considered a 997 * constant, since it is infrequently changed, and then only when the 998 * PPS signal is disabled. The watchdog counter pps_valid is updated 999 * once per second by hardclock() and is atomically cleared in this 1000 * routine. 1001 */ 1002 void 1003 hardpps(tvp, usec) 1004 struct timeval *tvp; /* time at PPS */ 1005 long usec; /* hardware counter at PPS */ 1006 { 1007 long u_usec, v_usec, bigtick; 1008 long cal_sec, cal_usec; 1009 1010 /* 1011 * An occasional glitch can be produced when the PPS interrupt 1012 * occurs in the hardclock() routine before the time variable is 1013 * updated. Here the offset is discarded when the difference 1014 * between it and the last one is greater than tick/2, but not 1015 * if the interval since the first discard exceeds 30 s. 1016 */ 1017 time_status |= STA_PPSSIGNAL; 1018 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR); 1019 pps_valid = 0; 1020 u_usec = -tvp->tv_usec; 1021 if (u_usec < -500000) 1022 u_usec += 1000000; 1023 v_usec = pps_offset - u_usec; 1024 if (v_usec < 0) 1025 v_usec = -v_usec; 1026 if (v_usec > (tick >> 1)) { 1027 if (pps_glitch > MAXGLITCH) { 1028 pps_glitch = 0; 1029 pps_tf[2] = u_usec; 1030 pps_tf[1] = u_usec; 1031 } else { 1032 pps_glitch++; 1033 u_usec = pps_offset; 1034 } 1035 } else 1036 pps_glitch = 0; 1037 1038 /* 1039 * A three-stage median filter is used to help deglitch the pps 1040 * time. The median sample becomes the time offset estimate; the 1041 * difference between the other two samples becomes the time 1042 * dispersion (jitter) estimate. 1043 */ 1044 pps_tf[2] = pps_tf[1]; 1045 pps_tf[1] = pps_tf[0]; 1046 pps_tf[0] = u_usec; 1047 if (pps_tf[0] > pps_tf[1]) { 1048 if (pps_tf[1] > pps_tf[2]) { 1049 pps_offset = pps_tf[1]; /* 0 1 2 */ 1050 v_usec = pps_tf[0] - pps_tf[2]; 1051 } else if (pps_tf[2] > pps_tf[0]) { 1052 pps_offset = pps_tf[0]; /* 2 0 1 */ 1053 v_usec = pps_tf[2] - pps_tf[1]; 1054 } else { 1055 pps_offset = pps_tf[2]; /* 0 2 1 */ 1056 v_usec = pps_tf[0] - pps_tf[1]; 1057 } 1058 } else { 1059 if (pps_tf[1] < pps_tf[2]) { 1060 pps_offset = pps_tf[1]; /* 2 1 0 */ 1061 v_usec = pps_tf[2] - pps_tf[0]; 1062 } else if (pps_tf[2] < pps_tf[0]) { 1063 pps_offset = pps_tf[0]; /* 1 0 2 */ 1064 v_usec = pps_tf[1] - pps_tf[2]; 1065 } else { 1066 pps_offset = pps_tf[2]; /* 1 2 0 */ 1067 v_usec = pps_tf[1] - pps_tf[0]; 1068 } 1069 } 1070 if (v_usec > MAXTIME) 1071 pps_jitcnt++; 1072 v_usec = (v_usec << PPS_AVG) - pps_jitter; 1073 if (v_usec < 0) 1074 pps_jitter -= -v_usec >> PPS_AVG; 1075 else 1076 pps_jitter += v_usec >> PPS_AVG; 1077 if (pps_jitter > (MAXTIME >> 1)) 1078 time_status |= STA_PPSJITTER; 1079 1080 /* 1081 * During the calibration interval adjust the starting time when 1082 * the tick overflows. At the end of the interval compute the 1083 * duration of the interval and the difference of the hardware 1084 * counters at the beginning and end of the interval. This code 1085 * is deliciously complicated by the fact valid differences may 1086 * exceed the value of tick when using long calibration 1087 * intervals and small ticks. Note that the counter can be 1088 * greater than tick if caught at just the wrong instant, but 1089 * the values returned and used here are correct. 1090 */ 1091 bigtick = (long)tick << SHIFT_USEC; 1092 pps_usec -= pps_freq; 1093 if (pps_usec >= bigtick) 1094 pps_usec -= bigtick; 1095 if (pps_usec < 0) 1096 pps_usec += bigtick; 1097 pps_time.tv_sec++; 1098 pps_count++; 1099 if (pps_count < (1 << pps_shift)) 1100 return; 1101 pps_count = 0; 1102 pps_calcnt++; 1103 u_usec = usec << SHIFT_USEC; 1104 v_usec = pps_usec - u_usec; 1105 if (v_usec >= bigtick >> 1) 1106 v_usec -= bigtick; 1107 if (v_usec < -(bigtick >> 1)) 1108 v_usec += bigtick; 1109 if (v_usec < 0) 1110 v_usec = -(-v_usec >> pps_shift); 1111 else 1112 v_usec = v_usec >> pps_shift; 1113 pps_usec = u_usec; 1114 cal_sec = tvp->tv_sec; 1115 cal_usec = tvp->tv_usec; 1116 cal_sec -= pps_time.tv_sec; 1117 cal_usec -= pps_time.tv_usec; 1118 if (cal_usec < 0) { 1119 cal_usec += 1000000; 1120 cal_sec--; 1121 } 1122 pps_time = *tvp; 1123 1124 /* 1125 * Check for lost interrupts, noise, excessive jitter and 1126 * excessive frequency error. The number of timer ticks during 1127 * the interval may vary +-1 tick. Add to this a margin of one 1128 * tick for the PPS signal jitter and maximum frequency 1129 * deviation. If the limits are exceeded, the calibration 1130 * interval is reset to the minimum and we start over. 1131 */ 1132 u_usec = (long)tick << 1; 1133 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec)) 1134 || (cal_sec == 0 && cal_usec < u_usec)) 1135 || v_usec > time_tolerance || v_usec < -time_tolerance) { 1136 pps_errcnt++; 1137 pps_shift = PPS_SHIFT; 1138 pps_intcnt = 0; 1139 time_status |= STA_PPSERROR; 1140 return; 1141 } 1142 1143 /* 1144 * A three-stage median filter is used to help deglitch the pps 1145 * frequency. The median sample becomes the frequency offset 1146 * estimate; the difference between the other two samples 1147 * becomes the frequency dispersion (stability) estimate. 1148 */ 1149 pps_ff[2] = pps_ff[1]; 1150 pps_ff[1] = pps_ff[0]; 1151 pps_ff[0] = v_usec; 1152 if (pps_ff[0] > pps_ff[1]) { 1153 if (pps_ff[1] > pps_ff[2]) { 1154 u_usec = pps_ff[1]; /* 0 1 2 */ 1155 v_usec = pps_ff[0] - pps_ff[2]; 1156 } else if (pps_ff[2] > pps_ff[0]) { 1157 u_usec = pps_ff[0]; /* 2 0 1 */ 1158 v_usec = pps_ff[2] - pps_ff[1]; 1159 } else { 1160 u_usec = pps_ff[2]; /* 0 2 1 */ 1161 v_usec = pps_ff[0] - pps_ff[1]; 1162 } 1163 } else { 1164 if (pps_ff[1] < pps_ff[2]) { 1165 u_usec = pps_ff[1]; /* 2 1 0 */ 1166 v_usec = pps_ff[2] - pps_ff[0]; 1167 } else if (pps_ff[2] < pps_ff[0]) { 1168 u_usec = pps_ff[0]; /* 1 0 2 */ 1169 v_usec = pps_ff[1] - pps_ff[2]; 1170 } else { 1171 u_usec = pps_ff[2]; /* 1 2 0 */ 1172 v_usec = pps_ff[1] - pps_ff[0]; 1173 } 1174 } 1175 1176 /* 1177 * Here the frequency dispersion (stability) is updated. If it 1178 * is less than one-fourth the maximum (MAXFREQ), the frequency 1179 * offset is updated as well, but clamped to the tolerance. It 1180 * will be processed later by the hardclock() routine. 1181 */ 1182 v_usec = (v_usec >> 1) - pps_stabil; 1183 if (v_usec < 0) 1184 pps_stabil -= -v_usec >> PPS_AVG; 1185 else 1186 pps_stabil += v_usec >> PPS_AVG; 1187 if (pps_stabil > MAXFREQ >> 2) { 1188 pps_stbcnt++; 1189 time_status |= STA_PPSWANDER; 1190 return; 1191 } 1192 if (time_status & STA_PPSFREQ) { 1193 if (u_usec < 0) { 1194 pps_freq -= -u_usec >> PPS_AVG; 1195 if (pps_freq < -time_tolerance) 1196 pps_freq = -time_tolerance; 1197 u_usec = -u_usec; 1198 } else { 1199 pps_freq += u_usec >> PPS_AVG; 1200 if (pps_freq > time_tolerance) 1201 pps_freq = time_tolerance; 1202 } 1203 } 1204 1205 /* 1206 * Here the calibration interval is adjusted. If the maximum 1207 * time difference is greater than tick / 4, reduce the interval 1208 * by half. If this is not the case for four consecutive 1209 * intervals, double the interval. 1210 */ 1211 if (u_usec << pps_shift > bigtick >> 2) { 1212 pps_intcnt = 0; 1213 if (pps_shift > PPS_SHIFT) 1214 pps_shift--; 1215 } else if (pps_intcnt >= 4) { 1216 pps_intcnt = 0; 1217 if (pps_shift < PPS_SHIFTMAX) 1218 pps_shift++; 1219 } else 1220 pps_intcnt++; 1221 } 1222 #endif /* PPS_SYNC */ 1223 #endif /* NTP */ 1224 1225 1226 /* 1227 * Return information about system clocks. 1228 */ 1229 int 1230 sysctl_clockrate(where, sizep) 1231 register char *where; 1232 size_t *sizep; 1233 { 1234 struct clockinfo clkinfo; 1235 1236 /* 1237 * Construct clockinfo structure. 1238 */ 1239 clkinfo.tick = tick; 1240 clkinfo.tickadj = tickadj; 1241 clkinfo.hz = hz; 1242 clkinfo.profhz = profhz; 1243 clkinfo.stathz = stathz ? stathz : hz; 1244 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo))); 1245 } 1246