Home | History | Annotate | Line # | Download | only in kern
kern_clock.c revision 1.30
      1 /*	$NetBSD: kern_clock.c,v 1.30 1996/03/08 06:27:30 mycroft 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 <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/dkstat.h>
     46 #include <sys/callout.h>
     47 #include <sys/kernel.h>
     48 #include <sys/proc.h>
     49 #include <sys/resourcevar.h>
     50 #include <sys/signalvar.h>
     51 #include <sys/cpu.h>
     52 #include <vm/vm.h>
     53 #include <sys/sysctl.h>
     54 #include <sys/timex.h>
     55 
     56 #include <machine/cpu.h>
     57 
     58 #ifdef GPROF
     59 #include <sys/gmon.h>
     60 #endif
     61 
     62 /*
     63  * Clock handling routines.
     64  *
     65  * This code is written to operate with two timers that run independently of
     66  * each other.  The main clock, running hz times per second, is used to keep
     67  * track of real time.  The second timer handles kernel and user profiling,
     68  * and does resource use estimation.  If the second timer is programmable,
     69  * it is randomized to avoid aliasing between the two clocks.  For example,
     70  * the randomization prevents an adversary from always giving up the cpu
     71  * just before its quantum expires.  Otherwise, it would never accumulate
     72  * cpu ticks.  The mean frequency of the second timer is stathz.
     73  *
     74  * If no second timer exists, stathz will be zero; in this case we drive
     75  * profiling and statistics off the main clock.  This WILL NOT be accurate;
     76  * do not do it unless absolutely necessary.
     77  *
     78  * The statistics clock may (or may not) be run at a higher rate while
     79  * profiling.  This profile clock runs at profhz.  We require that profhz
     80  * be an integral multiple of stathz.
     81  *
     82  * If the statistics clock is running fast, it must be divided by the ratio
     83  * profhz/stathz for statistics.  (For profiling, every tick counts.)
     84  */
     85 
     86 /*
     87  * TODO:
     88  *	allocate more timeout table slots when table overflows.
     89  */
     90 
     91 
     92 #ifdef NTP	/* NTP phase-locked loop in kernel */
     93 /*
     94  * Phase/frequency-lock loop (PLL/FLL) definitions
     95  *
     96  * The following variables are read and set by the ntp_adjtime() system
     97  * call.
     98  *
     99  * time_state shows the state of the system clock, with values defined
    100  * in the timex.h header file.
    101  *
    102  * time_status shows the status of the system clock, with bits defined
    103  * in the timex.h header file.
    104  *
    105  * time_offset is used by the PLL/FLL to adjust the system time in small
    106  * increments.
    107  *
    108  * time_constant determines the bandwidth or "stiffness" of the PLL.
    109  *
    110  * time_tolerance determines maximum frequency error or tolerance of the
    111  * CPU clock oscillator and is a property of the architecture; however,
    112  * in principle it could change as result of the presence of external
    113  * discipline signals, for instance.
    114  *
    115  * time_precision is usually equal to the kernel tick variable; however,
    116  * in cases where a precision clock counter or external clock is
    117  * available, the resolution can be much less than this and depend on
    118  * whether the external clock is working or not.
    119  *
    120  * time_maxerror is initialized by a ntp_adjtime() call and increased by
    121  * the kernel once each second to reflect the maximum error bound
    122  * growth.
    123  *
    124  * time_esterror is set and read by the ntp_adjtime() call, but
    125  * otherwise not used by the kernel.
    126  */
    127 int time_state = TIME_OK;	/* clock state */
    128 int time_status = STA_UNSYNC;	/* clock status bits */
    129 long time_offset = 0;		/* time offset (us) */
    130 long time_constant = 0;		/* pll time constant */
    131 long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
    132 long time_precision = 1;	/* clock precision (us) */
    133 long time_maxerror = MAXPHASE;	/* maximum error (us) */
    134 long time_esterror = MAXPHASE;	/* estimated error (us) */
    135 
    136 /*
    137  * The following variables establish the state of the PLL/FLL and the
    138  * residual time and frequency offset of the local clock. The scale
    139  * factors are defined in the timex.h header file.
    140  *
    141  * time_phase and time_freq are the phase increment and the frequency
    142  * increment, respectively, of the kernel time variable.
    143  *
    144  * time_freq is set via ntp_adjtime() from a value stored in a file when
    145  * the synchronization daemon is first started. Its value is retrieved
    146  * via ntp_adjtime() and written to the file about once per hour by the
    147  * daemon.
    148  *
    149  * time_adj is the adjustment added to the value of tick at each timer
    150  * interrupt and is recomputed from time_phase and time_freq at each
    151  * seconds rollover.
    152  *
    153  * time_reftime is the second's portion of the system time at the last
    154  * call to ntp_adjtime(). It is used to adjust the time_freq variable
    155  * and to increase the time_maxerror as the time since last update
    156  * increases.
    157  */
    158 long time_phase = 0;		/* phase offset (scaled us) */
    159 long time_freq = 0;		/* frequency offset (scaled ppm) */
    160 long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
    161 long time_reftime = 0;		/* time at last adjustment (s) */
    162 
    163 #ifdef PPS_SYNC
    164 /*
    165  * The following variables are used only if the kernel PPS discipline
    166  * code is configured (PPS_SYNC). The scale factors are defined in the
    167  * timex.h header file.
    168  *
    169  * pps_time contains the time at each calibration interval, as read by
    170  * microtime(). pps_count counts the seconds of the calibration
    171  * interval, the duration of which is nominally pps_shift in powers of
    172  * two.
    173  *
    174  * pps_offset is the time offset produced by the time median filter
    175  * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
    176  * this filter.
    177  *
    178  * pps_freq is the frequency offset produced by the frequency median
    179  * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
    180  * by this filter.
    181  *
    182  * pps_usec is latched from a high resolution counter or external clock
    183  * at pps_time. Here we want the hardware counter contents only, not the
    184  * contents plus the time_tv.usec as usual.
    185  *
    186  * pps_valid counts the number of seconds since the last PPS update. It
    187  * is used as a watchdog timer to disable the PPS discipline should the
    188  * PPS signal be lost.
    189  *
    190  * pps_glitch counts the number of seconds since the beginning of an
    191  * offset burst more than tick/2 from current nominal offset. It is used
    192  * mainly to suppress error bursts due to priority conflicts between the
    193  * PPS interrupt and timer interrupt.
    194  *
    195  * pps_intcnt counts the calibration intervals for use in the interval-
    196  * adaptation algorithm. It's just too complicated for words.
    197  */
    198 struct timeval pps_time;	/* kernel time at last interval */
    199 long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
    200 long pps_offset = 0;		/* pps time offset (us) */
    201 long pps_jitter = MAXTIME;	/* time dispersion (jitter) (us) */
    202 long pps_ff[] = {0, 0, 0};	/* pps frequency offset median filter */
    203 long pps_freq = 0;		/* frequency offset (scaled ppm) */
    204 long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
    205 long pps_usec = 0;		/* microsec counter at last interval */
    206 long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
    207 int pps_glitch = 0;		/* pps signal glitch counter */
    208 int pps_count = 0;		/* calibration interval counter (s) */
    209 int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
    210 int pps_intcnt = 0;		/* intervals at current duration */
    211 
    212 /*
    213  * PPS signal quality monitors
    214  *
    215  * pps_jitcnt counts the seconds that have been discarded because the
    216  * jitter measured by the time median filter exceeds the limit MAXTIME
    217  * (100 us).
    218  *
    219  * pps_calcnt counts the frequency calibration intervals, which are
    220  * variable from 4 s to 256 s.
    221  *
    222  * pps_errcnt counts the calibration intervals which have been discarded
    223  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
    224  * calibration interval jitter exceeds two ticks.
    225  *
    226  * pps_stbcnt counts the calibration intervals that have been discarded
    227  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
    228  */
    229 long pps_jitcnt = 0;		/* jitter limit exceeded */
    230 long pps_calcnt = 0;		/* calibration intervals */
    231 long pps_errcnt = 0;		/* calibration errors */
    232 long pps_stbcnt = 0;		/* stability limit exceeded */
    233 #endif /* PPS_SYNC */
    234 
    235 #ifdef EXT_CLOCK
    236 /*
    237  * External clock definitions
    238  *
    239  * The following definitions and declarations are used only if an
    240  * external clock is configured on the system.
    241  */
    242 #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
    243 
    244 /*
    245  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
    246  * interrupt and decremented once each second.
    247  */
    248 int clock_count = 0;		/* CPU clock counter */
    249 
    250 #ifdef HIGHBALL
    251 /*
    252  * The clock_offset and clock_cpu variables are used by the HIGHBALL
    253  * interface. The clock_offset variable defines the offset between
    254  * system time and the HIGBALL counters. The clock_cpu variable contains
    255  * the offset between the system clock and the HIGHBALL clock for use in
    256  * disciplining the kernel time variable.
    257  */
    258 extern struct timeval clock_offset; /* Highball clock offset */
    259 long clock_cpu = 0;		/* CPU clock adjust */
    260 #endif /* HIGHBALL */
    261 #endif /* EXT_CLOCK */
    262 
    263 /*
    264  * NetBSD notes:
    265  *
    266  * SHIFT_HZ is strongly recommended to be a constant, not a variable,
    267  * for performance reasons, so we define it appropriately here.
    268  * Ataris uses 48, or 96 Hz (as well as 64). Sparcs and Sun-3s use
    269  * 100Hz.  Non-power-of-two values for HZ are rounded up when
    270  * we define SHIFT_HZ, and then special-cased in the kernel
    271  * timekeeping code in kern_clock.c.
    272  * Alphas use 1024.  Decstations use 256, which covers all the powers
    273  * of 2 from 64 to 1024, inclusive.
    274  * Precision timekeeping does not support 48 Hz, so Ataris at 48Hz are
    275  * out of luck.
    276  */
    277 
    278 #if HZ == 64 || HZ == 60
    279 # define SHIFT_HZ 6		/* log2(64) */
    280 #else
    281 #if HZ == 128 || HZ == 100 ||  HZ == 96
    282 # define SHIFT_HZ 7		/* log2(128), 100 and 96 are fudged. */
    283 #else
    284 #if HZ == 256
    285 # define SHIFT_HZ 8		/* log2(256) */
    286 #else
    287 #if HZ == 1024
    288 # define SHIFT_HZ 10		/* log2(1024) */
    289 #else
    290 #error HZ is not a supported value. Please change HZ in your kernel config file
    291 #endif /* 1024Hz */
    292 #endif /* 256Hz */
    293 #endif /* 128HZ or 100Hz (or 96Hz, untested) */
    294 #endif /* 64Hz or 60Hz */
    295 
    296 /*
    297  * End of SHIFT_HZ computation
    298  */
    299 
    300 #endif /* NTP */
    301 
    302 
    303 /*
    304  * Bump a timeval by a small number of usec's.
    305  */
    306 #define BUMPTIME(t, usec) { \
    307 	register volatile struct timeval *tp = (t); \
    308 	register long us; \
    309  \
    310 	tp->tv_usec = us = tp->tv_usec + (usec); \
    311 	if (us >= 1000000) { \
    312 		tp->tv_usec = us - 1000000; \
    313 		tp->tv_sec++; \
    314 	} \
    315 }
    316 
    317 int	stathz;
    318 int	profhz;
    319 int	profprocs;
    320 int	ticks;
    321 static int psdiv, pscnt;		/* prof => stat divider */
    322 int	psratio;			/* ratio: prof / stat */
    323 int	tickfix, tickfixinterval;	/* used if tick not really integral */
    324 static int tickfixcnt;			/* number of ticks since last fix */
    325 int	fixtick;			/* used by NTP for same */
    326 
    327 volatile struct	timeval time;
    328 volatile struct	timeval mono_time;
    329 
    330 /*
    331  * Initialize clock frequencies and start both clocks running.
    332  */
    333 void
    334 initclocks()
    335 {
    336 	register int i;
    337 
    338 	/*
    339 	 * Set divisors to 1 (normal case) and let the machine-specific
    340 	 * code do its bit.
    341 	 */
    342 	psdiv = pscnt = 1;
    343 	cpu_initclocks();
    344 
    345 	/*
    346 	 * Compute profhz/stathz, and fix profhz if needed.
    347 	 */
    348 	i = stathz ? stathz : hz;
    349 	if (profhz == 0)
    350 		profhz = i;
    351 	psratio = profhz / i;
    352 }
    353 
    354 /*
    355  * The real-time timer, interrupting hz times per second.
    356  */
    357 void
    358 hardclock(frame)
    359 	register struct clockframe *frame;
    360 {
    361 	register struct callout *p1;
    362 	register struct proc *p;
    363 	register int delta, needsoft;
    364 	extern int tickdelta;
    365 	extern long timedelta;
    366 #ifdef NTP
    367 	register int time_update;
    368 	register int ltemp;
    369 #endif
    370 
    371 	/*
    372 	 * Update real-time timeout queue.
    373 	 * At front of queue are some number of events which are ``due''.
    374 	 * The time to these is <= 0 and if negative represents the
    375 	 * number of ticks which have passed since it was supposed to happen.
    376 	 * The rest of the q elements (times > 0) are events yet to happen,
    377 	 * where the time for each is given as a delta from the previous.
    378 	 * Decrementing just the first of these serves to decrement the time
    379 	 * to all events.
    380 	 */
    381 	needsoft = 0;
    382 	for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
    383 		if (--p1->c_time > 0)
    384 			break;
    385 		needsoft = 1;
    386 		if (p1->c_time == 0)
    387 			break;
    388 	}
    389 
    390 	p = curproc;
    391 	if (p) {
    392 		register struct pstats *pstats;
    393 
    394 		/*
    395 		 * Run current process's virtual and profile time, as needed.
    396 		 */
    397 		pstats = p->p_stats;
    398 		if (CLKF_USERMODE(frame) &&
    399 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
    400 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
    401 			psignal(p, SIGVTALRM);
    402 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
    403 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
    404 			psignal(p, SIGPROF);
    405 	}
    406 
    407 	/*
    408 	 * If no separate statistics clock is available, run it from here.
    409 	 */
    410 	if (stathz == 0)
    411 		statclock(frame);
    412 
    413 	/*
    414 	 * Increment the time-of-day.  The increment is normally just
    415 	 * ``tick''.  If the machine is one which has a clock frequency
    416 	 * such that ``hz'' would not divide the second evenly into
    417 	 * milliseconds, a periodic adjustment must be applied.  Finally,
    418 	 * if we are still adjusting the time (see adjtime()),
    419 	 * ``tickdelta'' may also be added in.
    420 	 */
    421 	ticks++;
    422 	delta = tick;
    423 
    424 #ifndef NTP
    425 	if (tickfix) {
    426 		tickfixcnt++;
    427 		if (tickfixcnt >= tickfixinterval) {
    428 			delta += tickfix;
    429 			tickfixcnt = 0;
    430 		}
    431 	}
    432 #endif /* !NTP */
    433 	/* Imprecise 4bsd adjtime() handling */
    434 	if (timedelta != 0) {
    435 		delta = tick + tickdelta;
    436 		timedelta -= tickdelta;
    437 	}
    438 
    439 #ifdef notyet
    440 	microset();
    441 #endif
    442 
    443 #ifndef NTP
    444 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
    445 #endif
    446 	BUMPTIME(&mono_time, delta);
    447 
    448 #ifdef NTP	/* XXX Start of David L. Mills' ntp precision-time fragment */
    449 	time_update = delta;
    450 
    451 	/*
    452 	 * Beginning of precision-kernel code fragment
    453 	 *
    454 	 * Compute the phase adjustment. If the low-order bits
    455 	 * (time_phase) of the update overflow, bump the high-order bits
    456 	 * (time_update).
    457 	 */
    458 	time_phase += time_adj;
    459 	if (time_phase <= -FINEUSEC) {
    460 		ltemp = -time_phase >> SHIFT_SCALE;
    461 		time_phase += ltemp << SHIFT_SCALE;
    462 		time_update -= ltemp;
    463 	}
    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 
    527 			case TIME_OK:
    528 			if (time_status & STA_INS)
    529 				time_state = TIME_INS;
    530 			else if (time_status & STA_DEL)
    531 				time_state = TIME_DEL;
    532 			break;
    533 
    534 			case TIME_INS:
    535 			if (time.tv_sec % 86400 == 0) {
    536 				time.tv_sec--;
    537 				time_state = TIME_OOP;
    538 			}
    539 			break;
    540 
    541 			case TIME_DEL:
    542 			if ((time.tv_sec + 1) % 86400 == 0) {
    543 				time.tv_sec++;
    544 				time_state = TIME_WAIT;
    545 			}
    546 			break;
    547 
    548 			case TIME_OOP:
    549 			time_state = TIME_WAIT;
    550 			break;
    551 
    552 			case TIME_WAIT:
    553 			if (!(time_status & (STA_INS | STA_DEL)))
    554 				time_state = TIME_OK;
    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 << (SHIFT_SCALE - SHIFT_HZ -
    575 			    SHIFT_UPDATE);
    576 		} else {
    577 			ltemp = time_offset;
    578 			if (!(time_status & STA_FLL))
    579 				ltemp >>= SHIFT_KG + time_constant;
    580 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
    581 				ltemp = (MAXPHASE / MINSEC) <<
    582 				    SHIFT_UPDATE;
    583 			time_offset -= ltemp;
    584 			time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ -
    585 			    SHIFT_UPDATE);
    586 		}
    587 
    588 		/*
    589 		 * Compute the frequency estimate and additional phase
    590 		 * adjustment due to frequency error for the next
    591 		 * second. When the PPS signal is engaged, gnaw on the
    592 		 * watchdog counter and update the frequency computed by
    593 		 * the pll and the PPS signal.
    594 		 */
    595 #ifdef PPS_SYNC
    596 		pps_valid++;
    597 		if (pps_valid == PPS_VALID) {
    598 			pps_jitter = MAXTIME;
    599 			pps_stabil = MAXFREQ;
    600 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
    601 			    STA_PPSWANDER | STA_PPSERROR);
    602 		}
    603 		ltemp = time_freq + pps_freq;
    604 #else
    605 		ltemp = time_freq;
    606 #endif /* PPS_SYNC */
    607 
    608 		if (ltemp < 0)
    609 			time_adj -= -ltemp >>
    610 			    (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
    611 		else
    612 			time_adj += ltemp >>
    613 			    (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
    614 		time_adj += (long)fixtick << (SHIFT_SCALE - SHIFT_HZ);
    615 
    616 
    617 #if SHIFT_HZ == 7
    618 		/*
    619 		 * When the CPU clock oscillator frequency is not a
    620 		 * power of 2 in Hz, the SHIFT_HZ is only an approximate
    621 		 * scale factor. In the SunOS kernel, this results in a
    622 		 * PLL gain factor of 1/1.28 = 0.78 what it should be.
    623 		 * In the following code the overall gain is increased
    624 		 * by a factor of 1.25, which results in a residual
    625 		 * error less than 3 percent.
    626 		 */
    627 		if (hz == 100) {
    628 			if (time_adj < 0)
    629 				time_adj -= -time_adj >> 2;
    630 			else
    631 				time_adj += time_adj >> 2;
    632 		}
    633 		else
    634 		if (hz == 96) {
    635 			if (time_adj < 0)
    636 				time_adj -= -time_adj >> 2;
    637 			else
    638 				time_adj += time_adj >> 2;
    639 		}
    640 
    641 #endif /* SHIFT_HZ */
    642 #if SHIFT_HZ == 6
    643 		/*
    644 		 * 60 Hz m68k and vaxes have a PLL gain factor of of
    645 		 * 60/64 (15/16) of what it should be.  In the following code
    646 		 * the overall gain is increased by a factor of 1.0625,
    647 		 * (17/16) which results in a residual error of just less
    648 		 * than 0.4 percent.
    649 		 */
    650 		if (hz == 60) {
    651 			if (time_adj < 0)
    652 				time_adj -= -time_adj >> 4;
    653 			else
    654 				time_adj += time_adj >> 4;
    655 		}
    656 #endif /* SHIFT_HZ */
    657 
    658 #ifdef EXT_CLOCK
    659 		/*
    660 		 * If an external clock is present, it is necessary to
    661 		 * discipline the kernel time variable anyway, since not
    662 		 * all system components use the microtime() interface.
    663 		 * Here, the time offset between the external clock and
    664 		 * kernel time variable is computed every so often.
    665 		 */
    666 		clock_count++;
    667 		if (clock_count > CLOCK_INTERVAL) {
    668 			clock_count = 0;
    669 			microtime(&clock_ext);
    670 			delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
    671 			delta.tv_usec = clock_ext.tv_usec -
    672 			    time.tv_usec;
    673 			if (delta.tv_usec < 0)
    674 				delta.tv_sec--;
    675 			if (delta.tv_usec >= 500000) {
    676 				delta.tv_usec -= 1000000;
    677 				delta.tv_sec++;
    678 			}
    679 			if (delta.tv_usec < -500000) {
    680 				delta.tv_usec += 1000000;
    681 				delta.tv_sec--;
    682 			}
    683 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
    684 			    delta.tv_usec > MAXPHASE) ||
    685 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
    686 			    delta.tv_usec < -MAXPHASE)) {
    687 				time = clock_ext;
    688 				delta.tv_sec = 0;
    689 				delta.tv_usec = 0;
    690 			}
    691 #ifdef HIGHBALL
    692 			clock_cpu = delta.tv_usec;
    693 #else /* HIGHBALL */
    694 			hardupdate(delta.tv_usec);
    695 #endif /* HIGHBALL */
    696 		}
    697 #endif /* EXT_CLOCK */
    698 	}
    699 
    700 	/*
    701 	 * End of precision-kernel code fragment
    702 	 */
    703 #endif /*NTP*/	/* XXX End of David L. Mills' ntp precision-time fragment */
    704 
    705 	/*
    706 	 * Process callouts at a very low cpu priority, so we don't keep the
    707 	 * relatively high clock interrupt priority any longer than necessary.
    708 	 */
    709 	if (needsoft) {
    710 		if (CLKF_BASEPRI(frame)) {
    711 			/*
    712 			 * Save the overhead of a software interrupt;
    713 			 * it will happen as soon as we return, so do it now.
    714 			 */
    715 			(void)splsoftclock();
    716 			softclock();
    717 		} else
    718 			setsoftclock();
    719 	}
    720 }
    721 
    722 /*
    723  * Software (low priority) clock interrupt.
    724  * Run periodic events from timeout queue.
    725  */
    726 /*ARGSUSED*/
    727 void
    728 softclock()
    729 {
    730 	register struct callout *c;
    731 	register void *arg;
    732 	register void (*func) __P((void *));
    733 	register int s;
    734 
    735 	s = splhigh();
    736 	while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
    737 		func = c->c_func;
    738 		arg = c->c_arg;
    739 		calltodo.c_next = c->c_next;
    740 		c->c_next = callfree;
    741 		callfree = c;
    742 		splx(s);
    743 		(*func)(arg);
    744 		(void) splhigh();
    745 	}
    746 	splx(s);
    747 }
    748 
    749 /*
    750  * timeout --
    751  *	Execute a function after a specified length of time.
    752  *
    753  * untimeout --
    754  *	Cancel previous timeout function call.
    755  *
    756  *	See AT&T BCI Driver Reference Manual for specification.  This
    757  *	implementation differs from that one in that no identification
    758  *	value is returned from timeout, rather, the original arguments
    759  *	to timeout are used to identify entries for untimeout.
    760  */
    761 void
    762 timeout(ftn, arg, ticks)
    763 	void (*ftn) __P((void *));
    764 	void *arg;
    765 	register int ticks;
    766 {
    767 	register struct callout *new, *p, *t;
    768 	register int s;
    769 
    770 	if (ticks <= 0)
    771 		ticks = 1;
    772 
    773 	/* Lock out the clock. */
    774 	s = splhigh();
    775 
    776 	/* Fill in the next free callout structure. */
    777 	if (callfree == NULL)
    778 		panic("timeout table full");
    779 	new = callfree;
    780 	callfree = new->c_next;
    781 	new->c_arg = arg;
    782 	new->c_func = ftn;
    783 
    784 	/*
    785 	 * The time for each event is stored as a difference from the time
    786 	 * of the previous event on the queue.  Walk the queue, correcting
    787 	 * the ticks argument for queue entries passed.  Correct the ticks
    788 	 * value for the queue entry immediately after the insertion point
    789 	 * as well.  Watch out for negative c_time values; these represent
    790 	 * overdue events.
    791 	 */
    792 	for (p = &calltodo;
    793 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
    794 		if (t->c_time > 0)
    795 			ticks -= t->c_time;
    796 	new->c_time = ticks;
    797 	if (t != NULL)
    798 		t->c_time -= ticks;
    799 
    800 	/* Insert the new entry into the queue. */
    801 	p->c_next = new;
    802 	new->c_next = t;
    803 	splx(s);
    804 }
    805 
    806 void
    807 untimeout(ftn, arg)
    808 	void (*ftn) __P((void *));
    809 	void *arg;
    810 {
    811 	register struct callout *p, *t;
    812 	register int s;
    813 
    814 	s = splhigh();
    815 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
    816 		if (t->c_func == ftn && t->c_arg == arg) {
    817 			/* Increment next entry's tick count. */
    818 			if (t->c_next && t->c_time > 0)
    819 				t->c_next->c_time += t->c_time;
    820 
    821 			/* Move entry from callout queue to callfree queue. */
    822 			p->c_next = t->c_next;
    823 			t->c_next = callfree;
    824 			callfree = t;
    825 			break;
    826 		}
    827 	splx(s);
    828 }
    829 
    830 /*
    831  * Compute number of hz until specified time.  Used to
    832  * compute third argument to timeout() from an absolute time.
    833  */
    834 int
    835 hzto(tv)
    836 	struct timeval *tv;
    837 {
    838 	register long ticks, sec;
    839 	int s;
    840 
    841 	/*
    842 	 * If number of microseconds will fit in 32 bit arithmetic,
    843 	 * then compute number of microseconds to time and scale to
    844 	 * ticks.  Otherwise just compute number of hz in time, rounding
    845 	 * times greater than representible to maximum value.  (We must
    846 	 * compute in microseconds, because hz can be greater than 1000,
    847 	 * and thus tick can be less than one millisecond).
    848 	 *
    849 	 * Delta times less than 14 hours can be computed ``exactly''.
    850 	 * (Note that if hz would yeild a non-integral number of us per
    851 	 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
    852 	 * than they should be.)  Maximum value for any timeout in 10ms
    853 	 * ticks is 250 days.
    854 	 */
    855 	s = splhigh();
    856 	sec = tv->tv_sec - time.tv_sec;
    857 	if (sec <= 0x7fffffff / 1000000 - 1)
    858 		ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
    859 			(tv->tv_usec - time.tv_usec)) / tick;
    860 	else if (sec <= 0x7fffffff / hz)
    861 		ticks = sec * hz;
    862 	else
    863 		ticks = 0x7fffffff;
    864 	splx(s);
    865 	return (ticks);
    866 }
    867 
    868 /*
    869  * Start profiling on a process.
    870  *
    871  * Kernel profiling passes proc0 which never exits and hence
    872  * keeps the profile clock running constantly.
    873  */
    874 void
    875 startprofclock(p)
    876 	register struct proc *p;
    877 {
    878 	int s;
    879 
    880 	if ((p->p_flag & P_PROFIL) == 0) {
    881 		p->p_flag |= P_PROFIL;
    882 		if (++profprocs == 1 && stathz != 0) {
    883 			s = splstatclock();
    884 			psdiv = pscnt = psratio;
    885 			setstatclockrate(profhz);
    886 			splx(s);
    887 		}
    888 	}
    889 }
    890 
    891 /*
    892  * Stop profiling on a process.
    893  */
    894 void
    895 stopprofclock(p)
    896 	register struct proc *p;
    897 {
    898 	int s;
    899 
    900 	if (p->p_flag & P_PROFIL) {
    901 		p->p_flag &= ~P_PROFIL;
    902 		if (--profprocs == 0 && stathz != 0) {
    903 			s = splstatclock();
    904 			psdiv = pscnt = 1;
    905 			setstatclockrate(stathz);
    906 			splx(s);
    907 		}
    908 	}
    909 }
    910 
    911 /*
    912  * Statistics clock.  Grab profile sample, and if divider reaches 0,
    913  * do process and kernel statistics.
    914  */
    915 void
    916 statclock(frame)
    917 	register struct clockframe *frame;
    918 {
    919 #ifdef GPROF
    920 	register struct gmonparam *g;
    921 #endif
    922 	register struct proc *p;
    923 	register int i;
    924 
    925 	if (CLKF_USERMODE(frame)) {
    926 		p = curproc;
    927 		if (p->p_flag & P_PROFIL)
    928 			addupc_intr(p, CLKF_PC(frame), 1);
    929 		if (--pscnt > 0)
    930 			return;
    931 		/*
    932 		 * Came from user mode; CPU was in user state.
    933 		 * If this process is being profiled record the tick.
    934 		 */
    935 		p->p_uticks++;
    936 		if (p->p_nice > NZERO)
    937 			cp_time[CP_NICE]++;
    938 		else
    939 			cp_time[CP_USER]++;
    940 	} else {
    941 #ifdef GPROF
    942 		/*
    943 		 * Kernel statistics are just like addupc_intr, only easier.
    944 		 */
    945 		g = &_gmonparam;
    946 		if (g->state == GMON_PROF_ON) {
    947 			i = CLKF_PC(frame) - g->lowpc;
    948 			if (i < g->textsize) {
    949 				i /= HISTFRACTION * sizeof(*g->kcount);
    950 				g->kcount[i]++;
    951 			}
    952 		}
    953 #endif
    954 		if (--pscnt > 0)
    955 			return;
    956 		/*
    957 		 * Came from kernel mode, so we were:
    958 		 * - handling an interrupt,
    959 		 * - doing syscall or trap work on behalf of the current
    960 		 *   user process, or
    961 		 * - spinning in the idle loop.
    962 		 * Whichever it is, charge the time as appropriate.
    963 		 * Note that we charge interrupts to the current process,
    964 		 * regardless of whether they are ``for'' that process,
    965 		 * so that we know how much of its real time was spent
    966 		 * in ``non-process'' (i.e., interrupt) work.
    967 		 */
    968 		p = curproc;
    969 		if (CLKF_INTR(frame)) {
    970 			if (p != NULL)
    971 				p->p_iticks++;
    972 			cp_time[CP_INTR]++;
    973 		} else if (p != NULL) {
    974 			p->p_sticks++;
    975 			cp_time[CP_SYS]++;
    976 		} else
    977 			cp_time[CP_IDLE]++;
    978 	}
    979 	pscnt = psdiv;
    980 
    981 	/*
    982 	 * XXX Support old-style instrumentation for now.
    983 	 *
    984 	 * We maintain statistics shown by user-level statistics
    985 	 * programs:  the amount of time in each cpu state, and
    986 	 * the amount of time each of DK_NDRIVE ``drives'' is busy.
    987 	 *
    988 	 * XXX	should either run linked list of drives, or (better)
    989 	 *	grab timestamps in the start & done code.
    990 	 */
    991 	for (i = 0; i < DK_NDRIVE; i++)
    992 		if (dk_busy & (1 << i))
    993 			dk_time[i]++;
    994 
    995 	/*
    996 	 * We adjust the priority of the current process.  The priority of
    997 	 * a process gets worse as it accumulates CPU time.  The cpu usage
    998 	 * estimator (p_estcpu) is increased here.  The formula for computing
    999 	 * priorities (in kern_synch.c) will compute a different value each
   1000 	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
   1001 	 * quite quickly when the process is running (linearly), and decays
   1002 	 * away exponentially, at a rate which is proportionally slower when
   1003 	 * the system is busy.  The basic principal is that the system will
   1004 	 * 90% forget that the process used a lot of CPU time in 5 * loadav
   1005 	 * seconds.  This causes the system to favor processes which haven't
   1006 	 * run much recently, and to round-robin among other processes.
   1007 	 */
   1008 	if (p != NULL) {
   1009 		p->p_cpticks++;
   1010 		if (++p->p_estcpu == 0)
   1011 			p->p_estcpu--;
   1012 		if ((p->p_estcpu & 3) == 0) {
   1013 			resetpriority(p);
   1014 			if (p->p_priority >= PUSER)
   1015 				p->p_priority = p->p_usrpri;
   1016 		}
   1017 	}
   1018 }
   1019 
   1020 
   1021 #ifdef NTP	/* NTP phase-locked loop in kernel */
   1022 
   1023 /*
   1024  * hardupdate() - local clock update
   1025  *
   1026  * This routine is called by ntp_adjtime() to update the local clock
   1027  * phase and frequency. The implementation is of an adaptive-parameter,
   1028  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
   1029  * time and frequency offset estimates for each call. If the kernel PPS
   1030  * discipline code is configured (PPS_SYNC), the PPS signal itself
   1031  * determines the new time offset, instead of the calling argument.
   1032  * Presumably, calls to ntp_adjtime() occur only when the caller
   1033  * believes the local clock is valid within some bound (+-128 ms with
   1034  * NTP). If the caller's time is far different than the PPS time, an
   1035  * argument will ensue, and it's not clear who will lose.
   1036  *
   1037  * For uncompensated quartz crystal oscillatores and nominal update
   1038  * intervals less than 1024 s, operation should be in phase-lock mode
   1039  * (STA_FLL = 0), where the loop is disciplined to phase. For update
   1040  * intervals greater than thiss, operation should be in frequency-lock
   1041  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
   1042  *
   1043  * Note: splclock() is in effect.
   1044  */
   1045 void
   1046 hardupdate(offset)
   1047 	long offset;
   1048 {
   1049 	long ltemp, mtemp;
   1050 
   1051 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
   1052 		return;
   1053 	ltemp = offset;
   1054 #ifdef PPS_SYNC
   1055 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
   1056 		ltemp = pps_offset;
   1057 #endif /* PPS_SYNC */
   1058 
   1059 	/*
   1060 	 * Scale the phase adjustment and clamp to the operating range.
   1061 	 */
   1062 	if (ltemp > MAXPHASE)
   1063 		time_offset = MAXPHASE << SHIFT_UPDATE;
   1064 	else if (ltemp < -MAXPHASE)
   1065 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
   1066 	else
   1067 		time_offset = ltemp << SHIFT_UPDATE;
   1068 
   1069 	/*
   1070 	 * Select whether the frequency is to be controlled and in which
   1071 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
   1072 	 * multiply/divide should be replaced someday.
   1073 	 */
   1074 	if (time_status & STA_FREQHOLD || time_reftime == 0)
   1075 		time_reftime = time.tv_sec;
   1076 	mtemp = time.tv_sec - time_reftime;
   1077 	time_reftime = time.tv_sec;
   1078 	if (time_status & STA_FLL) {
   1079 		if (mtemp >= MINSEC) {
   1080 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
   1081 			    SHIFT_UPDATE));
   1082 			if (ltemp < 0)
   1083 				time_freq -= -ltemp >> SHIFT_KH;
   1084 			else
   1085 				time_freq += ltemp >> SHIFT_KH;
   1086 		}
   1087 	} else {
   1088 		if (mtemp < MAXSEC) {
   1089 			ltemp *= mtemp;
   1090 			if (ltemp < 0)
   1091 				time_freq -= -ltemp >> (time_constant +
   1092 				    time_constant + SHIFT_KF -
   1093 				    SHIFT_USEC);
   1094 			else
   1095 				time_freq += ltemp >> (time_constant +
   1096 				    time_constant + SHIFT_KF -
   1097 				    SHIFT_USEC);
   1098 		}
   1099 	}
   1100 	if (time_freq > time_tolerance)
   1101 		time_freq = time_tolerance;
   1102 	else if (time_freq < -time_tolerance)
   1103 		time_freq = -time_tolerance;
   1104 }
   1105 
   1106 #ifdef PPS_SYNC
   1107 /*
   1108  * hardpps() - discipline CPU clock oscillator to external PPS signal
   1109  *
   1110  * This routine is called at each PPS interrupt in order to discipline
   1111  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
   1112  * and leaves it in a handy spot for the hardclock() routine. It
   1113  * integrates successive PPS phase differences and calculates the
   1114  * frequency offset. This is used in hardclock() to discipline the CPU
   1115  * clock oscillator so that intrinsic frequency error is cancelled out.
   1116  * The code requires the caller to capture the time and hardware counter
   1117  * value at the on-time PPS signal transition.
   1118  *
   1119  * Note that, on some Unix systems, this routine runs at an interrupt
   1120  * priority level higher than the timer interrupt routine hardclock().
   1121  * Therefore, the variables used are distinct from the hardclock()
   1122  * variables, except for certain exceptions: The PPS frequency pps_freq
   1123  * and phase pps_offset variables are determined by this routine and
   1124  * updated atomically. The time_tolerance variable can be considered a
   1125  * constant, since it is infrequently changed, and then only when the
   1126  * PPS signal is disabled. The watchdog counter pps_valid is updated
   1127  * once per second by hardclock() and is atomically cleared in this
   1128  * routine.
   1129  */
   1130 void
   1131 hardpps(tvp, usec)
   1132 	struct timeval *tvp;		/* time at PPS */
   1133 	long usec;			/* hardware counter at PPS */
   1134 {
   1135 	long u_usec, v_usec, bigtick;
   1136 	long cal_sec, cal_usec;
   1137 
   1138 	/*
   1139 	 * An occasional glitch can be produced when the PPS interrupt
   1140 	 * occurs in the hardclock() routine before the time variable is
   1141 	 * updated. Here the offset is discarded when the difference
   1142 	 * between it and the last one is greater than tick/2, but not
   1143 	 * if the interval since the first discard exceeds 30 s.
   1144 	 */
   1145 	time_status |= STA_PPSSIGNAL;
   1146 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
   1147 	pps_valid = 0;
   1148 	u_usec = -tvp->tv_usec;
   1149 	if (u_usec < -500000)
   1150 		u_usec += 1000000;
   1151 	v_usec = pps_offset - u_usec;
   1152 	if (v_usec < 0)
   1153 		v_usec = -v_usec;
   1154 	if (v_usec > (tick >> 1)) {
   1155 		if (pps_glitch > MAXGLITCH) {
   1156 			pps_glitch = 0;
   1157 			pps_tf[2] = u_usec;
   1158 			pps_tf[1] = u_usec;
   1159 		} else {
   1160 			pps_glitch++;
   1161 			u_usec = pps_offset;
   1162 		}
   1163 	} else
   1164 		pps_glitch = 0;
   1165 
   1166 	/*
   1167 	 * A three-stage median filter is used to help deglitch the pps
   1168 	 * time. The median sample becomes the time offset estimate; the
   1169 	 * difference between the other two samples becomes the time
   1170 	 * dispersion (jitter) estimate.
   1171 	 */
   1172 	pps_tf[2] = pps_tf[1];
   1173 	pps_tf[1] = pps_tf[0];
   1174 	pps_tf[0] = u_usec;
   1175 	if (pps_tf[0] > pps_tf[1]) {
   1176 		if (pps_tf[1] > pps_tf[2]) {
   1177 			pps_offset = pps_tf[1];		/* 0 1 2 */
   1178 			v_usec = pps_tf[0] - pps_tf[2];
   1179 		} else if (pps_tf[2] > pps_tf[0]) {
   1180 			pps_offset = pps_tf[0];		/* 2 0 1 */
   1181 			v_usec = pps_tf[2] - pps_tf[1];
   1182 		} else {
   1183 			pps_offset = pps_tf[2];		/* 0 2 1 */
   1184 			v_usec = pps_tf[0] - pps_tf[1];
   1185 		}
   1186 	} else {
   1187 		if (pps_tf[1] < pps_tf[2]) {
   1188 			pps_offset = pps_tf[1];		/* 2 1 0 */
   1189 			v_usec = pps_tf[2] - pps_tf[0];
   1190 		} else  if (pps_tf[2] < pps_tf[0]) {
   1191 			pps_offset = pps_tf[0];		/* 1 0 2 */
   1192 			v_usec = pps_tf[1] - pps_tf[2];
   1193 		} else {
   1194 			pps_offset = pps_tf[2];		/* 1 2 0 */
   1195 			v_usec = pps_tf[1] - pps_tf[0];
   1196 		}
   1197 	}
   1198 	if (v_usec > MAXTIME)
   1199 		pps_jitcnt++;
   1200 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
   1201 	if (v_usec < 0)
   1202 		pps_jitter -= -v_usec >> PPS_AVG;
   1203 	else
   1204 		pps_jitter += v_usec >> PPS_AVG;
   1205 	if (pps_jitter > (MAXTIME >> 1))
   1206 		time_status |= STA_PPSJITTER;
   1207 
   1208 	/*
   1209 	 * During the calibration interval adjust the starting time when
   1210 	 * the tick overflows. At the end of the interval compute the
   1211 	 * duration of the interval and the difference of the hardware
   1212 	 * counters at the beginning and end of the interval. This code
   1213 	 * is deliciously complicated by the fact valid differences may
   1214 	 * exceed the value of tick when using long calibration
   1215 	 * intervals and small ticks. Note that the counter can be
   1216 	 * greater than tick if caught at just the wrong instant, but
   1217 	 * the values returned and used here are correct.
   1218 	 */
   1219 	bigtick = (long)tick << SHIFT_USEC;
   1220 	pps_usec -= pps_freq;
   1221 	if (pps_usec >= bigtick)
   1222 		pps_usec -= bigtick;
   1223 	if (pps_usec < 0)
   1224 		pps_usec += bigtick;
   1225 	pps_time.tv_sec++;
   1226 	pps_count++;
   1227 	if (pps_count < (1 << pps_shift))
   1228 		return;
   1229 	pps_count = 0;
   1230 	pps_calcnt++;
   1231 	u_usec = usec << SHIFT_USEC;
   1232 	v_usec = pps_usec - u_usec;
   1233 	if (v_usec >= bigtick >> 1)
   1234 		v_usec -= bigtick;
   1235 	if (v_usec < -(bigtick >> 1))
   1236 		v_usec += bigtick;
   1237 	if (v_usec < 0)
   1238 		v_usec = -(-v_usec >> pps_shift);
   1239 	else
   1240 		v_usec = v_usec >> pps_shift;
   1241 	pps_usec = u_usec;
   1242 	cal_sec = tvp->tv_sec;
   1243 	cal_usec = tvp->tv_usec;
   1244 	cal_sec -= pps_time.tv_sec;
   1245 	cal_usec -= pps_time.tv_usec;
   1246 	if (cal_usec < 0) {
   1247 		cal_usec += 1000000;
   1248 		cal_sec--;
   1249 	}
   1250 	pps_time = *tvp;
   1251 
   1252 	/*
   1253 	 * Check for lost interrupts, noise, excessive jitter and
   1254 	 * excessive frequency error. The number of timer ticks during
   1255 	 * the interval may vary +-1 tick. Add to this a margin of one
   1256 	 * tick for the PPS signal jitter and maximum frequency
   1257 	 * deviation. If the limits are exceeded, the calibration
   1258 	 * interval is reset to the minimum and we start over.
   1259 	 */
   1260 	u_usec = (long)tick << 1;
   1261 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
   1262 	    || (cal_sec == 0 && cal_usec < u_usec))
   1263 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
   1264 		pps_errcnt++;
   1265 		pps_shift = PPS_SHIFT;
   1266 		pps_intcnt = 0;
   1267 		time_status |= STA_PPSERROR;
   1268 		return;
   1269 	}
   1270 
   1271 	/*
   1272 	 * A three-stage median filter is used to help deglitch the pps
   1273 	 * frequency. The median sample becomes the frequency offset
   1274 	 * estimate; the difference between the other two samples
   1275 	 * becomes the frequency dispersion (stability) estimate.
   1276 	 */
   1277 	pps_ff[2] = pps_ff[1];
   1278 	pps_ff[1] = pps_ff[0];
   1279 	pps_ff[0] = v_usec;
   1280 	if (pps_ff[0] > pps_ff[1]) {
   1281 		if (pps_ff[1] > pps_ff[2]) {
   1282 			u_usec = pps_ff[1];		/* 0 1 2 */
   1283 			v_usec = pps_ff[0] - pps_ff[2];
   1284 		} else if (pps_ff[2] > pps_ff[0]) {
   1285 			u_usec = pps_ff[0];		/* 2 0 1 */
   1286 			v_usec = pps_ff[2] - pps_ff[1];
   1287 		} else {
   1288 			u_usec = pps_ff[2];		/* 0 2 1 */
   1289 			v_usec = pps_ff[0] - pps_ff[1];
   1290 		}
   1291 	} else {
   1292 		if (pps_ff[1] < pps_ff[2]) {
   1293 			u_usec = pps_ff[1];		/* 2 1 0 */
   1294 			v_usec = pps_ff[2] - pps_ff[0];
   1295 		} else  if (pps_ff[2] < pps_ff[0]) {
   1296 			u_usec = pps_ff[0];		/* 1 0 2 */
   1297 			v_usec = pps_ff[1] - pps_ff[2];
   1298 		} else {
   1299 			u_usec = pps_ff[2];		/* 1 2 0 */
   1300 			v_usec = pps_ff[1] - pps_ff[0];
   1301 		}
   1302 	}
   1303 
   1304 	/*
   1305 	 * Here the frequency dispersion (stability) is updated. If it
   1306 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
   1307 	 * offset is updated as well, but clamped to the tolerance. It
   1308 	 * will be processed later by the hardclock() routine.
   1309 	 */
   1310 	v_usec = (v_usec >> 1) - pps_stabil;
   1311 	if (v_usec < 0)
   1312 		pps_stabil -= -v_usec >> PPS_AVG;
   1313 	else
   1314 		pps_stabil += v_usec >> PPS_AVG;
   1315 	if (pps_stabil > MAXFREQ >> 2) {
   1316 		pps_stbcnt++;
   1317 		time_status |= STA_PPSWANDER;
   1318 		return;
   1319 	}
   1320 	if (time_status & STA_PPSFREQ) {
   1321 		if (u_usec < 0) {
   1322 			pps_freq -= -u_usec >> PPS_AVG;
   1323 			if (pps_freq < -time_tolerance)
   1324 				pps_freq = -time_tolerance;
   1325 			u_usec = -u_usec;
   1326 		} else {
   1327 			pps_freq += u_usec >> PPS_AVG;
   1328 			if (pps_freq > time_tolerance)
   1329 				pps_freq = time_tolerance;
   1330 		}
   1331 	}
   1332 
   1333 	/*
   1334 	 * Here the calibration interval is adjusted. If the maximum
   1335 	 * time difference is greater than tick / 4, reduce the interval
   1336 	 * by half. If this is not the case for four consecutive
   1337 	 * intervals, double the interval.
   1338 	 */
   1339 	if (u_usec << pps_shift > bigtick >> 2) {
   1340 		pps_intcnt = 0;
   1341 		if (pps_shift > PPS_SHIFT)
   1342 			pps_shift--;
   1343 	} else if (pps_intcnt >= 4) {
   1344 		pps_intcnt = 0;
   1345 		if (pps_shift < PPS_SHIFTMAX)
   1346 			pps_shift++;
   1347 	} else
   1348 		pps_intcnt++;
   1349 }
   1350 #endif /* PPS_SYNC */
   1351 #endif /* NTP  */
   1352 
   1353 
   1354 /*
   1355  * Return information about system clocks.
   1356  */
   1357 int
   1358 sysctl_clockrate(where, sizep)
   1359 	register char *where;
   1360 	size_t *sizep;
   1361 {
   1362 	struct clockinfo clkinfo;
   1363 
   1364 	/*
   1365 	 * Construct clockinfo structure.
   1366 	 */
   1367 	clkinfo.tick = tick;
   1368 	clkinfo.tickadj = tickadj;
   1369 	clkinfo.hz = hz;
   1370 	clkinfo.profhz = profhz;
   1371 	clkinfo.stathz = stathz ? stathz : hz;
   1372 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
   1373 }
   1374 
   1375 #ifdef DDB
   1376 #include <machine/db_machdep.h>
   1377 
   1378 #include <ddb/db_interface.h>
   1379 #include <ddb/db_access.h>
   1380 #include <ddb/db_sym.h>
   1381 #include <ddb/db_output.h>
   1382 
   1383 void db_show_callout(addr, haddr, count, modif)
   1384 	db_expr_t addr;
   1385 	int haddr;
   1386 	db_expr_t count;
   1387 	char *modif;
   1388 {
   1389 	register struct callout *p1;
   1390 	register int	cum;
   1391 	register int	s;
   1392 	db_expr_t	offset;
   1393 	char		*name;
   1394 
   1395         db_printf("      cum     ticks      arg  func\n");
   1396 	s = splhigh();
   1397 	for (cum = 0, p1 = calltodo.c_next; p1; p1 = p1->c_next) {
   1398 		register int t = p1->c_time;
   1399 
   1400 		if (t > 0)
   1401 			cum += t;
   1402 
   1403 		db_find_sym_and_offset((db_addr_t)p1->c_func, &name, &offset);
   1404 		if (name == NULL)
   1405 			name = "?";
   1406 
   1407                 db_printf("%9d %9d %8x  %s (%x)\n",
   1408 			  cum, t, p1->c_arg, name, p1->c_func);
   1409 	}
   1410 	splx(s);
   1411 }
   1412 #endif
   1413