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