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