Home | History | Annotate | Line # | Download | only in kern
kern_clock.c revision 1.45
      1 /*	$NetBSD: kern_clock.c,v 1.45 1999/02/23 02:56:04 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 		switch (hz) {
    610 		case 96:
    611 		case 100:
    612 			/*
    613 			 * In the following code the overall gain is increased
    614 			 * by a factor of 1.25, which results in a residual
    615 			 * error less than 3 percent.
    616 			 */
    617 			if (time_adj < 0)
    618 				time_adj -= -time_adj >> 2;
    619 			else
    620 				time_adj += time_adj >> 2;
    621 			break;
    622 		case 60:
    623 			/*
    624 			 * 60 Hz m68k and vaxes have a PLL gain factor of of
    625 			 * 60/64 (15/16) of what it should be.  In the following code
    626 			 * the overall gain is increased by a factor of 1.0625,
    627 			 * (17/16) which results in a residual error of just less
    628 			 * than 0.4 percent.
    629 			 */
    630 			if (time_adj < 0)
    631 				time_adj -= -time_adj >> 4;
    632 			else
    633 				time_adj += time_adj >> 4;
    634 			break;
    635 		case 1000:
    636 			 /*
    637 			  * Do this the simple way; we're on an alpha, are
    638 			  * the shift police going to come and get us? We
    639 			  * would get a residual error of only .82% with
    640 			  * a 5 bit right shift, but we also have 64 bits
    641 			  * in time_adj to work with for fixed point scaling.
    642 			  */
    643 			time_adj = (time_adj * 1024) / 1000;
    644 			break;
    645 		}
    646 
    647 #ifdef EXT_CLOCK
    648 		/*
    649 		 * If an external clock is present, it is necessary to
    650 		 * discipline the kernel time variable anyway, since not
    651 		 * all system components use the microtime() interface.
    652 		 * Here, the time offset between the external clock and
    653 		 * kernel time variable is computed every so often.
    654 		 */
    655 		clock_count++;
    656 		if (clock_count > CLOCK_INTERVAL) {
    657 			clock_count = 0;
    658 			microtime(&clock_ext);
    659 			delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
    660 			delta.tv_usec = clock_ext.tv_usec -
    661 			    time.tv_usec;
    662 			if (delta.tv_usec < 0)
    663 				delta.tv_sec--;
    664 			if (delta.tv_usec >= 500000) {
    665 				delta.tv_usec -= 1000000;
    666 				delta.tv_sec++;
    667 			}
    668 			if (delta.tv_usec < -500000) {
    669 				delta.tv_usec += 1000000;
    670 				delta.tv_sec--;
    671 			}
    672 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
    673 			    delta.tv_usec > MAXPHASE) ||
    674 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
    675 			    delta.tv_usec < -MAXPHASE)) {
    676 				time = clock_ext;
    677 				delta.tv_sec = 0;
    678 				delta.tv_usec = 0;
    679 			}
    680 #ifdef HIGHBALL
    681 			clock_cpu = delta.tv_usec;
    682 #else /* HIGHBALL */
    683 			hardupdate(delta.tv_usec);
    684 #endif /* HIGHBALL */
    685 		}
    686 #endif /* EXT_CLOCK */
    687 	}
    688 
    689 #endif /* NTP */
    690 
    691 	/*
    692 	 * Process callouts at a very low cpu priority, so we don't keep the
    693 	 * relatively high clock interrupt priority any longer than necessary.
    694 	 */
    695 	if (needsoft) {
    696 		if (CLKF_BASEPRI(frame)) {
    697 			/*
    698 			 * Save the overhead of a software interrupt;
    699 			 * it will happen as soon as we return, so do it now.
    700 			 */
    701 			(void)splsoftclock();
    702 			softclock();
    703 		} else
    704 			setsoftclock();
    705 	}
    706 }
    707 
    708 /*
    709  * Software (low priority) clock interrupt.
    710  * Run periodic events from timeout queue.
    711  */
    712 /*ARGSUSED*/
    713 void
    714 softclock()
    715 {
    716 	register struct callout *c;
    717 	register void *arg;
    718 	register void (*func) __P((void *));
    719 	register int s;
    720 
    721 	s = splhigh();
    722 	while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
    723 		func = c->c_func;
    724 		arg = c->c_arg;
    725 		calltodo.c_next = c->c_next;
    726 		c->c_next = callfree;
    727 		callfree = c;
    728 		splx(s);
    729 		(*func)(arg);
    730 		(void) splhigh();
    731 	}
    732 	splx(s);
    733 }
    734 
    735 /*
    736  * timeout --
    737  *	Execute a function after a specified length of time.
    738  *
    739  * untimeout --
    740  *	Cancel previous timeout function call.
    741  *
    742  *	See AT&T BCI Driver Reference Manual for specification.  This
    743  *	implementation differs from that one in that no identification
    744  *	value is returned from timeout, rather, the original arguments
    745  *	to timeout are used to identify entries for untimeout.
    746  */
    747 void
    748 timeout(ftn, arg, ticks)
    749 	void (*ftn) __P((void *));
    750 	void *arg;
    751 	register int ticks;
    752 {
    753 	register struct callout *new, *p, *t;
    754 	register int s;
    755 
    756 	if (ticks <= 0)
    757 		ticks = 1;
    758 
    759 	/* Lock out the clock. */
    760 	s = splhigh();
    761 
    762 	/* Fill in the next free callout structure. */
    763 	if (callfree == NULL)
    764 		panic("timeout table full");
    765 	new = callfree;
    766 	callfree = new->c_next;
    767 	new->c_arg = arg;
    768 	new->c_func = ftn;
    769 
    770 	/*
    771 	 * The time for each event is stored as a difference from the time
    772 	 * of the previous event on the queue.  Walk the queue, correcting
    773 	 * the ticks argument for queue entries passed.  Correct the ticks
    774 	 * value for the queue entry immediately after the insertion point
    775 	 * as well.  Watch out for negative c_time values; these represent
    776 	 * overdue events.
    777 	 */
    778 	for (p = &calltodo;
    779 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
    780 		if (t->c_time > 0)
    781 			ticks -= t->c_time;
    782 	new->c_time = ticks;
    783 	if (t != NULL)
    784 		t->c_time -= ticks;
    785 
    786 	/* Insert the new entry into the queue. */
    787 	p->c_next = new;
    788 	new->c_next = t;
    789 	splx(s);
    790 }
    791 
    792 void
    793 untimeout(ftn, arg)
    794 	void (*ftn) __P((void *));
    795 	void *arg;
    796 {
    797 	register struct callout *p, *t;
    798 	register int s;
    799 
    800 	s = splhigh();
    801 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
    802 		if (t->c_func == ftn && t->c_arg == arg) {
    803 			/* Increment next entry's tick count. */
    804 			if (t->c_next && t->c_time > 0)
    805 				t->c_next->c_time += t->c_time;
    806 
    807 			/* Move entry from callout queue to callfree queue. */
    808 			p->c_next = t->c_next;
    809 			t->c_next = callfree;
    810 			callfree = t;
    811 			break;
    812 		}
    813 	splx(s);
    814 }
    815 
    816 /*
    817  * Compute number of hz until specified time.  Used to
    818  * compute third argument to timeout() from an absolute time.
    819  */
    820 int
    821 hzto(tv)
    822 	struct timeval *tv;
    823 {
    824 	register long ticks, sec;
    825 	int s;
    826 
    827 	/*
    828 	 * If number of microseconds will fit in 32 bit arithmetic,
    829 	 * then compute number of microseconds to time and scale to
    830 	 * ticks.  Otherwise just compute number of hz in time, rounding
    831 	 * times greater than representible to maximum value.  (We must
    832 	 * compute in microseconds, because hz can be greater than 1000,
    833 	 * and thus tick can be less than one millisecond).
    834 	 *
    835 	 * Delta times less than 14 hours can be computed ``exactly''.
    836 	 * (Note that if hz would yeild a non-integral number of us per
    837 	 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
    838 	 * than they should be.)  Maximum value for any timeout in 10ms
    839 	 * ticks is 250 days.
    840 	 */
    841 	s = splclock();
    842 	sec = tv->tv_sec - time.tv_sec;
    843 	if (sec <= 0x7fffffff / 1000000 - 1)
    844 		ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
    845 			(tv->tv_usec - time.tv_usec)) / tick;
    846 	else if (sec <= 0x7fffffff / hz)
    847 		ticks = sec * hz;
    848 	else
    849 		ticks = 0x7fffffff;
    850 	splx(s);
    851 	return (ticks);
    852 }
    853 
    854 /*
    855  * Start profiling on a process.
    856  *
    857  * Kernel profiling passes proc0 which never exits and hence
    858  * keeps the profile clock running constantly.
    859  */
    860 void
    861 startprofclock(p)
    862 	register struct proc *p;
    863 {
    864 	int s;
    865 
    866 	if ((p->p_flag & P_PROFIL) == 0) {
    867 		p->p_flag |= P_PROFIL;
    868 		if (++profprocs == 1 && stathz != 0) {
    869 			s = splstatclock();
    870 			psdiv = pscnt = psratio;
    871 			setstatclockrate(profhz);
    872 			splx(s);
    873 		}
    874 	}
    875 }
    876 
    877 /*
    878  * Stop profiling on a process.
    879  */
    880 void
    881 stopprofclock(p)
    882 	register struct proc *p;
    883 {
    884 	int s;
    885 
    886 	if (p->p_flag & P_PROFIL) {
    887 		p->p_flag &= ~P_PROFIL;
    888 		if (--profprocs == 0 && stathz != 0) {
    889 			s = splstatclock();
    890 			psdiv = pscnt = 1;
    891 			setstatclockrate(stathz);
    892 			splx(s);
    893 		}
    894 	}
    895 }
    896 
    897 /*
    898  * Statistics clock.  Grab profile sample, and if divider reaches 0,
    899  * do process and kernel statistics.
    900  */
    901 void
    902 statclock(frame)
    903 	register struct clockframe *frame;
    904 {
    905 #ifdef GPROF
    906 	register struct gmonparam *g;
    907 	register int i;
    908 #endif
    909 	static int schedclk2;
    910 	register struct proc *p;
    911 
    912 	if (CLKF_USERMODE(frame)) {
    913 		p = curproc;
    914 		if (p->p_flag & P_PROFIL)
    915 			addupc_intr(p, CLKF_PC(frame), 1);
    916 		if (--pscnt > 0)
    917 			return;
    918 		/*
    919 		 * Came from user mode; CPU was in user state.
    920 		 * If this process is being profiled record the tick.
    921 		 */
    922 		p->p_uticks++;
    923 		if (p->p_nice > NZERO)
    924 			cp_time[CP_NICE]++;
    925 		else
    926 			cp_time[CP_USER]++;
    927 	} else {
    928 #ifdef GPROF
    929 		/*
    930 		 * Kernel statistics are just like addupc_intr, only easier.
    931 		 */
    932 		g = &_gmonparam;
    933 		if (g->state == GMON_PROF_ON) {
    934 			i = CLKF_PC(frame) - g->lowpc;
    935 			if (i < g->textsize) {
    936 				i /= HISTFRACTION * sizeof(*g->kcount);
    937 				g->kcount[i]++;
    938 			}
    939 		}
    940 #endif
    941 		if (--pscnt > 0)
    942 			return;
    943 		/*
    944 		 * Came from kernel mode, so we were:
    945 		 * - handling an interrupt,
    946 		 * - doing syscall or trap work on behalf of the current
    947 		 *   user process, or
    948 		 * - spinning in the idle loop.
    949 		 * Whichever it is, charge the time as appropriate.
    950 		 * Note that we charge interrupts to the current process,
    951 		 * regardless of whether they are ``for'' that process,
    952 		 * so that we know how much of its real time was spent
    953 		 * in ``non-process'' (i.e., interrupt) work.
    954 		 */
    955 		p = curproc;
    956 		if (CLKF_INTR(frame)) {
    957 			if (p != NULL)
    958 				p->p_iticks++;
    959 			cp_time[CP_INTR]++;
    960 		} else if (p != NULL) {
    961 			p->p_sticks++;
    962 			cp_time[CP_SYS]++;
    963 		} else
    964 			cp_time[CP_IDLE]++;
    965 	}
    966 	pscnt = psdiv;
    967 
    968 	if (p != NULL) {
    969 		++p->p_cpticks;
    970 		/*
    971 		 * If no schedclk is provided, call it here at ~~12-25 Hz,
    972 		 * ~~16 Hz is best
    973 		 */
    974 		if(schedhz == 0)
    975 			if ((++schedclk2 & 3) == 0)
    976 				schedclk(p);
    977 	}
    978 }
    979 
    980 
    981 #ifdef NTP	/* NTP phase-locked loop in kernel */
    982 
    983 /*
    984  * hardupdate() - local clock update
    985  *
    986  * This routine is called by ntp_adjtime() to update the local clock
    987  * phase and frequency. The implementation is of an adaptive-parameter,
    988  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
    989  * time and frequency offset estimates for each call. If the kernel PPS
    990  * discipline code is configured (PPS_SYNC), the PPS signal itself
    991  * determines the new time offset, instead of the calling argument.
    992  * Presumably, calls to ntp_adjtime() occur only when the caller
    993  * believes the local clock is valid within some bound (+-128 ms with
    994  * NTP). If the caller's time is far different than the PPS time, an
    995  * argument will ensue, and it's not clear who will lose.
    996  *
    997  * For uncompensated quartz crystal oscillatores and nominal update
    998  * intervals less than 1024 s, operation should be in phase-lock mode
    999  * (STA_FLL = 0), where the loop is disciplined to phase. For update
   1000  * intervals greater than thiss, operation should be in frequency-lock
   1001  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
   1002  *
   1003  * Note: splclock() is in effect.
   1004  */
   1005 void
   1006 hardupdate(offset)
   1007 	long offset;
   1008 {
   1009 	long ltemp, mtemp;
   1010 
   1011 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
   1012 		return;
   1013 	ltemp = offset;
   1014 #ifdef PPS_SYNC
   1015 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
   1016 		ltemp = pps_offset;
   1017 #endif /* PPS_SYNC */
   1018 
   1019 	/*
   1020 	 * Scale the phase adjustment and clamp to the operating range.
   1021 	 */
   1022 	if (ltemp > MAXPHASE)
   1023 		time_offset = MAXPHASE << SHIFT_UPDATE;
   1024 	else if (ltemp < -MAXPHASE)
   1025 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
   1026 	else
   1027 		time_offset = ltemp << SHIFT_UPDATE;
   1028 
   1029 	/*
   1030 	 * Select whether the frequency is to be controlled and in which
   1031 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
   1032 	 * multiply/divide should be replaced someday.
   1033 	 */
   1034 	if (time_status & STA_FREQHOLD || time_reftime == 0)
   1035 		time_reftime = time.tv_sec;
   1036 	mtemp = time.tv_sec - time_reftime;
   1037 	time_reftime = time.tv_sec;
   1038 	if (time_status & STA_FLL) {
   1039 		if (mtemp >= MINSEC) {
   1040 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
   1041 			    SHIFT_UPDATE));
   1042 			if (ltemp < 0)
   1043 				time_freq -= -ltemp >> SHIFT_KH;
   1044 			else
   1045 				time_freq += ltemp >> SHIFT_KH;
   1046 		}
   1047 	} else {
   1048 		if (mtemp < MAXSEC) {
   1049 			ltemp *= mtemp;
   1050 			if (ltemp < 0)
   1051 				time_freq -= -ltemp >> (time_constant +
   1052 				    time_constant + SHIFT_KF -
   1053 				    SHIFT_USEC);
   1054 			else
   1055 				time_freq += ltemp >> (time_constant +
   1056 				    time_constant + SHIFT_KF -
   1057 				    SHIFT_USEC);
   1058 		}
   1059 	}
   1060 	if (time_freq > time_tolerance)
   1061 		time_freq = time_tolerance;
   1062 	else if (time_freq < -time_tolerance)
   1063 		time_freq = -time_tolerance;
   1064 }
   1065 
   1066 #ifdef PPS_SYNC
   1067 /*
   1068  * hardpps() - discipline CPU clock oscillator to external PPS signal
   1069  *
   1070  * This routine is called at each PPS interrupt in order to discipline
   1071  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
   1072  * and leaves it in a handy spot for the hardclock() routine. It
   1073  * integrates successive PPS phase differences and calculates the
   1074  * frequency offset. This is used in hardclock() to discipline the CPU
   1075  * clock oscillator so that intrinsic frequency error is cancelled out.
   1076  * The code requires the caller to capture the time and hardware counter
   1077  * value at the on-time PPS signal transition.
   1078  *
   1079  * Note that, on some Unix systems, this routine runs at an interrupt
   1080  * priority level higher than the timer interrupt routine hardclock().
   1081  * Therefore, the variables used are distinct from the hardclock()
   1082  * variables, except for certain exceptions: The PPS frequency pps_freq
   1083  * and phase pps_offset variables are determined by this routine and
   1084  * updated atomically. The time_tolerance variable can be considered a
   1085  * constant, since it is infrequently changed, and then only when the
   1086  * PPS signal is disabled. The watchdog counter pps_valid is updated
   1087  * once per second by hardclock() and is atomically cleared in this
   1088  * routine.
   1089  */
   1090 void
   1091 hardpps(tvp, usec)
   1092 	struct timeval *tvp;		/* time at PPS */
   1093 	long usec;			/* hardware counter at PPS */
   1094 {
   1095 	long u_usec, v_usec, bigtick;
   1096 	long cal_sec, cal_usec;
   1097 
   1098 	/*
   1099 	 * An occasional glitch can be produced when the PPS interrupt
   1100 	 * occurs in the hardclock() routine before the time variable is
   1101 	 * updated. Here the offset is discarded when the difference
   1102 	 * between it and the last one is greater than tick/2, but not
   1103 	 * if the interval since the first discard exceeds 30 s.
   1104 	 */
   1105 	time_status |= STA_PPSSIGNAL;
   1106 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
   1107 	pps_valid = 0;
   1108 	u_usec = -tvp->tv_usec;
   1109 	if (u_usec < -500000)
   1110 		u_usec += 1000000;
   1111 	v_usec = pps_offset - u_usec;
   1112 	if (v_usec < 0)
   1113 		v_usec = -v_usec;
   1114 	if (v_usec > (tick >> 1)) {
   1115 		if (pps_glitch > MAXGLITCH) {
   1116 			pps_glitch = 0;
   1117 			pps_tf[2] = u_usec;
   1118 			pps_tf[1] = u_usec;
   1119 		} else {
   1120 			pps_glitch++;
   1121 			u_usec = pps_offset;
   1122 		}
   1123 	} else
   1124 		pps_glitch = 0;
   1125 
   1126 	/*
   1127 	 * A three-stage median filter is used to help deglitch the pps
   1128 	 * time. The median sample becomes the time offset estimate; the
   1129 	 * difference between the other two samples becomes the time
   1130 	 * dispersion (jitter) estimate.
   1131 	 */
   1132 	pps_tf[2] = pps_tf[1];
   1133 	pps_tf[1] = pps_tf[0];
   1134 	pps_tf[0] = u_usec;
   1135 	if (pps_tf[0] > pps_tf[1]) {
   1136 		if (pps_tf[1] > pps_tf[2]) {
   1137 			pps_offset = pps_tf[1];		/* 0 1 2 */
   1138 			v_usec = pps_tf[0] - pps_tf[2];
   1139 		} else if (pps_tf[2] > pps_tf[0]) {
   1140 			pps_offset = pps_tf[0];		/* 2 0 1 */
   1141 			v_usec = pps_tf[2] - pps_tf[1];
   1142 		} else {
   1143 			pps_offset = pps_tf[2];		/* 0 2 1 */
   1144 			v_usec = pps_tf[0] - pps_tf[1];
   1145 		}
   1146 	} else {
   1147 		if (pps_tf[1] < pps_tf[2]) {
   1148 			pps_offset = pps_tf[1];		/* 2 1 0 */
   1149 			v_usec = pps_tf[2] - pps_tf[0];
   1150 		} else  if (pps_tf[2] < pps_tf[0]) {
   1151 			pps_offset = pps_tf[0];		/* 1 0 2 */
   1152 			v_usec = pps_tf[1] - pps_tf[2];
   1153 		} else {
   1154 			pps_offset = pps_tf[2];		/* 1 2 0 */
   1155 			v_usec = pps_tf[1] - pps_tf[0];
   1156 		}
   1157 	}
   1158 	if (v_usec > MAXTIME)
   1159 		pps_jitcnt++;
   1160 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
   1161 	if (v_usec < 0)
   1162 		pps_jitter -= -v_usec >> PPS_AVG;
   1163 	else
   1164 		pps_jitter += v_usec >> PPS_AVG;
   1165 	if (pps_jitter > (MAXTIME >> 1))
   1166 		time_status |= STA_PPSJITTER;
   1167 
   1168 	/*
   1169 	 * During the calibration interval adjust the starting time when
   1170 	 * the tick overflows. At the end of the interval compute the
   1171 	 * duration of the interval and the difference of the hardware
   1172 	 * counters at the beginning and end of the interval. This code
   1173 	 * is deliciously complicated by the fact valid differences may
   1174 	 * exceed the value of tick when using long calibration
   1175 	 * intervals and small ticks. Note that the counter can be
   1176 	 * greater than tick if caught at just the wrong instant, but
   1177 	 * the values returned and used here are correct.
   1178 	 */
   1179 	bigtick = (long)tick << SHIFT_USEC;
   1180 	pps_usec -= pps_freq;
   1181 	if (pps_usec >= bigtick)
   1182 		pps_usec -= bigtick;
   1183 	if (pps_usec < 0)
   1184 		pps_usec += bigtick;
   1185 	pps_time.tv_sec++;
   1186 	pps_count++;
   1187 	if (pps_count < (1 << pps_shift))
   1188 		return;
   1189 	pps_count = 0;
   1190 	pps_calcnt++;
   1191 	u_usec = usec << SHIFT_USEC;
   1192 	v_usec = pps_usec - u_usec;
   1193 	if (v_usec >= bigtick >> 1)
   1194 		v_usec -= bigtick;
   1195 	if (v_usec < -(bigtick >> 1))
   1196 		v_usec += bigtick;
   1197 	if (v_usec < 0)
   1198 		v_usec = -(-v_usec >> pps_shift);
   1199 	else
   1200 		v_usec = v_usec >> pps_shift;
   1201 	pps_usec = u_usec;
   1202 	cal_sec = tvp->tv_sec;
   1203 	cal_usec = tvp->tv_usec;
   1204 	cal_sec -= pps_time.tv_sec;
   1205 	cal_usec -= pps_time.tv_usec;
   1206 	if (cal_usec < 0) {
   1207 		cal_usec += 1000000;
   1208 		cal_sec--;
   1209 	}
   1210 	pps_time = *tvp;
   1211 
   1212 	/*
   1213 	 * Check for lost interrupts, noise, excessive jitter and
   1214 	 * excessive frequency error. The number of timer ticks during
   1215 	 * the interval may vary +-1 tick. Add to this a margin of one
   1216 	 * tick for the PPS signal jitter and maximum frequency
   1217 	 * deviation. If the limits are exceeded, the calibration
   1218 	 * interval is reset to the minimum and we start over.
   1219 	 */
   1220 	u_usec = (long)tick << 1;
   1221 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
   1222 	    || (cal_sec == 0 && cal_usec < u_usec))
   1223 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
   1224 		pps_errcnt++;
   1225 		pps_shift = PPS_SHIFT;
   1226 		pps_intcnt = 0;
   1227 		time_status |= STA_PPSERROR;
   1228 		return;
   1229 	}
   1230 
   1231 	/*
   1232 	 * A three-stage median filter is used to help deglitch the pps
   1233 	 * frequency. The median sample becomes the frequency offset
   1234 	 * estimate; the difference between the other two samples
   1235 	 * becomes the frequency dispersion (stability) estimate.
   1236 	 */
   1237 	pps_ff[2] = pps_ff[1];
   1238 	pps_ff[1] = pps_ff[0];
   1239 	pps_ff[0] = v_usec;
   1240 	if (pps_ff[0] > pps_ff[1]) {
   1241 		if (pps_ff[1] > pps_ff[2]) {
   1242 			u_usec = pps_ff[1];		/* 0 1 2 */
   1243 			v_usec = pps_ff[0] - pps_ff[2];
   1244 		} else if (pps_ff[2] > pps_ff[0]) {
   1245 			u_usec = pps_ff[0];		/* 2 0 1 */
   1246 			v_usec = pps_ff[2] - pps_ff[1];
   1247 		} else {
   1248 			u_usec = pps_ff[2];		/* 0 2 1 */
   1249 			v_usec = pps_ff[0] - pps_ff[1];
   1250 		}
   1251 	} else {
   1252 		if (pps_ff[1] < pps_ff[2]) {
   1253 			u_usec = pps_ff[1];		/* 2 1 0 */
   1254 			v_usec = pps_ff[2] - pps_ff[0];
   1255 		} else  if (pps_ff[2] < pps_ff[0]) {
   1256 			u_usec = pps_ff[0];		/* 1 0 2 */
   1257 			v_usec = pps_ff[1] - pps_ff[2];
   1258 		} else {
   1259 			u_usec = pps_ff[2];		/* 1 2 0 */
   1260 			v_usec = pps_ff[1] - pps_ff[0];
   1261 		}
   1262 	}
   1263 
   1264 	/*
   1265 	 * Here the frequency dispersion (stability) is updated. If it
   1266 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
   1267 	 * offset is updated as well, but clamped to the tolerance. It
   1268 	 * will be processed later by the hardclock() routine.
   1269 	 */
   1270 	v_usec = (v_usec >> 1) - pps_stabil;
   1271 	if (v_usec < 0)
   1272 		pps_stabil -= -v_usec >> PPS_AVG;
   1273 	else
   1274 		pps_stabil += v_usec >> PPS_AVG;
   1275 	if (pps_stabil > MAXFREQ >> 2) {
   1276 		pps_stbcnt++;
   1277 		time_status |= STA_PPSWANDER;
   1278 		return;
   1279 	}
   1280 	if (time_status & STA_PPSFREQ) {
   1281 		if (u_usec < 0) {
   1282 			pps_freq -= -u_usec >> PPS_AVG;
   1283 			if (pps_freq < -time_tolerance)
   1284 				pps_freq = -time_tolerance;
   1285 			u_usec = -u_usec;
   1286 		} else {
   1287 			pps_freq += u_usec >> PPS_AVG;
   1288 			if (pps_freq > time_tolerance)
   1289 				pps_freq = time_tolerance;
   1290 		}
   1291 	}
   1292 
   1293 	/*
   1294 	 * Here the calibration interval is adjusted. If the maximum
   1295 	 * time difference is greater than tick / 4, reduce the interval
   1296 	 * by half. If this is not the case for four consecutive
   1297 	 * intervals, double the interval.
   1298 	 */
   1299 	if (u_usec << pps_shift > bigtick >> 2) {
   1300 		pps_intcnt = 0;
   1301 		if (pps_shift > PPS_SHIFT)
   1302 			pps_shift--;
   1303 	} else if (pps_intcnt >= 4) {
   1304 		pps_intcnt = 0;
   1305 		if (pps_shift < PPS_SHIFTMAX)
   1306 			pps_shift++;
   1307 	} else
   1308 		pps_intcnt++;
   1309 }
   1310 #endif /* PPS_SYNC */
   1311 #endif /* NTP  */
   1312 
   1313 
   1314 /*
   1315  * Return information about system clocks.
   1316  */
   1317 int
   1318 sysctl_clockrate(where, sizep)
   1319 	register char *where;
   1320 	size_t *sizep;
   1321 {
   1322 	struct clockinfo clkinfo;
   1323 
   1324 	/*
   1325 	 * Construct clockinfo structure.
   1326 	 */
   1327 	clkinfo.tick = tick;
   1328 	clkinfo.tickadj = tickadj;
   1329 	clkinfo.hz = hz;
   1330 	clkinfo.profhz = profhz;
   1331 	clkinfo.stathz = stathz ? stathz : hz;
   1332 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
   1333 }
   1334 
   1335