xref: /openbsd-src/sys/kern/kern_clock.c (revision 12581b04a4be1be63744ec134d84a59f571e65b2)
1 /*	$OpenBSD: kern_clock.c,v 1.36 2002/06/07 08:16:26 nordin 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 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
695 		softintr_schedule(softclock_si);
696 #else
697 		setsoftclock();
698 #endif
699 	}
700 }
701 
702 /*
703  * Compute number of hz until specified time.  Used to
704  * compute the second argument to timeout_add() from an absolute time.
705  */
706 int
707 hzto(tv)
708 	struct timeval *tv;
709 {
710 	unsigned long ticks;
711 	long sec, usec;
712 	int s;
713 
714 	/*
715 	 * If the number of usecs in the whole seconds part of the time
716 	 * difference fits in a long, then the total number of usecs will
717 	 * fit in an unsigned long.  Compute the total and convert it to
718 	 * ticks, rounding up and adding 1 to allow for the current tick
719 	 * to expire.  Rounding also depends on unsigned long arithmetic
720 	 * to avoid overflow.
721 	 *
722 	 * Otherwise, if the number of ticks in the whole seconds part of
723 	 * the time difference fits in a long, then convert the parts to
724 	 * ticks separately and add, using similar rounding methods and
725 	 * overflow avoidance.  This method would work in the previous
726 	 * case but it is slightly slower and assumes that hz is integral.
727 	 *
728 	 * Otherwise, round the time difference down to the maximum
729 	 * representable value.
730 	 *
731 	 * If ints have 32 bits, then the maximum value for any timeout in
732 	 * 10ms ticks is 248 days.
733 	 */
734 	s = splhigh();
735 	sec = tv->tv_sec - time.tv_sec;
736 	usec = tv->tv_usec - time.tv_usec;
737 	splx(s);
738 	if (usec < 0) {
739 		sec--;
740 		usec += 1000000;
741 	}
742 	if (sec < 0 || (sec == 0 && usec <= 0)) {
743 		ticks = 0;
744 	} else if (sec <= LONG_MAX / 1000000)
745 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
746 		    / tick + 1;
747 	else if (sec <= LONG_MAX / hz)
748 		ticks = sec * hz
749 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
750 	else
751 		ticks = LONG_MAX;
752 	if (ticks > INT_MAX)
753 		ticks = INT_MAX;
754 	return ((int)ticks);
755 }
756 
757 /*
758  * Compute number of hz in the specified amount of time.
759  */
760 int
761 tvtohz(struct timeval *tv)
762 {
763 	unsigned long ticks;
764 	long sec, usec;
765 
766 	/*
767 	 * If the number of usecs in the whole seconds part of the time
768 	 * fits in a long, then the total number of usecs will
769 	 * fit in an unsigned long.  Compute the total and convert it to
770 	 * ticks, rounding up and adding 1 to allow for the current tick
771 	 * to expire.  Rounding also depends on unsigned long arithmetic
772 	 * to avoid overflow.
773 	 *
774 	 * Otherwise, if the number of ticks in the whole seconds part of
775 	 * the time fits in a long, then convert the parts to
776 	 * ticks separately and add, using similar rounding methods and
777 	 * overflow avoidance.  This method would work in the previous
778 	 * case but it is slightly slower and assumes that hz is integral.
779 	 *
780 	 * Otherwise, round the time down to the maximum
781 	 * representable value.
782 	 *
783 	 * If ints have 32 bits, then the maximum value for any timeout in
784 	 * 10ms ticks is 248 days.
785 	 */
786 	sec = tv->tv_sec;
787 	usec = tv->tv_usec;
788 	if (sec < 0 || (sec == 0 && usec <= 0))
789 		ticks = 0;
790 	else if (sec <= LONG_MAX / 1000000)
791 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
792 		    / tick + 1;
793 	else if (sec <= LONG_MAX / hz)
794 		ticks = sec * hz
795 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
796 	else
797 		ticks = LONG_MAX;
798 	if (ticks > INT_MAX)
799 		ticks = INT_MAX;
800 	return ((int)ticks);
801 }
802 
803 /*
804  * Start profiling on a process.
805  *
806  * Kernel profiling passes proc0 which never exits and hence
807  * keeps the profile clock running constantly.
808  */
809 void
810 startprofclock(p)
811 	register struct proc *p;
812 {
813 	int s;
814 
815 	if ((p->p_flag & P_PROFIL) == 0) {
816 		p->p_flag |= P_PROFIL;
817 		if (++profprocs == 1 && stathz != 0) {
818 			s = splstatclock();
819 			psdiv = pscnt = psratio;
820 			setstatclockrate(profhz);
821 			splx(s);
822 		}
823 	}
824 }
825 
826 /*
827  * Stop profiling on a process.
828  */
829 void
830 stopprofclock(p)
831 	register struct proc *p;
832 {
833 	int s;
834 
835 	if (p->p_flag & P_PROFIL) {
836 		p->p_flag &= ~P_PROFIL;
837 		if (--profprocs == 0 && stathz != 0) {
838 			s = splstatclock();
839 			psdiv = pscnt = 1;
840 			setstatclockrate(stathz);
841 			splx(s);
842 		}
843 	}
844 }
845 
846 /*
847  * Statistics clock.  Grab profile sample, and if divider reaches 0,
848  * do process and kernel statistics.
849  */
850 void
851 statclock(frame)
852 	register struct clockframe *frame;
853 {
854 #ifdef GPROF
855 	register struct gmonparam *g;
856 	register int i;
857 #endif
858 	static int schedclk;
859 	register struct proc *p;
860 
861 	if (CLKF_USERMODE(frame)) {
862 		p = curproc;
863 		if (p->p_flag & P_PROFIL)
864 			addupc_intr(p, CLKF_PC(frame), 1);
865 		if (--pscnt > 0)
866 			return;
867 		/*
868 		 * Came from user mode; CPU was in user state.
869 		 * If this process is being profiled record the tick.
870 		 */
871 		p->p_uticks++;
872 		if (p->p_nice > NZERO)
873 			cp_time[CP_NICE]++;
874 		else
875 			cp_time[CP_USER]++;
876 	} else {
877 #ifdef GPROF
878 		/*
879 		 * Kernel statistics are just like addupc_intr, only easier.
880 		 */
881 		g = &_gmonparam;
882 		if (g->state == GMON_PROF_ON) {
883 			i = CLKF_PC(frame) - g->lowpc;
884 			if (i < g->textsize) {
885 				i /= HISTFRACTION * sizeof(*g->kcount);
886 				g->kcount[i]++;
887 			}
888 		}
889 #endif
890 		if (--pscnt > 0)
891 			return;
892 		/*
893 		 * Came from kernel mode, so we were:
894 		 * - handling an interrupt,
895 		 * - doing syscall or trap work on behalf of the current
896 		 *   user process, or
897 		 * - spinning in the idle loop.
898 		 * Whichever it is, charge the time as appropriate.
899 		 * Note that we charge interrupts to the current process,
900 		 * regardless of whether they are ``for'' that process,
901 		 * so that we know how much of its real time was spent
902 		 * in ``non-process'' (i.e., interrupt) work.
903 		 */
904 		p = curproc;
905 		if (CLKF_INTR(frame)) {
906 			if (p != NULL)
907 				p->p_iticks++;
908 			cp_time[CP_INTR]++;
909 		} else if (p != NULL) {
910 			p->p_sticks++;
911 			cp_time[CP_SYS]++;
912 		} else
913 			cp_time[CP_IDLE]++;
914 	}
915 	pscnt = psdiv;
916 
917 	if (p != NULL) {
918 		p->p_cpticks++;
919 		/*
920 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
921 		 * ~~16 Hz is best
922 		 */
923 		if (schedhz == 0)
924 			if ((++schedclk & 3) == 0)
925 				schedclock(p);
926 	}
927 }
928 
929 
930 #ifdef NTP	/* NTP phase-locked loop in kernel */
931 
932 /*
933  * hardupdate() - local clock update
934  *
935  * This routine is called by ntp_adjtime() to update the local clock
936  * phase and frequency. The implementation is of an adaptive-parameter,
937  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
938  * time and frequency offset estimates for each call. If the kernel PPS
939  * discipline code is configured (PPS_SYNC), the PPS signal itself
940  * determines the new time offset, instead of the calling argument.
941  * Presumably, calls to ntp_adjtime() occur only when the caller
942  * believes the local clock is valid within some bound (+-128 ms with
943  * NTP). If the caller's time is far different than the PPS time, an
944  * argument will ensue, and it's not clear who will lose.
945  *
946  * For uncompensated quartz crystal oscillatores and nominal update
947  * intervals less than 1024 s, operation should be in phase-lock mode
948  * (STA_FLL = 0), where the loop is disciplined to phase. For update
949  * intervals greater than this, operation should be in frequency-lock
950  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
951  *
952  * Note: splclock() is in effect.
953  */
954 void
955 hardupdate(offset)
956 	long offset;
957 {
958 	long ltemp, mtemp;
959 
960 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
961 		return;
962 	ltemp = offset;
963 #ifdef PPS_SYNC
964 	if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
965 		ltemp = pps_offset;
966 #endif /* PPS_SYNC */
967 
968 	/*
969 	 * Scale the phase adjustment and clamp to the operating range.
970 	 */
971 	if (ltemp > MAXPHASE)
972 		time_offset = MAXPHASE << SHIFT_UPDATE;
973 	else if (ltemp < -MAXPHASE)
974 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
975 	else
976 		time_offset = ltemp << SHIFT_UPDATE;
977 
978 	/*
979 	 * Select whether the frequency is to be controlled and in which
980 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
981 	 * multiply/divide should be replaced someday.
982 	 */
983 	if (time_status & STA_FREQHOLD || time_reftime == 0)
984 		time_reftime = time.tv_sec;
985 	mtemp = time.tv_sec - time_reftime;
986 	time_reftime = time.tv_sec;
987 	if (time_status & STA_FLL) {
988 		if (mtemp >= MINSEC) {
989 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
990 			    SHIFT_UPDATE));
991 			if (ltemp < 0)
992 				time_freq -= -ltemp >> SHIFT_KH;
993 			else
994 				time_freq += ltemp >> SHIFT_KH;
995 		}
996 	} else {
997 		if (mtemp < MAXSEC) {
998 			ltemp *= mtemp;
999 			if (ltemp < 0)
1000 				time_freq -= -ltemp >> (time_constant +
1001 				    time_constant + SHIFT_KF -
1002 				    SHIFT_USEC);
1003 			else
1004 				time_freq += ltemp >> (time_constant +
1005 				    time_constant + SHIFT_KF -
1006 				    SHIFT_USEC);
1007 		}
1008 	}
1009 	if (time_freq > time_tolerance)
1010 		time_freq = time_tolerance;
1011 	else if (time_freq < -time_tolerance)
1012 		time_freq = -time_tolerance;
1013 }
1014 
1015 #ifdef PPS_SYNC
1016 /*
1017  * hardpps() - discipline CPU clock oscillator to external PPS signal
1018  *
1019  * This routine is called at each PPS interrupt in order to discipline
1020  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1021  * and leaves it in a handy spot for the hardclock() routine. It
1022  * integrates successive PPS phase differences and calculates the
1023  * frequency offset. This is used in hardclock() to discipline the CPU
1024  * clock oscillator so that intrinsic frequency error is cancelled out.
1025  * The code requires the caller to capture the time and hardware counter
1026  * value at the on-time PPS signal transition.
1027  *
1028  * Note that, on some Unix systems, this routine runs at an interrupt
1029  * priority level higher than the timer interrupt routine hardclock().
1030  * Therefore, the variables used are distinct from the hardclock()
1031  * variables, except for certain exceptions: The PPS frequency pps_freq
1032  * and phase pps_offset variables are determined by this routine and
1033  * updated atomically. The time_tolerance variable can be considered a
1034  * constant, since it is infrequently changed, and then only when the
1035  * PPS signal is disabled. The watchdog counter pps_valid is updated
1036  * once per second by hardclock() and is atomically cleared in this
1037  * routine.
1038  */
1039 void
1040 hardpps(tvp, usec)
1041 	struct timeval *tvp;		/* time at PPS */
1042 	long usec;			/* hardware counter at PPS */
1043 {
1044 	long u_usec, v_usec, bigtick;
1045 	long cal_sec, cal_usec;
1046 
1047 	/*
1048 	 * An occasional glitch can be produced when the PPS interrupt
1049 	 * occurs in the hardclock() routine before the time variable is
1050 	 * updated. Here the offset is discarded when the difference
1051 	 * between it and the last one is greater than tick/2, but not
1052 	 * if the interval since the first discard exceeds 30 s.
1053 	 */
1054 	time_status |= STA_PPSSIGNAL;
1055 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1056 	pps_valid = 0;
1057 	u_usec = -tvp->tv_usec;
1058 	if (u_usec < -500000)
1059 		u_usec += 1000000;
1060 	v_usec = pps_offset - u_usec;
1061 	if (v_usec < 0)
1062 		v_usec = -v_usec;
1063 	if (v_usec > (tick >> 1)) {
1064 		if (pps_glitch > MAXGLITCH) {
1065 			pps_glitch = 0;
1066 			pps_tf[2] = u_usec;
1067 			pps_tf[1] = u_usec;
1068 		} else {
1069 			pps_glitch++;
1070 			u_usec = pps_offset;
1071 		}
1072 	} else
1073 		pps_glitch = 0;
1074 
1075 	/*
1076 	 * A three-stage median filter is used to help deglitch the pps
1077 	 * time. The median sample becomes the time offset estimate; the
1078 	 * difference between the other two samples becomes the time
1079 	 * dispersion (jitter) estimate.
1080 	 */
1081 	pps_tf[2] = pps_tf[1];
1082 	pps_tf[1] = pps_tf[0];
1083 	pps_tf[0] = u_usec;
1084 	if (pps_tf[0] > pps_tf[1]) {
1085 		if (pps_tf[1] > pps_tf[2]) {
1086 			pps_offset = pps_tf[1];		/* 0 1 2 */
1087 			v_usec = pps_tf[0] - pps_tf[2];
1088 		} else if (pps_tf[2] > pps_tf[0]) {
1089 			pps_offset = pps_tf[0];		/* 2 0 1 */
1090 			v_usec = pps_tf[2] - pps_tf[1];
1091 		} else {
1092 			pps_offset = pps_tf[2];		/* 0 2 1 */
1093 			v_usec = pps_tf[0] - pps_tf[1];
1094 		}
1095 	} else {
1096 		if (pps_tf[1] < pps_tf[2]) {
1097 			pps_offset = pps_tf[1];		/* 2 1 0 */
1098 			v_usec = pps_tf[2] - pps_tf[0];
1099 		} else  if (pps_tf[2] < pps_tf[0]) {
1100 			pps_offset = pps_tf[0];		/* 1 0 2 */
1101 			v_usec = pps_tf[1] - pps_tf[2];
1102 		} else {
1103 			pps_offset = pps_tf[2];		/* 1 2 0 */
1104 			v_usec = pps_tf[1] - pps_tf[0];
1105 		}
1106 	}
1107 	if (v_usec > MAXTIME)
1108 		pps_jitcnt++;
1109 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1110 	if (v_usec < 0)
1111 		pps_jitter -= -v_usec >> PPS_AVG;
1112 	else
1113 		pps_jitter += v_usec >> PPS_AVG;
1114 	if (pps_jitter > (MAXTIME >> 1))
1115 		time_status |= STA_PPSJITTER;
1116 
1117 	/*
1118 	 * During the calibration interval adjust the starting time when
1119 	 * the tick overflows. At the end of the interval compute the
1120 	 * duration of the interval and the difference of the hardware
1121 	 * counters at the beginning and end of the interval. This code
1122 	 * is deliciously complicated by the fact valid differences may
1123 	 * exceed the value of tick when using long calibration
1124 	 * intervals and small ticks. Note that the counter can be
1125 	 * greater than tick if caught at just the wrong instant, but
1126 	 * the values returned and used here are correct.
1127 	 */
1128 	bigtick = (long)tick << SHIFT_USEC;
1129 	pps_usec -= pps_freq;
1130 	if (pps_usec >= bigtick)
1131 		pps_usec -= bigtick;
1132 	if (pps_usec < 0)
1133 		pps_usec += bigtick;
1134 	pps_time.tv_sec++;
1135 	pps_count++;
1136 	if (pps_count < (1 << pps_shift))
1137 		return;
1138 	pps_count = 0;
1139 	pps_calcnt++;
1140 	u_usec = usec << SHIFT_USEC;
1141 	v_usec = pps_usec - u_usec;
1142 	if (v_usec >= bigtick >> 1)
1143 		v_usec -= bigtick;
1144 	if (v_usec < -(bigtick >> 1))
1145 		v_usec += bigtick;
1146 	if (v_usec < 0)
1147 		v_usec = -(-v_usec >> pps_shift);
1148 	else
1149 		v_usec = v_usec >> pps_shift;
1150 	pps_usec = u_usec;
1151 	cal_sec = tvp->tv_sec;
1152 	cal_usec = tvp->tv_usec;
1153 	cal_sec -= pps_time.tv_sec;
1154 	cal_usec -= pps_time.tv_usec;
1155 	if (cal_usec < 0) {
1156 		cal_usec += 1000000;
1157 		cal_sec--;
1158 	}
1159 	pps_time = *tvp;
1160 
1161 	/*
1162 	 * Check for lost interrupts, noise, excessive jitter and
1163 	 * excessive frequency error. The number of timer ticks during
1164 	 * the interval may vary +-1 tick. Add to this a margin of one
1165 	 * tick for the PPS signal jitter and maximum frequency
1166 	 * deviation. If the limits are exceeded, the calibration
1167 	 * interval is reset to the minimum and we start over.
1168 	 */
1169 	u_usec = (long)tick << 1;
1170 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1171 	    || (cal_sec == 0 && cal_usec < u_usec))
1172 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1173 		pps_errcnt++;
1174 		pps_shift = PPS_SHIFT;
1175 		pps_intcnt = 0;
1176 		time_status |= STA_PPSERROR;
1177 		return;
1178 	}
1179 
1180 	/*
1181 	 * A three-stage median filter is used to help deglitch the pps
1182 	 * frequency. The median sample becomes the frequency offset
1183 	 * estimate; the difference between the other two samples
1184 	 * becomes the frequency dispersion (stability) estimate.
1185 	 */
1186 	pps_ff[2] = pps_ff[1];
1187 	pps_ff[1] = pps_ff[0];
1188 	pps_ff[0] = v_usec;
1189 	if (pps_ff[0] > pps_ff[1]) {
1190 		if (pps_ff[1] > pps_ff[2]) {
1191 			u_usec = pps_ff[1];		/* 0 1 2 */
1192 			v_usec = pps_ff[0] - pps_ff[2];
1193 		} else if (pps_ff[2] > pps_ff[0]) {
1194 			u_usec = pps_ff[0];		/* 2 0 1 */
1195 			v_usec = pps_ff[2] - pps_ff[1];
1196 		} else {
1197 			u_usec = pps_ff[2];		/* 0 2 1 */
1198 			v_usec = pps_ff[0] - pps_ff[1];
1199 		}
1200 	} else {
1201 		if (pps_ff[1] < pps_ff[2]) {
1202 			u_usec = pps_ff[1];		/* 2 1 0 */
1203 			v_usec = pps_ff[2] - pps_ff[0];
1204 		} else  if (pps_ff[2] < pps_ff[0]) {
1205 			u_usec = pps_ff[0];		/* 1 0 2 */
1206 			v_usec = pps_ff[1] - pps_ff[2];
1207 		} else {
1208 			u_usec = pps_ff[2];		/* 1 2 0 */
1209 			v_usec = pps_ff[1] - pps_ff[0];
1210 		}
1211 	}
1212 
1213 	/*
1214 	 * Here the frequency dispersion (stability) is updated. If it
1215 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1216 	 * offset is updated as well, but clamped to the tolerance. It
1217 	 * will be processed later by the hardclock() routine.
1218 	 */
1219 	v_usec = (v_usec >> 1) - pps_stabil;
1220 	if (v_usec < 0)
1221 		pps_stabil -= -v_usec >> PPS_AVG;
1222 	else
1223 		pps_stabil += v_usec >> PPS_AVG;
1224 	if (pps_stabil > MAXFREQ >> 2) {
1225 		pps_stbcnt++;
1226 		time_status |= STA_PPSWANDER;
1227 		return;
1228 	}
1229 	if (time_status & STA_PPSFREQ) {
1230 		if (u_usec < 0) {
1231 			pps_freq -= -u_usec >> PPS_AVG;
1232 			if (pps_freq < -time_tolerance)
1233 				pps_freq = -time_tolerance;
1234 			u_usec = -u_usec;
1235 		} else {
1236 			pps_freq += u_usec >> PPS_AVG;
1237 			if (pps_freq > time_tolerance)
1238 				pps_freq = time_tolerance;
1239 		}
1240 	}
1241 
1242 	/*
1243 	 * Here the calibration interval is adjusted. If the maximum
1244 	 * time difference is greater than tick / 4, reduce the interval
1245 	 * by half. If this is not the case for four consecutive
1246 	 * intervals, double the interval.
1247 	 */
1248 	if (u_usec << pps_shift > bigtick >> 2) {
1249 		pps_intcnt = 0;
1250 		if (pps_shift > PPS_SHIFT)
1251 			pps_shift--;
1252 	} else if (pps_intcnt >= 4) {
1253 		pps_intcnt = 0;
1254 		if (pps_shift < PPS_SHIFTMAX)
1255 			pps_shift++;
1256 	} else
1257 		pps_intcnt++;
1258 }
1259 #endif /* PPS_SYNC */
1260 #endif /* NTP  */
1261 
1262 
1263 /*
1264  * Return information about system clocks.
1265  */
1266 int
1267 sysctl_clockrate(where, sizep)
1268 	register char *where;
1269 	size_t *sizep;
1270 {
1271 	struct clockinfo clkinfo;
1272 
1273 	/*
1274 	 * Construct clockinfo structure.
1275 	 */
1276 	clkinfo.tick = tick;
1277 	clkinfo.tickadj = tickadj;
1278 	clkinfo.hz = hz;
1279 	clkinfo.profhz = profhz;
1280 	clkinfo.stathz = stathz ? stathz : hz;
1281 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1282 }
1283