xref: /openbsd-src/sys/kern/kern_clock.c (revision 5733d2de20d4f7b3fffcedce75a93c305745585f)
1 /*	$OpenBSD: kern_clock.c,v 1.35 2002/04/24 21:53:12 espie Exp $	*/
2 /*	$NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $	*/
3 
4 /*-
5  * Copyright (c) 1982, 1986, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by the University of
24  *	California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/dkstat.h>
47 #include <sys/timeout.h>
48 #include <sys/kernel.h>
49 #include <sys/limits.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/signalvar.h>
53 #include <uvm/uvm_extern.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 #ifdef NTP	/* NTP phase-locked loop in kernel */
89 /*
90  * Phase/frequency-lock loop (PLL/FLL) definitions
91  *
92  * The following variables are read and set by the ntp_adjtime() system
93  * call.
94  *
95  * time_state shows the state of the system clock, with values defined
96  * in the timex.h header file.
97  *
98  * time_status shows the status of the system clock, with bits defined
99  * in the timex.h header file.
100  *
101  * time_offset is used by the PLL/FLL to adjust the system time in small
102  * increments.
103  *
104  * time_constant determines the bandwidth or "stiffness" of the PLL.
105  *
106  * time_tolerance determines maximum frequency error or tolerance of the
107  * CPU clock oscillator and is a property of the architecture; however,
108  * in principle it could change as result of the presence of external
109  * discipline signals, for instance.
110  *
111  * time_precision is usually equal to the kernel tick variable; however,
112  * in cases where a precision clock counter or external clock is
113  * available, the resolution can be much less than this and depend on
114  * whether the external clock is working or not.
115  *
116  * time_maxerror is initialized by a ntp_adjtime() call and increased by
117  * the kernel once each second to reflect the maximum error bound
118  * growth.
119  *
120  * time_esterror is set and read by the ntp_adjtime() call, but
121  * otherwise not used by the kernel.
122  */
123 int time_state = TIME_OK;	/* clock state */
124 int time_status = STA_UNSYNC;	/* clock status bits */
125 long time_offset = 0;		/* time offset (us) */
126 long time_constant = 0;		/* pll time constant */
127 long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
128 long time_precision;		/* clock precision (us) */
129 long time_maxerror = MAXPHASE;	/* maximum error (us) */
130 long time_esterror = MAXPHASE;	/* estimated error (us) */
131 
132 /*
133  * The following variables establish the state of the PLL/FLL and the
134  * residual time and frequency offset of the local clock. The scale
135  * factors are defined in the timex.h header file.
136  *
137  * time_phase and time_freq are the phase increment and the frequency
138  * increment, respectively, of the kernel time variable.
139  *
140  * time_freq is set via ntp_adjtime() from a value stored in a file when
141  * the synchronization daemon is first started. Its value is retrieved
142  * via ntp_adjtime() and written to the file about once per hour by the
143  * daemon.
144  *
145  * time_adj is the adjustment added to the value of tick at each timer
146  * interrupt and is recomputed from time_phase and time_freq at each
147  * seconds rollover.
148  *
149  * time_reftime is the second's portion of the system time at the last
150  * call to ntp_adjtime(). It is used to adjust the time_freq variable
151  * and to increase the time_maxerror as the time since last update
152  * increases.
153  */
154 long time_phase = 0;		/* phase offset (scaled us) */
155 long time_freq = 0;		/* frequency offset (scaled ppm) */
156 long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
157 long time_reftime = 0;		/* time at last adjustment (s) */
158 
159 #ifdef PPS_SYNC
160 /*
161  * The following variables are used only if the kernel PPS discipline
162  * code is configured (PPS_SYNC). The scale factors are defined in the
163  * timex.h header file.
164  *
165  * pps_time contains the time at each calibration interval, as read by
166  * microtime(). pps_count counts the seconds of the calibration
167  * interval, the duration of which is nominally pps_shift in powers of
168  * two.
169  *
170  * pps_offset is the time offset produced by the time median filter
171  * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
172  * this filter.
173  *
174  * pps_freq is the frequency offset produced by the frequency median
175  * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
176  * by this filter.
177  *
178  * pps_usec is latched from a high resolution counter or external clock
179  * at pps_time. Here we want the hardware counter contents only, not the
180  * contents plus the time_tv.usec as usual.
181  *
182  * pps_valid counts the number of seconds since the last PPS update. It
183  * is used as a watchdog timer to disable the PPS discipline should the
184  * PPS signal be lost.
185  *
186  * pps_glitch counts the number of seconds since the beginning of an
187  * offset burst more than tick/2 from current nominal offset. It is used
188  * mainly to suppress error bursts due to priority conflicts between the
189  * PPS interrupt and timer interrupt.
190  *
191  * pps_intcnt counts the calibration intervals for use in the interval-
192  * adaptation algorithm. It's just too complicated for words.
193  */
194 struct timeval pps_time;	/* kernel time at last interval */
195 long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
196 long pps_offset = 0;		/* pps time offset (us) */
197 long pps_jitter = MAXTIME;	/* time dispersion (jitter) (us) */
198 long pps_ff[] = {0, 0, 0};	/* pps frequency offset median filter */
199 long pps_freq = 0;		/* frequency offset (scaled ppm) */
200 long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
201 long pps_usec = 0;		/* microsec counter at last interval */
202 long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
203 int pps_glitch = 0;		/* pps signal glitch counter */
204 int pps_count = 0;		/* calibration interval counter (s) */
205 int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
206 int pps_intcnt = 0;		/* intervals at current duration */
207 
208 /*
209  * PPS signal quality monitors
210  *
211  * pps_jitcnt counts the seconds that have been discarded because the
212  * jitter measured by the time median filter exceeds the limit MAXTIME
213  * (100 us).
214  *
215  * pps_calcnt counts the frequency calibration intervals, which are
216  * variable from 4 s to 256 s.
217  *
218  * pps_errcnt counts the calibration intervals which have been discarded
219  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
220  * calibration interval jitter exceeds two ticks.
221  *
222  * pps_stbcnt counts the calibration intervals that have been discarded
223  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
224  */
225 long pps_jitcnt = 0;		/* jitter limit exceeded */
226 long pps_calcnt = 0;		/* calibration intervals */
227 long pps_errcnt = 0;		/* calibration errors */
228 long pps_stbcnt = 0;		/* stability limit exceeded */
229 #endif /* PPS_SYNC */
230 
231 #ifdef EXT_CLOCK
232 /*
233  * External clock definitions
234  *
235  * The following definitions and declarations are used only if an
236  * external clock is configured on the system.
237  */
238 #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
239 
240 /*
241  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
242  * interrupt and decremented once each second.
243  */
244 int clock_count = 0;		/* CPU clock counter */
245 
246 #ifdef HIGHBALL
247 /*
248  * The clock_offset and clock_cpu variables are used by the HIGHBALL
249  * interface. The clock_offset variable defines the offset between
250  * system time and the HIGBALL counters. The clock_cpu variable contains
251  * the offset between the system clock and the HIGHBALL clock for use in
252  * disciplining the kernel time variable.
253  */
254 extern struct timeval clock_offset; /* Highball clock offset */
255 long clock_cpu = 0;		/* CPU clock adjust */
256 #endif /* HIGHBALL */
257 #endif /* EXT_CLOCK */
258 #endif /* NTP */
259 
260 
261 /*
262  * Bump a timeval by a small number of usec's.
263  */
264 #define BUMPTIME(t, usec) { \
265 	register volatile struct timeval *tp = (t); \
266 	register long us; \
267  \
268 	tp->tv_usec = us = tp->tv_usec + (usec); \
269 	if (us >= 1000000) { \
270 		tp->tv_usec = us - 1000000; \
271 		tp->tv_sec++; \
272 	} \
273 }
274 
275 int	stathz;
276 int	schedhz;
277 int	profhz;
278 int	profprocs;
279 int	ticks;
280 static int psdiv, pscnt;		/* prof => stat divider */
281 int	psratio;			/* ratio: prof / stat */
282 int	tickfix, tickfixinterval;	/* used if tick not really integral */
283 #ifndef NTP
284 static int tickfixcnt;			/* accumulated fractional error */
285 #else
286 int	fixtick;			/* used by NTP for same */
287 int	shifthz;
288 #endif
289 
290 volatile struct	timeval time;
291 volatile struct	timeval mono_time;
292 
293 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
294 void	*softclock_si;
295 void	generic_softclock(void *);
296 
297 void
298 generic_softclock(void *ignore)
299 {
300 	/*
301 	 * XXX - dont' commit, just a dummy wrapper until we learn everyone
302 	 *       deal with a changed proto for softclock().
303 	 */
304 	softclock();
305 }
306 #endif
307 
308 /*
309  * Initialize clock frequencies and start both clocks running.
310  */
311 void
312 initclocks()
313 {
314 	int i;
315 
316 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
317 	softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL);
318 	if (softclock_si == NULL)
319 		panic("initclocks: unable to register softclock intr");
320 #endif
321 
322 	/*
323 	 * Set divisors to 1 (normal case) and let the machine-specific
324 	 * code do its bit.
325 	 */
326 	psdiv = pscnt = 1;
327 	cpu_initclocks();
328 
329 	/*
330 	 * Compute profhz/stathz, and fix profhz if needed.
331 	 */
332 	i = stathz ? stathz : hz;
333 	if (profhz == 0)
334 		profhz = i;
335 	psratio = profhz / i;
336 
337 #ifdef NTP
338 	if (time_precision == 0)
339 		time_precision = tick;
340 
341 	switch (hz) {
342 	case 60:
343 	case 64:
344 		shifthz = SHIFT_SCALE - 6;
345 		break;
346 	case 96:
347 	case 100:
348 	case 128:
349 		shifthz = SHIFT_SCALE - 7;
350 		break;
351 	case 256:
352 		shifthz = SHIFT_SCALE - 8;
353 		break;
354 	case 1024:
355 		shifthz = SHIFT_SCALE - 10;
356 		break;
357 	case 1200:
358 		shifthz = SHIFT_SCALE - 11;
359 		break;
360 	default:
361 		panic("weird hz");
362 	}
363 #endif
364 }
365 
366 /*
367  * The real-time timer, interrupting hz times per second.
368  */
369 void
370 hardclock(frame)
371 	register struct clockframe *frame;
372 {
373 	register struct proc *p;
374 	register int delta;
375 	extern int tickdelta;
376 	extern long timedelta;
377 #ifdef NTP
378 	register int time_update;
379 	struct timeval newtime;
380 	register int ltemp;
381 #endif
382 
383 	p = curproc;
384 	if (p) {
385 		register struct pstats *pstats;
386 
387 		/*
388 		 * Run current process's virtual and profile time, as needed.
389 		 */
390 		pstats = p->p_stats;
391 		if (CLKF_USERMODE(frame) &&
392 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
393 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
394 			psignal(p, SIGVTALRM);
395 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
396 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
397 			psignal(p, SIGPROF);
398 	}
399 
400 	/*
401 	 * If no separate statistics clock is available, run it from here.
402 	 */
403 	if (stathz == 0)
404 		statclock(frame);
405 
406 	/*
407 	 * Increment the time-of-day.  The increment is normally just
408 	 * ``tick''.  If the machine is one which has a clock frequency
409 	 * such that ``hz'' would not divide the second evenly into
410 	 * milliseconds, a periodic adjustment must be applied.  Finally,
411 	 * if we are still adjusting the time (see adjtime()),
412 	 * ``tickdelta'' may also be added in.
413 	 */
414 	ticks++;
415 	delta = tick;
416 
417 #ifndef NTP
418 	if (tickfix) {
419 		tickfixcnt += tickfix;
420 		if (tickfixcnt >= tickfixinterval) {
421 			delta++;
422 			tickfixcnt -= tickfixinterval;
423 		}
424 	}
425 #else
426 	newtime = time;
427 #endif /* !NTP */
428 	/* Imprecise 4bsd adjtime() handling */
429 	if (timedelta != 0) {
430 		delta += tickdelta;
431 		timedelta -= tickdelta;
432 	}
433 
434 #ifdef notyet
435 	microset();
436 #endif
437 
438 #ifndef NTP
439 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
440 #endif
441 	BUMPTIME(&mono_time, delta);
442 
443 #ifdef NTP
444 	time_update = delta;
445 
446 	/*
447 	 * Compute the phase adjustment. If the low-order bits
448 	 * (time_phase) of the update overflow, bump the high-order bits
449 	 * (time_update).
450 	 */
451 	time_phase += time_adj;
452 	if (time_phase <= -FINEUSEC) {
453 		ltemp = -time_phase >> SHIFT_SCALE;
454 		time_phase += ltemp << SHIFT_SCALE;
455 		time_update -= ltemp;
456 	} else if (time_phase >= FINEUSEC) {
457 		ltemp = time_phase >> SHIFT_SCALE;
458 		time_phase -= ltemp << SHIFT_SCALE;
459 		time_update += ltemp;
460 	}
461 
462 #ifdef HIGHBALL
463 	/*
464 	 * If the HIGHBALL board is installed, we need to adjust the
465 	 * external clock offset in order to close the hardware feedback
466 	 * loop. This will adjust the external clock phase and frequency
467 	 * in small amounts. The additional phase noise and frequency
468 	 * wander this causes should be minimal. We also need to
469 	 * discipline the kernel time variable, since the PLL is used to
470 	 * discipline the external clock. If the Highball board is not
471 	 * present, we discipline kernel time with the PLL as usual. We
472 	 * assume that the external clock phase adjustment (time_update)
473 	 * and kernel phase adjustment (clock_cpu) are less than the
474 	 * value of tick.
475 	 */
476 	clock_offset.tv_usec += time_update;
477 	if (clock_offset.tv_usec >= 1000000) {
478 		clock_offset.tv_sec++;
479 		clock_offset.tv_usec -= 1000000;
480 	}
481 	if (clock_offset.tv_usec < 0) {
482 		clock_offset.tv_sec--;
483 		clock_offset.tv_usec += 1000000;
484 	}
485 	newtime.tv_usec += clock_cpu;
486 	clock_cpu = 0;
487 #else
488 	newtime.tv_usec += time_update;
489 #endif /* HIGHBALL */
490 
491 	/*
492 	 * On rollover of the second the phase adjustment to be used for
493 	 * the next second is calculated. Also, the maximum error is
494 	 * increased by the tolerance. If the PPS frequency discipline
495 	 * code is present, the phase is increased to compensate for the
496 	 * CPU clock oscillator frequency error.
497 	 *
498  	 * On a 32-bit machine and given parameters in the timex.h
499 	 * header file, the maximum phase adjustment is +-512 ms and
500 	 * maximum frequency offset is a tad less than) +-512 ppm. On a
501 	 * 64-bit machine, you shouldn't need to ask.
502 	 */
503 	if (newtime.tv_usec >= 1000000) {
504 		newtime.tv_usec -= 1000000;
505 		newtime.tv_sec++;
506 		time_maxerror += time_tolerance >> SHIFT_USEC;
507 
508 		/*
509 		 * Leap second processing. If in leap-insert state at
510 		 * the end of the day, the system clock is set back one
511 		 * second; if in leap-delete state, the system clock is
512 		 * set ahead one second. The microtime() routine or
513 		 * external clock driver will insure that reported time
514 		 * is always monotonic. The ugly divides should be
515 		 * replaced.
516 		 */
517 		switch (time_state) {
518 		case TIME_OK:
519 			if (time_status & STA_INS)
520 				time_state = TIME_INS;
521 			else if (time_status & STA_DEL)
522 				time_state = TIME_DEL;
523 			break;
524 
525 		case TIME_INS:
526 			if (newtime.tv_sec % 86400 == 0) {
527 				newtime.tv_sec--;
528 				time_state = TIME_OOP;
529 			}
530 			break;
531 
532 		case TIME_DEL:
533 			if ((newtime.tv_sec + 1) % 86400 == 0) {
534 				newtime.tv_sec++;
535 				time_state = TIME_WAIT;
536 			}
537 			break;
538 
539 		case TIME_OOP:
540 			time_state = TIME_WAIT;
541 			break;
542 
543 		case TIME_WAIT:
544 			if (!(time_status & (STA_INS | STA_DEL)))
545 				time_state = TIME_OK;
546 			break;
547 		}
548 
549 		/*
550 		 * Compute the phase adjustment for the next second. In
551 		 * PLL mode, the offset is reduced by a fixed factor
552 		 * times the time constant. In FLL mode the offset is
553 		 * used directly. In either mode, the maximum phase
554 		 * adjustment for each second is clamped so as to spread
555 		 * the adjustment over not more than the number of
556 		 * seconds between updates.
557 		 */
558 		if (time_offset < 0) {
559 			ltemp = -time_offset;
560 			if (!(time_status & STA_FLL))
561 				ltemp >>= SHIFT_KG + time_constant;
562 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
563 				ltemp = (MAXPHASE / MINSEC) <<
564 				    SHIFT_UPDATE;
565 			time_offset += ltemp;
566 			time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
567 		} else if (time_offset > 0) {
568 			ltemp = time_offset;
569 			if (!(time_status & STA_FLL))
570 				ltemp >>= SHIFT_KG + time_constant;
571 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
572 				ltemp = (MAXPHASE / MINSEC) <<
573 				    SHIFT_UPDATE;
574 			time_offset -= ltemp;
575 			time_adj = ltemp << (shifthz - SHIFT_UPDATE);
576 		} else
577 			time_adj = 0;
578 
579 		/*
580 		 * Compute the frequency estimate and additional phase
581 		 * adjustment due to frequency error for the next
582 		 * second. When the PPS signal is engaged, gnaw on the
583 		 * watchdog counter and update the frequency computed by
584 		 * the pll and the PPS signal.
585 		 */
586 #ifdef PPS_SYNC
587 		pps_valid++;
588 		if (pps_valid >= PPS_VALID) {
589 			pps_valid = PPS_VALID;	/* Avoid possible overflow */
590 			pps_jitter = MAXTIME;
591 			pps_stabil = MAXFREQ;
592 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
593 			    STA_PPSWANDER | STA_PPSERROR);
594 		}
595 		ltemp = time_freq + pps_freq;
596 #else
597 		ltemp = time_freq;
598 #endif /* PPS_SYNC */
599 
600 		if (ltemp < 0)
601 			time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
602 		else
603 			time_adj += ltemp >> (SHIFT_USEC - shifthz);
604 		time_adj += (long)fixtick << shifthz;
605 
606 		/*
607 		 * When the CPU clock oscillator frequency is not a
608 		 * power of 2 in Hz, shifthz is only an approximate
609 		 * scale factor.
610 		 */
611 		switch (hz) {
612 		case 96:
613 		case 100:
614 			/*
615 			 * In the following code the overall gain is increased
616 			 * by a factor of 1.25, which results in a residual
617 			 * error less than 3 percent.
618 			 */
619 			if (time_adj < 0)
620 				time_adj -= -time_adj >> 2;
621 			else
622 				time_adj += time_adj >> 2;
623 			break;
624 		case 60:
625 			/*
626 			 * 60 Hz m68k and vaxes have a PLL gain factor of of
627 			 * 60/64 (15/16) of what it should be.  In the following code
628 			 * the overall gain is increased by a factor of 1.0625,
629 			 * (17/16) which results in a residual error of just less
630 			 * than 0.4 percent.
631 			 */
632 			if (time_adj < 0)
633 				time_adj -= -time_adj >> 4;
634 			else
635 				time_adj += time_adj >> 4;
636 			break;
637 		}
638 
639 #ifdef EXT_CLOCK
640 		/*
641 		 * If an external clock is present, it is necessary to
642 		 * discipline the kernel time variable anyway, since not
643 		 * all system components use the microtime() interface.
644 		 * Here, the time offset between the external clock and
645 		 * kernel time variable is computed every so often.
646 		 */
647 		clock_count++;
648 		if (clock_count > CLOCK_INTERVAL) {
649 			clock_count = 0;
650 			microtime(&clock_ext);
651 			delta.tv_sec = clock_ext.tv_sec - newtime.tv_sec;
652 			delta.tv_usec = clock_ext.tv_usec - newtime.tv_usec;
653 			if (delta.tv_usec < 0)
654 				delta.tv_sec--;
655 			if (delta.tv_usec >= 500000) {
656 				delta.tv_usec -= 1000000;
657 				delta.tv_sec++;
658 			}
659 			if (delta.tv_usec < -500000) {
660 				delta.tv_usec += 1000000;
661 				delta.tv_sec--;
662 			}
663 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
664 			    delta.tv_usec > MAXPHASE) ||
665 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
666 			    delta.tv_usec < -MAXPHASE)) {
667 				newtime = clock_ext;
668 				delta.tv_sec = 0;
669 				delta.tv_usec = 0;
670 			}
671 #ifdef HIGHBALL
672 			clock_cpu = delta.tv_usec;
673 #else /* HIGHBALL */
674 			hardupdate(delta.tv_usec);
675 #endif /* HIGHBALL */
676 		}
677 #endif /* EXT_CLOCK */
678 	}
679 
680 #ifdef CPU_CLOCKUPDATE
681 	CPU_CLOCKUPDATE(&time, &newtime);
682 #else
683 	time = newtime;
684 #endif
685 
686 #endif /* NTP */
687 
688 	/*
689 	 * Update real-time timeout queue.
690 	 * Process callouts at a very low cpu priority, so we don't keep the
691 	 * relatively high clock interrupt priority any longer than necessary.
692 	 */
693 	if (timeout_hardclock_update()) {
694 		if (CLKF_BASEPRI(frame)) {
695 			/*
696 			 * Save the overhead of a software interrupt;
697 			 * it will happen as soon as we return, so do it now.
698 			 */
699 			spllowersoftclock();
700 			softclock();
701 		} else {
702 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
703 			softintr_schedule(softclock_si);
704 #else
705 			setsoftclock();
706 #endif
707 		}
708 	}
709 }
710 
711 /*
712  * Compute number of hz until specified time.  Used to
713  * compute the second argument to timeout_add() from an absolute time.
714  */
715 int
716 hzto(tv)
717 	struct timeval *tv;
718 {
719 	unsigned long ticks;
720 	long sec, usec;
721 	int s;
722 
723 	/*
724 	 * If the number of usecs in the whole seconds part of the time
725 	 * difference fits in a long, then the total number of usecs will
726 	 * fit in an unsigned long.  Compute the total and convert it to
727 	 * ticks, rounding up and adding 1 to allow for the current tick
728 	 * to expire.  Rounding also depends on unsigned long arithmetic
729 	 * to avoid overflow.
730 	 *
731 	 * Otherwise, if the number of ticks in the whole seconds part of
732 	 * the time difference fits in a long, then convert the parts to
733 	 * ticks separately and add, using similar rounding methods and
734 	 * overflow avoidance.  This method would work in the previous
735 	 * case but it is slightly slower and assumes that hz is integral.
736 	 *
737 	 * Otherwise, round the time difference down to the maximum
738 	 * representable value.
739 	 *
740 	 * If ints have 32 bits, then the maximum value for any timeout in
741 	 * 10ms ticks is 248 days.
742 	 */
743 	s = splhigh();
744 	sec = tv->tv_sec - time.tv_sec;
745 	usec = tv->tv_usec - time.tv_usec;
746 	splx(s);
747 	if (usec < 0) {
748 		sec--;
749 		usec += 1000000;
750 	}
751 	if (sec < 0 || (sec == 0 && usec <= 0)) {
752 		ticks = 0;
753 	} else if (sec <= LONG_MAX / 1000000)
754 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
755 		    / tick + 1;
756 	else if (sec <= LONG_MAX / hz)
757 		ticks = sec * hz
758 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
759 	else
760 		ticks = LONG_MAX;
761 	if (ticks > INT_MAX)
762 		ticks = INT_MAX;
763 	return ((int)ticks);
764 }
765 
766 /*
767  * Compute number of hz in the specified amount of time.
768  */
769 int
770 tvtohz(struct timeval *tv)
771 {
772 	unsigned long ticks;
773 	long sec, usec;
774 
775 	/*
776 	 * If the number of usecs in the whole seconds part of the time
777 	 * fits in a long, then the total number of usecs will
778 	 * fit in an unsigned long.  Compute the total and convert it to
779 	 * ticks, rounding up and adding 1 to allow for the current tick
780 	 * to expire.  Rounding also depends on unsigned long arithmetic
781 	 * to avoid overflow.
782 	 *
783 	 * Otherwise, if the number of ticks in the whole seconds part of
784 	 * the time fits in a long, then convert the parts to
785 	 * ticks separately and add, using similar rounding methods and
786 	 * overflow avoidance.  This method would work in the previous
787 	 * case but it is slightly slower and assumes that hz is integral.
788 	 *
789 	 * Otherwise, round the time down to the maximum
790 	 * representable value.
791 	 *
792 	 * If ints have 32 bits, then the maximum value for any timeout in
793 	 * 10ms ticks is 248 days.
794 	 */
795 	sec = tv->tv_sec;
796 	usec = tv->tv_usec;
797 	if (sec < 0 || (sec == 0 && usec <= 0))
798 		ticks = 0;
799 	else if (sec <= LONG_MAX / 1000000)
800 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
801 		    / tick + 1;
802 	else if (sec <= LONG_MAX / hz)
803 		ticks = sec * hz
804 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
805 	else
806 		ticks = LONG_MAX;
807 	if (ticks > INT_MAX)
808 		ticks = INT_MAX;
809 	return ((int)ticks);
810 }
811 
812 /*
813  * Start profiling on a process.
814  *
815  * Kernel profiling passes proc0 which never exits and hence
816  * keeps the profile clock running constantly.
817  */
818 void
819 startprofclock(p)
820 	register struct proc *p;
821 {
822 	int s;
823 
824 	if ((p->p_flag & P_PROFIL) == 0) {
825 		p->p_flag |= P_PROFIL;
826 		if (++profprocs == 1 && stathz != 0) {
827 			s = splstatclock();
828 			psdiv = pscnt = psratio;
829 			setstatclockrate(profhz);
830 			splx(s);
831 		}
832 	}
833 }
834 
835 /*
836  * Stop profiling on a process.
837  */
838 void
839 stopprofclock(p)
840 	register struct proc *p;
841 {
842 	int s;
843 
844 	if (p->p_flag & P_PROFIL) {
845 		p->p_flag &= ~P_PROFIL;
846 		if (--profprocs == 0 && stathz != 0) {
847 			s = splstatclock();
848 			psdiv = pscnt = 1;
849 			setstatclockrate(stathz);
850 			splx(s);
851 		}
852 	}
853 }
854 
855 /*
856  * Statistics clock.  Grab profile sample, and if divider reaches 0,
857  * do process and kernel statistics.
858  */
859 void
860 statclock(frame)
861 	register struct clockframe *frame;
862 {
863 #ifdef GPROF
864 	register struct gmonparam *g;
865 	register int i;
866 #endif
867 	static int schedclk;
868 	register struct proc *p;
869 
870 	if (CLKF_USERMODE(frame)) {
871 		p = curproc;
872 		if (p->p_flag & P_PROFIL)
873 			addupc_intr(p, CLKF_PC(frame), 1);
874 		if (--pscnt > 0)
875 			return;
876 		/*
877 		 * Came from user mode; CPU was in user state.
878 		 * If this process is being profiled record the tick.
879 		 */
880 		p->p_uticks++;
881 		if (p->p_nice > NZERO)
882 			cp_time[CP_NICE]++;
883 		else
884 			cp_time[CP_USER]++;
885 	} else {
886 #ifdef GPROF
887 		/*
888 		 * Kernel statistics are just like addupc_intr, only easier.
889 		 */
890 		g = &_gmonparam;
891 		if (g->state == GMON_PROF_ON) {
892 			i = CLKF_PC(frame) - g->lowpc;
893 			if (i < g->textsize) {
894 				i /= HISTFRACTION * sizeof(*g->kcount);
895 				g->kcount[i]++;
896 			}
897 		}
898 #endif
899 		if (--pscnt > 0)
900 			return;
901 		/*
902 		 * Came from kernel mode, so we were:
903 		 * - handling an interrupt,
904 		 * - doing syscall or trap work on behalf of the current
905 		 *   user process, or
906 		 * - spinning in the idle loop.
907 		 * Whichever it is, charge the time as appropriate.
908 		 * Note that we charge interrupts to the current process,
909 		 * regardless of whether they are ``for'' that process,
910 		 * so that we know how much of its real time was spent
911 		 * in ``non-process'' (i.e., interrupt) work.
912 		 */
913 		p = curproc;
914 		if (CLKF_INTR(frame)) {
915 			if (p != NULL)
916 				p->p_iticks++;
917 			cp_time[CP_INTR]++;
918 		} else if (p != NULL) {
919 			p->p_sticks++;
920 			cp_time[CP_SYS]++;
921 		} else
922 			cp_time[CP_IDLE]++;
923 	}
924 	pscnt = psdiv;
925 
926 	if (p != NULL) {
927 		p->p_cpticks++;
928 		/*
929 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
930 		 * ~~16 Hz is best
931 		 */
932 		if (schedhz == 0)
933 			if ((++schedclk & 3) == 0)
934 				schedclock(p);
935 	}
936 }
937 
938 
939 #ifdef NTP	/* NTP phase-locked loop in kernel */
940 
941 /*
942  * hardupdate() - local clock update
943  *
944  * This routine is called by ntp_adjtime() to update the local clock
945  * phase and frequency. The implementation is of an adaptive-parameter,
946  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
947  * time and frequency offset estimates for each call. If the kernel PPS
948  * discipline code is configured (PPS_SYNC), the PPS signal itself
949  * determines the new time offset, instead of the calling argument.
950  * Presumably, calls to ntp_adjtime() occur only when the caller
951  * believes the local clock is valid within some bound (+-128 ms with
952  * NTP). If the caller's time is far different than the PPS time, an
953  * argument will ensue, and it's not clear who will lose.
954  *
955  * For uncompensated quartz crystal oscillatores and nominal update
956  * intervals less than 1024 s, operation should be in phase-lock mode
957  * (STA_FLL = 0), where the loop is disciplined to phase. For update
958  * intervals greater than this, operation should be in frequency-lock
959  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
960  *
961  * Note: splclock() is in effect.
962  */
963 void
964 hardupdate(offset)
965 	long offset;
966 {
967 	long ltemp, mtemp;
968 
969 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
970 		return;
971 	ltemp = offset;
972 #ifdef PPS_SYNC
973 	if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
974 		ltemp = pps_offset;
975 #endif /* PPS_SYNC */
976 
977 	/*
978 	 * Scale the phase adjustment and clamp to the operating range.
979 	 */
980 	if (ltemp > MAXPHASE)
981 		time_offset = MAXPHASE << SHIFT_UPDATE;
982 	else if (ltemp < -MAXPHASE)
983 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
984 	else
985 		time_offset = ltemp << SHIFT_UPDATE;
986 
987 	/*
988 	 * Select whether the frequency is to be controlled and in which
989 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
990 	 * multiply/divide should be replaced someday.
991 	 */
992 	if (time_status & STA_FREQHOLD || time_reftime == 0)
993 		time_reftime = time.tv_sec;
994 	mtemp = time.tv_sec - time_reftime;
995 	time_reftime = time.tv_sec;
996 	if (time_status & STA_FLL) {
997 		if (mtemp >= MINSEC) {
998 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
999 			    SHIFT_UPDATE));
1000 			if (ltemp < 0)
1001 				time_freq -= -ltemp >> SHIFT_KH;
1002 			else
1003 				time_freq += ltemp >> SHIFT_KH;
1004 		}
1005 	} else {
1006 		if (mtemp < MAXSEC) {
1007 			ltemp *= mtemp;
1008 			if (ltemp < 0)
1009 				time_freq -= -ltemp >> (time_constant +
1010 				    time_constant + SHIFT_KF -
1011 				    SHIFT_USEC);
1012 			else
1013 				time_freq += ltemp >> (time_constant +
1014 				    time_constant + SHIFT_KF -
1015 				    SHIFT_USEC);
1016 		}
1017 	}
1018 	if (time_freq > time_tolerance)
1019 		time_freq = time_tolerance;
1020 	else if (time_freq < -time_tolerance)
1021 		time_freq = -time_tolerance;
1022 }
1023 
1024 #ifdef PPS_SYNC
1025 /*
1026  * hardpps() - discipline CPU clock oscillator to external PPS signal
1027  *
1028  * This routine is called at each PPS interrupt in order to discipline
1029  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1030  * and leaves it in a handy spot for the hardclock() routine. It
1031  * integrates successive PPS phase differences and calculates the
1032  * frequency offset. This is used in hardclock() to discipline the CPU
1033  * clock oscillator so that intrinsic frequency error is cancelled out.
1034  * The code requires the caller to capture the time and hardware counter
1035  * value at the on-time PPS signal transition.
1036  *
1037  * Note that, on some Unix systems, this routine runs at an interrupt
1038  * priority level higher than the timer interrupt routine hardclock().
1039  * Therefore, the variables used are distinct from the hardclock()
1040  * variables, except for certain exceptions: The PPS frequency pps_freq
1041  * and phase pps_offset variables are determined by this routine and
1042  * updated atomically. The time_tolerance variable can be considered a
1043  * constant, since it is infrequently changed, and then only when the
1044  * PPS signal is disabled. The watchdog counter pps_valid is updated
1045  * once per second by hardclock() and is atomically cleared in this
1046  * routine.
1047  */
1048 void
1049 hardpps(tvp, usec)
1050 	struct timeval *tvp;		/* time at PPS */
1051 	long usec;			/* hardware counter at PPS */
1052 {
1053 	long u_usec, v_usec, bigtick;
1054 	long cal_sec, cal_usec;
1055 
1056 	/*
1057 	 * An occasional glitch can be produced when the PPS interrupt
1058 	 * occurs in the hardclock() routine before the time variable is
1059 	 * updated. Here the offset is discarded when the difference
1060 	 * between it and the last one is greater than tick/2, but not
1061 	 * if the interval since the first discard exceeds 30 s.
1062 	 */
1063 	time_status |= STA_PPSSIGNAL;
1064 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1065 	pps_valid = 0;
1066 	u_usec = -tvp->tv_usec;
1067 	if (u_usec < -500000)
1068 		u_usec += 1000000;
1069 	v_usec = pps_offset - u_usec;
1070 	if (v_usec < 0)
1071 		v_usec = -v_usec;
1072 	if (v_usec > (tick >> 1)) {
1073 		if (pps_glitch > MAXGLITCH) {
1074 			pps_glitch = 0;
1075 			pps_tf[2] = u_usec;
1076 			pps_tf[1] = u_usec;
1077 		} else {
1078 			pps_glitch++;
1079 			u_usec = pps_offset;
1080 		}
1081 	} else
1082 		pps_glitch = 0;
1083 
1084 	/*
1085 	 * A three-stage median filter is used to help deglitch the pps
1086 	 * time. The median sample becomes the time offset estimate; the
1087 	 * difference between the other two samples becomes the time
1088 	 * dispersion (jitter) estimate.
1089 	 */
1090 	pps_tf[2] = pps_tf[1];
1091 	pps_tf[1] = pps_tf[0];
1092 	pps_tf[0] = u_usec;
1093 	if (pps_tf[0] > pps_tf[1]) {
1094 		if (pps_tf[1] > pps_tf[2]) {
1095 			pps_offset = pps_tf[1];		/* 0 1 2 */
1096 			v_usec = pps_tf[0] - pps_tf[2];
1097 		} else if (pps_tf[2] > pps_tf[0]) {
1098 			pps_offset = pps_tf[0];		/* 2 0 1 */
1099 			v_usec = pps_tf[2] - pps_tf[1];
1100 		} else {
1101 			pps_offset = pps_tf[2];		/* 0 2 1 */
1102 			v_usec = pps_tf[0] - pps_tf[1];
1103 		}
1104 	} else {
1105 		if (pps_tf[1] < pps_tf[2]) {
1106 			pps_offset = pps_tf[1];		/* 2 1 0 */
1107 			v_usec = pps_tf[2] - pps_tf[0];
1108 		} else  if (pps_tf[2] < pps_tf[0]) {
1109 			pps_offset = pps_tf[0];		/* 1 0 2 */
1110 			v_usec = pps_tf[1] - pps_tf[2];
1111 		} else {
1112 			pps_offset = pps_tf[2];		/* 1 2 0 */
1113 			v_usec = pps_tf[1] - pps_tf[0];
1114 		}
1115 	}
1116 	if (v_usec > MAXTIME)
1117 		pps_jitcnt++;
1118 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1119 	if (v_usec < 0)
1120 		pps_jitter -= -v_usec >> PPS_AVG;
1121 	else
1122 		pps_jitter += v_usec >> PPS_AVG;
1123 	if (pps_jitter > (MAXTIME >> 1))
1124 		time_status |= STA_PPSJITTER;
1125 
1126 	/*
1127 	 * During the calibration interval adjust the starting time when
1128 	 * the tick overflows. At the end of the interval compute the
1129 	 * duration of the interval and the difference of the hardware
1130 	 * counters at the beginning and end of the interval. This code
1131 	 * is deliciously complicated by the fact valid differences may
1132 	 * exceed the value of tick when using long calibration
1133 	 * intervals and small ticks. Note that the counter can be
1134 	 * greater than tick if caught at just the wrong instant, but
1135 	 * the values returned and used here are correct.
1136 	 */
1137 	bigtick = (long)tick << SHIFT_USEC;
1138 	pps_usec -= pps_freq;
1139 	if (pps_usec >= bigtick)
1140 		pps_usec -= bigtick;
1141 	if (pps_usec < 0)
1142 		pps_usec += bigtick;
1143 	pps_time.tv_sec++;
1144 	pps_count++;
1145 	if (pps_count < (1 << pps_shift))
1146 		return;
1147 	pps_count = 0;
1148 	pps_calcnt++;
1149 	u_usec = usec << SHIFT_USEC;
1150 	v_usec = pps_usec - u_usec;
1151 	if (v_usec >= bigtick >> 1)
1152 		v_usec -= bigtick;
1153 	if (v_usec < -(bigtick >> 1))
1154 		v_usec += bigtick;
1155 	if (v_usec < 0)
1156 		v_usec = -(-v_usec >> pps_shift);
1157 	else
1158 		v_usec = v_usec >> pps_shift;
1159 	pps_usec = u_usec;
1160 	cal_sec = tvp->tv_sec;
1161 	cal_usec = tvp->tv_usec;
1162 	cal_sec -= pps_time.tv_sec;
1163 	cal_usec -= pps_time.tv_usec;
1164 	if (cal_usec < 0) {
1165 		cal_usec += 1000000;
1166 		cal_sec--;
1167 	}
1168 	pps_time = *tvp;
1169 
1170 	/*
1171 	 * Check for lost interrupts, noise, excessive jitter and
1172 	 * excessive frequency error. The number of timer ticks during
1173 	 * the interval may vary +-1 tick. Add to this a margin of one
1174 	 * tick for the PPS signal jitter and maximum frequency
1175 	 * deviation. If the limits are exceeded, the calibration
1176 	 * interval is reset to the minimum and we start over.
1177 	 */
1178 	u_usec = (long)tick << 1;
1179 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1180 	    || (cal_sec == 0 && cal_usec < u_usec))
1181 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1182 		pps_errcnt++;
1183 		pps_shift = PPS_SHIFT;
1184 		pps_intcnt = 0;
1185 		time_status |= STA_PPSERROR;
1186 		return;
1187 	}
1188 
1189 	/*
1190 	 * A three-stage median filter is used to help deglitch the pps
1191 	 * frequency. The median sample becomes the frequency offset
1192 	 * estimate; the difference between the other two samples
1193 	 * becomes the frequency dispersion (stability) estimate.
1194 	 */
1195 	pps_ff[2] = pps_ff[1];
1196 	pps_ff[1] = pps_ff[0];
1197 	pps_ff[0] = v_usec;
1198 	if (pps_ff[0] > pps_ff[1]) {
1199 		if (pps_ff[1] > pps_ff[2]) {
1200 			u_usec = pps_ff[1];		/* 0 1 2 */
1201 			v_usec = pps_ff[0] - pps_ff[2];
1202 		} else if (pps_ff[2] > pps_ff[0]) {
1203 			u_usec = pps_ff[0];		/* 2 0 1 */
1204 			v_usec = pps_ff[2] - pps_ff[1];
1205 		} else {
1206 			u_usec = pps_ff[2];		/* 0 2 1 */
1207 			v_usec = pps_ff[0] - pps_ff[1];
1208 		}
1209 	} else {
1210 		if (pps_ff[1] < pps_ff[2]) {
1211 			u_usec = pps_ff[1];		/* 2 1 0 */
1212 			v_usec = pps_ff[2] - pps_ff[0];
1213 		} else  if (pps_ff[2] < pps_ff[0]) {
1214 			u_usec = pps_ff[0];		/* 1 0 2 */
1215 			v_usec = pps_ff[1] - pps_ff[2];
1216 		} else {
1217 			u_usec = pps_ff[2];		/* 1 2 0 */
1218 			v_usec = pps_ff[1] - pps_ff[0];
1219 		}
1220 	}
1221 
1222 	/*
1223 	 * Here the frequency dispersion (stability) is updated. If it
1224 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1225 	 * offset is updated as well, but clamped to the tolerance. It
1226 	 * will be processed later by the hardclock() routine.
1227 	 */
1228 	v_usec = (v_usec >> 1) - pps_stabil;
1229 	if (v_usec < 0)
1230 		pps_stabil -= -v_usec >> PPS_AVG;
1231 	else
1232 		pps_stabil += v_usec >> PPS_AVG;
1233 	if (pps_stabil > MAXFREQ >> 2) {
1234 		pps_stbcnt++;
1235 		time_status |= STA_PPSWANDER;
1236 		return;
1237 	}
1238 	if (time_status & STA_PPSFREQ) {
1239 		if (u_usec < 0) {
1240 			pps_freq -= -u_usec >> PPS_AVG;
1241 			if (pps_freq < -time_tolerance)
1242 				pps_freq = -time_tolerance;
1243 			u_usec = -u_usec;
1244 		} else {
1245 			pps_freq += u_usec >> PPS_AVG;
1246 			if (pps_freq > time_tolerance)
1247 				pps_freq = time_tolerance;
1248 		}
1249 	}
1250 
1251 	/*
1252 	 * Here the calibration interval is adjusted. If the maximum
1253 	 * time difference is greater than tick / 4, reduce the interval
1254 	 * by half. If this is not the case for four consecutive
1255 	 * intervals, double the interval.
1256 	 */
1257 	if (u_usec << pps_shift > bigtick >> 2) {
1258 		pps_intcnt = 0;
1259 		if (pps_shift > PPS_SHIFT)
1260 			pps_shift--;
1261 	} else if (pps_intcnt >= 4) {
1262 		pps_intcnt = 0;
1263 		if (pps_shift < PPS_SHIFTMAX)
1264 			pps_shift++;
1265 	} else
1266 		pps_intcnt++;
1267 }
1268 #endif /* PPS_SYNC */
1269 #endif /* NTP  */
1270 
1271 
1272 /*
1273  * Return information about system clocks.
1274  */
1275 int
1276 sysctl_clockrate(where, sizep)
1277 	register char *where;
1278 	size_t *sizep;
1279 {
1280 	struct clockinfo clkinfo;
1281 
1282 	/*
1283 	 * Construct clockinfo structure.
1284 	 */
1285 	clkinfo.tick = tick;
1286 	clkinfo.tickadj = tickadj;
1287 	clkinfo.hz = hz;
1288 	clkinfo.profhz = profhz;
1289 	clkinfo.stathz = stathz ? stathz : hz;
1290 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1291 }
1292