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