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