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