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