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