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