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