xref: /netbsd-src/sys/kern/kern_clock.c (revision e4d7c2e329d54c97e0c0bd3016bbe74f550c3d5e)
1 /*	$NetBSD: kern_clock.c,v 1.51 2000/01/19 20:05:51 thorpej 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  * callout_startup:
759  *
760  *	Initialize the callout freelist.
761  */
762 void
763 callout_startup()
764 {
765 	int i;
766 
767 	callfree = callout;
768 	for (i = 1; i < ncallout; i++)
769 		callout[i-1].c_next = &callout[i];
770 	callout[i-1].c_next = NULL;
771 }
772 
773 /*
774  * timeout --
775  *	Execute a function after a specified length of time.
776  *
777  * untimeout --
778  *	Cancel previous timeout function call.
779  *
780  *	See AT&T BCI Driver Reference Manual for specification.  This
781  *	implementation differs from that one in that no identification
782  *	value is returned from timeout, rather, the original arguments
783  *	to timeout are used to identify entries for untimeout.
784  */
785 void
786 timeout(ftn, arg, ticks)
787 	void (*ftn) __P((void *));
788 	void *arg;
789 	register int ticks;
790 {
791 	register struct callout *new, *p, *t;
792 	register int s;
793 
794 	if (ticks <= 0)
795 		ticks = 1;
796 
797 	/* Lock out the clock. */
798 	s = splhigh();
799 
800 	/* Fill in the next free callout structure. */
801 	if (callfree == NULL)
802 		panic("timeout table full");
803 	new = callfree;
804 	callfree = new->c_next;
805 	new->c_arg = arg;
806 	new->c_func = ftn;
807 
808 	/*
809 	 * The time for each event is stored as a difference from the time
810 	 * of the previous event on the queue.  Walk the queue, correcting
811 	 * the ticks argument for queue entries passed.  Correct the ticks
812 	 * value for the queue entry immediately after the insertion point
813 	 * as well.  Watch out for negative c_time values; these represent
814 	 * overdue events.
815 	 */
816 	for (p = &calltodo;
817 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
818 		if (t->c_time > 0)
819 			ticks -= t->c_time;
820 	new->c_time = ticks;
821 	if (t != NULL)
822 		t->c_time -= ticks;
823 
824 	/* Insert the new entry into the queue. */
825 	p->c_next = new;
826 	new->c_next = t;
827 	splx(s);
828 }
829 
830 void
831 untimeout(ftn, arg)
832 	void (*ftn) __P((void *));
833 	void *arg;
834 {
835 	register struct callout *p, *t;
836 	register int s;
837 
838 	s = splhigh();
839 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
840 		if (t->c_func == ftn && t->c_arg == arg) {
841 			/* Increment next entry's tick count. */
842 			if (t->c_next && t->c_time > 0)
843 				t->c_next->c_time += t->c_time;
844 
845 			/* Move entry from callout queue to callfree queue. */
846 			p->c_next = t->c_next;
847 			t->c_next = callfree;
848 			callfree = t;
849 			break;
850 		}
851 	splx(s);
852 }
853 
854 /*
855  * Compute number of hz until specified time.  Used to
856  * compute third argument to timeout() from an absolute time.
857  */
858 int
859 hzto(tv)
860 	struct timeval *tv;
861 {
862 	register long ticks, sec;
863 	int s;
864 
865 	/*
866 	 * If number of microseconds will fit in 32 bit arithmetic,
867 	 * then compute number of microseconds to time and scale to
868 	 * ticks.  Otherwise just compute number of hz in time, rounding
869 	 * times greater than representible to maximum value.  (We must
870 	 * compute in microseconds, because hz can be greater than 1000,
871 	 * and thus tick can be less than one millisecond).
872 	 *
873 	 * Delta times less than 14 hours can be computed ``exactly''.
874 	 * (Note that if hz would yeild a non-integral number of us per
875 	 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
876 	 * than they should be.)  Maximum value for any timeout in 10ms
877 	 * ticks is 250 days.
878 	 */
879 	s = splclock();
880 	sec = tv->tv_sec - time.tv_sec;
881 	if (sec <= 0x7fffffff / 1000000 - 1)
882 		ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
883 			(tv->tv_usec - time.tv_usec)) / tick;
884 	else if (sec <= 0x7fffffff / hz)
885 		ticks = sec * hz;
886 	else
887 		ticks = 0x7fffffff;
888 	splx(s);
889 	return (ticks);
890 }
891 
892 /*
893  * Start profiling on a process.
894  *
895  * Kernel profiling passes proc0 which never exits and hence
896  * keeps the profile clock running constantly.
897  */
898 void
899 startprofclock(p)
900 	register struct proc *p;
901 {
902 	int s;
903 
904 	if ((p->p_flag & P_PROFIL) == 0) {
905 		p->p_flag |= P_PROFIL;
906 		if (++profprocs == 1 && stathz != 0) {
907 			s = splstatclock();
908 			psdiv = pscnt = psratio;
909 			setstatclockrate(profhz);
910 			splx(s);
911 		}
912 	}
913 }
914 
915 /*
916  * Stop profiling on a process.
917  */
918 void
919 stopprofclock(p)
920 	register struct proc *p;
921 {
922 	int s;
923 
924 	if (p->p_flag & P_PROFIL) {
925 		p->p_flag &= ~P_PROFIL;
926 		if (--profprocs == 0 && stathz != 0) {
927 			s = splstatclock();
928 			psdiv = pscnt = 1;
929 			setstatclockrate(stathz);
930 			splx(s);
931 		}
932 	}
933 }
934 
935 /*
936  * Statistics clock.  Grab profile sample, and if divider reaches 0,
937  * do process and kernel statistics.
938  */
939 void
940 statclock(frame)
941 	register struct clockframe *frame;
942 {
943 #ifdef GPROF
944 	register struct gmonparam *g;
945 	register int i;
946 #endif
947 	static int schedclk;
948 	register struct proc *p;
949 
950 	if (CLKF_USERMODE(frame)) {
951 		p = curproc;
952 		if (p->p_flag & P_PROFIL)
953 			addupc_intr(p, CLKF_PC(frame), 1);
954 		if (--pscnt > 0)
955 			return;
956 		/*
957 		 * Came from user mode; CPU was in user state.
958 		 * If this process is being profiled record the tick.
959 		 */
960 		p->p_uticks++;
961 		if (p->p_nice > NZERO)
962 			cp_time[CP_NICE]++;
963 		else
964 			cp_time[CP_USER]++;
965 	} else {
966 #ifdef GPROF
967 		/*
968 		 * Kernel statistics are just like addupc_intr, only easier.
969 		 */
970 		g = &_gmonparam;
971 		if (g->state == GMON_PROF_ON) {
972 			i = CLKF_PC(frame) - g->lowpc;
973 			if (i < g->textsize) {
974 				i /= HISTFRACTION * sizeof(*g->kcount);
975 				g->kcount[i]++;
976 			}
977 		}
978 #endif
979 		if (--pscnt > 0)
980 			return;
981 		/*
982 		 * Came from kernel mode, so we were:
983 		 * - handling an interrupt,
984 		 * - doing syscall or trap work on behalf of the current
985 		 *   user process, or
986 		 * - spinning in the idle loop.
987 		 * Whichever it is, charge the time as appropriate.
988 		 * Note that we charge interrupts to the current process,
989 		 * regardless of whether they are ``for'' that process,
990 		 * so that we know how much of its real time was spent
991 		 * in ``non-process'' (i.e., interrupt) work.
992 		 */
993 		p = curproc;
994 		if (CLKF_INTR(frame)) {
995 			if (p != NULL)
996 				p->p_iticks++;
997 			cp_time[CP_INTR]++;
998 		} else if (p != NULL) {
999 			p->p_sticks++;
1000 			cp_time[CP_SYS]++;
1001 		} else
1002 			cp_time[CP_IDLE]++;
1003 	}
1004 	pscnt = psdiv;
1005 
1006 	if (p != NULL) {
1007 		++p->p_cpticks;
1008 		/*
1009 		 * If no schedclock is provided, call it here at ~~12-25 Hz,
1010 		 * ~~16 Hz is best
1011 		 */
1012 		if(schedhz == 0)
1013 			if ((++schedclk & 3) == 0)
1014 				schedclock(p);
1015 	}
1016 }
1017 
1018 
1019 #ifdef NTP	/* NTP phase-locked loop in kernel */
1020 
1021 /*
1022  * hardupdate() - local clock update
1023  *
1024  * This routine is called by ntp_adjtime() to update the local clock
1025  * phase and frequency. The implementation is of an adaptive-parameter,
1026  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1027  * time and frequency offset estimates for each call. If the kernel PPS
1028  * discipline code is configured (PPS_SYNC), the PPS signal itself
1029  * determines the new time offset, instead of the calling argument.
1030  * Presumably, calls to ntp_adjtime() occur only when the caller
1031  * believes the local clock is valid within some bound (+-128 ms with
1032  * NTP). If the caller's time is far different than the PPS time, an
1033  * argument will ensue, and it's not clear who will lose.
1034  *
1035  * For uncompensated quartz crystal oscillatores and nominal update
1036  * intervals less than 1024 s, operation should be in phase-lock mode
1037  * (STA_FLL = 0), where the loop is disciplined to phase. For update
1038  * intervals greater than thiss, operation should be in frequency-lock
1039  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1040  *
1041  * Note: splclock() is in effect.
1042  */
1043 void
1044 hardupdate(offset)
1045 	long offset;
1046 {
1047 	long ltemp, mtemp;
1048 
1049 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1050 		return;
1051 	ltemp = offset;
1052 #ifdef PPS_SYNC
1053 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1054 		ltemp = pps_offset;
1055 #endif /* PPS_SYNC */
1056 
1057 	/*
1058 	 * Scale the phase adjustment and clamp to the operating range.
1059 	 */
1060 	if (ltemp > MAXPHASE)
1061 		time_offset = MAXPHASE << SHIFT_UPDATE;
1062 	else if (ltemp < -MAXPHASE)
1063 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
1064 	else
1065 		time_offset = ltemp << SHIFT_UPDATE;
1066 
1067 	/*
1068 	 * Select whether the frequency is to be controlled and in which
1069 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
1070 	 * multiply/divide should be replaced someday.
1071 	 */
1072 	if (time_status & STA_FREQHOLD || time_reftime == 0)
1073 		time_reftime = time.tv_sec;
1074 	mtemp = time.tv_sec - time_reftime;
1075 	time_reftime = time.tv_sec;
1076 	if (time_status & STA_FLL) {
1077 		if (mtemp >= MINSEC) {
1078 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1079 			    SHIFT_UPDATE));
1080 			if (ltemp < 0)
1081 				time_freq -= -ltemp >> SHIFT_KH;
1082 			else
1083 				time_freq += ltemp >> SHIFT_KH;
1084 		}
1085 	} else {
1086 		if (mtemp < MAXSEC) {
1087 			ltemp *= mtemp;
1088 			if (ltemp < 0)
1089 				time_freq -= -ltemp >> (time_constant +
1090 				    time_constant + SHIFT_KF -
1091 				    SHIFT_USEC);
1092 			else
1093 				time_freq += ltemp >> (time_constant +
1094 				    time_constant + SHIFT_KF -
1095 				    SHIFT_USEC);
1096 		}
1097 	}
1098 	if (time_freq > time_tolerance)
1099 		time_freq = time_tolerance;
1100 	else if (time_freq < -time_tolerance)
1101 		time_freq = -time_tolerance;
1102 }
1103 
1104 #ifdef PPS_SYNC
1105 /*
1106  * hardpps() - discipline CPU clock oscillator to external PPS signal
1107  *
1108  * This routine is called at each PPS interrupt in order to discipline
1109  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1110  * and leaves it in a handy spot for the hardclock() routine. It
1111  * integrates successive PPS phase differences and calculates the
1112  * frequency offset. This is used in hardclock() to discipline the CPU
1113  * clock oscillator so that intrinsic frequency error is cancelled out.
1114  * The code requires the caller to capture the time and hardware counter
1115  * value at the on-time PPS signal transition.
1116  *
1117  * Note that, on some Unix systems, this routine runs at an interrupt
1118  * priority level higher than the timer interrupt routine hardclock().
1119  * Therefore, the variables used are distinct from the hardclock()
1120  * variables, except for certain exceptions: The PPS frequency pps_freq
1121  * and phase pps_offset variables are determined by this routine and
1122  * updated atomically. The time_tolerance variable can be considered a
1123  * constant, since it is infrequently changed, and then only when the
1124  * PPS signal is disabled. The watchdog counter pps_valid is updated
1125  * once per second by hardclock() and is atomically cleared in this
1126  * routine.
1127  */
1128 void
1129 hardpps(tvp, usec)
1130 	struct timeval *tvp;		/* time at PPS */
1131 	long usec;			/* hardware counter at PPS */
1132 {
1133 	long u_usec, v_usec, bigtick;
1134 	long cal_sec, cal_usec;
1135 
1136 	/*
1137 	 * An occasional glitch can be produced when the PPS interrupt
1138 	 * occurs in the hardclock() routine before the time variable is
1139 	 * updated. Here the offset is discarded when the difference
1140 	 * between it and the last one is greater than tick/2, but not
1141 	 * if the interval since the first discard exceeds 30 s.
1142 	 */
1143 	time_status |= STA_PPSSIGNAL;
1144 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1145 	pps_valid = 0;
1146 	u_usec = -tvp->tv_usec;
1147 	if (u_usec < -500000)
1148 		u_usec += 1000000;
1149 	v_usec = pps_offset - u_usec;
1150 	if (v_usec < 0)
1151 		v_usec = -v_usec;
1152 	if (v_usec > (tick >> 1)) {
1153 		if (pps_glitch > MAXGLITCH) {
1154 			pps_glitch = 0;
1155 			pps_tf[2] = u_usec;
1156 			pps_tf[1] = u_usec;
1157 		} else {
1158 			pps_glitch++;
1159 			u_usec = pps_offset;
1160 		}
1161 	} else
1162 		pps_glitch = 0;
1163 
1164 	/*
1165 	 * A three-stage median filter is used to help deglitch the pps
1166 	 * time. The median sample becomes the time offset estimate; the
1167 	 * difference between the other two samples becomes the time
1168 	 * dispersion (jitter) estimate.
1169 	 */
1170 	pps_tf[2] = pps_tf[1];
1171 	pps_tf[1] = pps_tf[0];
1172 	pps_tf[0] = u_usec;
1173 	if (pps_tf[0] > pps_tf[1]) {
1174 		if (pps_tf[1] > pps_tf[2]) {
1175 			pps_offset = pps_tf[1];		/* 0 1 2 */
1176 			v_usec = pps_tf[0] - pps_tf[2];
1177 		} else if (pps_tf[2] > pps_tf[0]) {
1178 			pps_offset = pps_tf[0];		/* 2 0 1 */
1179 			v_usec = pps_tf[2] - pps_tf[1];
1180 		} else {
1181 			pps_offset = pps_tf[2];		/* 0 2 1 */
1182 			v_usec = pps_tf[0] - pps_tf[1];
1183 		}
1184 	} else {
1185 		if (pps_tf[1] < pps_tf[2]) {
1186 			pps_offset = pps_tf[1];		/* 2 1 0 */
1187 			v_usec = pps_tf[2] - pps_tf[0];
1188 		} else  if (pps_tf[2] < pps_tf[0]) {
1189 			pps_offset = pps_tf[0];		/* 1 0 2 */
1190 			v_usec = pps_tf[1] - pps_tf[2];
1191 		} else {
1192 			pps_offset = pps_tf[2];		/* 1 2 0 */
1193 			v_usec = pps_tf[1] - pps_tf[0];
1194 		}
1195 	}
1196 	if (v_usec > MAXTIME)
1197 		pps_jitcnt++;
1198 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1199 	if (v_usec < 0)
1200 		pps_jitter -= -v_usec >> PPS_AVG;
1201 	else
1202 		pps_jitter += v_usec >> PPS_AVG;
1203 	if (pps_jitter > (MAXTIME >> 1))
1204 		time_status |= STA_PPSJITTER;
1205 
1206 	/*
1207 	 * During the calibration interval adjust the starting time when
1208 	 * the tick overflows. At the end of the interval compute the
1209 	 * duration of the interval and the difference of the hardware
1210 	 * counters at the beginning and end of the interval. This code
1211 	 * is deliciously complicated by the fact valid differences may
1212 	 * exceed the value of tick when using long calibration
1213 	 * intervals and small ticks. Note that the counter can be
1214 	 * greater than tick if caught at just the wrong instant, but
1215 	 * the values returned and used here are correct.
1216 	 */
1217 	bigtick = (long)tick << SHIFT_USEC;
1218 	pps_usec -= pps_freq;
1219 	if (pps_usec >= bigtick)
1220 		pps_usec -= bigtick;
1221 	if (pps_usec < 0)
1222 		pps_usec += bigtick;
1223 	pps_time.tv_sec++;
1224 	pps_count++;
1225 	if (pps_count < (1 << pps_shift))
1226 		return;
1227 	pps_count = 0;
1228 	pps_calcnt++;
1229 	u_usec = usec << SHIFT_USEC;
1230 	v_usec = pps_usec - u_usec;
1231 	if (v_usec >= bigtick >> 1)
1232 		v_usec -= bigtick;
1233 	if (v_usec < -(bigtick >> 1))
1234 		v_usec += bigtick;
1235 	if (v_usec < 0)
1236 		v_usec = -(-v_usec >> pps_shift);
1237 	else
1238 		v_usec = v_usec >> pps_shift;
1239 	pps_usec = u_usec;
1240 	cal_sec = tvp->tv_sec;
1241 	cal_usec = tvp->tv_usec;
1242 	cal_sec -= pps_time.tv_sec;
1243 	cal_usec -= pps_time.tv_usec;
1244 	if (cal_usec < 0) {
1245 		cal_usec += 1000000;
1246 		cal_sec--;
1247 	}
1248 	pps_time = *tvp;
1249 
1250 	/*
1251 	 * Check for lost interrupts, noise, excessive jitter and
1252 	 * excessive frequency error. The number of timer ticks during
1253 	 * the interval may vary +-1 tick. Add to this a margin of one
1254 	 * tick for the PPS signal jitter and maximum frequency
1255 	 * deviation. If the limits are exceeded, the calibration
1256 	 * interval is reset to the minimum and we start over.
1257 	 */
1258 	u_usec = (long)tick << 1;
1259 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1260 	    || (cal_sec == 0 && cal_usec < u_usec))
1261 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1262 		pps_errcnt++;
1263 		pps_shift = PPS_SHIFT;
1264 		pps_intcnt = 0;
1265 		time_status |= STA_PPSERROR;
1266 		return;
1267 	}
1268 
1269 	/*
1270 	 * A three-stage median filter is used to help deglitch the pps
1271 	 * frequency. The median sample becomes the frequency offset
1272 	 * estimate; the difference between the other two samples
1273 	 * becomes the frequency dispersion (stability) estimate.
1274 	 */
1275 	pps_ff[2] = pps_ff[1];
1276 	pps_ff[1] = pps_ff[0];
1277 	pps_ff[0] = v_usec;
1278 	if (pps_ff[0] > pps_ff[1]) {
1279 		if (pps_ff[1] > pps_ff[2]) {
1280 			u_usec = pps_ff[1];		/* 0 1 2 */
1281 			v_usec = pps_ff[0] - pps_ff[2];
1282 		} else if (pps_ff[2] > pps_ff[0]) {
1283 			u_usec = pps_ff[0];		/* 2 0 1 */
1284 			v_usec = pps_ff[2] - pps_ff[1];
1285 		} else {
1286 			u_usec = pps_ff[2];		/* 0 2 1 */
1287 			v_usec = pps_ff[0] - pps_ff[1];
1288 		}
1289 	} else {
1290 		if (pps_ff[1] < pps_ff[2]) {
1291 			u_usec = pps_ff[1];		/* 2 1 0 */
1292 			v_usec = pps_ff[2] - pps_ff[0];
1293 		} else  if (pps_ff[2] < pps_ff[0]) {
1294 			u_usec = pps_ff[0];		/* 1 0 2 */
1295 			v_usec = pps_ff[1] - pps_ff[2];
1296 		} else {
1297 			u_usec = pps_ff[2];		/* 1 2 0 */
1298 			v_usec = pps_ff[1] - pps_ff[0];
1299 		}
1300 	}
1301 
1302 	/*
1303 	 * Here the frequency dispersion (stability) is updated. If it
1304 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1305 	 * offset is updated as well, but clamped to the tolerance. It
1306 	 * will be processed later by the hardclock() routine.
1307 	 */
1308 	v_usec = (v_usec >> 1) - pps_stabil;
1309 	if (v_usec < 0)
1310 		pps_stabil -= -v_usec >> PPS_AVG;
1311 	else
1312 		pps_stabil += v_usec >> PPS_AVG;
1313 	if (pps_stabil > MAXFREQ >> 2) {
1314 		pps_stbcnt++;
1315 		time_status |= STA_PPSWANDER;
1316 		return;
1317 	}
1318 	if (time_status & STA_PPSFREQ) {
1319 		if (u_usec < 0) {
1320 			pps_freq -= -u_usec >> PPS_AVG;
1321 			if (pps_freq < -time_tolerance)
1322 				pps_freq = -time_tolerance;
1323 			u_usec = -u_usec;
1324 		} else {
1325 			pps_freq += u_usec >> PPS_AVG;
1326 			if (pps_freq > time_tolerance)
1327 				pps_freq = time_tolerance;
1328 		}
1329 	}
1330 
1331 	/*
1332 	 * Here the calibration interval is adjusted. If the maximum
1333 	 * time difference is greater than tick / 4, reduce the interval
1334 	 * by half. If this is not the case for four consecutive
1335 	 * intervals, double the interval.
1336 	 */
1337 	if (u_usec << pps_shift > bigtick >> 2) {
1338 		pps_intcnt = 0;
1339 		if (pps_shift > PPS_SHIFT)
1340 			pps_shift--;
1341 	} else if (pps_intcnt >= 4) {
1342 		pps_intcnt = 0;
1343 		if (pps_shift < PPS_SHIFTMAX)
1344 			pps_shift++;
1345 	} else
1346 		pps_intcnt++;
1347 }
1348 #endif /* PPS_SYNC */
1349 #endif /* NTP  */
1350 
1351 
1352 /*
1353  * Return information about system clocks.
1354  */
1355 int
1356 sysctl_clockrate(where, sizep)
1357 	register char *where;
1358 	size_t *sizep;
1359 {
1360 	struct clockinfo clkinfo;
1361 
1362 	/*
1363 	 * Construct clockinfo structure.
1364 	 */
1365 	clkinfo.tick = tick;
1366 	clkinfo.tickadj = tickadj;
1367 	clkinfo.hz = hz;
1368 	clkinfo.profhz = profhz;
1369 	clkinfo.stathz = stathz ? stathz : hz;
1370 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1371 }
1372 
1373