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