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