1 /* $OpenBSD: kern_clock.c,v 1.38 2002/07/03 21:19:08 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. 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/limits.h> 50 #include <sys/proc.h> 51 #include <sys/resourcevar.h> 52 #include <sys/signalvar.h> 53 #include <uvm/uvm_extern.h> 54 #include <sys/sysctl.h> 55 #include <sys/timex.h> 56 #include <sys/sched.h> 57 58 #include <machine/cpu.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 long cp_time[CPUSTATES]; 291 292 volatile struct timeval time; 293 volatile struct timeval mono_time; 294 295 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 296 void *softclock_si; 297 void generic_softclock(void *); 298 299 void 300 generic_softclock(void *ignore) 301 { 302 /* 303 * XXX - dont' commit, just a dummy wrapper until we learn everyone 304 * deal with a changed proto for softclock(). 305 */ 306 softclock(); 307 } 308 #endif 309 310 /* 311 * Initialize clock frequencies and start both clocks running. 312 */ 313 void 314 initclocks() 315 { 316 int i; 317 318 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 319 softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL); 320 if (softclock_si == NULL) 321 panic("initclocks: unable to register softclock intr"); 322 #endif 323 324 /* 325 * Set divisors to 1 (normal case) and let the machine-specific 326 * code do its bit. 327 */ 328 psdiv = pscnt = 1; 329 cpu_initclocks(); 330 331 /* 332 * Compute profhz/stathz, and fix profhz if needed. 333 */ 334 i = stathz ? stathz : hz; 335 if (profhz == 0) 336 profhz = i; 337 psratio = profhz / i; 338 339 #ifdef NTP 340 if (time_precision == 0) 341 time_precision = tick; 342 343 switch (hz) { 344 case 60: 345 case 64: 346 shifthz = SHIFT_SCALE - 6; 347 break; 348 case 96: 349 case 100: 350 case 128: 351 shifthz = SHIFT_SCALE - 7; 352 break; 353 case 256: 354 shifthz = SHIFT_SCALE - 8; 355 break; 356 case 1024: 357 shifthz = SHIFT_SCALE - 10; 358 break; 359 case 1200: 360 shifthz = SHIFT_SCALE - 11; 361 break; 362 default: 363 panic("weird hz"); 364 } 365 #endif 366 } 367 368 /* 369 * The real-time timer, interrupting hz times per second. 370 */ 371 void 372 hardclock(frame) 373 register struct clockframe *frame; 374 { 375 register struct proc *p; 376 register int delta; 377 extern int tickdelta; 378 extern long timedelta; 379 #ifdef NTP 380 register int time_update; 381 struct timeval newtime; 382 register int ltemp; 383 #endif 384 385 p = curproc; 386 if (p) { 387 register struct pstats *pstats; 388 389 /* 390 * Run current process's virtual and profile time, as needed. 391 */ 392 pstats = p->p_stats; 393 if (CLKF_USERMODE(frame) && 394 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 395 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 396 psignal(p, SIGVTALRM); 397 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 398 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 399 psignal(p, SIGPROF); 400 } 401 402 /* 403 * If no separate statistics clock is available, run it from here. 404 */ 405 if (stathz == 0) 406 statclock(frame); 407 408 /* 409 * Increment the time-of-day. The increment is normally just 410 * ``tick''. If the machine is one which has a clock frequency 411 * such that ``hz'' would not divide the second evenly into 412 * milliseconds, a periodic adjustment must be applied. Finally, 413 * if we are still adjusting the time (see adjtime()), 414 * ``tickdelta'' may also be added in. 415 */ 416 ticks++; 417 delta = tick; 418 419 #ifndef NTP 420 if (tickfix) { 421 tickfixcnt += tickfix; 422 if (tickfixcnt >= tickfixinterval) { 423 delta++; 424 tickfixcnt -= tickfixinterval; 425 } 426 } 427 #else 428 newtime = time; 429 #endif /* !NTP */ 430 /* Imprecise 4bsd adjtime() handling */ 431 if (timedelta != 0) { 432 delta += tickdelta; 433 timedelta -= tickdelta; 434 } 435 436 #ifdef notyet 437 microset(); 438 #endif 439 440 #ifndef NTP 441 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */ 442 #endif 443 BUMPTIME(&mono_time, delta); 444 445 #ifdef NTP 446 time_update = delta; 447 448 /* 449 * Compute the phase adjustment. If the low-order bits 450 * (time_phase) of the update overflow, bump the high-order bits 451 * (time_update). 452 */ 453 time_phase += time_adj; 454 if (time_phase <= -FINEUSEC) { 455 ltemp = -time_phase >> SHIFT_SCALE; 456 time_phase += ltemp << SHIFT_SCALE; 457 time_update -= ltemp; 458 } else if (time_phase >= FINEUSEC) { 459 ltemp = time_phase >> SHIFT_SCALE; 460 time_phase -= ltemp << SHIFT_SCALE; 461 time_update += ltemp; 462 } 463 464 #ifdef HIGHBALL 465 /* 466 * If the HIGHBALL board is installed, we need to adjust the 467 * external clock offset in order to close the hardware feedback 468 * loop. This will adjust the external clock phase and frequency 469 * in small amounts. The additional phase noise and frequency 470 * wander this causes should be minimal. We also need to 471 * discipline the kernel time variable, since the PLL is used to 472 * discipline the external clock. If the Highball board is not 473 * present, we discipline kernel time with the PLL as usual. We 474 * assume that the external clock phase adjustment (time_update) 475 * and kernel phase adjustment (clock_cpu) are less than the 476 * value of tick. 477 */ 478 clock_offset.tv_usec += time_update; 479 if (clock_offset.tv_usec >= 1000000) { 480 clock_offset.tv_sec++; 481 clock_offset.tv_usec -= 1000000; 482 } 483 if (clock_offset.tv_usec < 0) { 484 clock_offset.tv_sec--; 485 clock_offset.tv_usec += 1000000; 486 } 487 newtime.tv_usec += clock_cpu; 488 clock_cpu = 0; 489 #else 490 newtime.tv_usec += time_update; 491 #endif /* HIGHBALL */ 492 493 /* 494 * On rollover of the second the phase adjustment to be used for 495 * the next second is calculated. Also, the maximum error is 496 * increased by the tolerance. If the PPS frequency discipline 497 * code is present, the phase is increased to compensate for the 498 * CPU clock oscillator frequency error. 499 * 500 * On a 32-bit machine and given parameters in the timex.h 501 * header file, the maximum phase adjustment is +-512 ms and 502 * maximum frequency offset is a tad less than) +-512 ppm. On a 503 * 64-bit machine, you shouldn't need to ask. 504 */ 505 if (newtime.tv_usec >= 1000000) { 506 newtime.tv_usec -= 1000000; 507 newtime.tv_sec++; 508 time_maxerror += time_tolerance >> SHIFT_USEC; 509 510 /* 511 * Leap second processing. If in leap-insert state at 512 * the end of the day, the system clock is set back one 513 * second; if in leap-delete state, the system clock is 514 * set ahead one second. The microtime() routine or 515 * external clock driver will insure that reported time 516 * is always monotonic. The ugly divides should be 517 * replaced. 518 */ 519 switch (time_state) { 520 case TIME_OK: 521 if (time_status & STA_INS) 522 time_state = TIME_INS; 523 else if (time_status & STA_DEL) 524 time_state = TIME_DEL; 525 break; 526 527 case TIME_INS: 528 if (newtime.tv_sec % 86400 == 0) { 529 newtime.tv_sec--; 530 time_state = TIME_OOP; 531 } 532 break; 533 534 case TIME_DEL: 535 if ((newtime.tv_sec + 1) % 86400 == 0) { 536 newtime.tv_sec++; 537 time_state = TIME_WAIT; 538 } 539 break; 540 541 case TIME_OOP: 542 time_state = TIME_WAIT; 543 break; 544 545 case TIME_WAIT: 546 if (!(time_status & (STA_INS | STA_DEL))) 547 time_state = TIME_OK; 548 break; 549 } 550 551 /* 552 * Compute the phase adjustment for the next second. In 553 * PLL mode, the offset is reduced by a fixed factor 554 * times the time constant. In FLL mode the offset is 555 * used directly. In either mode, the maximum phase 556 * adjustment for each second is clamped so as to spread 557 * the adjustment over not more than the number of 558 * seconds between updates. 559 */ 560 if (time_offset < 0) { 561 ltemp = -time_offset; 562 if (!(time_status & STA_FLL)) 563 ltemp >>= SHIFT_KG + time_constant; 564 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE) 565 ltemp = (MAXPHASE / MINSEC) << 566 SHIFT_UPDATE; 567 time_offset += ltemp; 568 time_adj = -ltemp << (shifthz - SHIFT_UPDATE); 569 } else if (time_offset > 0) { 570 ltemp = time_offset; 571 if (!(time_status & STA_FLL)) 572 ltemp >>= SHIFT_KG + time_constant; 573 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE) 574 ltemp = (MAXPHASE / MINSEC) << 575 SHIFT_UPDATE; 576 time_offset -= ltemp; 577 time_adj = ltemp << (shifthz - SHIFT_UPDATE); 578 } else 579 time_adj = 0; 580 581 /* 582 * Compute the frequency estimate and additional phase 583 * adjustment due to frequency error for the next 584 * second. When the PPS signal is engaged, gnaw on the 585 * watchdog counter and update the frequency computed by 586 * the pll and the PPS signal. 587 */ 588 #ifdef PPS_SYNC 589 pps_valid++; 590 if (pps_valid >= PPS_VALID) { 591 pps_valid = PPS_VALID; /* Avoid possible overflow */ 592 pps_jitter = MAXTIME; 593 pps_stabil = MAXFREQ; 594 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER | 595 STA_PPSWANDER | STA_PPSERROR); 596 } 597 ltemp = time_freq + pps_freq; 598 #else 599 ltemp = time_freq; 600 #endif /* PPS_SYNC */ 601 602 if (ltemp < 0) 603 time_adj -= -ltemp >> (SHIFT_USEC - shifthz); 604 else 605 time_adj += ltemp >> (SHIFT_USEC - shifthz); 606 time_adj += (long)fixtick << shifthz; 607 608 /* 609 * When the CPU clock oscillator frequency is not a 610 * power of 2 in Hz, shifthz is only an approximate 611 * scale factor. 612 */ 613 switch (hz) { 614 case 96: 615 case 100: 616 /* 617 * In the following code the overall gain is increased 618 * by a factor of 1.25, which results in a residual 619 * error less than 3 percent. 620 */ 621 if (time_adj < 0) 622 time_adj -= -time_adj >> 2; 623 else 624 time_adj += time_adj >> 2; 625 break; 626 case 60: 627 /* 628 * 60 Hz m68k and vaxes have a PLL gain factor of of 629 * 60/64 (15/16) of what it should be. In the following code 630 * the overall gain is increased by a factor of 1.0625, 631 * (17/16) which results in a residual error of just less 632 * than 0.4 percent. 633 */ 634 if (time_adj < 0) 635 time_adj -= -time_adj >> 4; 636 else 637 time_adj += time_adj >> 4; 638 break; 639 } 640 641 #ifdef EXT_CLOCK 642 /* 643 * If an external clock is present, it is necessary to 644 * discipline the kernel time variable anyway, since not 645 * all system components use the microtime() interface. 646 * Here, the time offset between the external clock and 647 * kernel time variable is computed every so often. 648 */ 649 clock_count++; 650 if (clock_count > CLOCK_INTERVAL) { 651 clock_count = 0; 652 microtime(&clock_ext); 653 delta.tv_sec = clock_ext.tv_sec - newtime.tv_sec; 654 delta.tv_usec = clock_ext.tv_usec - newtime.tv_usec; 655 if (delta.tv_usec < 0) 656 delta.tv_sec--; 657 if (delta.tv_usec >= 500000) { 658 delta.tv_usec -= 1000000; 659 delta.tv_sec++; 660 } 661 if (delta.tv_usec < -500000) { 662 delta.tv_usec += 1000000; 663 delta.tv_sec--; 664 } 665 if (delta.tv_sec > 0 || (delta.tv_sec == 0 && 666 delta.tv_usec > MAXPHASE) || 667 delta.tv_sec < -1 || (delta.tv_sec == -1 && 668 delta.tv_usec < -MAXPHASE)) { 669 newtime = clock_ext; 670 delta.tv_sec = 0; 671 delta.tv_usec = 0; 672 } 673 #ifdef HIGHBALL 674 clock_cpu = delta.tv_usec; 675 #else /* HIGHBALL */ 676 hardupdate(delta.tv_usec); 677 #endif /* HIGHBALL */ 678 } 679 #endif /* EXT_CLOCK */ 680 } 681 682 #ifdef CPU_CLOCKUPDATE 683 CPU_CLOCKUPDATE(&time, &newtime); 684 #else 685 time = newtime; 686 #endif 687 688 #endif /* NTP */ 689 690 /* 691 * Update real-time timeout queue. 692 * Process callouts at a very low cpu priority, so we don't keep the 693 * relatively high clock interrupt priority any longer than necessary. 694 */ 695 if (timeout_hardclock_update()) { 696 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS 697 softintr_schedule(softclock_si); 698 #else 699 setsoftclock(); 700 #endif 701 } 702 } 703 704 /* 705 * Compute number of hz until specified time. Used to 706 * compute the second argument to timeout_add() from an absolute time. 707 */ 708 int 709 hzto(tv) 710 struct timeval *tv; 711 { 712 unsigned long ticks; 713 long sec, usec; 714 int s; 715 716 /* 717 * If the number of usecs in the whole seconds part of the time 718 * difference fits in a long, then the total number of usecs will 719 * fit in an unsigned long. Compute the total and convert it to 720 * ticks, rounding up and adding 1 to allow for the current tick 721 * to expire. Rounding also depends on unsigned long arithmetic 722 * to avoid overflow. 723 * 724 * Otherwise, if the number of ticks in the whole seconds part of 725 * the time difference fits in a long, then convert the parts to 726 * ticks separately and add, using similar rounding methods and 727 * overflow avoidance. This method would work in the previous 728 * case but it is slightly slower and assumes that hz is integral. 729 * 730 * Otherwise, round the time difference down to the maximum 731 * representable value. 732 * 733 * If ints have 32 bits, then the maximum value for any timeout in 734 * 10ms ticks is 248 days. 735 */ 736 s = splhigh(); 737 sec = tv->tv_sec - time.tv_sec; 738 usec = tv->tv_usec - time.tv_usec; 739 splx(s); 740 if (usec < 0) { 741 sec--; 742 usec += 1000000; 743 } 744 if (sec < 0 || (sec == 0 && usec <= 0)) { 745 ticks = 0; 746 } else if (sec <= LONG_MAX / 1000000) 747 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 748 / tick + 1; 749 else if (sec <= LONG_MAX / hz) 750 ticks = sec * hz 751 + ((unsigned long)usec + (tick - 1)) / tick + 1; 752 else 753 ticks = LONG_MAX; 754 if (ticks > INT_MAX) 755 ticks = INT_MAX; 756 return ((int)ticks); 757 } 758 759 /* 760 * Compute number of hz in the specified amount of time. 761 */ 762 int 763 tvtohz(struct timeval *tv) 764 { 765 unsigned long ticks; 766 long sec, usec; 767 768 /* 769 * If the number of usecs in the whole seconds part of the time 770 * fits in a long, then the total number of usecs will 771 * fit in an unsigned long. Compute the total and convert it to 772 * ticks, rounding up and adding 1 to allow for the current tick 773 * to expire. Rounding also depends on unsigned long arithmetic 774 * to avoid overflow. 775 * 776 * Otherwise, if the number of ticks in the whole seconds part of 777 * the time fits in a long, then convert the parts to 778 * ticks separately and add, using similar rounding methods and 779 * overflow avoidance. This method would work in the previous 780 * case but it is slightly slower and assumes that hz is integral. 781 * 782 * Otherwise, round the time down to the maximum 783 * representable value. 784 * 785 * If ints have 32 bits, then the maximum value for any timeout in 786 * 10ms ticks is 248 days. 787 */ 788 sec = tv->tv_sec; 789 usec = tv->tv_usec; 790 if (sec < 0 || (sec == 0 && usec <= 0)) 791 ticks = 0; 792 else if (sec <= LONG_MAX / 1000000) 793 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 794 / tick + 1; 795 else if (sec <= LONG_MAX / hz) 796 ticks = sec * hz 797 + ((unsigned long)usec + (tick - 1)) / tick + 1; 798 else 799 ticks = LONG_MAX; 800 if (ticks > INT_MAX) 801 ticks = INT_MAX; 802 return ((int)ticks); 803 } 804 805 /* 806 * Start profiling on a process. 807 * 808 * Kernel profiling passes proc0 which never exits and hence 809 * keeps the profile clock running constantly. 810 */ 811 void 812 startprofclock(p) 813 register struct proc *p; 814 { 815 int s; 816 817 if ((p->p_flag & P_PROFIL) == 0) { 818 p->p_flag |= P_PROFIL; 819 if (++profprocs == 1 && stathz != 0) { 820 s = splstatclock(); 821 psdiv = pscnt = psratio; 822 setstatclockrate(profhz); 823 splx(s); 824 } 825 } 826 } 827 828 /* 829 * Stop profiling on a process. 830 */ 831 void 832 stopprofclock(p) 833 register struct proc *p; 834 { 835 int s; 836 837 if (p->p_flag & P_PROFIL) { 838 p->p_flag &= ~P_PROFIL; 839 if (--profprocs == 0 && stathz != 0) { 840 s = splstatclock(); 841 psdiv = pscnt = 1; 842 setstatclockrate(stathz); 843 splx(s); 844 } 845 } 846 } 847 848 /* 849 * Statistics clock. Grab profile sample, and if divider reaches 0, 850 * do process and kernel statistics. 851 */ 852 void 853 statclock(frame) 854 register struct clockframe *frame; 855 { 856 #ifdef GPROF 857 register struct gmonparam *g; 858 register int i; 859 #endif 860 static int schedclk; 861 register struct proc *p; 862 863 if (CLKF_USERMODE(frame)) { 864 p = curproc; 865 if (p->p_flag & P_PROFIL) 866 addupc_intr(p, CLKF_PC(frame)); 867 if (--pscnt > 0) 868 return; 869 /* 870 * Came from user mode; CPU was in user state. 871 * If this process is being profiled record the tick. 872 */ 873 p->p_uticks++; 874 if (p->p_nice > NZERO) 875 cp_time[CP_NICE]++; 876 else 877 cp_time[CP_USER]++; 878 } else { 879 #ifdef GPROF 880 /* 881 * Kernel statistics are just like addupc_intr, only easier. 882 */ 883 g = &_gmonparam; 884 if (g->state == GMON_PROF_ON) { 885 i = CLKF_PC(frame) - g->lowpc; 886 if (i < g->textsize) { 887 i /= HISTFRACTION * sizeof(*g->kcount); 888 g->kcount[i]++; 889 } 890 } 891 #endif 892 if (--pscnt > 0) 893 return; 894 /* 895 * Came from kernel mode, so we were: 896 * - handling an interrupt, 897 * - doing syscall or trap work on behalf of the current 898 * user process, or 899 * - spinning in the idle loop. 900 * Whichever it is, charge the time as appropriate. 901 * Note that we charge interrupts to the current process, 902 * regardless of whether they are ``for'' that process, 903 * so that we know how much of its real time was spent 904 * in ``non-process'' (i.e., interrupt) work. 905 */ 906 p = curproc; 907 if (CLKF_INTR(frame)) { 908 if (p != NULL) 909 p->p_iticks++; 910 cp_time[CP_INTR]++; 911 } else if (p != NULL) { 912 p->p_sticks++; 913 cp_time[CP_SYS]++; 914 } else 915 cp_time[CP_IDLE]++; 916 } 917 pscnt = psdiv; 918 919 if (p != NULL) { 920 p->p_cpticks++; 921 /* 922 * If no schedclock is provided, call it here at ~~12-25 Hz; 923 * ~~16 Hz is best 924 */ 925 if (schedhz == 0) 926 if ((++schedclk & 3) == 0) 927 schedclock(p); 928 } 929 } 930 931 932 #ifdef NTP /* NTP phase-locked loop in kernel */ 933 934 /* 935 * hardupdate() - local clock update 936 * 937 * This routine is called by ntp_adjtime() to update the local clock 938 * phase and frequency. The implementation is of an adaptive-parameter, 939 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new 940 * time and frequency offset estimates for each call. If the kernel PPS 941 * discipline code is configured (PPS_SYNC), the PPS signal itself 942 * determines the new time offset, instead of the calling argument. 943 * Presumably, calls to ntp_adjtime() occur only when the caller 944 * believes the local clock is valid within some bound (+-128 ms with 945 * NTP). If the caller's time is far different than the PPS time, an 946 * argument will ensue, and it's not clear who will lose. 947 * 948 * For uncompensated quartz crystal oscillatores and nominal update 949 * intervals less than 1024 s, operation should be in phase-lock mode 950 * (STA_FLL = 0), where the loop is disciplined to phase. For update 951 * intervals greater than this, operation should be in frequency-lock 952 * mode (STA_FLL = 1), where the loop is disciplined to frequency. 953 * 954 * Note: splclock() is in effect. 955 */ 956 void 957 hardupdate(offset) 958 long offset; 959 { 960 long ltemp, mtemp; 961 962 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME)) 963 return; 964 ltemp = offset; 965 #ifdef PPS_SYNC 966 if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL)) 967 ltemp = pps_offset; 968 #endif /* PPS_SYNC */ 969 970 /* 971 * Scale the phase adjustment and clamp to the operating range. 972 */ 973 if (ltemp > MAXPHASE) 974 time_offset = MAXPHASE << SHIFT_UPDATE; 975 else if (ltemp < -MAXPHASE) 976 time_offset = -(MAXPHASE << SHIFT_UPDATE); 977 else 978 time_offset = ltemp << SHIFT_UPDATE; 979 980 /* 981 * Select whether the frequency is to be controlled and in which 982 * mode (PLL or FLL). Clamp to the operating range. Ugly 983 * multiply/divide should be replaced someday. 984 */ 985 if (time_status & STA_FREQHOLD || time_reftime == 0) 986 time_reftime = time.tv_sec; 987 mtemp = time.tv_sec - time_reftime; 988 time_reftime = time.tv_sec; 989 if (time_status & STA_FLL) { 990 if (mtemp >= MINSEC) { 991 ltemp = ((time_offset / mtemp) << (SHIFT_USEC - 992 SHIFT_UPDATE)); 993 if (ltemp < 0) 994 time_freq -= -ltemp >> SHIFT_KH; 995 else 996 time_freq += ltemp >> SHIFT_KH; 997 } 998 } else { 999 if (mtemp < MAXSEC) { 1000 ltemp *= mtemp; 1001 if (ltemp < 0) 1002 time_freq -= -ltemp >> (time_constant + 1003 time_constant + SHIFT_KF - 1004 SHIFT_USEC); 1005 else 1006 time_freq += ltemp >> (time_constant + 1007 time_constant + SHIFT_KF - 1008 SHIFT_USEC); 1009 } 1010 } 1011 if (time_freq > time_tolerance) 1012 time_freq = time_tolerance; 1013 else if (time_freq < -time_tolerance) 1014 time_freq = -time_tolerance; 1015 } 1016 1017 #ifdef PPS_SYNC 1018 /* 1019 * hardpps() - discipline CPU clock oscillator to external PPS signal 1020 * 1021 * This routine is called at each PPS interrupt in order to discipline 1022 * the CPU clock oscillator to the PPS signal. It measures the PPS phase 1023 * and leaves it in a handy spot for the hardclock() routine. It 1024 * integrates successive PPS phase differences and calculates the 1025 * frequency offset. This is used in hardclock() to discipline the CPU 1026 * clock oscillator so that intrinsic frequency error is cancelled out. 1027 * The code requires the caller to capture the time and hardware counter 1028 * value at the on-time PPS signal transition. 1029 * 1030 * Note that, on some Unix systems, this routine runs at an interrupt 1031 * priority level higher than the timer interrupt routine hardclock(). 1032 * Therefore, the variables used are distinct from the hardclock() 1033 * variables, except for certain exceptions: The PPS frequency pps_freq 1034 * and phase pps_offset variables are determined by this routine and 1035 * updated atomically. The time_tolerance variable can be considered a 1036 * constant, since it is infrequently changed, and then only when the 1037 * PPS signal is disabled. The watchdog counter pps_valid is updated 1038 * once per second by hardclock() and is atomically cleared in this 1039 * routine. 1040 */ 1041 void 1042 hardpps(tvp, usec) 1043 struct timeval *tvp; /* time at PPS */ 1044 long usec; /* hardware counter at PPS */ 1045 { 1046 long u_usec, v_usec, bigtick; 1047 long cal_sec, cal_usec; 1048 1049 /* 1050 * An occasional glitch can be produced when the PPS interrupt 1051 * occurs in the hardclock() routine before the time variable is 1052 * updated. Here the offset is discarded when the difference 1053 * between it and the last one is greater than tick/2, but not 1054 * if the interval since the first discard exceeds 30 s. 1055 */ 1056 time_status |= STA_PPSSIGNAL; 1057 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR); 1058 pps_valid = 0; 1059 u_usec = -tvp->tv_usec; 1060 if (u_usec < -500000) 1061 u_usec += 1000000; 1062 v_usec = pps_offset - u_usec; 1063 if (v_usec < 0) 1064 v_usec = -v_usec; 1065 if (v_usec > (tick >> 1)) { 1066 if (pps_glitch > MAXGLITCH) { 1067 pps_glitch = 0; 1068 pps_tf[2] = u_usec; 1069 pps_tf[1] = u_usec; 1070 } else { 1071 pps_glitch++; 1072 u_usec = pps_offset; 1073 } 1074 } else 1075 pps_glitch = 0; 1076 1077 /* 1078 * A three-stage median filter is used to help deglitch the pps 1079 * time. The median sample becomes the time offset estimate; the 1080 * difference between the other two samples becomes the time 1081 * dispersion (jitter) estimate. 1082 */ 1083 pps_tf[2] = pps_tf[1]; 1084 pps_tf[1] = pps_tf[0]; 1085 pps_tf[0] = u_usec; 1086 if (pps_tf[0] > pps_tf[1]) { 1087 if (pps_tf[1] > pps_tf[2]) { 1088 pps_offset = pps_tf[1]; /* 0 1 2 */ 1089 v_usec = pps_tf[0] - pps_tf[2]; 1090 } else if (pps_tf[2] > pps_tf[0]) { 1091 pps_offset = pps_tf[0]; /* 2 0 1 */ 1092 v_usec = pps_tf[2] - pps_tf[1]; 1093 } else { 1094 pps_offset = pps_tf[2]; /* 0 2 1 */ 1095 v_usec = pps_tf[0] - pps_tf[1]; 1096 } 1097 } else { 1098 if (pps_tf[1] < pps_tf[2]) { 1099 pps_offset = pps_tf[1]; /* 2 1 0 */ 1100 v_usec = pps_tf[2] - pps_tf[0]; 1101 } else if (pps_tf[2] < pps_tf[0]) { 1102 pps_offset = pps_tf[0]; /* 1 0 2 */ 1103 v_usec = pps_tf[1] - pps_tf[2]; 1104 } else { 1105 pps_offset = pps_tf[2]; /* 1 2 0 */ 1106 v_usec = pps_tf[1] - pps_tf[0]; 1107 } 1108 } 1109 if (v_usec > MAXTIME) 1110 pps_jitcnt++; 1111 v_usec = (v_usec << PPS_AVG) - pps_jitter; 1112 if (v_usec < 0) 1113 pps_jitter -= -v_usec >> PPS_AVG; 1114 else 1115 pps_jitter += v_usec >> PPS_AVG; 1116 if (pps_jitter > (MAXTIME >> 1)) 1117 time_status |= STA_PPSJITTER; 1118 1119 /* 1120 * During the calibration interval adjust the starting time when 1121 * the tick overflows. At the end of the interval compute the 1122 * duration of the interval and the difference of the hardware 1123 * counters at the beginning and end of the interval. This code 1124 * is deliciously complicated by the fact valid differences may 1125 * exceed the value of tick when using long calibration 1126 * intervals and small ticks. Note that the counter can be 1127 * greater than tick if caught at just the wrong instant, but 1128 * the values returned and used here are correct. 1129 */ 1130 bigtick = (long)tick << SHIFT_USEC; 1131 pps_usec -= pps_freq; 1132 if (pps_usec >= bigtick) 1133 pps_usec -= bigtick; 1134 if (pps_usec < 0) 1135 pps_usec += bigtick; 1136 pps_time.tv_sec++; 1137 pps_count++; 1138 if (pps_count < (1 << pps_shift)) 1139 return; 1140 pps_count = 0; 1141 pps_calcnt++; 1142 u_usec = usec << SHIFT_USEC; 1143 v_usec = pps_usec - u_usec; 1144 if (v_usec >= bigtick >> 1) 1145 v_usec -= bigtick; 1146 if (v_usec < -(bigtick >> 1)) 1147 v_usec += bigtick; 1148 if (v_usec < 0) 1149 v_usec = -(-v_usec >> pps_shift); 1150 else 1151 v_usec = v_usec >> pps_shift; 1152 pps_usec = u_usec; 1153 cal_sec = tvp->tv_sec; 1154 cal_usec = tvp->tv_usec; 1155 cal_sec -= pps_time.tv_sec; 1156 cal_usec -= pps_time.tv_usec; 1157 if (cal_usec < 0) { 1158 cal_usec += 1000000; 1159 cal_sec--; 1160 } 1161 pps_time = *tvp; 1162 1163 /* 1164 * Check for lost interrupts, noise, excessive jitter and 1165 * excessive frequency error. The number of timer ticks during 1166 * the interval may vary +-1 tick. Add to this a margin of one 1167 * tick for the PPS signal jitter and maximum frequency 1168 * deviation. If the limits are exceeded, the calibration 1169 * interval is reset to the minimum and we start over. 1170 */ 1171 u_usec = (long)tick << 1; 1172 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec)) 1173 || (cal_sec == 0 && cal_usec < u_usec)) 1174 || v_usec > time_tolerance || v_usec < -time_tolerance) { 1175 pps_errcnt++; 1176 pps_shift = PPS_SHIFT; 1177 pps_intcnt = 0; 1178 time_status |= STA_PPSERROR; 1179 return; 1180 } 1181 1182 /* 1183 * A three-stage median filter is used to help deglitch the pps 1184 * frequency. The median sample becomes the frequency offset 1185 * estimate; the difference between the other two samples 1186 * becomes the frequency dispersion (stability) estimate. 1187 */ 1188 pps_ff[2] = pps_ff[1]; 1189 pps_ff[1] = pps_ff[0]; 1190 pps_ff[0] = v_usec; 1191 if (pps_ff[0] > pps_ff[1]) { 1192 if (pps_ff[1] > pps_ff[2]) { 1193 u_usec = pps_ff[1]; /* 0 1 2 */ 1194 v_usec = pps_ff[0] - pps_ff[2]; 1195 } else if (pps_ff[2] > pps_ff[0]) { 1196 u_usec = pps_ff[0]; /* 2 0 1 */ 1197 v_usec = pps_ff[2] - pps_ff[1]; 1198 } else { 1199 u_usec = pps_ff[2]; /* 0 2 1 */ 1200 v_usec = pps_ff[0] - pps_ff[1]; 1201 } 1202 } else { 1203 if (pps_ff[1] < pps_ff[2]) { 1204 u_usec = pps_ff[1]; /* 2 1 0 */ 1205 v_usec = pps_ff[2] - pps_ff[0]; 1206 } else if (pps_ff[2] < pps_ff[0]) { 1207 u_usec = pps_ff[0]; /* 1 0 2 */ 1208 v_usec = pps_ff[1] - pps_ff[2]; 1209 } else { 1210 u_usec = pps_ff[2]; /* 1 2 0 */ 1211 v_usec = pps_ff[1] - pps_ff[0]; 1212 } 1213 } 1214 1215 /* 1216 * Here the frequency dispersion (stability) is updated. If it 1217 * is less than one-fourth the maximum (MAXFREQ), the frequency 1218 * offset is updated as well, but clamped to the tolerance. It 1219 * will be processed later by the hardclock() routine. 1220 */ 1221 v_usec = (v_usec >> 1) - pps_stabil; 1222 if (v_usec < 0) 1223 pps_stabil -= -v_usec >> PPS_AVG; 1224 else 1225 pps_stabil += v_usec >> PPS_AVG; 1226 if (pps_stabil > MAXFREQ >> 2) { 1227 pps_stbcnt++; 1228 time_status |= STA_PPSWANDER; 1229 return; 1230 } 1231 if (time_status & STA_PPSFREQ) { 1232 if (u_usec < 0) { 1233 pps_freq -= -u_usec >> PPS_AVG; 1234 if (pps_freq < -time_tolerance) 1235 pps_freq = -time_tolerance; 1236 u_usec = -u_usec; 1237 } else { 1238 pps_freq += u_usec >> PPS_AVG; 1239 if (pps_freq > time_tolerance) 1240 pps_freq = time_tolerance; 1241 } 1242 } 1243 1244 /* 1245 * Here the calibration interval is adjusted. If the maximum 1246 * time difference is greater than tick / 4, reduce the interval 1247 * by half. If this is not the case for four consecutive 1248 * intervals, double the interval. 1249 */ 1250 if (u_usec << pps_shift > bigtick >> 2) { 1251 pps_intcnt = 0; 1252 if (pps_shift > PPS_SHIFT) 1253 pps_shift--; 1254 } else if (pps_intcnt >= 4) { 1255 pps_intcnt = 0; 1256 if (pps_shift < PPS_SHIFTMAX) 1257 pps_shift++; 1258 } else 1259 pps_intcnt++; 1260 } 1261 #endif /* PPS_SYNC */ 1262 #endif /* NTP */ 1263 1264 1265 /* 1266 * Return information about system clocks. 1267 */ 1268 int 1269 sysctl_clockrate(where, sizep) 1270 register char *where; 1271 size_t *sizep; 1272 { 1273 struct clockinfo clkinfo; 1274 1275 /* 1276 * Construct clockinfo structure. 1277 */ 1278 clkinfo.tick = tick; 1279 clkinfo.tickadj = tickadj; 1280 clkinfo.hz = hz; 1281 clkinfo.profhz = profhz; 1282 clkinfo.stathz = stathz ? stathz : hz; 1283 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo))); 1284 } 1285