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