xref: /netbsd/sys/kern/kern_clock.c (revision bf9ec67e)
1 /*	$NetBSD: kern_clock.c,v 1.79 2002/03/17 11:10:43 simonb Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the NetBSD
22  *	Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*-
41  * Copyright (c) 1982, 1986, 1991, 1993
42  *	The Regents of the University of California.  All rights reserved.
43  * (c) UNIX System Laboratories, Inc.
44  * All or some portions of this file are derived from material licensed
45  * to the University of California by American Telephone and Telegraph
46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47  * the permission of UNIX System Laboratories, Inc.
48  *
49  * Redistribution and use in source and binary forms, with or without
50  * modification, are permitted provided that the following conditions
51  * are met:
52  * 1. Redistributions of source code must retain the above copyright
53  *    notice, this list of conditions and the following disclaimer.
54  * 2. Redistributions in binary form must reproduce the above copyright
55  *    notice, this list of conditions and the following disclaimer in the
56  *    documentation and/or other materials provided with the distribution.
57  * 3. All advertising materials mentioning features or use of this software
58  *    must display the following acknowledgement:
59  *	This product includes software developed by the University of
60  *	California, Berkeley and its contributors.
61  * 4. Neither the name of the University nor the names of its contributors
62  *    may be used to endorse or promote products derived from this software
63  *    without specific prior written permission.
64  *
65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75  * SUCH DAMAGE.
76  *
77  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
78  */
79 
80 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.79 2002/03/17 11:10:43 simonb Exp $");
82 
83 #include "opt_callout.h"
84 #include "opt_ntp.h"
85 
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/dkstat.h>
89 #include <sys/callout.h>
90 #include <sys/kernel.h>
91 #include <sys/proc.h>
92 #include <sys/resourcevar.h>
93 #include <sys/signalvar.h>
94 #include <sys/sysctl.h>
95 #include <sys/timex.h>
96 #include <sys/sched.h>
97 #ifdef CALLWHEEL_STATS
98 #include <sys/device.h>
99 #endif
100 
101 #include <machine/cpu.h>
102 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
103 #include <machine/intr.h>
104 #endif
105 
106 #ifdef GPROF
107 #include <sys/gmon.h>
108 #endif
109 
110 /*
111  * Clock handling routines.
112  *
113  * This code is written to operate with two timers that run independently of
114  * each other.  The main clock, running hz times per second, is used to keep
115  * track of real time.  The second timer handles kernel and user profiling,
116  * and does resource use estimation.  If the second timer is programmable,
117  * it is randomized to avoid aliasing between the two clocks.  For example,
118  * the randomization prevents an adversary from always giving up the cpu
119  * just before its quantum expires.  Otherwise, it would never accumulate
120  * cpu ticks.  The mean frequency of the second timer is stathz.
121  *
122  * If no second timer exists, stathz will be zero; in this case we drive
123  * profiling and statistics off the main clock.  This WILL NOT be accurate;
124  * do not do it unless absolutely necessary.
125  *
126  * The statistics clock may (or may not) be run at a higher rate while
127  * profiling.  This profile clock runs at profhz.  We require that profhz
128  * be an integral multiple of stathz.
129  *
130  * If the statistics clock is running fast, it must be divided by the ratio
131  * profhz/stathz for statistics.  (For profiling, every tick counts.)
132  */
133 
134 #ifdef NTP	/* NTP phase-locked loop in kernel */
135 /*
136  * Phase/frequency-lock loop (PLL/FLL) definitions
137  *
138  * The following variables are read and set by the ntp_adjtime() system
139  * call.
140  *
141  * time_state shows the state of the system clock, with values defined
142  * in the timex.h header file.
143  *
144  * time_status shows the status of the system clock, with bits defined
145  * in the timex.h header file.
146  *
147  * time_offset is used by the PLL/FLL to adjust the system time in small
148  * increments.
149  *
150  * time_constant determines the bandwidth or "stiffness" of the PLL.
151  *
152  * time_tolerance determines maximum frequency error or tolerance of the
153  * CPU clock oscillator and is a property of the architecture; however,
154  * in principle it could change as result of the presence of external
155  * discipline signals, for instance.
156  *
157  * time_precision is usually equal to the kernel tick variable; however,
158  * in cases where a precision clock counter or external clock is
159  * available, the resolution can be much less than this and depend on
160  * whether the external clock is working or not.
161  *
162  * time_maxerror is initialized by a ntp_adjtime() call and increased by
163  * the kernel once each second to reflect the maximum error bound
164  * growth.
165  *
166  * time_esterror is set and read by the ntp_adjtime() call, but
167  * otherwise not used by the kernel.
168  */
169 int time_state = TIME_OK;	/* clock state */
170 int time_status = STA_UNSYNC;	/* clock status bits */
171 long time_offset = 0;		/* time offset (us) */
172 long time_constant = 0;		/* pll time constant */
173 long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
174 long time_precision = 1;	/* clock precision (us) */
175 long time_maxerror = MAXPHASE;	/* maximum error (us) */
176 long time_esterror = MAXPHASE;	/* estimated error (us) */
177 
178 /*
179  * The following variables establish the state of the PLL/FLL and the
180  * residual time and frequency offset of the local clock. The scale
181  * factors are defined in the timex.h header file.
182  *
183  * time_phase and time_freq are the phase increment and the frequency
184  * increment, respectively, of the kernel time variable.
185  *
186  * time_freq is set via ntp_adjtime() from a value stored in a file when
187  * the synchronization daemon is first started. Its value is retrieved
188  * via ntp_adjtime() and written to the file about once per hour by the
189  * daemon.
190  *
191  * time_adj is the adjustment added to the value of tick at each timer
192  * interrupt and is recomputed from time_phase and time_freq at each
193  * seconds rollover.
194  *
195  * time_reftime is the second's portion of the system time at the last
196  * call to ntp_adjtime(). It is used to adjust the time_freq variable
197  * and to increase the time_maxerror as the time since last update
198  * increases.
199  */
200 long time_phase = 0;		/* phase offset (scaled us) */
201 long time_freq = 0;		/* frequency offset (scaled ppm) */
202 long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
203 long time_reftime = 0;		/* time at last adjustment (s) */
204 
205 #ifdef PPS_SYNC
206 /*
207  * The following variables are used only if the kernel PPS discipline
208  * code is configured (PPS_SYNC). The scale factors are defined in the
209  * timex.h header file.
210  *
211  * pps_time contains the time at each calibration interval, as read by
212  * microtime(). pps_count counts the seconds of the calibration
213  * interval, the duration of which is nominally pps_shift in powers of
214  * two.
215  *
216  * pps_offset is the time offset produced by the time median filter
217  * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
218  * this filter.
219  *
220  * pps_freq is the frequency offset produced by the frequency median
221  * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
222  * by this filter.
223  *
224  * pps_usec is latched from a high resolution counter or external clock
225  * at pps_time. Here we want the hardware counter contents only, not the
226  * contents plus the time_tv.usec as usual.
227  *
228  * pps_valid counts the number of seconds since the last PPS update. It
229  * is used as a watchdog timer to disable the PPS discipline should the
230  * PPS signal be lost.
231  *
232  * pps_glitch counts the number of seconds since the beginning of an
233  * offset burst more than tick/2 from current nominal offset. It is used
234  * mainly to suppress error bursts due to priority conflicts between the
235  * PPS interrupt and timer interrupt.
236  *
237  * pps_intcnt counts the calibration intervals for use in the interval-
238  * adaptation algorithm. It's just too complicated for words.
239  */
240 struct timeval pps_time;	/* kernel time at last interval */
241 long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
242 long pps_offset = 0;		/* pps time offset (us) */
243 long pps_jitter = MAXTIME;	/* time dispersion (jitter) (us) */
244 long pps_ff[] = {0, 0, 0};	/* pps frequency offset median filter */
245 long pps_freq = 0;		/* frequency offset (scaled ppm) */
246 long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
247 long pps_usec = 0;		/* microsec counter at last interval */
248 long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
249 int pps_glitch = 0;		/* pps signal glitch counter */
250 int pps_count = 0;		/* calibration interval counter (s) */
251 int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
252 int pps_intcnt = 0;		/* intervals at current duration */
253 
254 /*
255  * PPS signal quality monitors
256  *
257  * pps_jitcnt counts the seconds that have been discarded because the
258  * jitter measured by the time median filter exceeds the limit MAXTIME
259  * (100 us).
260  *
261  * pps_calcnt counts the frequency calibration intervals, which are
262  * variable from 4 s to 256 s.
263  *
264  * pps_errcnt counts the calibration intervals which have been discarded
265  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
266  * calibration interval jitter exceeds two ticks.
267  *
268  * pps_stbcnt counts the calibration intervals that have been discarded
269  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
270  */
271 long pps_jitcnt = 0;		/* jitter limit exceeded */
272 long pps_calcnt = 0;		/* calibration intervals */
273 long pps_errcnt = 0;		/* calibration errors */
274 long pps_stbcnt = 0;		/* stability limit exceeded */
275 #endif /* PPS_SYNC */
276 
277 #ifdef EXT_CLOCK
278 /*
279  * External clock definitions
280  *
281  * The following definitions and declarations are used only if an
282  * external clock is configured on the system.
283  */
284 #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
285 
286 /*
287  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
288  * interrupt and decremented once each second.
289  */
290 int clock_count = 0;		/* CPU clock counter */
291 
292 #ifdef HIGHBALL
293 /*
294  * The clock_offset and clock_cpu variables are used by the HIGHBALL
295  * interface. The clock_offset variable defines the offset between
296  * system time and the HIGBALL counters. The clock_cpu variable contains
297  * the offset between the system clock and the HIGHBALL clock for use in
298  * disciplining the kernel time variable.
299  */
300 extern struct timeval clock_offset; /* Highball clock offset */
301 long clock_cpu = 0;		/* CPU clock adjust */
302 #endif /* HIGHBALL */
303 #endif /* EXT_CLOCK */
304 #endif /* NTP */
305 
306 
307 /*
308  * Bump a timeval by a small number of usec's.
309  */
310 #define BUMPTIME(t, usec) { \
311 	volatile struct timeval *tp = (t); \
312 	long us; \
313  \
314 	tp->tv_usec = us = tp->tv_usec + (usec); \
315 	if (us >= 1000000) { \
316 		tp->tv_usec = us - 1000000; \
317 		tp->tv_sec++; \
318 	} \
319 }
320 
321 int	stathz;
322 int	profhz;
323 int	schedhz;
324 int	profprocs;
325 int	softclock_running;		/* 1 => softclock() is running */
326 static int psdiv;			/* prof => stat divider */
327 int	psratio;			/* ratio: prof / stat */
328 int	tickfix, tickfixinterval;	/* used if tick not really integral */
329 #ifndef NTP
330 static int tickfixcnt;			/* accumulated fractional error */
331 #else
332 int	fixtick;			/* used by NTP for same */
333 int	shifthz;
334 #endif
335 
336 /*
337  * We might want ldd to load the both words from time at once.
338  * To succeed we need to be quadword aligned.
339  * The sparc already does that, and that it has worked so far is a fluke.
340  */
341 volatile struct	timeval time  __attribute__((__aligned__(__alignof__(quad_t))));
342 volatile struct	timeval mono_time;
343 
344 /*
345  * The callout mechanism is based on the work of Adam M. Costello and
346  * George Varghese, published in a technical report entitled "Redesigning
347  * the BSD Callout and Timer Facilities", and Justin Gibbs's subsequent
348  * integration into FreeBSD, modified for NetBSD by Jason R. Thorpe.
349  *
350  * The original work on the data structures used in this implementation
351  * was published by G. Varghese and A. Lauck in the paper "Hashed and
352  * Hierarchical Timing Wheels: Data Structures for the Efficient
353  * Implementation of a Timer Facility" in the Proceedings of the 11th
354  * ACM Annual Symposium on Operating System Principles, Austin, Texas,
355  * November 1987.
356  */
357 struct callout_queue *callwheel;
358 int	callwheelsize, callwheelbits, callwheelmask;
359 
360 static struct callout *nextsoftcheck;	/* next callout to be checked */
361 
362 #ifdef CALLWHEEL_STATS
363 int	     *callwheel_sizes;		/* per-bucket length count */
364 struct evcnt callwheel_collisions;	/* number of hash collisions */
365 struct evcnt callwheel_maxlength;	/* length of the longest hash chain */
366 struct evcnt callwheel_count;		/* # callouts currently */
367 struct evcnt callwheel_established;	/* # callouts established */
368 struct evcnt callwheel_fired;		/* # callouts that fired */
369 struct evcnt callwheel_disestablished;	/* # callouts disestablished */
370 struct evcnt callwheel_changed;		/* # callouts changed */
371 struct evcnt callwheel_softclocks;	/* # times softclock() called */
372 struct evcnt callwheel_softchecks;	/* # checks per softclock() */
373 struct evcnt callwheel_softempty;	/* # empty buckets seen */
374 struct evcnt callwheel_hintworked;	/* # times hint saved scan */
375 #endif /* CALLWHEEL_STATS */
376 
377 /*
378  * This value indicates the number of consecutive callouts that
379  * will be checked before we allow interrupts to have a chance
380  * again.
381  */
382 #ifndef MAX_SOFTCLOCK_STEPS
383 #define	MAX_SOFTCLOCK_STEPS	100
384 #endif
385 
386 struct simplelock callwheel_slock;
387 
388 #define	CALLWHEEL_LOCK(s)						\
389 do {									\
390 	s = splclock();							\
391 	simple_lock(&callwheel_slock);					\
392 } while (0)
393 
394 #define	CALLWHEEL_UNLOCK(s)						\
395 do {									\
396 	simple_unlock(&callwheel_slock);				\
397 	splx(s);							\
398 } while (0)
399 
400 static void callout_stop_locked(struct callout *);
401 
402 /*
403  * These are both protected by callwheel_lock.
404  * XXX SHOULD BE STATIC!!
405  */
406 u_int64_t hardclock_ticks, softclock_ticks;
407 
408 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
409 void	softclock(void *);
410 void	*softclock_si;
411 #endif
412 
413 /*
414  * Initialize clock frequencies and start both clocks running.
415  */
416 void
417 initclocks(void)
418 {
419 	int i;
420 
421 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
422 	softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
423 	if (softclock_si == NULL)
424 		panic("initclocks: unable to register softclock intr");
425 #endif
426 
427 	/*
428 	 * Set divisors to 1 (normal case) and let the machine-specific
429 	 * code do its bit.
430 	 */
431 	psdiv = 1;
432 	cpu_initclocks();
433 
434 	/*
435 	 * Compute profhz/stathz/rrticks, and fix profhz if needed.
436 	 */
437 	i = stathz ? stathz : hz;
438 	if (profhz == 0)
439 		profhz = i;
440 	psratio = profhz / i;
441 	rrticks = hz / 10;
442 
443 #ifdef NTP
444 	switch (hz) {
445 	case 1:
446 		shifthz = SHIFT_SCALE - 0;
447 		break;
448 	case 2:
449 		shifthz = SHIFT_SCALE - 1;
450 		break;
451 	case 4:
452 		shifthz = SHIFT_SCALE - 2;
453 		break;
454 	case 8:
455 		shifthz = SHIFT_SCALE - 3;
456 		break;
457 	case 16:
458 		shifthz = SHIFT_SCALE - 4;
459 		break;
460 	case 32:
461 		shifthz = SHIFT_SCALE - 5;
462 		break;
463 	case 60:
464 	case 64:
465 		shifthz = SHIFT_SCALE - 6;
466 		break;
467 	case 96:
468 	case 100:
469 	case 128:
470 		shifthz = SHIFT_SCALE - 7;
471 		break;
472 	case 256:
473 		shifthz = SHIFT_SCALE - 8;
474 		break;
475 	case 512:
476 		shifthz = SHIFT_SCALE - 9;
477 		break;
478 	case 1000:
479 	case 1024:
480 		shifthz = SHIFT_SCALE - 10;
481 		break;
482 	case 1200:
483 	case 2048:
484 		shifthz = SHIFT_SCALE - 11;
485 		break;
486 	case 4096:
487 		shifthz = SHIFT_SCALE - 12;
488 		break;
489 	case 8192:
490 		shifthz = SHIFT_SCALE - 13;
491 		break;
492 	case 16384:
493 		shifthz = SHIFT_SCALE - 14;
494 		break;
495 	case 32768:
496 		shifthz = SHIFT_SCALE - 15;
497 		break;
498 	case 65536:
499 		shifthz = SHIFT_SCALE - 16;
500 		break;
501 	default:
502 		panic("weird hz");
503 	}
504 	if (fixtick == 0) {
505 		/*
506 		 * Give MD code a chance to set this to a better
507 		 * value; but, if it doesn't, we should.
508 		 */
509 		fixtick = (1000000 - (hz*tick));
510 	}
511 #endif
512 }
513 
514 /*
515  * The real-time timer, interrupting hz times per second.
516  */
517 void
518 hardclock(struct clockframe *frame)
519 {
520 	struct proc *p;
521 	int delta;
522 	extern int tickdelta;
523 	extern long timedelta;
524 	struct cpu_info *ci = curcpu();
525 #ifdef NTP
526 	int time_update;
527 	int ltemp;
528 #endif
529 
530 	p = curproc;
531 	if (p) {
532 		struct pstats *pstats;
533 
534 		/*
535 		 * Run current process's virtual and profile time, as needed.
536 		 */
537 		pstats = p->p_stats;
538 		if (CLKF_USERMODE(frame) &&
539 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
540 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
541 			psignal(p, SIGVTALRM);
542 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
543 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
544 			psignal(p, SIGPROF);
545 	}
546 
547 	/*
548 	 * If no separate statistics clock is available, run it from here.
549 	 */
550 	if (stathz == 0)
551 		statclock(frame);
552 	if ((--ci->ci_schedstate.spc_rrticks) <= 0)
553 		roundrobin(ci);
554 
555 #if defined(MULTIPROCESSOR)
556 	/*
557 	 * If we are not the primary CPU, we're not allowed to do
558 	 * any more work.
559 	 */
560 	if (CPU_IS_PRIMARY(ci) == 0)
561 		return;
562 #endif
563 
564 	/*
565 	 * Increment the time-of-day.  The increment is normally just
566 	 * ``tick''.  If the machine is one which has a clock frequency
567 	 * such that ``hz'' would not divide the second evenly into
568 	 * milliseconds, a periodic adjustment must be applied.  Finally,
569 	 * if we are still adjusting the time (see adjtime()),
570 	 * ``tickdelta'' may also be added in.
571 	 */
572 	delta = tick;
573 
574 #ifndef NTP
575 	if (tickfix) {
576 		tickfixcnt += tickfix;
577 		if (tickfixcnt >= tickfixinterval) {
578 			delta++;
579 			tickfixcnt -= tickfixinterval;
580 		}
581 	}
582 #endif /* !NTP */
583 	/* Imprecise 4bsd adjtime() handling */
584 	if (timedelta != 0) {
585 		delta += tickdelta;
586 		timedelta -= tickdelta;
587 	}
588 
589 #ifdef notyet
590 	microset();
591 #endif
592 
593 #ifndef NTP
594 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
595 #endif
596 	BUMPTIME(&mono_time, delta);
597 
598 #ifdef NTP
599 	time_update = delta;
600 
601 	/*
602 	 * Compute the phase adjustment. If the low-order bits
603 	 * (time_phase) of the update overflow, bump the high-order bits
604 	 * (time_update).
605 	 */
606 	time_phase += time_adj;
607 	if (time_phase <= -FINEUSEC) {
608 		ltemp = -time_phase >> SHIFT_SCALE;
609 		time_phase += ltemp << SHIFT_SCALE;
610 		time_update -= ltemp;
611 	} else if (time_phase >= FINEUSEC) {
612 		ltemp = time_phase >> SHIFT_SCALE;
613 		time_phase -= ltemp << SHIFT_SCALE;
614 		time_update += ltemp;
615 	}
616 
617 #ifdef HIGHBALL
618 	/*
619 	 * If the HIGHBALL board is installed, we need to adjust the
620 	 * external clock offset in order to close the hardware feedback
621 	 * loop. This will adjust the external clock phase and frequency
622 	 * in small amounts. The additional phase noise and frequency
623 	 * wander this causes should be minimal. We also need to
624 	 * discipline the kernel time variable, since the PLL is used to
625 	 * discipline the external clock. If the Highball board is not
626 	 * present, we discipline kernel time with the PLL as usual. We
627 	 * assume that the external clock phase adjustment (time_update)
628 	 * and kernel phase adjustment (clock_cpu) are less than the
629 	 * value of tick.
630 	 */
631 	clock_offset.tv_usec += time_update;
632 	if (clock_offset.tv_usec >= 1000000) {
633 		clock_offset.tv_sec++;
634 		clock_offset.tv_usec -= 1000000;
635 	}
636 	if (clock_offset.tv_usec < 0) {
637 		clock_offset.tv_sec--;
638 		clock_offset.tv_usec += 1000000;
639 	}
640 	time.tv_usec += clock_cpu;
641 	clock_cpu = 0;
642 #else
643 	time.tv_usec += time_update;
644 #endif /* HIGHBALL */
645 
646 	/*
647 	 * On rollover of the second the phase adjustment to be used for
648 	 * the next second is calculated. Also, the maximum error is
649 	 * increased by the tolerance. If the PPS frequency discipline
650 	 * code is present, the phase is increased to compensate for the
651 	 * CPU clock oscillator frequency error.
652 	 *
653  	 * On a 32-bit machine and given parameters in the timex.h
654 	 * header file, the maximum phase adjustment is +-512 ms and
655 	 * maximum frequency offset is a tad less than) +-512 ppm. On a
656 	 * 64-bit machine, you shouldn't need to ask.
657 	 */
658 	if (time.tv_usec >= 1000000) {
659 		time.tv_usec -= 1000000;
660 		time.tv_sec++;
661 		time_maxerror += time_tolerance >> SHIFT_USEC;
662 
663 		/*
664 		 * Leap second processing. If in leap-insert state at
665 		 * the end of the day, the system clock is set back one
666 		 * second; if in leap-delete state, the system clock is
667 		 * set ahead one second. The microtime() routine or
668 		 * external clock driver will insure that reported time
669 		 * is always monotonic. The ugly divides should be
670 		 * replaced.
671 		 */
672 		switch (time_state) {
673 		case TIME_OK:
674 			if (time_status & STA_INS)
675 				time_state = TIME_INS;
676 			else if (time_status & STA_DEL)
677 				time_state = TIME_DEL;
678 			break;
679 
680 		case TIME_INS:
681 			if (time.tv_sec % 86400 == 0) {
682 				time.tv_sec--;
683 				time_state = TIME_OOP;
684 			}
685 			break;
686 
687 		case TIME_DEL:
688 			if ((time.tv_sec + 1) % 86400 == 0) {
689 				time.tv_sec++;
690 				time_state = TIME_WAIT;
691 			}
692 			break;
693 
694 		case TIME_OOP:
695 			time_state = TIME_WAIT;
696 			break;
697 
698 		case TIME_WAIT:
699 			if (!(time_status & (STA_INS | STA_DEL)))
700 				time_state = TIME_OK;
701 			break;
702 		}
703 
704 		/*
705 		 * Compute the phase adjustment for the next second. In
706 		 * PLL mode, the offset is reduced by a fixed factor
707 		 * times the time constant. In FLL mode the offset is
708 		 * used directly. In either mode, the maximum phase
709 		 * adjustment for each second is clamped so as to spread
710 		 * the adjustment over not more than the number of
711 		 * seconds between updates.
712 		 */
713 		if (time_offset < 0) {
714 			ltemp = -time_offset;
715 			if (!(time_status & STA_FLL))
716 				ltemp >>= SHIFT_KG + time_constant;
717 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
718 				ltemp = (MAXPHASE / MINSEC) <<
719 				    SHIFT_UPDATE;
720 			time_offset += ltemp;
721 			time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
722 		} else if (time_offset > 0) {
723 			ltemp = time_offset;
724 			if (!(time_status & STA_FLL))
725 				ltemp >>= SHIFT_KG + time_constant;
726 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
727 				ltemp = (MAXPHASE / MINSEC) <<
728 				    SHIFT_UPDATE;
729 			time_offset -= ltemp;
730 			time_adj = ltemp << (shifthz - SHIFT_UPDATE);
731 		} else
732 			time_adj = 0;
733 
734 		/*
735 		 * Compute the frequency estimate and additional phase
736 		 * adjustment due to frequency error for the next
737 		 * second. When the PPS signal is engaged, gnaw on the
738 		 * watchdog counter and update the frequency computed by
739 		 * the pll and the PPS signal.
740 		 */
741 #ifdef PPS_SYNC
742 		pps_valid++;
743 		if (pps_valid == PPS_VALID) {
744 			pps_jitter = MAXTIME;
745 			pps_stabil = MAXFREQ;
746 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
747 			    STA_PPSWANDER | STA_PPSERROR);
748 		}
749 		ltemp = time_freq + pps_freq;
750 #else
751 		ltemp = time_freq;
752 #endif /* PPS_SYNC */
753 
754 		if (ltemp < 0)
755 			time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
756 		else
757 			time_adj += ltemp >> (SHIFT_USEC - shifthz);
758 		time_adj += (long)fixtick << shifthz;
759 
760 		/*
761 		 * When the CPU clock oscillator frequency is not a
762 		 * power of 2 in Hz, shifthz is only an approximate
763 		 * scale factor.
764 		 *
765 		 * To determine the adjustment, you can do the following:
766 		 *   bc -q
767 		 *   scale=24
768 		 *   obase=2
769 		 *   idealhz/realhz
770 		 * where `idealhz' is the next higher power of 2, and `realhz'
771 		 * is the actual value.  You may need to factor this result
772 		 * into a sequence of 2 multipliers to get better precision.
773 		 *
774 		 * Likewise, the error can be calculated with (e.g. for 100Hz):
775 		 *   bc -q
776 		 *   scale=24
777 		 *   ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
778 		 * (and then multiply by 1000000 to get ppm).
779 		 */
780 		switch (hz) {
781 		case 60:
782 			/* A factor of 1.000100010001 gives about 15ppm
783 			   error. */
784 			if (time_adj < 0) {
785 				time_adj -= (-time_adj >> 4);
786 				time_adj -= (-time_adj >> 8);
787 			} else {
788 				time_adj += (time_adj >> 4);
789 				time_adj += (time_adj >> 8);
790 			}
791 			break;
792 
793 		case 96:
794 			/* A factor of 1.0101010101 gives about 244ppm error. */
795 			if (time_adj < 0) {
796 				time_adj -= (-time_adj >> 2);
797 				time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
798 			} else {
799 				time_adj += (time_adj >> 2);
800 				time_adj += (time_adj >> 4) + (time_adj >> 8);
801 			}
802 			break;
803 
804 		case 100:
805 			/* A factor of 1.010001111010111 gives about 1ppm
806 			   error. */
807 			if (time_adj < 0) {
808 				time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
809 				time_adj += (-time_adj >> 10);
810 			} else {
811 				time_adj += (time_adj >> 2) + (time_adj >> 5);
812 				time_adj -= (time_adj >> 10);
813 			}
814 			break;
815 
816 		case 1000:
817 			/* A factor of 1.000001100010100001 gives about 50ppm
818 			   error. */
819 			if (time_adj < 0) {
820 				time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
821 				time_adj -= (-time_adj >> 7);
822 			} else {
823 				time_adj += (time_adj >> 6) + (time_adj >> 11);
824 				time_adj += (time_adj >> 7);
825 			}
826 			break;
827 
828 		case 1200:
829 			/* A factor of 1.1011010011100001 gives about 64ppm
830 			   error. */
831 			if (time_adj < 0) {
832 				time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
833 				time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
834 			} else {
835 				time_adj += (time_adj >> 1) + (time_adj >> 6);
836 				time_adj += (time_adj >> 3) + (time_adj >> 10);
837 			}
838 			break;
839 		}
840 
841 #ifdef EXT_CLOCK
842 		/*
843 		 * If an external clock is present, it is necessary to
844 		 * discipline the kernel time variable anyway, since not
845 		 * all system components use the microtime() interface.
846 		 * Here, the time offset between the external clock and
847 		 * kernel time variable is computed every so often.
848 		 */
849 		clock_count++;
850 		if (clock_count > CLOCK_INTERVAL) {
851 			clock_count = 0;
852 			microtime(&clock_ext);
853 			delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
854 			delta.tv_usec = clock_ext.tv_usec -
855 			    time.tv_usec;
856 			if (delta.tv_usec < 0)
857 				delta.tv_sec--;
858 			if (delta.tv_usec >= 500000) {
859 				delta.tv_usec -= 1000000;
860 				delta.tv_sec++;
861 			}
862 			if (delta.tv_usec < -500000) {
863 				delta.tv_usec += 1000000;
864 				delta.tv_sec--;
865 			}
866 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
867 			    delta.tv_usec > MAXPHASE) ||
868 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
869 			    delta.tv_usec < -MAXPHASE)) {
870 				time = clock_ext;
871 				delta.tv_sec = 0;
872 				delta.tv_usec = 0;
873 			}
874 #ifdef HIGHBALL
875 			clock_cpu = delta.tv_usec;
876 #else /* HIGHBALL */
877 			hardupdate(delta.tv_usec);
878 #endif /* HIGHBALL */
879 		}
880 #endif /* EXT_CLOCK */
881 	}
882 
883 #endif /* NTP */
884 
885 	/*
886 	 * Process callouts at a very low cpu priority, so we don't keep the
887 	 * relatively high clock interrupt priority any longer than necessary.
888 	 */
889 	simple_lock(&callwheel_slock);	/* already at splclock() */
890 	hardclock_ticks++;
891 	if (! TAILQ_EMPTY(&callwheel[hardclock_ticks & callwheelmask].cq_q)) {
892 		simple_unlock(&callwheel_slock);
893 		if (CLKF_BASEPRI(frame)) {
894 			/*
895 			 * Save the overhead of a software interrupt;
896 			 * it will happen as soon as we return, so do
897 			 * it now.
898 			 *
899 			 * NOTE: If we're at ``base priority'', softclock()
900 			 * was not already running.
901 			 */
902 			spllowersoftclock();
903 			KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
904 			softclock(NULL);
905 			KERNEL_UNLOCK();
906 		} else {
907 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
908 			softintr_schedule(softclock_si);
909 #else
910 			setsoftclock();
911 #endif
912 		}
913 		return;
914 	} else if (softclock_running == 0 &&
915 		   (softclock_ticks + 1) == hardclock_ticks) {
916 		softclock_ticks++;
917 	}
918 	simple_unlock(&callwheel_slock);
919 }
920 
921 /*
922  * Software (low priority) clock interrupt.
923  * Run periodic events from timeout queue.
924  */
925 /*ARGSUSED*/
926 void
927 softclock(void *v)
928 {
929 	struct callout_queue *bucket;
930 	struct callout *c;
931 	void (*func)(void *);
932 	void *arg;
933 	int s, idx;
934 	int steps = 0;
935 
936 	CALLWHEEL_LOCK(s);
937 
938 	softclock_running = 1;
939 
940 #ifdef CALLWHEEL_STATS
941 	callwheel_softclocks.ev_count++;
942 #endif
943 
944 	while (softclock_ticks != hardclock_ticks) {
945 		softclock_ticks++;
946 		idx = (int)(softclock_ticks & callwheelmask);
947 		bucket = &callwheel[idx];
948 		c = TAILQ_FIRST(&bucket->cq_q);
949 		if (c == NULL) {
950 #ifdef CALLWHEEL_STATS
951 			callwheel_softempty.ev_count++;
952 #endif
953 			continue;
954 		}
955 		if (softclock_ticks < bucket->cq_hint) {
956 #ifdef CALLWHEEL_STATS
957 			callwheel_hintworked.ev_count++;
958 #endif
959 			continue;
960 		}
961 		bucket->cq_hint = UQUAD_MAX;
962 		while (c != NULL) {
963 #ifdef CALLWHEEL_STATS
964 			callwheel_softchecks.ev_count++;
965 #endif
966 			if (c->c_time != softclock_ticks) {
967 				if (c->c_time < bucket->cq_hint)
968 					bucket->cq_hint = c->c_time;
969 				c = TAILQ_NEXT(c, c_link);
970 				if (++steps >= MAX_SOFTCLOCK_STEPS) {
971 					nextsoftcheck = c;
972 					/* Give interrupts a chance. */
973 					CALLWHEEL_UNLOCK(s);
974 					CALLWHEEL_LOCK(s);
975 					c = nextsoftcheck;
976 					steps = 0;
977 				}
978 			} else {
979 				nextsoftcheck = TAILQ_NEXT(c, c_link);
980 				TAILQ_REMOVE(&bucket->cq_q, c, c_link);
981 #ifdef CALLWHEEL_STATS
982 				callwheel_sizes[idx]--;
983 				callwheel_fired.ev_count++;
984 				callwheel_count.ev_count--;
985 #endif
986 				func = c->c_func;
987 				arg = c->c_arg;
988 				c->c_func = NULL;
989 				c->c_flags &= ~CALLOUT_PENDING;
990 				CALLWHEEL_UNLOCK(s);
991 				(*func)(arg);
992 				CALLWHEEL_LOCK(s);
993 				steps = 0;
994 				c = nextsoftcheck;
995 			}
996 		}
997 		if (TAILQ_EMPTY(&bucket->cq_q))
998 			bucket->cq_hint = UQUAD_MAX;
999 	}
1000 	nextsoftcheck = NULL;
1001 	softclock_running = 0;
1002 	CALLWHEEL_UNLOCK(s);
1003 }
1004 
1005 /*
1006  * callout_setsize:
1007  *
1008  *	Determine how many callwheels are necessary and
1009  *	set hash mask.  Called from allocsys().
1010  */
1011 void
1012 callout_setsize(void)
1013 {
1014 
1015 	for (callwheelsize = 1; callwheelsize < ncallout; callwheelsize <<= 1)
1016 		/* loop */ ;
1017 	callwheelmask = callwheelsize - 1;
1018 }
1019 
1020 /*
1021  * callout_startup:
1022  *
1023  *	Initialize the callwheel buckets.
1024  */
1025 void
1026 callout_startup(void)
1027 {
1028 	int i;
1029 
1030 	for (i = 0; i < callwheelsize; i++) {
1031 		callwheel[i].cq_hint = UQUAD_MAX;
1032 		TAILQ_INIT(&callwheel[i].cq_q);
1033 	}
1034 
1035 	simple_lock_init(&callwheel_slock);
1036 
1037 #ifdef CALLWHEEL_STATS
1038 	evcnt_attach_dynamic(&callwheel_collisions, EVCNT_TYPE_MISC,
1039 	    NULL, "callwheel", "collisions");
1040 	evcnt_attach_dynamic(&callwheel_maxlength, EVCNT_TYPE_MISC,
1041 	    NULL, "callwheel", "maxlength");
1042 	evcnt_attach_dynamic(&callwheel_count, EVCNT_TYPE_MISC,
1043 	    NULL, "callwheel", "count");
1044 	evcnt_attach_dynamic(&callwheel_established, EVCNT_TYPE_MISC,
1045 	    NULL, "callwheel", "established");
1046 	evcnt_attach_dynamic(&callwheel_fired, EVCNT_TYPE_MISC,
1047 	    NULL, "callwheel", "fired");
1048 	evcnt_attach_dynamic(&callwheel_disestablished, EVCNT_TYPE_MISC,
1049 	    NULL, "callwheel", "disestablished");
1050 	evcnt_attach_dynamic(&callwheel_changed, EVCNT_TYPE_MISC,
1051 	    NULL, "callwheel", "changed");
1052 	evcnt_attach_dynamic(&callwheel_softclocks, EVCNT_TYPE_MISC,
1053 	    NULL, "callwheel", "softclocks");
1054 	evcnt_attach_dynamic(&callwheel_softempty, EVCNT_TYPE_MISC,
1055 	    NULL, "callwheel", "softempty");
1056 	evcnt_attach_dynamic(&callwheel_hintworked, EVCNT_TYPE_MISC,
1057 	    NULL, "callwheel", "hintworked");
1058 #endif /* CALLWHEEL_STATS */
1059 }
1060 
1061 /*
1062  * callout_init:
1063  *
1064  *	Initialize a callout structure so that it can be used
1065  *	by callout_reset() and callout_stop().
1066  */
1067 void
1068 callout_init(struct callout *c)
1069 {
1070 
1071 	memset(c, 0, sizeof(*c));
1072 }
1073 
1074 /*
1075  * callout_reset:
1076  *
1077  *	Establish or change a timeout.
1078  */
1079 void
1080 callout_reset(struct callout *c, int ticks, void (*func)(void *), void *arg)
1081 {
1082 	struct callout_queue *bucket;
1083 	int s;
1084 
1085 	if (ticks <= 0)
1086 		ticks = 1;
1087 
1088 	CALLWHEEL_LOCK(s);
1089 
1090 	/*
1091 	 * If this callout's timer is already running, cancel it
1092 	 * before we modify it.
1093 	 */
1094 	if (c->c_flags & CALLOUT_PENDING) {
1095 		callout_stop_locked(c);	/* Already locked */
1096 #ifdef CALLWHEEL_STATS
1097 		callwheel_changed.ev_count++;
1098 #endif
1099 	}
1100 
1101 	c->c_arg = arg;
1102 	c->c_func = func;
1103 	c->c_flags = CALLOUT_ACTIVE | CALLOUT_PENDING;
1104 	c->c_time = hardclock_ticks + ticks;
1105 
1106 	bucket = &callwheel[c->c_time & callwheelmask];
1107 
1108 #ifdef CALLWHEEL_STATS
1109 	if (! TAILQ_EMPTY(&bucket->cq_q))
1110 		callwheel_collisions.ev_count++;
1111 #endif
1112 
1113 	TAILQ_INSERT_TAIL(&bucket->cq_q, c, c_link);
1114 	if (c->c_time < bucket->cq_hint)
1115 		bucket->cq_hint = c->c_time;
1116 
1117 #ifdef CALLWHEEL_STATS
1118 	callwheel_count.ev_count++;
1119 	callwheel_established.ev_count++;
1120 	if (++callwheel_sizes[c->c_time & callwheelmask] >
1121 	    callwheel_maxlength.ev_count)
1122 		callwheel_maxlength.ev_count =
1123 		    callwheel_sizes[c->c_time & callwheelmask];
1124 #endif
1125 
1126 	CALLWHEEL_UNLOCK(s);
1127 }
1128 
1129 /*
1130  * callout_stop_locked:
1131  *
1132  *	Disestablish a timeout.  Callwheel is locked.
1133  */
1134 static void
1135 callout_stop_locked(struct callout *c)
1136 {
1137 	struct callout_queue *bucket;
1138 
1139 	/*
1140 	 * Don't attempt to delete a callout that's not on the queue.
1141 	 */
1142 	if ((c->c_flags & CALLOUT_PENDING) == 0) {
1143 		c->c_flags &= ~CALLOUT_ACTIVE;
1144 		return;
1145 	}
1146 
1147 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1148 
1149 	if (nextsoftcheck == c)
1150 		nextsoftcheck = TAILQ_NEXT(c, c_link);
1151 
1152 	bucket = &callwheel[c->c_time & callwheelmask];
1153 	TAILQ_REMOVE(&bucket->cq_q, c, c_link);
1154 	if (TAILQ_EMPTY(&bucket->cq_q))
1155 		bucket->cq_hint = UQUAD_MAX;
1156 #ifdef CALLWHEEL_STATS
1157 	callwheel_count.ev_count--;
1158 	callwheel_disestablished.ev_count++;
1159 	callwheel_sizes[c->c_time & callwheelmask]--;
1160 #endif
1161 
1162 	c->c_func = NULL;
1163 }
1164 
1165 /*
1166  * callout_stop:
1167  *
1168  *	Disestablish a timeout.  Callwheel is unlocked.  This is
1169  *	the standard entry point.
1170  */
1171 void
1172 callout_stop(struct callout *c)
1173 {
1174 	int s;
1175 
1176 	CALLWHEEL_LOCK(s);
1177 	callout_stop_locked(c);
1178 	CALLWHEEL_UNLOCK(s);
1179 }
1180 
1181 #ifdef CALLWHEEL_STATS
1182 /*
1183  * callout_showstats:
1184  *
1185  *	Display callout statistics.  Call it from DDB.
1186  */
1187 void
1188 callout_showstats(void)
1189 {
1190 	u_int64_t curticks;
1191 	int s;
1192 
1193 	s = splclock();
1194 	curticks = softclock_ticks;
1195 	splx(s);
1196 
1197 	printf("Callwheel statistics:\n");
1198 	printf("\tCallouts currently queued: %llu\n",
1199 	    (long long) callwheel_count.ev_count);
1200 	printf("\tCallouts established: %llu\n",
1201 	    (long long) callwheel_established.ev_count);
1202 	printf("\tCallouts disestablished: %llu\n",
1203 	    (long long) callwheel_disestablished.ev_count);
1204 	if (callwheel_changed.ev_count != 0)
1205 		printf("\t\tOf those, %llu were changes\n",
1206 		    (long long) callwheel_changed.ev_count);
1207 	printf("\tCallouts that fired: %llu\n",
1208 	    (long long) callwheel_fired.ev_count);
1209 	printf("\tNumber of buckets: %d\n", callwheelsize);
1210 	printf("\tNumber of hash collisions: %llu\n",
1211 	    (long long) callwheel_collisions.ev_count);
1212 	printf("\tMaximum hash chain length: %llu\n",
1213 	    (long long) callwheel_maxlength.ev_count);
1214 	printf("\tSoftclocks: %llu, Softchecks: %llu\n",
1215 	    (long long) callwheel_softclocks.ev_count,
1216 	    (long long) callwheel_softchecks.ev_count);
1217 	printf("\t\tEmpty buckets seen: %llu\n",
1218 	    (long long) callwheel_softempty.ev_count);
1219 	printf("\t\tTimes hint saved scan: %llu\n",
1220 	    (long long) callwheel_hintworked.ev_count);
1221 }
1222 #endif
1223 
1224 /*
1225  * Compute number of hz until specified time.  Used to compute second
1226  * argument to callout_reset() from an absolute time.
1227  */
1228 int
1229 hzto(struct timeval *tv)
1230 {
1231 	unsigned long ticks;
1232 	long sec, usec;
1233 	int s;
1234 
1235 	/*
1236 	 * If the number of usecs in the whole seconds part of the time
1237 	 * difference fits in a long, then the total number of usecs will
1238 	 * fit in an unsigned long.  Compute the total and convert it to
1239 	 * ticks, rounding up and adding 1 to allow for the current tick
1240 	 * to expire.  Rounding also depends on unsigned long arithmetic
1241 	 * to avoid overflow.
1242 	 *
1243 	 * Otherwise, if the number of ticks in the whole seconds part of
1244 	 * the time difference fits in a long, then convert the parts to
1245 	 * ticks separately and add, using similar rounding methods and
1246 	 * overflow avoidance.  This method would work in the previous
1247 	 * case, but it is slightly slower and assume that hz is integral.
1248 	 *
1249 	 * Otherwise, round the time difference down to the maximum
1250 	 * representable value.
1251 	 *
1252 	 * If ints are 32-bit, then the maximum value for any timeout in
1253 	 * 10ms ticks is 248 days.
1254 	 */
1255 	s = splclock();
1256 	sec = tv->tv_sec - time.tv_sec;
1257 	usec = tv->tv_usec - time.tv_usec;
1258 	splx(s);
1259 
1260 	if (usec < 0) {
1261 		sec--;
1262 		usec += 1000000;
1263 	}
1264 
1265 	if (sec < 0 || (sec == 0 && usec <= 0)) {
1266 		/*
1267 		 * Would expire now or in the past.  Return 0 ticks.
1268 		 * This is different from the legacy hzto() interface,
1269 		 * and callers need to check for it.
1270 		 */
1271 		ticks = 0;
1272 	} else if (sec <= (LONG_MAX / 1000000))
1273 		ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1274 		    / tick) + 1;
1275 	else if (sec <= (LONG_MAX / hz))
1276 		ticks = (sec * hz) +
1277 		    (((unsigned long)usec + (tick - 1)) / tick) + 1;
1278 	else
1279 		ticks = LONG_MAX;
1280 
1281 	if (ticks > INT_MAX)
1282 		ticks = INT_MAX;
1283 
1284 	return ((int)ticks);
1285 }
1286 
1287 /*
1288  * Start profiling on a process.
1289  *
1290  * Kernel profiling passes proc0 which never exits and hence
1291  * keeps the profile clock running constantly.
1292  */
1293 void
1294 startprofclock(struct proc *p)
1295 {
1296 
1297 	if ((p->p_flag & P_PROFIL) == 0) {
1298 		p->p_flag |= P_PROFIL;
1299 		if (++profprocs == 1 && stathz != 0)
1300 			psdiv = psratio;
1301 	}
1302 }
1303 
1304 /*
1305  * Stop profiling on a process.
1306  */
1307 void
1308 stopprofclock(struct proc *p)
1309 {
1310 
1311 	if (p->p_flag & P_PROFIL) {
1312 		p->p_flag &= ~P_PROFIL;
1313 		if (--profprocs == 0 && stathz != 0)
1314 			psdiv = 1;
1315 	}
1316 }
1317 
1318 /*
1319  * Statistics clock.  Grab profile sample, and if divider reaches 0,
1320  * do process and kernel statistics.
1321  */
1322 void
1323 statclock(struct clockframe *frame)
1324 {
1325 #ifdef GPROF
1326 	struct gmonparam *g;
1327 	intptr_t i;
1328 #endif
1329 	struct cpu_info *ci = curcpu();
1330 	struct schedstate_percpu *spc = &ci->ci_schedstate;
1331 	struct proc *p;
1332 
1333 	/*
1334 	 * Notice changes in divisor frequency, and adjust clock
1335 	 * frequency accordingly.
1336 	 */
1337 	if (spc->spc_psdiv != psdiv) {
1338 		spc->spc_psdiv = psdiv;
1339 		spc->spc_pscnt = psdiv;
1340 		if (psdiv == 1) {
1341 			setstatclockrate(stathz);
1342 		} else {
1343 			setstatclockrate(profhz);
1344 		}
1345 	}
1346 	p = curproc;
1347 	if (CLKF_USERMODE(frame)) {
1348 		if (p->p_flag & P_PROFIL)
1349 			addupc_intr(p, CLKF_PC(frame));
1350 		if (--spc->spc_pscnt > 0)
1351 			return;
1352 		/*
1353 		 * Came from user mode; CPU was in user state.
1354 		 * If this process is being profiled record the tick.
1355 		 */
1356 		p->p_uticks++;
1357 		if (p->p_nice > NZERO)
1358 			spc->spc_cp_time[CP_NICE]++;
1359 		else
1360 			spc->spc_cp_time[CP_USER]++;
1361 	} else {
1362 #ifdef GPROF
1363 		/*
1364 		 * Kernel statistics are just like addupc_intr, only easier.
1365 		 */
1366 		g = &_gmonparam;
1367 		if (g->state == GMON_PROF_ON) {
1368 			i = CLKF_PC(frame) - g->lowpc;
1369 			if (i < g->textsize) {
1370 				i /= HISTFRACTION * sizeof(*g->kcount);
1371 				g->kcount[i]++;
1372 			}
1373 		}
1374 #endif
1375 #ifdef PROC_PC
1376 		if (p && p->p_flag & P_PROFIL)
1377 			addupc_intr(p, PROC_PC(p));
1378 #endif
1379 		if (--spc->spc_pscnt > 0)
1380 			return;
1381 		/*
1382 		 * Came from kernel mode, so we were:
1383 		 * - handling an interrupt,
1384 		 * - doing syscall or trap work on behalf of the current
1385 		 *   user process, or
1386 		 * - spinning in the idle loop.
1387 		 * Whichever it is, charge the time as appropriate.
1388 		 * Note that we charge interrupts to the current process,
1389 		 * regardless of whether they are ``for'' that process,
1390 		 * so that we know how much of its real time was spent
1391 		 * in ``non-process'' (i.e., interrupt) work.
1392 		 */
1393 		if (CLKF_INTR(frame)) {
1394 			if (p != NULL)
1395 				p->p_iticks++;
1396 			spc->spc_cp_time[CP_INTR]++;
1397 		} else if (p != NULL) {
1398 			p->p_sticks++;
1399 			spc->spc_cp_time[CP_SYS]++;
1400 		} else
1401 			spc->spc_cp_time[CP_IDLE]++;
1402 	}
1403 	spc->spc_pscnt = psdiv;
1404 
1405 	if (p != NULL) {
1406 		++p->p_cpticks;
1407 		/*
1408 		 * If no separate schedclock is provided, call it here
1409 		 * at ~~12-25 Hz, ~~16 Hz is best
1410 		 */
1411 		if (schedhz == 0)
1412 			if ((++ci->ci_schedstate.spc_schedticks & 3) == 0)
1413 				schedclock(p);
1414 	}
1415 }
1416 
1417 
1418 #ifdef NTP	/* NTP phase-locked loop in kernel */
1419 
1420 /*
1421  * hardupdate() - local clock update
1422  *
1423  * This routine is called by ntp_adjtime() to update the local clock
1424  * phase and frequency. The implementation is of an adaptive-parameter,
1425  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1426  * time and frequency offset estimates for each call. If the kernel PPS
1427  * discipline code is configured (PPS_SYNC), the PPS signal itself
1428  * determines the new time offset, instead of the calling argument.
1429  * Presumably, calls to ntp_adjtime() occur only when the caller
1430  * believes the local clock is valid within some bound (+-128 ms with
1431  * NTP). If the caller's time is far different than the PPS time, an
1432  * argument will ensue, and it's not clear who will lose.
1433  *
1434  * For uncompensated quartz crystal oscillatores and nominal update
1435  * intervals less than 1024 s, operation should be in phase-lock mode
1436  * (STA_FLL = 0), where the loop is disciplined to phase. For update
1437  * intervals greater than thiss, operation should be in frequency-lock
1438  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1439  *
1440  * Note: splclock() is in effect.
1441  */
1442 void
1443 hardupdate(long offset)
1444 {
1445 	long ltemp, mtemp;
1446 
1447 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1448 		return;
1449 	ltemp = offset;
1450 #ifdef PPS_SYNC
1451 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1452 		ltemp = pps_offset;
1453 #endif /* PPS_SYNC */
1454 
1455 	/*
1456 	 * Scale the phase adjustment and clamp to the operating range.
1457 	 */
1458 	if (ltemp > MAXPHASE)
1459 		time_offset = MAXPHASE << SHIFT_UPDATE;
1460 	else if (ltemp < -MAXPHASE)
1461 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
1462 	else
1463 		time_offset = ltemp << SHIFT_UPDATE;
1464 
1465 	/*
1466 	 * Select whether the frequency is to be controlled and in which
1467 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
1468 	 * multiply/divide should be replaced someday.
1469 	 */
1470 	if (time_status & STA_FREQHOLD || time_reftime == 0)
1471 		time_reftime = time.tv_sec;
1472 	mtemp = time.tv_sec - time_reftime;
1473 	time_reftime = time.tv_sec;
1474 	if (time_status & STA_FLL) {
1475 		if (mtemp >= MINSEC) {
1476 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1477 			    SHIFT_UPDATE));
1478 			if (ltemp < 0)
1479 				time_freq -= -ltemp >> SHIFT_KH;
1480 			else
1481 				time_freq += ltemp >> SHIFT_KH;
1482 		}
1483 	} else {
1484 		if (mtemp < MAXSEC) {
1485 			ltemp *= mtemp;
1486 			if (ltemp < 0)
1487 				time_freq -= -ltemp >> (time_constant +
1488 				    time_constant + SHIFT_KF -
1489 				    SHIFT_USEC);
1490 			else
1491 				time_freq += ltemp >> (time_constant +
1492 				    time_constant + SHIFT_KF -
1493 				    SHIFT_USEC);
1494 		}
1495 	}
1496 	if (time_freq > time_tolerance)
1497 		time_freq = time_tolerance;
1498 	else if (time_freq < -time_tolerance)
1499 		time_freq = -time_tolerance;
1500 }
1501 
1502 #ifdef PPS_SYNC
1503 /*
1504  * hardpps() - discipline CPU clock oscillator to external PPS signal
1505  *
1506  * This routine is called at each PPS interrupt in order to discipline
1507  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1508  * and leaves it in a handy spot for the hardclock() routine. It
1509  * integrates successive PPS phase differences and calculates the
1510  * frequency offset. This is used in hardclock() to discipline the CPU
1511  * clock oscillator so that intrinsic frequency error is cancelled out.
1512  * The code requires the caller to capture the time and hardware counter
1513  * value at the on-time PPS signal transition.
1514  *
1515  * Note that, on some Unix systems, this routine runs at an interrupt
1516  * priority level higher than the timer interrupt routine hardclock().
1517  * Therefore, the variables used are distinct from the hardclock()
1518  * variables, except for certain exceptions: The PPS frequency pps_freq
1519  * and phase pps_offset variables are determined by this routine and
1520  * updated atomically. The time_tolerance variable can be considered a
1521  * constant, since it is infrequently changed, and then only when the
1522  * PPS signal is disabled. The watchdog counter pps_valid is updated
1523  * once per second by hardclock() and is atomically cleared in this
1524  * routine.
1525  */
1526 void
1527 hardpps(struct timeval *tvp,		/* time at PPS */
1528 	long usec			/* hardware counter at PPS */)
1529 {
1530 	long u_usec, v_usec, bigtick;
1531 	long cal_sec, cal_usec;
1532 
1533 	/*
1534 	 * An occasional glitch can be produced when the PPS interrupt
1535 	 * occurs in the hardclock() routine before the time variable is
1536 	 * updated. Here the offset is discarded when the difference
1537 	 * between it and the last one is greater than tick/2, but not
1538 	 * if the interval since the first discard exceeds 30 s.
1539 	 */
1540 	time_status |= STA_PPSSIGNAL;
1541 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1542 	pps_valid = 0;
1543 	u_usec = -tvp->tv_usec;
1544 	if (u_usec < -500000)
1545 		u_usec += 1000000;
1546 	v_usec = pps_offset - u_usec;
1547 	if (v_usec < 0)
1548 		v_usec = -v_usec;
1549 	if (v_usec > (tick >> 1)) {
1550 		if (pps_glitch > MAXGLITCH) {
1551 			pps_glitch = 0;
1552 			pps_tf[2] = u_usec;
1553 			pps_tf[1] = u_usec;
1554 		} else {
1555 			pps_glitch++;
1556 			u_usec = pps_offset;
1557 		}
1558 	} else
1559 		pps_glitch = 0;
1560 
1561 	/*
1562 	 * A three-stage median filter is used to help deglitch the pps
1563 	 * time. The median sample becomes the time offset estimate; the
1564 	 * difference between the other two samples becomes the time
1565 	 * dispersion (jitter) estimate.
1566 	 */
1567 	pps_tf[2] = pps_tf[1];
1568 	pps_tf[1] = pps_tf[0];
1569 	pps_tf[0] = u_usec;
1570 	if (pps_tf[0] > pps_tf[1]) {
1571 		if (pps_tf[1] > pps_tf[2]) {
1572 			pps_offset = pps_tf[1];		/* 0 1 2 */
1573 			v_usec = pps_tf[0] - pps_tf[2];
1574 		} else if (pps_tf[2] > pps_tf[0]) {
1575 			pps_offset = pps_tf[0];		/* 2 0 1 */
1576 			v_usec = pps_tf[2] - pps_tf[1];
1577 		} else {
1578 			pps_offset = pps_tf[2];		/* 0 2 1 */
1579 			v_usec = pps_tf[0] - pps_tf[1];
1580 		}
1581 	} else {
1582 		if (pps_tf[1] < pps_tf[2]) {
1583 			pps_offset = pps_tf[1];		/* 2 1 0 */
1584 			v_usec = pps_tf[2] - pps_tf[0];
1585 		} else  if (pps_tf[2] < pps_tf[0]) {
1586 			pps_offset = pps_tf[0];		/* 1 0 2 */
1587 			v_usec = pps_tf[1] - pps_tf[2];
1588 		} else {
1589 			pps_offset = pps_tf[2];		/* 1 2 0 */
1590 			v_usec = pps_tf[1] - pps_tf[0];
1591 		}
1592 	}
1593 	if (v_usec > MAXTIME)
1594 		pps_jitcnt++;
1595 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1596 	if (v_usec < 0)
1597 		pps_jitter -= -v_usec >> PPS_AVG;
1598 	else
1599 		pps_jitter += v_usec >> PPS_AVG;
1600 	if (pps_jitter > (MAXTIME >> 1))
1601 		time_status |= STA_PPSJITTER;
1602 
1603 	/*
1604 	 * During the calibration interval adjust the starting time when
1605 	 * the tick overflows. At the end of the interval compute the
1606 	 * duration of the interval and the difference of the hardware
1607 	 * counters at the beginning and end of the interval. This code
1608 	 * is deliciously complicated by the fact valid differences may
1609 	 * exceed the value of tick when using long calibration
1610 	 * intervals and small ticks. Note that the counter can be
1611 	 * greater than tick if caught at just the wrong instant, but
1612 	 * the values returned and used here are correct.
1613 	 */
1614 	bigtick = (long)tick << SHIFT_USEC;
1615 	pps_usec -= pps_freq;
1616 	if (pps_usec >= bigtick)
1617 		pps_usec -= bigtick;
1618 	if (pps_usec < 0)
1619 		pps_usec += bigtick;
1620 	pps_time.tv_sec++;
1621 	pps_count++;
1622 	if (pps_count < (1 << pps_shift))
1623 		return;
1624 	pps_count = 0;
1625 	pps_calcnt++;
1626 	u_usec = usec << SHIFT_USEC;
1627 	v_usec = pps_usec - u_usec;
1628 	if (v_usec >= bigtick >> 1)
1629 		v_usec -= bigtick;
1630 	if (v_usec < -(bigtick >> 1))
1631 		v_usec += bigtick;
1632 	if (v_usec < 0)
1633 		v_usec = -(-v_usec >> pps_shift);
1634 	else
1635 		v_usec = v_usec >> pps_shift;
1636 	pps_usec = u_usec;
1637 	cal_sec = tvp->tv_sec;
1638 	cal_usec = tvp->tv_usec;
1639 	cal_sec -= pps_time.tv_sec;
1640 	cal_usec -= pps_time.tv_usec;
1641 	if (cal_usec < 0) {
1642 		cal_usec += 1000000;
1643 		cal_sec--;
1644 	}
1645 	pps_time = *tvp;
1646 
1647 	/*
1648 	 * Check for lost interrupts, noise, excessive jitter and
1649 	 * excessive frequency error. The number of timer ticks during
1650 	 * the interval may vary +-1 tick. Add to this a margin of one
1651 	 * tick for the PPS signal jitter and maximum frequency
1652 	 * deviation. If the limits are exceeded, the calibration
1653 	 * interval is reset to the minimum and we start over.
1654 	 */
1655 	u_usec = (long)tick << 1;
1656 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1657 	    || (cal_sec == 0 && cal_usec < u_usec))
1658 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1659 		pps_errcnt++;
1660 		pps_shift = PPS_SHIFT;
1661 		pps_intcnt = 0;
1662 		time_status |= STA_PPSERROR;
1663 		return;
1664 	}
1665 
1666 	/*
1667 	 * A three-stage median filter is used to help deglitch the pps
1668 	 * frequency. The median sample becomes the frequency offset
1669 	 * estimate; the difference between the other two samples
1670 	 * becomes the frequency dispersion (stability) estimate.
1671 	 */
1672 	pps_ff[2] = pps_ff[1];
1673 	pps_ff[1] = pps_ff[0];
1674 	pps_ff[0] = v_usec;
1675 	if (pps_ff[0] > pps_ff[1]) {
1676 		if (pps_ff[1] > pps_ff[2]) {
1677 			u_usec = pps_ff[1];		/* 0 1 2 */
1678 			v_usec = pps_ff[0] - pps_ff[2];
1679 		} else if (pps_ff[2] > pps_ff[0]) {
1680 			u_usec = pps_ff[0];		/* 2 0 1 */
1681 			v_usec = pps_ff[2] - pps_ff[1];
1682 		} else {
1683 			u_usec = pps_ff[2];		/* 0 2 1 */
1684 			v_usec = pps_ff[0] - pps_ff[1];
1685 		}
1686 	} else {
1687 		if (pps_ff[1] < pps_ff[2]) {
1688 			u_usec = pps_ff[1];		/* 2 1 0 */
1689 			v_usec = pps_ff[2] - pps_ff[0];
1690 		} else  if (pps_ff[2] < pps_ff[0]) {
1691 			u_usec = pps_ff[0];		/* 1 0 2 */
1692 			v_usec = pps_ff[1] - pps_ff[2];
1693 		} else {
1694 			u_usec = pps_ff[2];		/* 1 2 0 */
1695 			v_usec = pps_ff[1] - pps_ff[0];
1696 		}
1697 	}
1698 
1699 	/*
1700 	 * Here the frequency dispersion (stability) is updated. If it
1701 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1702 	 * offset is updated as well, but clamped to the tolerance. It
1703 	 * will be processed later by the hardclock() routine.
1704 	 */
1705 	v_usec = (v_usec >> 1) - pps_stabil;
1706 	if (v_usec < 0)
1707 		pps_stabil -= -v_usec >> PPS_AVG;
1708 	else
1709 		pps_stabil += v_usec >> PPS_AVG;
1710 	if (pps_stabil > MAXFREQ >> 2) {
1711 		pps_stbcnt++;
1712 		time_status |= STA_PPSWANDER;
1713 		return;
1714 	}
1715 	if (time_status & STA_PPSFREQ) {
1716 		if (u_usec < 0) {
1717 			pps_freq -= -u_usec >> PPS_AVG;
1718 			if (pps_freq < -time_tolerance)
1719 				pps_freq = -time_tolerance;
1720 			u_usec = -u_usec;
1721 		} else {
1722 			pps_freq += u_usec >> PPS_AVG;
1723 			if (pps_freq > time_tolerance)
1724 				pps_freq = time_tolerance;
1725 		}
1726 	}
1727 
1728 	/*
1729 	 * Here the calibration interval is adjusted. If the maximum
1730 	 * time difference is greater than tick / 4, reduce the interval
1731 	 * by half. If this is not the case for four consecutive
1732 	 * intervals, double the interval.
1733 	 */
1734 	if (u_usec << pps_shift > bigtick >> 2) {
1735 		pps_intcnt = 0;
1736 		if (pps_shift > PPS_SHIFT)
1737 			pps_shift--;
1738 	} else if (pps_intcnt >= 4) {
1739 		pps_intcnt = 0;
1740 		if (pps_shift < PPS_SHIFTMAX)
1741 			pps_shift++;
1742 	} else
1743 		pps_intcnt++;
1744 }
1745 #endif /* PPS_SYNC */
1746 #endif /* NTP  */
1747 
1748 /*
1749  * Return information about system clocks.
1750  */
1751 int
1752 sysctl_clockrate(void *where, size_t *sizep)
1753 {
1754 	struct clockinfo clkinfo;
1755 
1756 	/*
1757 	 * Construct clockinfo structure.
1758 	 */
1759 	clkinfo.tick = tick;
1760 	clkinfo.tickadj = tickadj;
1761 	clkinfo.hz = hz;
1762 	clkinfo.profhz = profhz;
1763 	clkinfo.stathz = stathz ? stathz : hz;
1764 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1765 }
1766