xref: /openbsd-src/sys/kern/kern_clock.c (revision c17885f6d1c5f472bdf2fcc79250c459383ac6ec)
1 /*	$OpenBSD: kern_clock.c,v 1.25 2000/07/06 15:33:31 ho 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, needsoft;
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 	/*
366 	 * Update real-time timeout queue.
367 	 */
368 	needsoft = timeout_hardclock_update();
369 
370 	p = curproc;
371 	if (p) {
372 		register struct pstats *pstats;
373 
374 		/*
375 		 * Run current process's virtual and profile time, as needed.
376 		 */
377 		pstats = p->p_stats;
378 		if (CLKF_USERMODE(frame) &&
379 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
380 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
381 			psignal(p, SIGVTALRM);
382 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
383 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
384 			psignal(p, SIGPROF);
385 	}
386 
387 	/*
388 	 * If no separate statistics clock is available, run it from here.
389 	 */
390 	if (stathz == 0)
391 		statclock(frame);
392 
393 	/*
394 	 * Increment the time-of-day.  The increment is normally just
395 	 * ``tick''.  If the machine is one which has a clock frequency
396 	 * such that ``hz'' would not divide the second evenly into
397 	 * milliseconds, a periodic adjustment must be applied.  Finally,
398 	 * if we are still adjusting the time (see adjtime()),
399 	 * ``tickdelta'' may also be added in.
400 	 */
401 	ticks++;
402 	delta = tick;
403 
404 #ifndef NTP
405 	if (tickfix) {
406 		tickfixcnt += tickfix;
407 		if (tickfixcnt >= tickfixinterval) {
408 			delta++;
409 			tickfixcnt -= tickfixinterval;
410 		}
411 	}
412 #else
413 	newtime = time;
414 #endif /* !NTP */
415 	/* Imprecise 4bsd adjtime() handling */
416 	if (timedelta != 0) {
417 		delta += tickdelta;
418 		timedelta -= tickdelta;
419 	}
420 
421 #ifdef notyet
422 	microset();
423 #endif
424 
425 #ifndef NTP
426 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
427 #endif
428 	BUMPTIME(&mono_time, delta);
429 
430 #ifdef NTP
431 	time_update = delta;
432 
433 	/*
434 	 * Compute the phase adjustment. If the low-order bits
435 	 * (time_phase) of the update overflow, bump the high-order bits
436 	 * (time_update).
437 	 */
438 	time_phase += time_adj;
439 	if (time_phase <= -FINEUSEC) {
440 		ltemp = -time_phase >> SHIFT_SCALE;
441 		time_phase += ltemp << SHIFT_SCALE;
442 		time_update -= ltemp;
443 	} else if (time_phase >= FINEUSEC) {
444 		ltemp = time_phase >> SHIFT_SCALE;
445 		time_phase -= ltemp << SHIFT_SCALE;
446 		time_update += ltemp;
447 	}
448 
449 #ifdef HIGHBALL
450 	/*
451 	 * If the HIGHBALL board is installed, we need to adjust the
452 	 * external clock offset in order to close the hardware feedback
453 	 * loop. This will adjust the external clock phase and frequency
454 	 * in small amounts. The additional phase noise and frequency
455 	 * wander this causes should be minimal. We also need to
456 	 * discipline the kernel time variable, since the PLL is used to
457 	 * discipline the external clock. If the Highball board is not
458 	 * present, we discipline kernel time with the PLL as usual. We
459 	 * assume that the external clock phase adjustment (time_update)
460 	 * and kernel phase adjustment (clock_cpu) are less than the
461 	 * value of tick.
462 	 */
463 	clock_offset.tv_usec += time_update;
464 	if (clock_offset.tv_usec >= 1000000) {
465 		clock_offset.tv_sec++;
466 		clock_offset.tv_usec -= 1000000;
467 	}
468 	if (clock_offset.tv_usec < 0) {
469 		clock_offset.tv_sec--;
470 		clock_offset.tv_usec += 1000000;
471 	}
472 	newtime.tv_usec += clock_cpu;
473 	clock_cpu = 0;
474 #else
475 	newtime.tv_usec += time_update;
476 #endif /* HIGHBALL */
477 
478 	/*
479 	 * On rollover of the second the phase adjustment to be used for
480 	 * the next second is calculated. Also, the maximum error is
481 	 * increased by the tolerance. If the PPS frequency discipline
482 	 * code is present, the phase is increased to compensate for the
483 	 * CPU clock oscillator frequency error.
484 	 *
485  	 * On a 32-bit machine and given parameters in the timex.h
486 	 * header file, the maximum phase adjustment is +-512 ms and
487 	 * maximum frequency offset is a tad less than) +-512 ppm. On a
488 	 * 64-bit machine, you shouldn't need to ask.
489 	 */
490 	if (newtime.tv_usec >= 1000000) {
491 		newtime.tv_usec -= 1000000;
492 		newtime.tv_sec++;
493 		time_maxerror += time_tolerance >> SHIFT_USEC;
494 
495 		/*
496 		 * Leap second processing. If in leap-insert state at
497 		 * the end of the day, the system clock is set back one
498 		 * second; if in leap-delete state, the system clock is
499 		 * set ahead one second. The microtime() routine or
500 		 * external clock driver will insure that reported time
501 		 * is always monotonic. The ugly divides should be
502 		 * replaced.
503 		 */
504 		switch (time_state) {
505 		case TIME_OK:
506 			if (time_status & STA_INS)
507 				time_state = TIME_INS;
508 			else if (time_status & STA_DEL)
509 				time_state = TIME_DEL;
510 			break;
511 
512 		case TIME_INS:
513 			if (newtime.tv_sec % 86400 == 0) {
514 				newtime.tv_sec--;
515 				time_state = TIME_OOP;
516 			}
517 			break;
518 
519 		case TIME_DEL:
520 			if ((newtime.tv_sec + 1) % 86400 == 0) {
521 				newtime.tv_sec++;
522 				time_state = TIME_WAIT;
523 			}
524 			break;
525 
526 		case TIME_OOP:
527 			time_state = TIME_WAIT;
528 			break;
529 
530 		case TIME_WAIT:
531 			if (!(time_status & (STA_INS | STA_DEL)))
532 				time_state = TIME_OK;
533 			break;
534 		}
535 
536 		/*
537 		 * Compute the phase adjustment for the next second. In
538 		 * PLL mode, the offset is reduced by a fixed factor
539 		 * times the time constant. In FLL mode the offset is
540 		 * used directly. In either mode, the maximum phase
541 		 * adjustment for each second is clamped so as to spread
542 		 * the adjustment over not more than the number of
543 		 * seconds between updates.
544 		 */
545 		if (time_offset < 0) {
546 			ltemp = -time_offset;
547 			if (!(time_status & STA_FLL))
548 				ltemp >>= SHIFT_KG + time_constant;
549 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
550 				ltemp = (MAXPHASE / MINSEC) <<
551 				    SHIFT_UPDATE;
552 			time_offset += ltemp;
553 			time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
554 		} else if (time_offset > 0) {
555 			ltemp = time_offset;
556 			if (!(time_status & STA_FLL))
557 				ltemp >>= SHIFT_KG + time_constant;
558 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
559 				ltemp = (MAXPHASE / MINSEC) <<
560 				    SHIFT_UPDATE;
561 			time_offset -= ltemp;
562 			time_adj = ltemp << (shifthz - SHIFT_UPDATE);
563 		} else
564 			time_adj = 0;
565 
566 		/*
567 		 * Compute the frequency estimate and additional phase
568 		 * adjustment due to frequency error for the next
569 		 * second. When the PPS signal is engaged, gnaw on the
570 		 * watchdog counter and update the frequency computed by
571 		 * the pll and the PPS signal.
572 		 */
573 #ifdef PPS_SYNC
574 		pps_valid++;
575 		if (pps_valid >= PPS_VALID) {
576 			pps_valid = PPS_VALID;	/* Avoid possible overflow */
577 			pps_jitter = MAXTIME;
578 			pps_stabil = MAXFREQ;
579 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
580 			    STA_PPSWANDER | STA_PPSERROR);
581 		}
582 		ltemp = time_freq + pps_freq;
583 #else
584 		ltemp = time_freq;
585 #endif /* PPS_SYNC */
586 
587 		if (ltemp < 0)
588 			time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
589 		else
590 			time_adj += ltemp >> (SHIFT_USEC - shifthz);
591 		time_adj += (long)fixtick << shifthz;
592 
593 		/*
594 		 * When the CPU clock oscillator frequency is not a
595 		 * power of 2 in Hz, shifthz is only an approximate
596 		 * scale factor.
597 		 */
598 		switch (hz) {
599 		case 96:
600 		case 100:
601 			/*
602 			 * In the following code the overall gain is increased
603 			 * by a factor of 1.25, which results in a residual
604 			 * error less than 3 percent.
605 			 */
606 			if (time_adj < 0)
607 				time_adj -= -time_adj >> 2;
608 			else
609 				time_adj += time_adj >> 2;
610 			break;
611 		case 60:
612 			/*
613 			 * 60 Hz m68k and vaxes have a PLL gain factor of of
614 			 * 60/64 (15/16) of what it should be.  In the following code
615 			 * the overall gain is increased by a factor of 1.0625,
616 			 * (17/16) which results in a residual error of just less
617 			 * than 0.4 percent.
618 			 */
619 			if (time_adj < 0)
620 				time_adj -= -time_adj >> 4;
621 			else
622 				time_adj += time_adj >> 4;
623 			break;
624 		}
625 
626 #ifdef EXT_CLOCK
627 		/*
628 		 * If an external clock is present, it is necessary to
629 		 * discipline the kernel time variable anyway, since not
630 		 * all system components use the microtime() interface.
631 		 * Here, the time offset between the external clock and
632 		 * kernel time variable is computed every so often.
633 		 */
634 		clock_count++;
635 		if (clock_count > CLOCK_INTERVAL) {
636 			clock_count = 0;
637 			microtime(&clock_ext);
638 			delta.tv_sec = clock_ext.tv_sec - newtime.tv_sec;
639 			delta.tv_usec = clock_ext.tv_usec - newtime.tv_usec;
640 			if (delta.tv_usec < 0)
641 				delta.tv_sec--;
642 			if (delta.tv_usec >= 500000) {
643 				delta.tv_usec -= 1000000;
644 				delta.tv_sec++;
645 			}
646 			if (delta.tv_usec < -500000) {
647 				delta.tv_usec += 1000000;
648 				delta.tv_sec--;
649 			}
650 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
651 			    delta.tv_usec > MAXPHASE) ||
652 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
653 			    delta.tv_usec < -MAXPHASE)) {
654 				newtime = clock_ext;
655 				delta.tv_sec = 0;
656 				delta.tv_usec = 0;
657 			}
658 #ifdef HIGHBALL
659 			clock_cpu = delta.tv_usec;
660 #else /* HIGHBALL */
661 			hardupdate(delta.tv_usec);
662 #endif /* HIGHBALL */
663 		}
664 #endif /* EXT_CLOCK */
665 	}
666 
667 #ifdef CPU_CLOCKUPDATE
668 	CPU_CLOCKUPDATE(&time, &newtime);
669 #else
670 	time = newtime;
671 #endif
672 
673 #endif /* NTP */
674 
675 	/*
676 	 * Process callouts at a very low cpu priority, so we don't keep the
677 	 * relatively high clock interrupt priority any longer than necessary.
678 	 */
679 	if (needsoft) {
680 		if (CLKF_BASEPRI(frame)) {
681 			/*
682 			 * Save the overhead of a software interrupt;
683 			 * it will happen as soon as we return, so do it now.
684 			 */
685 			(void)spllowersoftclock();
686 			softclock();
687 		} else
688 			setsoftclock();
689 	}
690 }
691 
692 /*
693  * Compute number of hz until specified time.  Used to
694  * compute the second argument to timeout_add() from an absolute time.
695  */
696 int
697 hzto(tv)
698 	struct timeval *tv;
699 {
700 	register unsigned long ticks;
701 	register long sec, usec;
702 	int s;
703 
704 	/*
705 	 * If the number of usecs in the whole seconds part of the time
706 	 * difference fits in a long, then the total number of usecs will
707 	 * fit in an unsigned long.  Compute the total and convert it to
708 	 * ticks, rounding up and adding 1 to allow for the current tick
709 	 * to expire.  Rounding also depends on unsigned long arithmetic
710 	 * to avoid overflow.
711 	 *
712 	 * Otherwise, if the number of ticks in the whole seconds part of
713 	 * the time difference fits in a long, then convert the parts to
714 	 * ticks separately and add, using similar rounding methods and
715 	 * overflow avoidance.  This method would work in the previous
716 	 * case but it is slightly slower and assumes that hz is integral.
717 	 *
718 	 * Otherwise, round the time difference down to the maximum
719 	 * representable value.
720 	 *
721 	 * If ints have 32 bits, then the maximum value for any timeout in
722 	 * 10ms ticks is 248 days.
723 	 */
724 	s = splhigh();
725 	sec = tv->tv_sec - time.tv_sec;
726 	usec = tv->tv_usec - time.tv_usec;
727 	splx(s);
728 	if (usec < 0) {
729 		sec--;
730 		usec += 1000000;
731 	}
732 	if (sec < 0) {
733 		ticks = 1;
734 	} else if (sec <= LONG_MAX / 1000000)
735 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
736 		    / tick + 1;
737 	else if (sec <= LONG_MAX / hz)
738 		ticks = sec * hz
739 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
740 	else
741 		ticks = LONG_MAX;
742 	if (ticks > INT_MAX)
743 		ticks = INT_MAX;
744 	return ((int)ticks);
745 }
746 
747 /*
748  * Start profiling on a process.
749  *
750  * Kernel profiling passes proc0 which never exits and hence
751  * keeps the profile clock running constantly.
752  */
753 void
754 startprofclock(p)
755 	register struct proc *p;
756 {
757 	int s;
758 
759 	if ((p->p_flag & P_PROFIL) == 0) {
760 		p->p_flag |= P_PROFIL;
761 		if (++profprocs == 1 && stathz != 0) {
762 			s = splstatclock();
763 			psdiv = pscnt = psratio;
764 			setstatclockrate(profhz);
765 			splx(s);
766 		}
767 	}
768 }
769 
770 /*
771  * Stop profiling on a process.
772  */
773 void
774 stopprofclock(p)
775 	register struct proc *p;
776 {
777 	int s;
778 
779 	if (p->p_flag & P_PROFIL) {
780 		p->p_flag &= ~P_PROFIL;
781 		if (--profprocs == 0 && stathz != 0) {
782 			s = splstatclock();
783 			psdiv = pscnt = 1;
784 			setstatclockrate(stathz);
785 			splx(s);
786 		}
787 	}
788 }
789 
790 /*
791  * Statistics clock.  Grab profile sample, and if divider reaches 0,
792  * do process and kernel statistics.
793  */
794 void
795 statclock(frame)
796 	register struct clockframe *frame;
797 {
798 #ifdef GPROF
799 	register struct gmonparam *g;
800 	register int i;
801 #endif
802 	static int schedclk;
803 	register struct proc *p;
804 
805 	if (CLKF_USERMODE(frame)) {
806 		p = curproc;
807 		if (p->p_flag & P_PROFIL)
808 			addupc_intr(p, CLKF_PC(frame), 1);
809 		if (--pscnt > 0)
810 			return;
811 		/*
812 		 * Came from user mode; CPU was in user state.
813 		 * If this process is being profiled record the tick.
814 		 */
815 		p->p_uticks++;
816 		if (p->p_nice > NZERO)
817 			cp_time[CP_NICE]++;
818 		else
819 			cp_time[CP_USER]++;
820 	} else {
821 #ifdef GPROF
822 		/*
823 		 * Kernel statistics are just like addupc_intr, only easier.
824 		 */
825 		g = &_gmonparam;
826 		if (g->state == GMON_PROF_ON) {
827 			i = CLKF_PC(frame) - g->lowpc;
828 			if (i < g->textsize) {
829 				i /= HISTFRACTION * sizeof(*g->kcount);
830 				g->kcount[i]++;
831 			}
832 		}
833 #endif
834 		if (--pscnt > 0)
835 			return;
836 		/*
837 		 * Came from kernel mode, so we were:
838 		 * - handling an interrupt,
839 		 * - doing syscall or trap work on behalf of the current
840 		 *   user process, or
841 		 * - spinning in the idle loop.
842 		 * Whichever it is, charge the time as appropriate.
843 		 * Note that we charge interrupts to the current process,
844 		 * regardless of whether they are ``for'' that process,
845 		 * so that we know how much of its real time was spent
846 		 * in ``non-process'' (i.e., interrupt) work.
847 		 */
848 		p = curproc;
849 		if (CLKF_INTR(frame)) {
850 			if (p != NULL)
851 				p->p_iticks++;
852 			cp_time[CP_INTR]++;
853 		} else if (p != NULL) {
854 			p->p_sticks++;
855 			cp_time[CP_SYS]++;
856 		} else
857 			cp_time[CP_IDLE]++;
858 	}
859 	pscnt = psdiv;
860 
861 	if (p != NULL) {
862 		p->p_cpticks++;
863 		/*
864 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
865 		 * ~~16 Hz is best
866 		 */
867 		if (schedhz == 0)
868 			if ((++schedclk & 3) == 0)
869 				schedclock(p);
870 	}
871 }
872 
873 
874 #ifdef NTP	/* NTP phase-locked loop in kernel */
875 
876 /*
877  * hardupdate() - local clock update
878  *
879  * This routine is called by ntp_adjtime() to update the local clock
880  * phase and frequency. The implementation is of an adaptive-parameter,
881  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
882  * time and frequency offset estimates for each call. If the kernel PPS
883  * discipline code is configured (PPS_SYNC), the PPS signal itself
884  * determines the new time offset, instead of the calling argument.
885  * Presumably, calls to ntp_adjtime() occur only when the caller
886  * believes the local clock is valid within some bound (+-128 ms with
887  * NTP). If the caller's time is far different than the PPS time, an
888  * argument will ensue, and it's not clear who will lose.
889  *
890  * For uncompensated quartz crystal oscillatores and nominal update
891  * intervals less than 1024 s, operation should be in phase-lock mode
892  * (STA_FLL = 0), where the loop is disciplined to phase. For update
893  * intervals greater than thiss, operation should be in frequency-lock
894  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
895  *
896  * Note: splclock() is in effect.
897  */
898 void
899 hardupdate(offset)
900 	long offset;
901 {
902 	long ltemp, mtemp;
903 
904 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
905 		return;
906 	ltemp = offset;
907 #ifdef PPS_SYNC
908 	if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
909 		ltemp = pps_offset;
910 #endif /* PPS_SYNC */
911 
912 	/*
913 	 * Scale the phase adjustment and clamp to the operating range.
914 	 */
915 	if (ltemp > MAXPHASE)
916 		time_offset = MAXPHASE << SHIFT_UPDATE;
917 	else if (ltemp < -MAXPHASE)
918 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
919 	else
920 		time_offset = ltemp << SHIFT_UPDATE;
921 
922 	/*
923 	 * Select whether the frequency is to be controlled and in which
924 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
925 	 * multiply/divide should be replaced someday.
926 	 */
927 	if (time_status & STA_FREQHOLD || time_reftime == 0)
928 		time_reftime = time.tv_sec;
929 	mtemp = time.tv_sec - time_reftime;
930 	time_reftime = time.tv_sec;
931 	if (time_status & STA_FLL) {
932 		if (mtemp >= MINSEC) {
933 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
934 			    SHIFT_UPDATE));
935 			if (ltemp < 0)
936 				time_freq -= -ltemp >> SHIFT_KH;
937 			else
938 				time_freq += ltemp >> SHIFT_KH;
939 		}
940 	} else {
941 		if (mtemp < MAXSEC) {
942 			ltemp *= mtemp;
943 			if (ltemp < 0)
944 				time_freq -= -ltemp >> (time_constant +
945 				    time_constant + SHIFT_KF -
946 				    SHIFT_USEC);
947 			else
948 				time_freq += ltemp >> (time_constant +
949 				    time_constant + SHIFT_KF -
950 				    SHIFT_USEC);
951 		}
952 	}
953 	if (time_freq > time_tolerance)
954 		time_freq = time_tolerance;
955 	else if (time_freq < -time_tolerance)
956 		time_freq = -time_tolerance;
957 }
958 
959 #ifdef PPS_SYNC
960 /*
961  * hardpps() - discipline CPU clock oscillator to external PPS signal
962  *
963  * This routine is called at each PPS interrupt in order to discipline
964  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
965  * and leaves it in a handy spot for the hardclock() routine. It
966  * integrates successive PPS phase differences and calculates the
967  * frequency offset. This is used in hardclock() to discipline the CPU
968  * clock oscillator so that intrinsic frequency error is cancelled out.
969  * The code requires the caller to capture the time and hardware counter
970  * value at the on-time PPS signal transition.
971  *
972  * Note that, on some Unix systems, this routine runs at an interrupt
973  * priority level higher than the timer interrupt routine hardclock().
974  * Therefore, the variables used are distinct from the hardclock()
975  * variables, except for certain exceptions: The PPS frequency pps_freq
976  * and phase pps_offset variables are determined by this routine and
977  * updated atomically. The time_tolerance variable can be considered a
978  * constant, since it is infrequently changed, and then only when the
979  * PPS signal is disabled. The watchdog counter pps_valid is updated
980  * once per second by hardclock() and is atomically cleared in this
981  * routine.
982  */
983 void
984 hardpps(tvp, usec)
985 	struct timeval *tvp;		/* time at PPS */
986 	long usec;			/* hardware counter at PPS */
987 {
988 	long u_usec, v_usec, bigtick;
989 	long cal_sec, cal_usec;
990 
991 	/*
992 	 * An occasional glitch can be produced when the PPS interrupt
993 	 * occurs in the hardclock() routine before the time variable is
994 	 * updated. Here the offset is discarded when the difference
995 	 * between it and the last one is greater than tick/2, but not
996 	 * if the interval since the first discard exceeds 30 s.
997 	 */
998 	time_status |= STA_PPSSIGNAL;
999 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1000 	pps_valid = 0;
1001 	u_usec = -tvp->tv_usec;
1002 	if (u_usec < -500000)
1003 		u_usec += 1000000;
1004 	v_usec = pps_offset - u_usec;
1005 	if (v_usec < 0)
1006 		v_usec = -v_usec;
1007 	if (v_usec > (tick >> 1)) {
1008 		if (pps_glitch > MAXGLITCH) {
1009 			pps_glitch = 0;
1010 			pps_tf[2] = u_usec;
1011 			pps_tf[1] = u_usec;
1012 		} else {
1013 			pps_glitch++;
1014 			u_usec = pps_offset;
1015 		}
1016 	} else
1017 		pps_glitch = 0;
1018 
1019 	/*
1020 	 * A three-stage median filter is used to help deglitch the pps
1021 	 * time. The median sample becomes the time offset estimate; the
1022 	 * difference between the other two samples becomes the time
1023 	 * dispersion (jitter) estimate.
1024 	 */
1025 	pps_tf[2] = pps_tf[1];
1026 	pps_tf[1] = pps_tf[0];
1027 	pps_tf[0] = u_usec;
1028 	if (pps_tf[0] > pps_tf[1]) {
1029 		if (pps_tf[1] > pps_tf[2]) {
1030 			pps_offset = pps_tf[1];		/* 0 1 2 */
1031 			v_usec = pps_tf[0] - pps_tf[2];
1032 		} else if (pps_tf[2] > pps_tf[0]) {
1033 			pps_offset = pps_tf[0];		/* 2 0 1 */
1034 			v_usec = pps_tf[2] - pps_tf[1];
1035 		} else {
1036 			pps_offset = pps_tf[2];		/* 0 2 1 */
1037 			v_usec = pps_tf[0] - pps_tf[1];
1038 		}
1039 	} else {
1040 		if (pps_tf[1] < pps_tf[2]) {
1041 			pps_offset = pps_tf[1];		/* 2 1 0 */
1042 			v_usec = pps_tf[2] - pps_tf[0];
1043 		} else  if (pps_tf[2] < pps_tf[0]) {
1044 			pps_offset = pps_tf[0];		/* 1 0 2 */
1045 			v_usec = pps_tf[1] - pps_tf[2];
1046 		} else {
1047 			pps_offset = pps_tf[2];		/* 1 2 0 */
1048 			v_usec = pps_tf[1] - pps_tf[0];
1049 		}
1050 	}
1051 	if (v_usec > MAXTIME)
1052 		pps_jitcnt++;
1053 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1054 	if (v_usec < 0)
1055 		pps_jitter -= -v_usec >> PPS_AVG;
1056 	else
1057 		pps_jitter += v_usec >> PPS_AVG;
1058 	if (pps_jitter > (MAXTIME >> 1))
1059 		time_status |= STA_PPSJITTER;
1060 
1061 	/*
1062 	 * During the calibration interval adjust the starting time when
1063 	 * the tick overflows. At the end of the interval compute the
1064 	 * duration of the interval and the difference of the hardware
1065 	 * counters at the beginning and end of the interval. This code
1066 	 * is deliciously complicated by the fact valid differences may
1067 	 * exceed the value of tick when using long calibration
1068 	 * intervals and small ticks. Note that the counter can be
1069 	 * greater than tick if caught at just the wrong instant, but
1070 	 * the values returned and used here are correct.
1071 	 */
1072 	bigtick = (long)tick << SHIFT_USEC;
1073 	pps_usec -= pps_freq;
1074 	if (pps_usec >= bigtick)
1075 		pps_usec -= bigtick;
1076 	if (pps_usec < 0)
1077 		pps_usec += bigtick;
1078 	pps_time.tv_sec++;
1079 	pps_count++;
1080 	if (pps_count < (1 << pps_shift))
1081 		return;
1082 	pps_count = 0;
1083 	pps_calcnt++;
1084 	u_usec = usec << SHIFT_USEC;
1085 	v_usec = pps_usec - u_usec;
1086 	if (v_usec >= bigtick >> 1)
1087 		v_usec -= bigtick;
1088 	if (v_usec < -(bigtick >> 1))
1089 		v_usec += bigtick;
1090 	if (v_usec < 0)
1091 		v_usec = -(-v_usec >> pps_shift);
1092 	else
1093 		v_usec = v_usec >> pps_shift;
1094 	pps_usec = u_usec;
1095 	cal_sec = tvp->tv_sec;
1096 	cal_usec = tvp->tv_usec;
1097 	cal_sec -= pps_time.tv_sec;
1098 	cal_usec -= pps_time.tv_usec;
1099 	if (cal_usec < 0) {
1100 		cal_usec += 1000000;
1101 		cal_sec--;
1102 	}
1103 	pps_time = *tvp;
1104 
1105 	/*
1106 	 * Check for lost interrupts, noise, excessive jitter and
1107 	 * excessive frequency error. The number of timer ticks during
1108 	 * the interval may vary +-1 tick. Add to this a margin of one
1109 	 * tick for the PPS signal jitter and maximum frequency
1110 	 * deviation. If the limits are exceeded, the calibration
1111 	 * interval is reset to the minimum and we start over.
1112 	 */
1113 	u_usec = (long)tick << 1;
1114 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1115 	    || (cal_sec == 0 && cal_usec < u_usec))
1116 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1117 		pps_errcnt++;
1118 		pps_shift = PPS_SHIFT;
1119 		pps_intcnt = 0;
1120 		time_status |= STA_PPSERROR;
1121 		return;
1122 	}
1123 
1124 	/*
1125 	 * A three-stage median filter is used to help deglitch the pps
1126 	 * frequency. The median sample becomes the frequency offset
1127 	 * estimate; the difference between the other two samples
1128 	 * becomes the frequency dispersion (stability) estimate.
1129 	 */
1130 	pps_ff[2] = pps_ff[1];
1131 	pps_ff[1] = pps_ff[0];
1132 	pps_ff[0] = v_usec;
1133 	if (pps_ff[0] > pps_ff[1]) {
1134 		if (pps_ff[1] > pps_ff[2]) {
1135 			u_usec = pps_ff[1];		/* 0 1 2 */
1136 			v_usec = pps_ff[0] - pps_ff[2];
1137 		} else if (pps_ff[2] > pps_ff[0]) {
1138 			u_usec = pps_ff[0];		/* 2 0 1 */
1139 			v_usec = pps_ff[2] - pps_ff[1];
1140 		} else {
1141 			u_usec = pps_ff[2];		/* 0 2 1 */
1142 			v_usec = pps_ff[0] - pps_ff[1];
1143 		}
1144 	} else {
1145 		if (pps_ff[1] < pps_ff[2]) {
1146 			u_usec = pps_ff[1];		/* 2 1 0 */
1147 			v_usec = pps_ff[2] - pps_ff[0];
1148 		} else  if (pps_ff[2] < pps_ff[0]) {
1149 			u_usec = pps_ff[0];		/* 1 0 2 */
1150 			v_usec = pps_ff[1] - pps_ff[2];
1151 		} else {
1152 			u_usec = pps_ff[2];		/* 1 2 0 */
1153 			v_usec = pps_ff[1] - pps_ff[0];
1154 		}
1155 	}
1156 
1157 	/*
1158 	 * Here the frequency dispersion (stability) is updated. If it
1159 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1160 	 * offset is updated as well, but clamped to the tolerance. It
1161 	 * will be processed later by the hardclock() routine.
1162 	 */
1163 	v_usec = (v_usec >> 1) - pps_stabil;
1164 	if (v_usec < 0)
1165 		pps_stabil -= -v_usec >> PPS_AVG;
1166 	else
1167 		pps_stabil += v_usec >> PPS_AVG;
1168 	if (pps_stabil > MAXFREQ >> 2) {
1169 		pps_stbcnt++;
1170 		time_status |= STA_PPSWANDER;
1171 		return;
1172 	}
1173 	if (time_status & STA_PPSFREQ) {
1174 		if (u_usec < 0) {
1175 			pps_freq -= -u_usec >> PPS_AVG;
1176 			if (pps_freq < -time_tolerance)
1177 				pps_freq = -time_tolerance;
1178 			u_usec = -u_usec;
1179 		} else {
1180 			pps_freq += u_usec >> PPS_AVG;
1181 			if (pps_freq > time_tolerance)
1182 				pps_freq = time_tolerance;
1183 		}
1184 	}
1185 
1186 	/*
1187 	 * Here the calibration interval is adjusted. If the maximum
1188 	 * time difference is greater than tick / 4, reduce the interval
1189 	 * by half. If this is not the case for four consecutive
1190 	 * intervals, double the interval.
1191 	 */
1192 	if (u_usec << pps_shift > bigtick >> 2) {
1193 		pps_intcnt = 0;
1194 		if (pps_shift > PPS_SHIFT)
1195 			pps_shift--;
1196 	} else if (pps_intcnt >= 4) {
1197 		pps_intcnt = 0;
1198 		if (pps_shift < PPS_SHIFTMAX)
1199 			pps_shift++;
1200 	} else
1201 		pps_intcnt++;
1202 }
1203 #endif /* PPS_SYNC */
1204 #endif /* NTP  */
1205 
1206 
1207 /*
1208  * Return information about system clocks.
1209  */
1210 int
1211 sysctl_clockrate(where, sizep)
1212 	register char *where;
1213 	size_t *sizep;
1214 {
1215 	struct clockinfo clkinfo;
1216 
1217 	/*
1218 	 * Construct clockinfo structure.
1219 	 */
1220 	clkinfo.tick = tick;
1221 	clkinfo.tickadj = tickadj;
1222 	clkinfo.hz = hz;
1223 	clkinfo.profhz = profhz;
1224 	clkinfo.stathz = stathz ? stathz : hz;
1225 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1226 }
1227