Home | History | Annotate | Line # | Download | only in kern
kern_clock.c revision 1.74.2.8
      1 /*	$NetBSD: kern_clock.c,v 1.74.2.8 2002/07/12 01:40:13 nathanw 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.74.2.8 2002/07/12 01:40:13 nathanw Exp $");
     82 
     83 #include "opt_callout.h"
     84 #include "opt_ntp.h"
     85 
     86 #include <sys/param.h>
     87 #include <sys/systm.h>
     88 #include <sys/dkstat.h>
     89 #include <sys/callout.h>
     90 #include <sys/kernel.h>
     91 #include <sys/proc.h>
     92 #include <sys/resourcevar.h>
     93 #include <sys/signalvar.h>
     94 #include <sys/sysctl.h>
     95 #include <sys/timex.h>
     96 #include <sys/sched.h>
     97 #include <sys/time.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 lwp *l;
    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 	l = curlwp;
    533 	if (l) {
    534 		p = l->l_proc;
    535 		/*
    536 		 * Run current process's virtual and profile time, as needed.
    537 		 */
    538 		if (CLKF_USERMODE(frame) &&
    539 		    p->p_timers && p->p_timers[ITIMER_VIRTUAL] &&
    540 		    timerisset(&p->p_timers[ITIMER_VIRTUAL]->pt_time.it_value) &&
    541 		    (itimerdecr(&p->p_timers[ITIMER_VIRTUAL]->pt_time, tick) == 0))
    542 			psignal(p, SIGVTALRM);
    543 		if (p->p_timers && p->p_timers[ITIMER_PROF] &&
    544 		    timerisset(&p->p_timers[ITIMER_PROF]->pt_time.it_value) &&
    545 		    (itimerdecr(&p->p_timers[ITIMER_PROF]->pt_time, 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 		if (++profprocs == 1 && stathz != 0)
   1302 			psdiv = psratio;
   1303 	}
   1304 }
   1305 
   1306 /*
   1307  * Stop profiling on a process.
   1308  */
   1309 void
   1310 stopprofclock(struct proc *p)
   1311 {
   1312 
   1313 	if (p->p_flag & P_PROFIL) {
   1314 		p->p_flag &= ~P_PROFIL;
   1315 		if (--profprocs == 0 && stathz != 0)
   1316 			psdiv = 1;
   1317 	}
   1318 }
   1319 
   1320 /*
   1321  * Statistics clock.  Grab profile sample, and if divider reaches 0,
   1322  * do process and kernel statistics.
   1323  */
   1324 void
   1325 statclock(struct clockframe *frame)
   1326 {
   1327 #ifdef GPROF
   1328 	struct gmonparam *g;
   1329 	intptr_t i;
   1330 #endif
   1331 	struct cpu_info *ci = curcpu();
   1332 	struct schedstate_percpu *spc = &ci->ci_schedstate;
   1333 	struct lwp *l;
   1334 	struct proc *p;
   1335 
   1336 	/*
   1337 	 * Notice changes in divisor frequency, and adjust clock
   1338 	 * frequency accordingly.
   1339 	 */
   1340 	if (spc->spc_psdiv != psdiv) {
   1341 		spc->spc_psdiv = psdiv;
   1342 		spc->spc_pscnt = psdiv;
   1343 		if (psdiv == 1) {
   1344 			setstatclockrate(stathz);
   1345 		} else {
   1346 			setstatclockrate(profhz);
   1347 		}
   1348 	}
   1349 	l = curlwp;
   1350 	p = (l ? l->l_proc : 0);
   1351 	if (CLKF_USERMODE(frame)) {
   1352 		if (p->p_flag & P_PROFIL)
   1353 			addupc_intr(p, CLKF_PC(frame));
   1354 		if (--spc->spc_pscnt > 0)
   1355 			return;
   1356 		/*
   1357 		 * Came from user mode; CPU was in user state.
   1358 		 * If this process is being profiled record the tick.
   1359 		 */
   1360 		p->p_uticks++;
   1361 		if (p->p_nice > NZERO)
   1362 			spc->spc_cp_time[CP_NICE]++;
   1363 		else
   1364 			spc->spc_cp_time[CP_USER]++;
   1365 	} else {
   1366 #ifdef GPROF
   1367 		/*
   1368 		 * Kernel statistics are just like addupc_intr, only easier.
   1369 		 */
   1370 		g = &_gmonparam;
   1371 		if (g->state == GMON_PROF_ON) {
   1372 			i = CLKF_PC(frame) - g->lowpc;
   1373 			if (i < g->textsize) {
   1374 				i /= HISTFRACTION * sizeof(*g->kcount);
   1375 				g->kcount[i]++;
   1376 			}
   1377 		}
   1378 #endif
   1379 #ifdef LWP_PC
   1380 		if (p && p->p_flag & P_PROFIL)
   1381 			addupc_intr(p, LWP_PC(l));
   1382 #endif
   1383 		if (--spc->spc_pscnt > 0)
   1384 			return;
   1385 		/*
   1386 		 * Came from kernel mode, so we were:
   1387 		 * - handling an interrupt,
   1388 		 * - doing syscall or trap work on behalf of the current
   1389 		 *   user process, or
   1390 		 * - spinning in the idle loop.
   1391 		 * Whichever it is, charge the time as appropriate.
   1392 		 * Note that we charge interrupts to the current process,
   1393 		 * regardless of whether they are ``for'' that process,
   1394 		 * so that we know how much of its real time was spent
   1395 		 * in ``non-process'' (i.e., interrupt) work.
   1396 		 */
   1397 		if (CLKF_INTR(frame)) {
   1398 			if (p != NULL)
   1399 				p->p_iticks++;
   1400 			spc->spc_cp_time[CP_INTR]++;
   1401 		} else if (p != NULL) {
   1402 			p->p_sticks++;
   1403 			spc->spc_cp_time[CP_SYS]++;
   1404 		} else
   1405 			spc->spc_cp_time[CP_IDLE]++;
   1406 	}
   1407 	spc->spc_pscnt = psdiv;
   1408 
   1409 	if (l != NULL) {
   1410 		++p->p_cpticks;
   1411 		/*
   1412 		 * If no separate schedclock is provided, call it here
   1413 		 * at ~~12-25 Hz, ~~16 Hz is best
   1414 		 */
   1415 		if (schedhz == 0)
   1416 			if ((++ci->ci_schedstate.spc_schedticks & 3) == 0)
   1417 				schedclock(l);
   1418 	}
   1419 }
   1420 
   1421 
   1422 #ifdef NTP	/* NTP phase-locked loop in kernel */
   1423 
   1424 /*
   1425  * hardupdate() - local clock update
   1426  *
   1427  * This routine is called by ntp_adjtime() to update the local clock
   1428  * phase and frequency. The implementation is of an adaptive-parameter,
   1429  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
   1430  * time and frequency offset estimates for each call. If the kernel PPS
   1431  * discipline code is configured (PPS_SYNC), the PPS signal itself
   1432  * determines the new time offset, instead of the calling argument.
   1433  * Presumably, calls to ntp_adjtime() occur only when the caller
   1434  * believes the local clock is valid within some bound (+-128 ms with
   1435  * NTP). If the caller's time is far different than the PPS time, an
   1436  * argument will ensue, and it's not clear who will lose.
   1437  *
   1438  * For uncompensated quartz crystal oscillatores and nominal update
   1439  * intervals less than 1024 s, operation should be in phase-lock mode
   1440  * (STA_FLL = 0), where the loop is disciplined to phase. For update
   1441  * intervals greater than thiss, operation should be in frequency-lock
   1442  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
   1443  *
   1444  * Note: splclock() is in effect.
   1445  */
   1446 void
   1447 hardupdate(long offset)
   1448 {
   1449 	long ltemp, mtemp;
   1450 
   1451 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
   1452 		return;
   1453 	ltemp = offset;
   1454 #ifdef PPS_SYNC
   1455 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
   1456 		ltemp = pps_offset;
   1457 #endif /* PPS_SYNC */
   1458 
   1459 	/*
   1460 	 * Scale the phase adjustment and clamp to the operating range.
   1461 	 */
   1462 	if (ltemp > MAXPHASE)
   1463 		time_offset = MAXPHASE << SHIFT_UPDATE;
   1464 	else if (ltemp < -MAXPHASE)
   1465 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
   1466 	else
   1467 		time_offset = ltemp << SHIFT_UPDATE;
   1468 
   1469 	/*
   1470 	 * Select whether the frequency is to be controlled and in which
   1471 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
   1472 	 * multiply/divide should be replaced someday.
   1473 	 */
   1474 	if (time_status & STA_FREQHOLD || time_reftime == 0)
   1475 		time_reftime = time.tv_sec;
   1476 	mtemp = time.tv_sec - time_reftime;
   1477 	time_reftime = time.tv_sec;
   1478 	if (time_status & STA_FLL) {
   1479 		if (mtemp >= MINSEC) {
   1480 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
   1481 			    SHIFT_UPDATE));
   1482 			if (ltemp < 0)
   1483 				time_freq -= -ltemp >> SHIFT_KH;
   1484 			else
   1485 				time_freq += ltemp >> SHIFT_KH;
   1486 		}
   1487 	} else {
   1488 		if (mtemp < MAXSEC) {
   1489 			ltemp *= mtemp;
   1490 			if (ltemp < 0)
   1491 				time_freq -= -ltemp >> (time_constant +
   1492 				    time_constant + SHIFT_KF -
   1493 				    SHIFT_USEC);
   1494 			else
   1495 				time_freq += ltemp >> (time_constant +
   1496 				    time_constant + SHIFT_KF -
   1497 				    SHIFT_USEC);
   1498 		}
   1499 	}
   1500 	if (time_freq > time_tolerance)
   1501 		time_freq = time_tolerance;
   1502 	else if (time_freq < -time_tolerance)
   1503 		time_freq = -time_tolerance;
   1504 }
   1505 
   1506 #ifdef PPS_SYNC
   1507 /*
   1508  * hardpps() - discipline CPU clock oscillator to external PPS signal
   1509  *
   1510  * This routine is called at each PPS interrupt in order to discipline
   1511  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
   1512  * and leaves it in a handy spot for the hardclock() routine. It
   1513  * integrates successive PPS phase differences and calculates the
   1514  * frequency offset. This is used in hardclock() to discipline the CPU
   1515  * clock oscillator so that intrinsic frequency error is cancelled out.
   1516  * The code requires the caller to capture the time and hardware counter
   1517  * value at the on-time PPS signal transition.
   1518  *
   1519  * Note that, on some Unix systems, this routine runs at an interrupt
   1520  * priority level higher than the timer interrupt routine hardclock().
   1521  * Therefore, the variables used are distinct from the hardclock()
   1522  * variables, except for certain exceptions: The PPS frequency pps_freq
   1523  * and phase pps_offset variables are determined by this routine and
   1524  * updated atomically. The time_tolerance variable can be considered a
   1525  * constant, since it is infrequently changed, and then only when the
   1526  * PPS signal is disabled. The watchdog counter pps_valid is updated
   1527  * once per second by hardclock() and is atomically cleared in this
   1528  * routine.
   1529  */
   1530 void
   1531 hardpps(struct timeval *tvp,		/* time at PPS */
   1532 	long usec			/* hardware counter at PPS */)
   1533 {
   1534 	long u_usec, v_usec, bigtick;
   1535 	long cal_sec, cal_usec;
   1536 
   1537 	/*
   1538 	 * An occasional glitch can be produced when the PPS interrupt
   1539 	 * occurs in the hardclock() routine before the time variable is
   1540 	 * updated. Here the offset is discarded when the difference
   1541 	 * between it and the last one is greater than tick/2, but not
   1542 	 * if the interval since the first discard exceeds 30 s.
   1543 	 */
   1544 	time_status |= STA_PPSSIGNAL;
   1545 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
   1546 	pps_valid = 0;
   1547 	u_usec = -tvp->tv_usec;
   1548 	if (u_usec < -500000)
   1549 		u_usec += 1000000;
   1550 	v_usec = pps_offset - u_usec;
   1551 	if (v_usec < 0)
   1552 		v_usec = -v_usec;
   1553 	if (v_usec > (tick >> 1)) {
   1554 		if (pps_glitch > MAXGLITCH) {
   1555 			pps_glitch = 0;
   1556 			pps_tf[2] = u_usec;
   1557 			pps_tf[1] = u_usec;
   1558 		} else {
   1559 			pps_glitch++;
   1560 			u_usec = pps_offset;
   1561 		}
   1562 	} else
   1563 		pps_glitch = 0;
   1564 
   1565 	/*
   1566 	 * A three-stage median filter is used to help deglitch the pps
   1567 	 * time. The median sample becomes the time offset estimate; the
   1568 	 * difference between the other two samples becomes the time
   1569 	 * dispersion (jitter) estimate.
   1570 	 */
   1571 	pps_tf[2] = pps_tf[1];
   1572 	pps_tf[1] = pps_tf[0];
   1573 	pps_tf[0] = u_usec;
   1574 	if (pps_tf[0] > pps_tf[1]) {
   1575 		if (pps_tf[1] > pps_tf[2]) {
   1576 			pps_offset = pps_tf[1];		/* 0 1 2 */
   1577 			v_usec = pps_tf[0] - pps_tf[2];
   1578 		} else if (pps_tf[2] > pps_tf[0]) {
   1579 			pps_offset = pps_tf[0];		/* 2 0 1 */
   1580 			v_usec = pps_tf[2] - pps_tf[1];
   1581 		} else {
   1582 			pps_offset = pps_tf[2];		/* 0 2 1 */
   1583 			v_usec = pps_tf[0] - pps_tf[1];
   1584 		}
   1585 	} else {
   1586 		if (pps_tf[1] < pps_tf[2]) {
   1587 			pps_offset = pps_tf[1];		/* 2 1 0 */
   1588 			v_usec = pps_tf[2] - pps_tf[0];
   1589 		} else  if (pps_tf[2] < pps_tf[0]) {
   1590 			pps_offset = pps_tf[0];		/* 1 0 2 */
   1591 			v_usec = pps_tf[1] - pps_tf[2];
   1592 		} else {
   1593 			pps_offset = pps_tf[2];		/* 1 2 0 */
   1594 			v_usec = pps_tf[1] - pps_tf[0];
   1595 		}
   1596 	}
   1597 	if (v_usec > MAXTIME)
   1598 		pps_jitcnt++;
   1599 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
   1600 	if (v_usec < 0)
   1601 		pps_jitter -= -v_usec >> PPS_AVG;
   1602 	else
   1603 		pps_jitter += v_usec >> PPS_AVG;
   1604 	if (pps_jitter > (MAXTIME >> 1))
   1605 		time_status |= STA_PPSJITTER;
   1606 
   1607 	/*
   1608 	 * During the calibration interval adjust the starting time when
   1609 	 * the tick overflows. At the end of the interval compute the
   1610 	 * duration of the interval and the difference of the hardware
   1611 	 * counters at the beginning and end of the interval. This code
   1612 	 * is deliciously complicated by the fact valid differences may
   1613 	 * exceed the value of tick when using long calibration
   1614 	 * intervals and small ticks. Note that the counter can be
   1615 	 * greater than tick if caught at just the wrong instant, but
   1616 	 * the values returned and used here are correct.
   1617 	 */
   1618 	bigtick = (long)tick << SHIFT_USEC;
   1619 	pps_usec -= pps_freq;
   1620 	if (pps_usec >= bigtick)
   1621 		pps_usec -= bigtick;
   1622 	if (pps_usec < 0)
   1623 		pps_usec += bigtick;
   1624 	pps_time.tv_sec++;
   1625 	pps_count++;
   1626 	if (pps_count < (1 << pps_shift))
   1627 		return;
   1628 	pps_count = 0;
   1629 	pps_calcnt++;
   1630 	u_usec = usec << SHIFT_USEC;
   1631 	v_usec = pps_usec - u_usec;
   1632 	if (v_usec >= bigtick >> 1)
   1633 		v_usec -= bigtick;
   1634 	if (v_usec < -(bigtick >> 1))
   1635 		v_usec += bigtick;
   1636 	if (v_usec < 0)
   1637 		v_usec = -(-v_usec >> pps_shift);
   1638 	else
   1639 		v_usec = v_usec >> pps_shift;
   1640 	pps_usec = u_usec;
   1641 	cal_sec = tvp->tv_sec;
   1642 	cal_usec = tvp->tv_usec;
   1643 	cal_sec -= pps_time.tv_sec;
   1644 	cal_usec -= pps_time.tv_usec;
   1645 	if (cal_usec < 0) {
   1646 		cal_usec += 1000000;
   1647 		cal_sec--;
   1648 	}
   1649 	pps_time = *tvp;
   1650 
   1651 	/*
   1652 	 * Check for lost interrupts, noise, excessive jitter and
   1653 	 * excessive frequency error. The number of timer ticks during
   1654 	 * the interval may vary +-1 tick. Add to this a margin of one
   1655 	 * tick for the PPS signal jitter and maximum frequency
   1656 	 * deviation. If the limits are exceeded, the calibration
   1657 	 * interval is reset to the minimum and we start over.
   1658 	 */
   1659 	u_usec = (long)tick << 1;
   1660 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
   1661 	    || (cal_sec == 0 && cal_usec < u_usec))
   1662 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
   1663 		pps_errcnt++;
   1664 		pps_shift = PPS_SHIFT;
   1665 		pps_intcnt = 0;
   1666 		time_status |= STA_PPSERROR;
   1667 		return;
   1668 	}
   1669 
   1670 	/*
   1671 	 * A three-stage median filter is used to help deglitch the pps
   1672 	 * frequency. The median sample becomes the frequency offset
   1673 	 * estimate; the difference between the other two samples
   1674 	 * becomes the frequency dispersion (stability) estimate.
   1675 	 */
   1676 	pps_ff[2] = pps_ff[1];
   1677 	pps_ff[1] = pps_ff[0];
   1678 	pps_ff[0] = v_usec;
   1679 	if (pps_ff[0] > pps_ff[1]) {
   1680 		if (pps_ff[1] > pps_ff[2]) {
   1681 			u_usec = pps_ff[1];		/* 0 1 2 */
   1682 			v_usec = pps_ff[0] - pps_ff[2];
   1683 		} else if (pps_ff[2] > pps_ff[0]) {
   1684 			u_usec = pps_ff[0];		/* 2 0 1 */
   1685 			v_usec = pps_ff[2] - pps_ff[1];
   1686 		} else {
   1687 			u_usec = pps_ff[2];		/* 0 2 1 */
   1688 			v_usec = pps_ff[0] - pps_ff[1];
   1689 		}
   1690 	} else {
   1691 		if (pps_ff[1] < pps_ff[2]) {
   1692 			u_usec = pps_ff[1];		/* 2 1 0 */
   1693 			v_usec = pps_ff[2] - pps_ff[0];
   1694 		} else  if (pps_ff[2] < pps_ff[0]) {
   1695 			u_usec = pps_ff[0];		/* 1 0 2 */
   1696 			v_usec = pps_ff[1] - pps_ff[2];
   1697 		} else {
   1698 			u_usec = pps_ff[2];		/* 1 2 0 */
   1699 			v_usec = pps_ff[1] - pps_ff[0];
   1700 		}
   1701 	}
   1702 
   1703 	/*
   1704 	 * Here the frequency dispersion (stability) is updated. If it
   1705 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
   1706 	 * offset is updated as well, but clamped to the tolerance. It
   1707 	 * will be processed later by the hardclock() routine.
   1708 	 */
   1709 	v_usec = (v_usec >> 1) - pps_stabil;
   1710 	if (v_usec < 0)
   1711 		pps_stabil -= -v_usec >> PPS_AVG;
   1712 	else
   1713 		pps_stabil += v_usec >> PPS_AVG;
   1714 	if (pps_stabil > MAXFREQ >> 2) {
   1715 		pps_stbcnt++;
   1716 		time_status |= STA_PPSWANDER;
   1717 		return;
   1718 	}
   1719 	if (time_status & STA_PPSFREQ) {
   1720 		if (u_usec < 0) {
   1721 			pps_freq -= -u_usec >> PPS_AVG;
   1722 			if (pps_freq < -time_tolerance)
   1723 				pps_freq = -time_tolerance;
   1724 			u_usec = -u_usec;
   1725 		} else {
   1726 			pps_freq += u_usec >> PPS_AVG;
   1727 			if (pps_freq > time_tolerance)
   1728 				pps_freq = time_tolerance;
   1729 		}
   1730 	}
   1731 
   1732 	/*
   1733 	 * Here the calibration interval is adjusted. If the maximum
   1734 	 * time difference is greater than tick / 4, reduce the interval
   1735 	 * by half. If this is not the case for four consecutive
   1736 	 * intervals, double the interval.
   1737 	 */
   1738 	if (u_usec << pps_shift > bigtick >> 2) {
   1739 		pps_intcnt = 0;
   1740 		if (pps_shift > PPS_SHIFT)
   1741 			pps_shift--;
   1742 	} else if (pps_intcnt >= 4) {
   1743 		pps_intcnt = 0;
   1744 		if (pps_shift < PPS_SHIFTMAX)
   1745 			pps_shift++;
   1746 	} else
   1747 		pps_intcnt++;
   1748 }
   1749 #endif /* PPS_SYNC */
   1750 #endif /* NTP  */
   1751 
   1752 /*
   1753  * Return information about system clocks.
   1754  */
   1755 int
   1756 sysctl_clockrate(void *where, size_t *sizep)
   1757 {
   1758 	struct clockinfo clkinfo;
   1759 
   1760 	/*
   1761 	 * Construct clockinfo structure.
   1762 	 */
   1763 	clkinfo.tick = tick;
   1764 	clkinfo.tickadj = tickadj;
   1765 	clkinfo.hz = hz;
   1766 	clkinfo.profhz = profhz;
   1767 	clkinfo.stathz = stathz ? stathz : hz;
   1768 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
   1769 }
   1770