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