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