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