xref: /freebsd/sys/kern/kern_clock.c (revision 797f2d22f0ccb2cbdc4395b57de8348fa6879743)
1df8bae1dSRodney W. Grimes /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
5df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
6df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
7df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
18df8bae1dSRodney W. Grimes  * 3. All advertising materials mentioning features or use of this software
19df8bae1dSRodney W. Grimes  *    must display the following acknowledgement:
20df8bae1dSRodney W. Grimes  *	This product includes software developed by the University of
21df8bae1dSRodney W. Grimes  *	California, Berkeley and its contributors.
22df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
23df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
24df8bae1dSRodney W. Grimes  *    without specific prior written permission.
25df8bae1dSRodney W. Grimes  *
26df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
37df8bae1dSRodney W. Grimes  *
38df8bae1dSRodney W. Grimes  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
39797f2d22SPoul-Henning Kamp  * $Id: kern_clock.c,v 1.8 1994/09/29 00:52:06 wollman Exp $
40df8bae1dSRodney W. Grimes  */
41df8bae1dSRodney W. Grimes 
423f31c649SGarrett Wollman /* Portions of this software are covered by the following: */
433f31c649SGarrett Wollman /******************************************************************************
443f31c649SGarrett Wollman  *                                                                            *
453f31c649SGarrett Wollman  * Copyright (c) David L. Mills 1993, 1994                                    *
463f31c649SGarrett Wollman  *                                                                            *
473f31c649SGarrett Wollman  * Permission to use, copy, modify, and distribute this software and its      *
483f31c649SGarrett Wollman  * documentation for any purpose and without fee is hereby granted, provided  *
493f31c649SGarrett Wollman  * that the above copyright notice appears in all copies and that both the    *
503f31c649SGarrett Wollman  * copyright notice and this permission notice appear in supporting           *
513f31c649SGarrett Wollman  * documentation, and that the name University of Delaware not be used in     *
523f31c649SGarrett Wollman  * advertising or publicity pertaining to distribution of the software        *
533f31c649SGarrett Wollman  * without specific, written prior permission.  The University of Delaware    *
543f31c649SGarrett Wollman  * makes no representations about the suitability this software for any       *
553f31c649SGarrett Wollman  * purpose.  It is provided "as is" without express or implied warranty.      *
563f31c649SGarrett Wollman  *                                                                            *
573f31c649SGarrett Wollman  *****************************************************************************/
583f31c649SGarrett Wollman 
59df8bae1dSRodney W. Grimes #include <sys/param.h>
60df8bae1dSRodney W. Grimes #include <sys/systm.h>
61df8bae1dSRodney W. Grimes #include <sys/dkstat.h>
62df8bae1dSRodney W. Grimes #include <sys/callout.h>
63df8bae1dSRodney W. Grimes #include <sys/kernel.h>
64df8bae1dSRodney W. Grimes #include <sys/proc.h>
65df8bae1dSRodney W. Grimes #include <sys/resourcevar.h>
66797f2d22SPoul-Henning Kamp #include <sys/signalvar.h>
673f31c649SGarrett Wollman #include <sys/timex.h>
688a129caeSDavid Greenman #include <vm/vm.h>
69797f2d22SPoul-Henning Kamp #include <sys/sysctl.h>
70df8bae1dSRodney W. Grimes 
71df8bae1dSRodney W. Grimes #include <machine/cpu.h>
723f31c649SGarrett Wollman #include <machine/clock.h>
73df8bae1dSRodney W. Grimes 
74df8bae1dSRodney W. Grimes #ifdef GPROF
75df8bae1dSRodney W. Grimes #include <sys/gmon.h>
76df8bae1dSRodney W. Grimes #endif
77df8bae1dSRodney W. Grimes 
78f23b4c91SGarrett Wollman /* Does anybody else really care about these? */
79f23b4c91SGarrett Wollman struct callout *callfree, *callout, calltodo;
80f23b4c91SGarrett Wollman int ncallout;
81f23b4c91SGarrett Wollman 
82f23b4c91SGarrett Wollman /* Some of these don't belong here, but it's easiest to concentrate them. */
83f23b4c91SGarrett Wollman long cp_time[CPUSTATES];
84f23b4c91SGarrett Wollman long dk_seek[DK_NDRIVE];
85f23b4c91SGarrett Wollman long dk_time[DK_NDRIVE];
86f23b4c91SGarrett Wollman long dk_wds[DK_NDRIVE];
87f23b4c91SGarrett Wollman long dk_wpms[DK_NDRIVE];
88f23b4c91SGarrett Wollman long dk_xfer[DK_NDRIVE];
89f23b4c91SGarrett Wollman 
90f23b4c91SGarrett Wollman int dk_busy;
91f23b4c91SGarrett Wollman int dk_ndrive = DK_NDRIVE;
92f23b4c91SGarrett Wollman 
93f23b4c91SGarrett Wollman long tk_cancc;
94f23b4c91SGarrett Wollman long tk_nin;
95f23b4c91SGarrett Wollman long tk_nout;
96f23b4c91SGarrett Wollman long tk_rawcc;
97f23b4c91SGarrett Wollman 
98df8bae1dSRodney W. Grimes /*
99df8bae1dSRodney W. Grimes  * Clock handling routines.
100df8bae1dSRodney W. Grimes  *
101df8bae1dSRodney W. Grimes  * This code is written to operate with two timers that run independently of
102df8bae1dSRodney W. Grimes  * each other.  The main clock, running hz times per second, is used to keep
103df8bae1dSRodney W. Grimes  * track of real time.  The second timer handles kernel and user profiling,
104df8bae1dSRodney W. Grimes  * and does resource use estimation.  If the second timer is programmable,
105df8bae1dSRodney W. Grimes  * it is randomized to avoid aliasing between the two clocks.  For example,
106df8bae1dSRodney W. Grimes  * the randomization prevents an adversary from always giving up the cpu
107df8bae1dSRodney W. Grimes  * just before its quantum expires.  Otherwise, it would never accumulate
108df8bae1dSRodney W. Grimes  * cpu ticks.  The mean frequency of the second timer is stathz.
109df8bae1dSRodney W. Grimes  *
110df8bae1dSRodney W. Grimes  * If no second timer exists, stathz will be zero; in this case we drive
111df8bae1dSRodney W. Grimes  * profiling and statistics off the main clock.  This WILL NOT be accurate;
112df8bae1dSRodney W. Grimes  * do not do it unless absolutely necessary.
113df8bae1dSRodney W. Grimes  *
114df8bae1dSRodney W. Grimes  * The statistics clock may (or may not) be run at a higher rate while
115df8bae1dSRodney W. Grimes  * profiling.  This profile clock runs at profhz.  We require that profhz
116df8bae1dSRodney W. Grimes  * be an integral multiple of stathz.
117df8bae1dSRodney W. Grimes  *
118df8bae1dSRodney W. Grimes  * If the statistics clock is running fast, it must be divided by the ratio
119df8bae1dSRodney W. Grimes  * profhz/stathz for statistics.  (For profiling, every tick counts.)
120df8bae1dSRodney W. Grimes  */
121df8bae1dSRodney W. Grimes 
122df8bae1dSRodney W. Grimes /*
123df8bae1dSRodney W. Grimes  * TODO:
124df8bae1dSRodney W. Grimes  *	allocate more timeout table slots when table overflows.
125df8bae1dSRodney W. Grimes  */
126df8bae1dSRodney W. Grimes 
127df8bae1dSRodney W. Grimes /*
128df8bae1dSRodney W. Grimes  * Bump a timeval by a small number of usec's.
129df8bae1dSRodney W. Grimes  */
130df8bae1dSRodney W. Grimes #define BUMPTIME(t, usec) { \
131df8bae1dSRodney W. Grimes 	register volatile struct timeval *tp = (t); \
132df8bae1dSRodney W. Grimes 	register long us; \
133df8bae1dSRodney W. Grimes  \
134df8bae1dSRodney W. Grimes 	tp->tv_usec = us = tp->tv_usec + (usec); \
135df8bae1dSRodney W. Grimes 	if (us >= 1000000) { \
136df8bae1dSRodney W. Grimes 		tp->tv_usec = us - 1000000; \
137df8bae1dSRodney W. Grimes 		tp->tv_sec++; \
138df8bae1dSRodney W. Grimes 	} \
139df8bae1dSRodney W. Grimes }
140df8bae1dSRodney W. Grimes 
141df8bae1dSRodney W. Grimes int	stathz;
142df8bae1dSRodney W. Grimes int	profhz;
143df8bae1dSRodney W. Grimes int	profprocs;
144df8bae1dSRodney W. Grimes int	ticks;
145df8bae1dSRodney W. Grimes static int psdiv, pscnt;	/* prof => stat divider */
146df8bae1dSRodney W. Grimes int	psratio;		/* ratio: prof / stat */
147df8bae1dSRodney W. Grimes 
148df8bae1dSRodney W. Grimes volatile struct	timeval time;
149df8bae1dSRodney W. Grimes volatile struct	timeval mono_time;
150df8bae1dSRodney W. Grimes 
151df8bae1dSRodney W. Grimes /*
1523f31c649SGarrett Wollman  * Phase-lock loop (PLL) definitions
1533f31c649SGarrett Wollman  *
1543f31c649SGarrett Wollman  * The following variables are read and set by the ntp_adjtime() system
1553f31c649SGarrett Wollman  * call.
1563f31c649SGarrett Wollman  *
1573f31c649SGarrett Wollman  * time_state shows the state of the system clock, with values defined
1583f31c649SGarrett Wollman  * in the timex.h header file.
1593f31c649SGarrett Wollman  *
1603f31c649SGarrett Wollman  * time_status shows the status of the system clock, with bits defined
1613f31c649SGarrett Wollman  * in the timex.h header file.
1623f31c649SGarrett Wollman  *
1633f31c649SGarrett Wollman  * time_offset is used by the PLL to adjust the system time in small
1643f31c649SGarrett Wollman  * increments.
1653f31c649SGarrett Wollman  *
1663f31c649SGarrett Wollman  * time_constant determines the bandwidth or "stiffness" of the PLL.
1673f31c649SGarrett Wollman  *
1683f31c649SGarrett Wollman  * time_tolerance determines maximum frequency error or tolerance of the
1693f31c649SGarrett Wollman  * CPU clock oscillator and is a property of the architecture; however,
1703f31c649SGarrett Wollman  * in principle it could change as result of the presence of external
1713f31c649SGarrett Wollman  * discipline signals, for instance.
1723f31c649SGarrett Wollman  *
1733f31c649SGarrett Wollman  * time_precision is usually equal to the kernel tick variable; however,
1743f31c649SGarrett Wollman  * in cases where a precision clock counter or external clock is
1753f31c649SGarrett Wollman  * available, the resolution can be much less than this and depend on
1763f31c649SGarrett Wollman  * whether the external clock is working or not.
1773f31c649SGarrett Wollman  *
1783f31c649SGarrett Wollman  * time_maxerror is initialized by a ntp_adjtime() call and increased by
1793f31c649SGarrett Wollman  * the kernel once each second to reflect the maximum error
1803f31c649SGarrett Wollman  * bound growth.
1813f31c649SGarrett Wollman  *
1823f31c649SGarrett Wollman  * time_esterror is set and read by the ntp_adjtime() call, but
1833f31c649SGarrett Wollman  * otherwise not used by the kernel.
1843f31c649SGarrett Wollman  */
1853f31c649SGarrett Wollman int time_status = STA_UNSYNC;	/* clock status bits */
1863f31c649SGarrett Wollman int time_state = TIME_OK;	/* clock state */
1873f31c649SGarrett Wollman long time_offset = 0;		/* time offset (us) */
1883f31c649SGarrett Wollman long time_constant = 0;		/* pll time constant */
1893f31c649SGarrett Wollman long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
1903f31c649SGarrett Wollman long time_precision = 1;	/* clock precision (us) */
1913f31c649SGarrett Wollman long time_maxerror = MAXPHASE;	/* maximum error (us) */
1923f31c649SGarrett Wollman long time_esterror = MAXPHASE;	/* estimated error (us) */
1933f31c649SGarrett Wollman 
1943f31c649SGarrett Wollman /*
1953f31c649SGarrett Wollman  * The following variables establish the state of the PLL and the
1963f31c649SGarrett Wollman  * residual time and frequency offset of the local clock. The scale
1973f31c649SGarrett Wollman  * factors are defined in the timex.h header file.
1983f31c649SGarrett Wollman  *
1993f31c649SGarrett Wollman  * time_phase and time_freq are the phase increment and the frequency
2003f31c649SGarrett Wollman  * increment, respectively, of the kernel time variable at each tick of
2013f31c649SGarrett Wollman  * the clock.
2023f31c649SGarrett Wollman  *
2033f31c649SGarrett Wollman  * time_freq is set via ntp_adjtime() from a value stored in a file when
2043f31c649SGarrett Wollman  * the synchronization daemon is first started. Its value is retrieved
2053f31c649SGarrett Wollman  * via ntp_adjtime() and written to the file about once per hour by the
2063f31c649SGarrett Wollman  * daemon.
2073f31c649SGarrett Wollman  *
2083f31c649SGarrett Wollman  * time_adj is the adjustment added to the value of tick at each timer
2093f31c649SGarrett Wollman  * interrupt and is recomputed at each timer interrupt.
2103f31c649SGarrett Wollman  *
2113f31c649SGarrett Wollman  * time_reftime is the second's portion of the system time on the last
2123f31c649SGarrett Wollman  * call to ntp_adjtime(). It is used to adjust the time_freq variable
2133f31c649SGarrett Wollman  * and to increase the time_maxerror as the time since last update
2143f31c649SGarrett Wollman  * increases.
2153f31c649SGarrett Wollman  */
2163f31c649SGarrett Wollman long time_phase = 0;		/* phase offset (scaled us) */
2173f31c649SGarrett Wollman long time_freq = 0;		/* frequency offset (scaled ppm) */
2183f31c649SGarrett Wollman long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
2193f31c649SGarrett Wollman long time_reftime = 0;		/* time at last adjustment (s) */
2203f31c649SGarrett Wollman 
2213f31c649SGarrett Wollman #ifdef PPS_SYNC
2223f31c649SGarrett Wollman /*
2233f31c649SGarrett Wollman  * The following variables are used only if the if the kernel PPS
2243f31c649SGarrett Wollman  * discipline code is configured (PPS_SYNC). The scale factors are
2253f31c649SGarrett Wollman  * defined in the timex.h header file.
2263f31c649SGarrett Wollman  *
2273f31c649SGarrett Wollman  * pps_time contains the time at each calibration interval, as read by
2283f31c649SGarrett Wollman  * microtime().
2293f31c649SGarrett Wollman  *
2303f31c649SGarrett Wollman  * pps_offset is the time offset produced by the time median filter
2313f31c649SGarrett Wollman  * pps_tf[], while pps_jitter is the dispersion measured by this
2323f31c649SGarrett Wollman  * filter.
2333f31c649SGarrett Wollman  *
2343f31c649SGarrett Wollman  * pps_freq is the frequency offset produced by the frequency median
2353f31c649SGarrett Wollman  * filter pps_ff[], while pps_stabil is the dispersion measured by
2363f31c649SGarrett Wollman  * this filter.
2373f31c649SGarrett Wollman  *
2383f31c649SGarrett Wollman  * pps_usec is latched from a high resolution counter or external clock
2393f31c649SGarrett Wollman  * at pps_time. Here we want the hardware counter contents only, not the
2403f31c649SGarrett Wollman  * contents plus the time_tv.usec as usual.
2413f31c649SGarrett Wollman  *
2423f31c649SGarrett Wollman  * pps_valid counts the number of seconds since the last PPS update. It
2433f31c649SGarrett Wollman  * is used as a watchdog timer to disable the PPS discipline should the
2443f31c649SGarrett Wollman  * PPS signal be lost.
2453f31c649SGarrett Wollman  *
2463f31c649SGarrett Wollman  * pps_glitch counts the number of seconds since the beginning of an
2473f31c649SGarrett Wollman  * offset burst more than tick/2 from current nominal offset. It is used
2483f31c649SGarrett Wollman  * mainly to suppress error bursts due to priority conflicts between the
2493f31c649SGarrett Wollman  * PPS interrupt and timer interrupt.
2503f31c649SGarrett Wollman  *
2513f31c649SGarrett Wollman  * pps_count counts the seconds of the calibration interval, the
2523f31c649SGarrett Wollman  * duration of which is pps_shift in powers of two.
2533f31c649SGarrett Wollman  *
2543f31c649SGarrett Wollman  * pps_intcnt counts the calibration intervals for use in the interval-
2553f31c649SGarrett Wollman  * adaptation algorithm. It's just too complicated for words.
2563f31c649SGarrett Wollman  */
2573f31c649SGarrett Wollman struct timeval pps_time;	/* kernel time at last interval */
2583f31c649SGarrett Wollman long pps_offset = 0;		/* pps time offset (us) */
2593f31c649SGarrett Wollman long pps_jitter = MAXTIME;	/* pps time dispersion (jitter) (us) */
2603f31c649SGarrett Wollman long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
2613f31c649SGarrett Wollman long pps_freq = 0;		/* frequency offset (scaled ppm) */
2623f31c649SGarrett Wollman long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
2633f31c649SGarrett Wollman long pps_ff[] = {0, 0, 0};	/* frequency offset median filter */
2643f31c649SGarrett Wollman long pps_usec = 0;		/* microsec counter at last interval */
2653f31c649SGarrett Wollman long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
2663f31c649SGarrett Wollman int pps_glitch = 0;		/* pps signal glitch counter */
2673f31c649SGarrett Wollman int pps_count = 0;		/* calibration interval counter (s) */
2683f31c649SGarrett Wollman int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
2693f31c649SGarrett Wollman int pps_intcnt = 0;		/* intervals at current duration */
2703f31c649SGarrett Wollman 
2713f31c649SGarrett Wollman /*
2723f31c649SGarrett Wollman  * PPS signal quality monitors
2733f31c649SGarrett Wollman  *
2743f31c649SGarrett Wollman  * pps_jitcnt counts the seconds that have been discarded because the
2753f31c649SGarrett Wollman  * jitter measured by the time median filter exceeds the limit MAXTIME
2763f31c649SGarrett Wollman  * (100 us).
2773f31c649SGarrett Wollman  *
2783f31c649SGarrett Wollman  * pps_calcnt counts the frequency calibration intervals, which are
2793f31c649SGarrett Wollman  * variable from 4 s to 256 s.
2803f31c649SGarrett Wollman  *
2813f31c649SGarrett Wollman  * pps_errcnt counts the calibration intervals which have been discarded
2823f31c649SGarrett Wollman  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
2833f31c649SGarrett Wollman  * calibration interval jitter exceeds two ticks.
2843f31c649SGarrett Wollman  *
2853f31c649SGarrett Wollman  * pps_stbcnt counts the calibration intervals that have been discarded
2863f31c649SGarrett Wollman  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
2873f31c649SGarrett Wollman  */
2883f31c649SGarrett Wollman long pps_jitcnt = 0;		/* jitter limit exceeded */
2893f31c649SGarrett Wollman long pps_calcnt = 0;		/* calibration intervals */
2903f31c649SGarrett Wollman long pps_errcnt = 0;		/* calibration errors */
2913f31c649SGarrett Wollman long pps_stbcnt = 0;		/* stability limit exceeded */
2923f31c649SGarrett Wollman #endif /* PPS_SYNC */
2933f31c649SGarrett Wollman 
2943f31c649SGarrett Wollman /* XXX none of this stuff works under FreeBSD */
2953f31c649SGarrett Wollman #ifdef EXT_CLOCK
2963f31c649SGarrett Wollman /*
2973f31c649SGarrett Wollman  * External clock definitions
2983f31c649SGarrett Wollman  *
2993f31c649SGarrett Wollman  * The following definitions and declarations are used only if an
3003f31c649SGarrett Wollman  * external clock (HIGHBALL or TPRO) is configured on the system.
3013f31c649SGarrett Wollman  */
3023f31c649SGarrett Wollman #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
3033f31c649SGarrett Wollman 
3043f31c649SGarrett Wollman /*
3053f31c649SGarrett Wollman  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
3063f31c649SGarrett Wollman  * interrupt and decremented once each second.
3073f31c649SGarrett Wollman  */
3083f31c649SGarrett Wollman int clock_count = 0;		/* CPU clock counter */
3093f31c649SGarrett Wollman 
3103f31c649SGarrett Wollman #ifdef HIGHBALL
3113f31c649SGarrett Wollman /*
3123f31c649SGarrett Wollman  * The clock_offset and clock_cpu variables are used by the HIGHBALL
3133f31c649SGarrett Wollman  * interface. The clock_offset variable defines the offset between
3143f31c649SGarrett Wollman  * system time and the HIGBALL counters. The clock_cpu variable contains
3153f31c649SGarrett Wollman  * the offset between the system clock and the HIGHBALL clock for use in
3163f31c649SGarrett Wollman  * disciplining the kernel time variable.
3173f31c649SGarrett Wollman  */
3183f31c649SGarrett Wollman extern struct timeval clock_offset; /* Highball clock offset */
3193f31c649SGarrett Wollman long clock_cpu = 0;		/* CPU clock adjust */
3203f31c649SGarrett Wollman #endif /* HIGHBALL */
3213f31c649SGarrett Wollman #endif /* EXT_CLOCK */
3223f31c649SGarrett Wollman 
3233f31c649SGarrett Wollman /*
3243f31c649SGarrett Wollman  * hardupdate() - local clock update
3253f31c649SGarrett Wollman  *
3263f31c649SGarrett Wollman  * This routine is called by ntp_adjtime() to update the local clock
3273f31c649SGarrett Wollman  * phase and frequency. This is used to implement an adaptive-parameter,
3283f31c649SGarrett Wollman  * first-order, type-II phase-lock loop. The code computes new time and
3293f31c649SGarrett Wollman  * frequency offsets each time it is called. The hardclock() routine
3303f31c649SGarrett Wollman  * amortizes these offsets at each tick interrupt. If the kernel PPS
3313f31c649SGarrett Wollman  * discipline code is configured (PPS_SYNC), the PPS signal itself
3323f31c649SGarrett Wollman  * determines the new time offset, instead of the calling argument.
3333f31c649SGarrett Wollman  * Presumably, calls to ntp_adjtime() occur only when the caller
3343f31c649SGarrett Wollman  * believes the local clock is valid within some bound (+-128 ms with
3353f31c649SGarrett Wollman  * NTP). If the caller's time is far different than the PPS time, an
3363f31c649SGarrett Wollman  * argument will ensue, and it's not clear who will lose.
3373f31c649SGarrett Wollman  *
3383f31c649SGarrett Wollman  * For default SHIFT_UPDATE = 12, the offset is limited to +-512 ms, the
3393f31c649SGarrett Wollman  * maximum interval between updates is 4096 s and the maximum frequency
3403f31c649SGarrett Wollman  * offset is +-31.25 ms/s.
3413f31c649SGarrett Wollman  *
3423f31c649SGarrett Wollman  * Note: splclock() is in effect.
3433f31c649SGarrett Wollman  */
3443f31c649SGarrett Wollman void
3453f31c649SGarrett Wollman hardupdate(offset)
3463f31c649SGarrett Wollman 	long offset;
3473f31c649SGarrett Wollman {
3483f31c649SGarrett Wollman 	long ltemp, mtemp;
3493f31c649SGarrett Wollman 
3503f31c649SGarrett Wollman 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
3513f31c649SGarrett Wollman 		return;
3523f31c649SGarrett Wollman 	ltemp = offset;
3533f31c649SGarrett Wollman #ifdef PPS_SYNC
3543f31c649SGarrett Wollman 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
3553f31c649SGarrett Wollman 		ltemp = pps_offset;
3563f31c649SGarrett Wollman #endif /* PPS_SYNC */
3573f31c649SGarrett Wollman 	if (ltemp > MAXPHASE)
3583f31c649SGarrett Wollman 		time_offset = MAXPHASE << SHIFT_UPDATE;
3593f31c649SGarrett Wollman 	else if (ltemp < -MAXPHASE)
3603f31c649SGarrett Wollman 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
3613f31c649SGarrett Wollman 	else
3623f31c649SGarrett Wollman 		time_offset = ltemp << SHIFT_UPDATE;
3633f31c649SGarrett Wollman 	mtemp = time.tv_sec - time_reftime;
3643f31c649SGarrett Wollman 	time_reftime = time.tv_sec;
3653f31c649SGarrett Wollman 	if (mtemp > MAXSEC)
3663f31c649SGarrett Wollman 		mtemp = 0;
3673f31c649SGarrett Wollman 
3683f31c649SGarrett Wollman 	/* ugly multiply should be replaced */
3693f31c649SGarrett Wollman 	if (ltemp < 0)
3703f31c649SGarrett Wollman 		time_freq -= (-ltemp * mtemp) >> (time_constant +
3713f31c649SGarrett Wollman 		    time_constant + SHIFT_KF - SHIFT_USEC);
3723f31c649SGarrett Wollman 	else
3733f31c649SGarrett Wollman 		time_freq += (ltemp * mtemp) >> (time_constant +
3743f31c649SGarrett Wollman 		    time_constant + SHIFT_KF - SHIFT_USEC);
3753f31c649SGarrett Wollman 	if (time_freq > time_tolerance)
3763f31c649SGarrett Wollman 		time_freq = time_tolerance;
3773f31c649SGarrett Wollman 	else if (time_freq < -time_tolerance)
3783f31c649SGarrett Wollman 		time_freq = -time_tolerance;
3793f31c649SGarrett Wollman }
3803f31c649SGarrett Wollman 
3813f31c649SGarrett Wollman 
3823f31c649SGarrett Wollman 
3833f31c649SGarrett Wollman /*
384df8bae1dSRodney W. Grimes  * Initialize clock frequencies and start both clocks running.
385df8bae1dSRodney W. Grimes  */
386df8bae1dSRodney W. Grimes void
387df8bae1dSRodney W. Grimes initclocks()
388df8bae1dSRodney W. Grimes {
389df8bae1dSRodney W. Grimes 	register int i;
390df8bae1dSRodney W. Grimes 
391df8bae1dSRodney W. Grimes 	/*
392df8bae1dSRodney W. Grimes 	 * Set divisors to 1 (normal case) and let the machine-specific
393df8bae1dSRodney W. Grimes 	 * code do its bit.
394df8bae1dSRodney W. Grimes 	 */
395df8bae1dSRodney W. Grimes 	psdiv = pscnt = 1;
396df8bae1dSRodney W. Grimes 	cpu_initclocks();
397df8bae1dSRodney W. Grimes 
398df8bae1dSRodney W. Grimes 	/*
399df8bae1dSRodney W. Grimes 	 * Compute profhz/stathz, and fix profhz if needed.
400df8bae1dSRodney W. Grimes 	 */
401df8bae1dSRodney W. Grimes 	i = stathz ? stathz : hz;
402df8bae1dSRodney W. Grimes 	if (profhz == 0)
403df8bae1dSRodney W. Grimes 		profhz = i;
404df8bae1dSRodney W. Grimes 	psratio = profhz / i;
405df8bae1dSRodney W. Grimes }
406df8bae1dSRodney W. Grimes 
407df8bae1dSRodney W. Grimes /*
408df8bae1dSRodney W. Grimes  * The real-time timer, interrupting hz times per second.
409df8bae1dSRodney W. Grimes  */
410df8bae1dSRodney W. Grimes void
411df8bae1dSRodney W. Grimes hardclock(frame)
412df8bae1dSRodney W. Grimes 	register struct clockframe *frame;
413df8bae1dSRodney W. Grimes {
414df8bae1dSRodney W. Grimes 	register struct callout *p1;
415df8bae1dSRodney W. Grimes 	register struct proc *p;
416bb56ec4aSPoul-Henning Kamp 	register int needsoft;
417df8bae1dSRodney W. Grimes 	extern int tickdelta;
418df8bae1dSRodney W. Grimes 	extern long timedelta;
419df8bae1dSRodney W. Grimes 
420df8bae1dSRodney W. Grimes 	/*
421df8bae1dSRodney W. Grimes 	 * Update real-time timeout queue.
422df8bae1dSRodney W. Grimes 	 * At front of queue are some number of events which are ``due''.
423df8bae1dSRodney W. Grimes 	 * The time to these is <= 0 and if negative represents the
424df8bae1dSRodney W. Grimes 	 * number of ticks which have passed since it was supposed to happen.
425df8bae1dSRodney W. Grimes 	 * The rest of the q elements (times > 0) are events yet to happen,
426df8bae1dSRodney W. Grimes 	 * where the time for each is given as a delta from the previous.
427df8bae1dSRodney W. Grimes 	 * Decrementing just the first of these serves to decrement the time
428df8bae1dSRodney W. Grimes 	 * to all events.
429df8bae1dSRodney W. Grimes 	 */
430df8bae1dSRodney W. Grimes 	needsoft = 0;
431df8bae1dSRodney W. Grimes 	for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
432df8bae1dSRodney W. Grimes 		if (--p1->c_time > 0)
433df8bae1dSRodney W. Grimes 			break;
434df8bae1dSRodney W. Grimes 		needsoft = 1;
435df8bae1dSRodney W. Grimes 		if (p1->c_time == 0)
436df8bae1dSRodney W. Grimes 			break;
437df8bae1dSRodney W. Grimes 	}
438df8bae1dSRodney W. Grimes 
439df8bae1dSRodney W. Grimes 	p = curproc;
440df8bae1dSRodney W. Grimes 	if (p) {
441df8bae1dSRodney W. Grimes 		register struct pstats *pstats;
442df8bae1dSRodney W. Grimes 
443df8bae1dSRodney W. Grimes 		/*
444df8bae1dSRodney W. Grimes 		 * Run current process's virtual and profile time, as needed.
445df8bae1dSRodney W. Grimes 		 */
446df8bae1dSRodney W. Grimes 		pstats = p->p_stats;
447df8bae1dSRodney W. Grimes 		if (CLKF_USERMODE(frame) &&
448df8bae1dSRodney W. Grimes 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
449df8bae1dSRodney W. Grimes 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
450df8bae1dSRodney W. Grimes 			psignal(p, SIGVTALRM);
451df8bae1dSRodney W. Grimes 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
452df8bae1dSRodney W. Grimes 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
453df8bae1dSRodney W. Grimes 			psignal(p, SIGPROF);
454df8bae1dSRodney W. Grimes 	}
455df8bae1dSRodney W. Grimes 
456df8bae1dSRodney W. Grimes 	/*
457df8bae1dSRodney W. Grimes 	 * If no separate statistics clock is available, run it from here.
458df8bae1dSRodney W. Grimes 	 */
459df8bae1dSRodney W. Grimes 	if (stathz == 0)
460df8bae1dSRodney W. Grimes 		statclock(frame);
461df8bae1dSRodney W. Grimes 
462df8bae1dSRodney W. Grimes 	/*
4633f31c649SGarrett Wollman 	 * Increment the time-of-day.
464df8bae1dSRodney W. Grimes 	 */
465df8bae1dSRodney W. Grimes 	ticks++;
4663f31c649SGarrett Wollman 	{
4673f31c649SGarrett Wollman 		int time_update;
4683f31c649SGarrett Wollman 		struct timeval newtime = time;
4693f31c649SGarrett Wollman 		long ltemp;
4703f31c649SGarrett Wollman 
4713f31c649SGarrett Wollman 		if (timedelta == 0) {
4723f31c649SGarrett Wollman 			time_update = tick;
4733f31c649SGarrett Wollman 		} else {
4743f31c649SGarrett Wollman 			time_update = tick + tickdelta;
475df8bae1dSRodney W. Grimes 			timedelta -= tickdelta;
476df8bae1dSRodney W. Grimes 		}
4773f31c649SGarrett Wollman 		BUMPTIME(&mono_time, time_update);
4783f31c649SGarrett Wollman 
4793f31c649SGarrett Wollman 		/*
4803f31c649SGarrett Wollman 		 * Compute the phase adjustment. If the low-order bits
4813f31c649SGarrett Wollman 		 * (time_phase) of the update overflow, bump the high-order bits
4823f31c649SGarrett Wollman 		 * (time_update).
4833f31c649SGarrett Wollman 		 */
4843f31c649SGarrett Wollman 		time_phase += time_adj;
4853f31c649SGarrett Wollman 		if (time_phase <= -FINEUSEC) {
4863f31c649SGarrett Wollman 		  ltemp = -time_phase >> SHIFT_SCALE;
4873f31c649SGarrett Wollman 		  time_phase += ltemp << SHIFT_SCALE;
4883f31c649SGarrett Wollman 		  time_update -= ltemp;
4893f31c649SGarrett Wollman 		}
4903f31c649SGarrett Wollman 		else if (time_phase >= FINEUSEC) {
4913f31c649SGarrett Wollman 		  ltemp = time_phase >> SHIFT_SCALE;
4923f31c649SGarrett Wollman 		  time_phase -= ltemp << SHIFT_SCALE;
4933f31c649SGarrett Wollman 		  time_update += ltemp;
4943f31c649SGarrett Wollman 		}
4953f31c649SGarrett Wollman 
4963f31c649SGarrett Wollman 		newtime.tv_usec += time_update;
4973f31c649SGarrett Wollman 		/*
4983f31c649SGarrett Wollman 		 * On rollover of the second the phase adjustment to be used for
4993f31c649SGarrett Wollman 		 * the next second is calculated. Also, the maximum error is
5003f31c649SGarrett Wollman 		 * increased by the tolerance. If the PPS frequency discipline
5013f31c649SGarrett Wollman 		 * code is present, the phase is increased to compensate for the
5023f31c649SGarrett Wollman 		 * CPU clock oscillator frequency error.
5033f31c649SGarrett Wollman 		 *
5043f31c649SGarrett Wollman 		 * With SHIFT_SCALE = 23, the maximum frequency adjustment is
5053f31c649SGarrett Wollman 		 * +-256 us per tick, or 25.6 ms/s at a clock frequency of 100
5063f31c649SGarrett Wollman 		 * Hz. The time contribution is shifted right a minimum of two
5073f31c649SGarrett Wollman 		 * bits, while the frequency contribution is a right shift.
5083f31c649SGarrett Wollman 		 * Thus, overflow is prevented if the frequency contribution is
5093f31c649SGarrett Wollman 		 * limited to half the maximum or 15.625 ms/s.
5103f31c649SGarrett Wollman 		 */
5113f31c649SGarrett Wollman 		if (newtime.tv_usec >= 1000000) {
5123f31c649SGarrett Wollman 		  newtime.tv_usec -= 1000000;
5133f31c649SGarrett Wollman 		  newtime.tv_sec++;
5143f31c649SGarrett Wollman 		  time_maxerror += time_tolerance >> SHIFT_USEC;
5153f31c649SGarrett Wollman 		  if (time_offset < 0) {
5163f31c649SGarrett Wollman 		    ltemp = -time_offset >>
5173f31c649SGarrett Wollman 		      (SHIFT_KG + time_constant);
5183f31c649SGarrett Wollman 		    time_offset += ltemp;
5193f31c649SGarrett Wollman 		    time_adj = -ltemp <<
5203f31c649SGarrett Wollman 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
5213f31c649SGarrett Wollman 		  } else {
5223f31c649SGarrett Wollman 		    ltemp = time_offset >>
5233f31c649SGarrett Wollman 		      (SHIFT_KG + time_constant);
5243f31c649SGarrett Wollman 		    time_offset -= ltemp;
5253f31c649SGarrett Wollman 		    time_adj = ltemp <<
5263f31c649SGarrett Wollman 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
5273f31c649SGarrett Wollman 		  }
5283f31c649SGarrett Wollman #ifdef PPS_SYNC
5293f31c649SGarrett Wollman 		  /*
5303f31c649SGarrett Wollman 		   * Gnaw on the watchdog counter and update the frequency
5313f31c649SGarrett Wollman 		   * computed by the pll and the PPS signal.
5323f31c649SGarrett Wollman 		   */
5333f31c649SGarrett Wollman 		  pps_valid++;
5343f31c649SGarrett Wollman 		  if (pps_valid == PPS_VALID) {
5353f31c649SGarrett Wollman 		    pps_jitter = MAXTIME;
5363f31c649SGarrett Wollman 		    pps_stabil = MAXFREQ;
5373f31c649SGarrett Wollman 		    time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
5383f31c649SGarrett Wollman 				     STA_PPSWANDER | STA_PPSERROR);
5393f31c649SGarrett Wollman 		  }
5403f31c649SGarrett Wollman 		  ltemp = time_freq + pps_freq;
5413f31c649SGarrett Wollman #else
5423f31c649SGarrett Wollman 		  ltemp = time_freq;
5433f31c649SGarrett Wollman #endif /* PPS_SYNC */
5443f31c649SGarrett Wollman 		  if (ltemp < 0)
5453f31c649SGarrett Wollman 		    time_adj -= -ltemp >>
5463f31c649SGarrett Wollman 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
5473f31c649SGarrett Wollman 		  else
5483f31c649SGarrett Wollman 		    time_adj += ltemp >>
5493f31c649SGarrett Wollman 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
5503f31c649SGarrett Wollman 
5513f31c649SGarrett Wollman 		  /*
5523f31c649SGarrett Wollman 		   * When the CPU clock oscillator frequency is not a
5533f31c649SGarrett Wollman 		   * power of two in Hz, the SHIFT_HZ is only an
5543f31c649SGarrett Wollman 		   * approximate scale factor. In the SunOS kernel, this
5553f31c649SGarrett Wollman 		   * results in a PLL gain factor of 1/1.28 = 0.78 what it
5563f31c649SGarrett Wollman 		   * should be. In the following code the overall gain is
5573f31c649SGarrett Wollman 		   * increased by a factor of 1.25, which results in a
5583f31c649SGarrett Wollman 		   * residual error less than 3 percent.
5593f31c649SGarrett Wollman 		   */
5603f31c649SGarrett Wollman 		  /* Same thing applies for FreeBSD --GAW */
5613f31c649SGarrett Wollman 		  if (hz == 100) {
5623f31c649SGarrett Wollman 		    if (time_adj < 0)
5633f31c649SGarrett Wollman 		      time_adj -= -time_adj >> 2;
5643f31c649SGarrett Wollman 		    else
5653f31c649SGarrett Wollman 		      time_adj += time_adj >> 2;
5663f31c649SGarrett Wollman 		  }
5673f31c649SGarrett Wollman 
5683f31c649SGarrett Wollman 		  /* XXX - this is really bogus, but can't be fixed until
5693f31c649SGarrett Wollman 		     xntpd's idea of the system clock is fixed to know how
5703f31c649SGarrett Wollman 		     the user wants leap seconds handled; in the mean time,
5713f31c649SGarrett Wollman 		     we assume that users of NTP are running without proper
5723f31c649SGarrett Wollman 		     leap second support (this is now the default anyway) */
5733f31c649SGarrett Wollman 		  /*
5743f31c649SGarrett Wollman 		   * Leap second processing. If in leap-insert state at
5753f31c649SGarrett Wollman 		   * the end of the day, the system clock is set back one
5763f31c649SGarrett Wollman 		   * second; if in leap-delete state, the system clock is
5773f31c649SGarrett Wollman 		   * set ahead one second. The microtime() routine or
5783f31c649SGarrett Wollman 		   * external clock driver will insure that reported time
5793f31c649SGarrett Wollman 		   * is always monotonic. The ugly divides should be
5803f31c649SGarrett Wollman 		   * replaced.
5813f31c649SGarrett Wollman 		   */
5823f31c649SGarrett Wollman 		  switch (time_state) {
5833f31c649SGarrett Wollman 
5843f31c649SGarrett Wollman 		  case TIME_OK:
5853f31c649SGarrett Wollman 		    if (time_status & STA_INS)
5863f31c649SGarrett Wollman 		      time_state = TIME_INS;
5873f31c649SGarrett Wollman 		    else if (time_status & STA_DEL)
5883f31c649SGarrett Wollman 		      time_state = TIME_DEL;
5893f31c649SGarrett Wollman 		    break;
5903f31c649SGarrett Wollman 
5913f31c649SGarrett Wollman 		  case TIME_INS:
5923f31c649SGarrett Wollman 		    if (newtime.tv_sec % 86400 == 0) {
5933f31c649SGarrett Wollman 		      newtime.tv_sec--;
5943f31c649SGarrett Wollman 		      time_state = TIME_OOP;
5953f31c649SGarrett Wollman 		    }
5963f31c649SGarrett Wollman 		    break;
5973f31c649SGarrett Wollman 
5983f31c649SGarrett Wollman 		  case TIME_DEL:
5993f31c649SGarrett Wollman 		    if ((newtime.tv_sec + 1) % 86400 == 0) {
6003f31c649SGarrett Wollman 		      newtime.tv_sec++;
6013f31c649SGarrett Wollman 		      time_state = TIME_WAIT;
6023f31c649SGarrett Wollman 		    }
6033f31c649SGarrett Wollman 		    break;
6043f31c649SGarrett Wollman 
6053f31c649SGarrett Wollman 		  case TIME_OOP:
6063f31c649SGarrett Wollman 		    time_state = TIME_WAIT;
6073f31c649SGarrett Wollman 		    break;
6083f31c649SGarrett Wollman 
6093f31c649SGarrett Wollman 		  case TIME_WAIT:
6103f31c649SGarrett Wollman 		    if (!(time_status & (STA_INS | STA_DEL)))
6113f31c649SGarrett Wollman 		      time_state = TIME_OK;
6123f31c649SGarrett Wollman 		  }
6133f31c649SGarrett Wollman 		}
6143f31c649SGarrett Wollman 		CPU_CLOCKUPDATE(&time, &newtime);
6153f31c649SGarrett Wollman 	}
616df8bae1dSRodney W. Grimes 
617df8bae1dSRodney W. Grimes 	/*
618df8bae1dSRodney W. Grimes 	 * Process callouts at a very low cpu priority, so we don't keep the
619df8bae1dSRodney W. Grimes 	 * relatively high clock interrupt priority any longer than necessary.
620df8bae1dSRodney W. Grimes 	 */
621df8bae1dSRodney W. Grimes 	if (needsoft) {
622df8bae1dSRodney W. Grimes 		if (CLKF_BASEPRI(frame)) {
623df8bae1dSRodney W. Grimes 			/*
624df8bae1dSRodney W. Grimes 			 * Save the overhead of a software interrupt;
625df8bae1dSRodney W. Grimes 			 * it will happen as soon as we return, so do it now.
626df8bae1dSRodney W. Grimes 			 */
627df8bae1dSRodney W. Grimes 			(void)splsoftclock();
628df8bae1dSRodney W. Grimes 			softclock();
629df8bae1dSRodney W. Grimes 		} else
630df8bae1dSRodney W. Grimes 			setsoftclock();
631df8bae1dSRodney W. Grimes 	}
632df8bae1dSRodney W. Grimes }
633df8bae1dSRodney W. Grimes 
634df8bae1dSRodney W. Grimes /*
635df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
636df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
637df8bae1dSRodney W. Grimes  */
638df8bae1dSRodney W. Grimes /*ARGSUSED*/
639df8bae1dSRodney W. Grimes void
640df8bae1dSRodney W. Grimes softclock()
641df8bae1dSRodney W. Grimes {
642df8bae1dSRodney W. Grimes 	register struct callout *c;
643df8bae1dSRodney W. Grimes 	register void *arg;
644df8bae1dSRodney W. Grimes 	register void (*func) __P((void *));
645df8bae1dSRodney W. Grimes 	register int s;
646df8bae1dSRodney W. Grimes 
647df8bae1dSRodney W. Grimes 	s = splhigh();
648df8bae1dSRodney W. Grimes 	while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
649df8bae1dSRodney W. Grimes 		func = c->c_func;
650df8bae1dSRodney W. Grimes 		arg = c->c_arg;
651df8bae1dSRodney W. Grimes 		calltodo.c_next = c->c_next;
652df8bae1dSRodney W. Grimes 		c->c_next = callfree;
653df8bae1dSRodney W. Grimes 		callfree = c;
654df8bae1dSRodney W. Grimes 		splx(s);
655df8bae1dSRodney W. Grimes 		(*func)(arg);
656df8bae1dSRodney W. Grimes 		(void) splhigh();
657df8bae1dSRodney W. Grimes 	}
658df8bae1dSRodney W. Grimes 	splx(s);
659df8bae1dSRodney W. Grimes }
660df8bae1dSRodney W. Grimes 
661df8bae1dSRodney W. Grimes /*
662df8bae1dSRodney W. Grimes  * timeout --
663df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
664df8bae1dSRodney W. Grimes  *
665df8bae1dSRodney W. Grimes  * untimeout --
666df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
667df8bae1dSRodney W. Grimes  *
668df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
669df8bae1dSRodney W. Grimes  *	implementation differs from that one in that no identification
670df8bae1dSRodney W. Grimes  *	value is returned from timeout, rather, the original arguments
671df8bae1dSRodney W. Grimes  *	to timeout are used to identify entries for untimeout.
672df8bae1dSRodney W. Grimes  */
673df8bae1dSRodney W. Grimes void
674df8bae1dSRodney W. Grimes timeout(ftn, arg, ticks)
675f23b4c91SGarrett Wollman 	timeout_t ftn;
676df8bae1dSRodney W. Grimes 	void *arg;
677df8bae1dSRodney W. Grimes 	register int ticks;
678df8bae1dSRodney W. Grimes {
679df8bae1dSRodney W. Grimes 	register struct callout *new, *p, *t;
680df8bae1dSRodney W. Grimes 	register int s;
681df8bae1dSRodney W. Grimes 
682df8bae1dSRodney W. Grimes 	if (ticks <= 0)
683df8bae1dSRodney W. Grimes 		ticks = 1;
684df8bae1dSRodney W. Grimes 
685df8bae1dSRodney W. Grimes 	/* Lock out the clock. */
686df8bae1dSRodney W. Grimes 	s = splhigh();
687df8bae1dSRodney W. Grimes 
688df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
689df8bae1dSRodney W. Grimes 	if (callfree == NULL)
690df8bae1dSRodney W. Grimes 		panic("timeout table full");
691df8bae1dSRodney W. Grimes 	new = callfree;
692df8bae1dSRodney W. Grimes 	callfree = new->c_next;
693df8bae1dSRodney W. Grimes 	new->c_arg = arg;
694df8bae1dSRodney W. Grimes 	new->c_func = ftn;
695df8bae1dSRodney W. Grimes 
696df8bae1dSRodney W. Grimes 	/*
697df8bae1dSRodney W. Grimes 	 * The time for each event is stored as a difference from the time
698df8bae1dSRodney W. Grimes 	 * of the previous event on the queue.  Walk the queue, correcting
699df8bae1dSRodney W. Grimes 	 * the ticks argument for queue entries passed.  Correct the ticks
700df8bae1dSRodney W. Grimes 	 * value for the queue entry immediately after the insertion point
701df8bae1dSRodney W. Grimes 	 * as well.  Watch out for negative c_time values; these represent
702df8bae1dSRodney W. Grimes 	 * overdue events.
703df8bae1dSRodney W. Grimes 	 */
704df8bae1dSRodney W. Grimes 	for (p = &calltodo;
705df8bae1dSRodney W. Grimes 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
706df8bae1dSRodney W. Grimes 		if (t->c_time > 0)
707df8bae1dSRodney W. Grimes 			ticks -= t->c_time;
708df8bae1dSRodney W. Grimes 	new->c_time = ticks;
709df8bae1dSRodney W. Grimes 	if (t != NULL)
710df8bae1dSRodney W. Grimes 		t->c_time -= ticks;
711df8bae1dSRodney W. Grimes 
712df8bae1dSRodney W. Grimes 	/* Insert the new entry into the queue. */
713df8bae1dSRodney W. Grimes 	p->c_next = new;
714df8bae1dSRodney W. Grimes 	new->c_next = t;
715df8bae1dSRodney W. Grimes 	splx(s);
716df8bae1dSRodney W. Grimes }
717df8bae1dSRodney W. Grimes 
718df8bae1dSRodney W. Grimes void
719df8bae1dSRodney W. Grimes untimeout(ftn, arg)
720f23b4c91SGarrett Wollman 	timeout_t ftn;
721df8bae1dSRodney W. Grimes 	void *arg;
722df8bae1dSRodney W. Grimes {
723df8bae1dSRodney W. Grimes 	register struct callout *p, *t;
724df8bae1dSRodney W. Grimes 	register int s;
725df8bae1dSRodney W. Grimes 
726df8bae1dSRodney W. Grimes 	s = splhigh();
727df8bae1dSRodney W. Grimes 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
728df8bae1dSRodney W. Grimes 		if (t->c_func == ftn && t->c_arg == arg) {
729df8bae1dSRodney W. Grimes 			/* Increment next entry's tick count. */
730df8bae1dSRodney W. Grimes 			if (t->c_next && t->c_time > 0)
731df8bae1dSRodney W. Grimes 				t->c_next->c_time += t->c_time;
732df8bae1dSRodney W. Grimes 
733df8bae1dSRodney W. Grimes 			/* Move entry from callout queue to callfree queue. */
734df8bae1dSRodney W. Grimes 			p->c_next = t->c_next;
735df8bae1dSRodney W. Grimes 			t->c_next = callfree;
736df8bae1dSRodney W. Grimes 			callfree = t;
737df8bae1dSRodney W. Grimes 			break;
738df8bae1dSRodney W. Grimes 		}
739df8bae1dSRodney W. Grimes 	splx(s);
740df8bae1dSRodney W. Grimes }
741df8bae1dSRodney W. Grimes 
742df8bae1dSRodney W. Grimes /*
743df8bae1dSRodney W. Grimes  * Compute number of hz until specified time.  Used to
744df8bae1dSRodney W. Grimes  * compute third argument to timeout() from an absolute time.
745df8bae1dSRodney W. Grimes  */
746df8bae1dSRodney W. Grimes int
747df8bae1dSRodney W. Grimes hzto(tv)
748df8bae1dSRodney W. Grimes 	struct timeval *tv;
749df8bae1dSRodney W. Grimes {
750df8bae1dSRodney W. Grimes 	register long ticks, sec;
751df8bae1dSRodney W. Grimes 	int s;
752df8bae1dSRodney W. Grimes 
753df8bae1dSRodney W. Grimes 	/*
754df8bae1dSRodney W. Grimes 	 * If number of milliseconds will fit in 32 bit arithmetic,
755df8bae1dSRodney W. Grimes 	 * then compute number of milliseconds to time and scale to
756df8bae1dSRodney W. Grimes 	 * ticks.  Otherwise just compute number of hz in time, rounding
757df8bae1dSRodney W. Grimes 	 * times greater than representible to maximum value.
758df8bae1dSRodney W. Grimes 	 *
759df8bae1dSRodney W. Grimes 	 * Delta times less than 25 days can be computed ``exactly''.
760df8bae1dSRodney W. Grimes 	 * Maximum value for any timeout in 10ms ticks is 250 days.
761df8bae1dSRodney W. Grimes 	 */
762df8bae1dSRodney W. Grimes 	s = splhigh();
763df8bae1dSRodney W. Grimes 	sec = tv->tv_sec - time.tv_sec;
764df8bae1dSRodney W. Grimes 	if (sec <= 0x7fffffff / 1000 - 1000)
765df8bae1dSRodney W. Grimes 		ticks = ((tv->tv_sec - time.tv_sec) * 1000 +
766df8bae1dSRodney W. Grimes 			(tv->tv_usec - time.tv_usec) / 1000) / (tick / 1000);
767df8bae1dSRodney W. Grimes 	else if (sec <= 0x7fffffff / hz)
768df8bae1dSRodney W. Grimes 		ticks = sec * hz;
769df8bae1dSRodney W. Grimes 	else
770df8bae1dSRodney W. Grimes 		ticks = 0x7fffffff;
771df8bae1dSRodney W. Grimes 	splx(s);
772df8bae1dSRodney W. Grimes 	return (ticks);
773df8bae1dSRodney W. Grimes }
774df8bae1dSRodney W. Grimes 
775df8bae1dSRodney W. Grimes /*
776df8bae1dSRodney W. Grimes  * Start profiling on a process.
777df8bae1dSRodney W. Grimes  *
778df8bae1dSRodney W. Grimes  * Kernel profiling passes proc0 which never exits and hence
779df8bae1dSRodney W. Grimes  * keeps the profile clock running constantly.
780df8bae1dSRodney W. Grimes  */
781df8bae1dSRodney W. Grimes void
782df8bae1dSRodney W. Grimes startprofclock(p)
783df8bae1dSRodney W. Grimes 	register struct proc *p;
784df8bae1dSRodney W. Grimes {
785df8bae1dSRodney W. Grimes 	int s;
786df8bae1dSRodney W. Grimes 
787df8bae1dSRodney W. Grimes 	if ((p->p_flag & P_PROFIL) == 0) {
788df8bae1dSRodney W. Grimes 		p->p_flag |= P_PROFIL;
789df8bae1dSRodney W. Grimes 		if (++profprocs == 1 && stathz != 0) {
790df8bae1dSRodney W. Grimes 			s = splstatclock();
791df8bae1dSRodney W. Grimes 			psdiv = pscnt = psratio;
792df8bae1dSRodney W. Grimes 			setstatclockrate(profhz);
793df8bae1dSRodney W. Grimes 			splx(s);
794df8bae1dSRodney W. Grimes 		}
795df8bae1dSRodney W. Grimes 	}
796df8bae1dSRodney W. Grimes }
797df8bae1dSRodney W. Grimes 
798df8bae1dSRodney W. Grimes /*
799df8bae1dSRodney W. Grimes  * Stop profiling on a process.
800df8bae1dSRodney W. Grimes  */
801df8bae1dSRodney W. Grimes void
802df8bae1dSRodney W. Grimes stopprofclock(p)
803df8bae1dSRodney W. Grimes 	register struct proc *p;
804df8bae1dSRodney W. Grimes {
805df8bae1dSRodney W. Grimes 	int s;
806df8bae1dSRodney W. Grimes 
807df8bae1dSRodney W. Grimes 	if (p->p_flag & P_PROFIL) {
808df8bae1dSRodney W. Grimes 		p->p_flag &= ~P_PROFIL;
809df8bae1dSRodney W. Grimes 		if (--profprocs == 0 && stathz != 0) {
810df8bae1dSRodney W. Grimes 			s = splstatclock();
811df8bae1dSRodney W. Grimes 			psdiv = pscnt = 1;
812df8bae1dSRodney W. Grimes 			setstatclockrate(stathz);
813df8bae1dSRodney W. Grimes 			splx(s);
814df8bae1dSRodney W. Grimes 		}
815df8bae1dSRodney W. Grimes 	}
816df8bae1dSRodney W. Grimes }
817df8bae1dSRodney W. Grimes 
818df8bae1dSRodney W. Grimes /*
819df8bae1dSRodney W. Grimes  * Statistics clock.  Grab profile sample, and if divider reaches 0,
820df8bae1dSRodney W. Grimes  * do process and kernel statistics.
821df8bae1dSRodney W. Grimes  */
822df8bae1dSRodney W. Grimes void
823df8bae1dSRodney W. Grimes statclock(frame)
824df8bae1dSRodney W. Grimes 	register struct clockframe *frame;
825df8bae1dSRodney W. Grimes {
826df8bae1dSRodney W. Grimes #ifdef GPROF
827df8bae1dSRodney W. Grimes 	register struct gmonparam *g;
828df8bae1dSRodney W. Grimes #endif
8298a129caeSDavid Greenman 	register struct proc *p = curproc;
830df8bae1dSRodney W. Grimes 	register int i;
831df8bae1dSRodney W. Grimes 
8328a129caeSDavid Greenman 	if (p) {
8338a129caeSDavid Greenman 		struct pstats *pstats;
8348a129caeSDavid Greenman 		struct rusage *ru;
8358a129caeSDavid Greenman 		struct vmspace *vm;
8368a129caeSDavid Greenman 
8378a129caeSDavid Greenman 		/* bump the resource usage of integral space use */
8388a129caeSDavid Greenman 		if ((pstats = p->p_stats) && (ru = &pstats->p_ru) && (vm = p->p_vmspace)) {
8398a129caeSDavid Greenman 			ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024;
8408a129caeSDavid Greenman 			ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024;
8418a129caeSDavid Greenman 			ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024;
8428a129caeSDavid Greenman 			if ((vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024) >
8438a129caeSDavid Greenman 			    ru->ru_maxrss) {
8448a129caeSDavid Greenman 				ru->ru_maxrss =
8458a129caeSDavid Greenman 				    vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024;
8468a129caeSDavid Greenman 			}
8478a129caeSDavid Greenman         	}
8488a129caeSDavid Greenman 	}
8498a129caeSDavid Greenman 
850df8bae1dSRodney W. Grimes 	if (CLKF_USERMODE(frame)) {
851df8bae1dSRodney W. Grimes 		if (p->p_flag & P_PROFIL)
852df8bae1dSRodney W. Grimes 			addupc_intr(p, CLKF_PC(frame), 1);
853df8bae1dSRodney W. Grimes 		if (--pscnt > 0)
854df8bae1dSRodney W. Grimes 			return;
855df8bae1dSRodney W. Grimes 		/*
856df8bae1dSRodney W. Grimes 		 * Came from user mode; CPU was in user state.
857df8bae1dSRodney W. Grimes 		 * If this process is being profiled record the tick.
858df8bae1dSRodney W. Grimes 		 */
859df8bae1dSRodney W. Grimes 		p->p_uticks++;
860df8bae1dSRodney W. Grimes 		if (p->p_nice > NZERO)
861df8bae1dSRodney W. Grimes 			cp_time[CP_NICE]++;
862df8bae1dSRodney W. Grimes 		else
863df8bae1dSRodney W. Grimes 			cp_time[CP_USER]++;
864df8bae1dSRodney W. Grimes 	} else {
865df8bae1dSRodney W. Grimes #ifdef GPROF
866df8bae1dSRodney W. Grimes 		/*
867df8bae1dSRodney W. Grimes 		 * Kernel statistics are just like addupc_intr, only easier.
868df8bae1dSRodney W. Grimes 		 */
869df8bae1dSRodney W. Grimes 		g = &_gmonparam;
870df8bae1dSRodney W. Grimes 		if (g->state == GMON_PROF_ON) {
871df8bae1dSRodney W. Grimes 			i = CLKF_PC(frame) - g->lowpc;
872df8bae1dSRodney W. Grimes 			if (i < g->textsize) {
873df8bae1dSRodney W. Grimes 				i /= HISTFRACTION * sizeof(*g->kcount);
874df8bae1dSRodney W. Grimes 				g->kcount[i]++;
875df8bae1dSRodney W. Grimes 			}
876df8bae1dSRodney W. Grimes 		}
877df8bae1dSRodney W. Grimes #endif
878df8bae1dSRodney W. Grimes 		if (--pscnt > 0)
879df8bae1dSRodney W. Grimes 			return;
880df8bae1dSRodney W. Grimes 		/*
881df8bae1dSRodney W. Grimes 		 * Came from kernel mode, so we were:
882df8bae1dSRodney W. Grimes 		 * - handling an interrupt,
883df8bae1dSRodney W. Grimes 		 * - doing syscall or trap work on behalf of the current
884df8bae1dSRodney W. Grimes 		 *   user process, or
885df8bae1dSRodney W. Grimes 		 * - spinning in the idle loop.
886df8bae1dSRodney W. Grimes 		 * Whichever it is, charge the time as appropriate.
887df8bae1dSRodney W. Grimes 		 * Note that we charge interrupts to the current process,
888df8bae1dSRodney W. Grimes 		 * regardless of whether they are ``for'' that process,
889df8bae1dSRodney W. Grimes 		 * so that we know how much of its real time was spent
890df8bae1dSRodney W. Grimes 		 * in ``non-process'' (i.e., interrupt) work.
891df8bae1dSRodney W. Grimes 		 */
892df8bae1dSRodney W. Grimes 		if (CLKF_INTR(frame)) {
893df8bae1dSRodney W. Grimes 			if (p != NULL)
894df8bae1dSRodney W. Grimes 				p->p_iticks++;
895df8bae1dSRodney W. Grimes 			cp_time[CP_INTR]++;
896df8bae1dSRodney W. Grimes 		} else if (p != NULL) {
897df8bae1dSRodney W. Grimes 			p->p_sticks++;
898df8bae1dSRodney W. Grimes 			cp_time[CP_SYS]++;
899df8bae1dSRodney W. Grimes 		} else
900df8bae1dSRodney W. Grimes 			cp_time[CP_IDLE]++;
901df8bae1dSRodney W. Grimes 	}
902df8bae1dSRodney W. Grimes 	pscnt = psdiv;
903df8bae1dSRodney W. Grimes 
904df8bae1dSRodney W. Grimes 	/*
905df8bae1dSRodney W. Grimes 	 * We maintain statistics shown by user-level statistics
906df8bae1dSRodney W. Grimes 	 * programs:  the amount of time in each cpu state, and
907df8bae1dSRodney W. Grimes 	 * the amount of time each of DK_NDRIVE ``drives'' is busy.
908df8bae1dSRodney W. Grimes 	 *
909df8bae1dSRodney W. Grimes 	 * XXX	should either run linked list of drives, or (better)
910df8bae1dSRodney W. Grimes 	 *	grab timestamps in the start & done code.
911df8bae1dSRodney W. Grimes 	 */
912df8bae1dSRodney W. Grimes 	for (i = 0; i < DK_NDRIVE; i++)
913df8bae1dSRodney W. Grimes 		if (dk_busy & (1 << i))
914df8bae1dSRodney W. Grimes 			dk_time[i]++;
915df8bae1dSRodney W. Grimes 
916df8bae1dSRodney W. Grimes 	/*
917df8bae1dSRodney W. Grimes 	 * We adjust the priority of the current process.  The priority of
918df8bae1dSRodney W. Grimes 	 * a process gets worse as it accumulates CPU time.  The cpu usage
919df8bae1dSRodney W. Grimes 	 * estimator (p_estcpu) is increased here.  The formula for computing
920df8bae1dSRodney W. Grimes 	 * priorities (in kern_synch.c) will compute a different value each
921df8bae1dSRodney W. Grimes 	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
922df8bae1dSRodney W. Grimes 	 * quite quickly when the process is running (linearly), and decays
923df8bae1dSRodney W. Grimes 	 * away exponentially, at a rate which is proportionally slower when
924df8bae1dSRodney W. Grimes 	 * the system is busy.  The basic principal is that the system will
925df8bae1dSRodney W. Grimes 	 * 90% forget that the process used a lot of CPU time in 5 * loadav
926df8bae1dSRodney W. Grimes 	 * seconds.  This causes the system to favor processes which haven't
927df8bae1dSRodney W. Grimes 	 * run much recently, and to round-robin among other processes.
928df8bae1dSRodney W. Grimes 	 */
929df8bae1dSRodney W. Grimes 	if (p != NULL) {
930df8bae1dSRodney W. Grimes 		p->p_cpticks++;
931df8bae1dSRodney W. Grimes 		if (++p->p_estcpu == 0)
932df8bae1dSRodney W. Grimes 			p->p_estcpu--;
933df8bae1dSRodney W. Grimes 		if ((p->p_estcpu & 3) == 0) {
934df8bae1dSRodney W. Grimes 			resetpriority(p);
935df8bae1dSRodney W. Grimes 			if (p->p_priority >= PUSER)
936df8bae1dSRodney W. Grimes 				p->p_priority = p->p_usrpri;
937df8bae1dSRodney W. Grimes 		}
938df8bae1dSRodney W. Grimes 	}
939df8bae1dSRodney W. Grimes }
940df8bae1dSRodney W. Grimes 
941df8bae1dSRodney W. Grimes /*
942df8bae1dSRodney W. Grimes  * Return information about system clocks.
943df8bae1dSRodney W. Grimes  */
94426f9a767SRodney W. Grimes int
945df8bae1dSRodney W. Grimes sysctl_clockrate(where, sizep)
946df8bae1dSRodney W. Grimes 	register char *where;
947df8bae1dSRodney W. Grimes 	size_t *sizep;
948df8bae1dSRodney W. Grimes {
949df8bae1dSRodney W. Grimes 	struct clockinfo clkinfo;
950df8bae1dSRodney W. Grimes 
951df8bae1dSRodney W. Grimes 	/*
952df8bae1dSRodney W. Grimes 	 * Construct clockinfo structure.
953df8bae1dSRodney W. Grimes 	 */
954df8bae1dSRodney W. Grimes 	clkinfo.hz = hz;
955df8bae1dSRodney W. Grimes 	clkinfo.tick = tick;
956df8bae1dSRodney W. Grimes 	clkinfo.profhz = profhz;
957df8bae1dSRodney W. Grimes 	clkinfo.stathz = stathz ? stathz : hz;
958df8bae1dSRodney W. Grimes 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
959df8bae1dSRodney W. Grimes }
9603f31c649SGarrett Wollman 
9613f31c649SGarrett Wollman /*#ifdef PPS_SYNC*/
9623f31c649SGarrett Wollman #if 0
9633f31c649SGarrett Wollman /* This code is completely bogus; if anybody ever wants to use it, get
9643f31c649SGarrett Wollman  * the current version from Dave Mills. */
9653f31c649SGarrett Wollman 
9663f31c649SGarrett Wollman /*
9673f31c649SGarrett Wollman  * hardpps() - discipline CPU clock oscillator to external pps signal
9683f31c649SGarrett Wollman  *
9693f31c649SGarrett Wollman  * This routine is called at each PPS interrupt in order to discipline
9703f31c649SGarrett Wollman  * the CPU clock oscillator to the PPS signal. It integrates successive
9713f31c649SGarrett Wollman  * phase differences between the two oscillators and calculates the
9723f31c649SGarrett Wollman  * frequency offset. This is used in hardclock() to discipline the CPU
9733f31c649SGarrett Wollman  * clock oscillator so that intrinsic frequency error is cancelled out.
9743f31c649SGarrett Wollman  * The code requires the caller to capture the time and hardware
9753f31c649SGarrett Wollman  * counter value at the designated PPS signal transition.
9763f31c649SGarrett Wollman  */
9773f31c649SGarrett Wollman void
9783f31c649SGarrett Wollman hardpps(tvp, usec)
9793f31c649SGarrett Wollman 	struct timeval *tvp;		/* time at PPS */
9803f31c649SGarrett Wollman 	long usec;			/* hardware counter at PPS */
9813f31c649SGarrett Wollman {
9823f31c649SGarrett Wollman 	long u_usec, v_usec, bigtick;
9833f31c649SGarrett Wollman 	long cal_sec, cal_usec;
9843f31c649SGarrett Wollman 
9853f31c649SGarrett Wollman 	/*
9863f31c649SGarrett Wollman 	 * During the calibration interval adjust the starting time when
9873f31c649SGarrett Wollman 	 * the tick overflows. At the end of the interval compute the
9883f31c649SGarrett Wollman 	 * duration of the interval and the difference of the hardware
9893f31c649SGarrett Wollman 	 * counters at the beginning and end of the interval. This code
9903f31c649SGarrett Wollman 	 * is deliciously complicated by the fact valid differences may
9913f31c649SGarrett Wollman 	 * exceed the value of tick when using long calibration
9923f31c649SGarrett Wollman 	 * intervals and small ticks. Note that the counter can be
9933f31c649SGarrett Wollman 	 * greater than tick if caught at just the wrong instant, but
9943f31c649SGarrett Wollman 	 * the values returned and used here are correct.
9953f31c649SGarrett Wollman 	 */
9963f31c649SGarrett Wollman 	bigtick = (long)tick << SHIFT_USEC;
9973f31c649SGarrett Wollman 	pps_usec -= ntp_pll.ybar;
9983f31c649SGarrett Wollman 	if (pps_usec >= bigtick)
9993f31c649SGarrett Wollman 		pps_usec -= bigtick;
10003f31c649SGarrett Wollman 	if (pps_usec < 0)
10013f31c649SGarrett Wollman 		pps_usec += bigtick;
10023f31c649SGarrett Wollman 	pps_time.tv_sec++;
10033f31c649SGarrett Wollman 	pps_count++;
10043f31c649SGarrett Wollman 	if (pps_count < (1 << pps_shift))
10053f31c649SGarrett Wollman 		return;
10063f31c649SGarrett Wollman 	pps_count = 0;
10073f31c649SGarrett Wollman 	ntp_pll.calcnt++;
10083f31c649SGarrett Wollman 	u_usec = usec << SHIFT_USEC;
10093f31c649SGarrett Wollman 	v_usec = pps_usec - u_usec;
10103f31c649SGarrett Wollman 	if (v_usec >= bigtick >> 1)
10113f31c649SGarrett Wollman 		v_usec -= bigtick;
10123f31c649SGarrett Wollman 	if (v_usec < -(bigtick >> 1))
10133f31c649SGarrett Wollman 		v_usec += bigtick;
10143f31c649SGarrett Wollman 	if (v_usec < 0)
10153f31c649SGarrett Wollman 		v_usec = -(-v_usec >> ntp_pll.shift);
10163f31c649SGarrett Wollman 	else
10173f31c649SGarrett Wollman 		v_usec = v_usec >> ntp_pll.shift;
10183f31c649SGarrett Wollman 	pps_usec = u_usec;
10193f31c649SGarrett Wollman 	cal_sec = tvp->tv_sec;
10203f31c649SGarrett Wollman 	cal_usec = tvp->tv_usec;
10213f31c649SGarrett Wollman 	cal_sec -= pps_time.tv_sec;
10223f31c649SGarrett Wollman 	cal_usec -= pps_time.tv_usec;
10233f31c649SGarrett Wollman 	if (cal_usec < 0) {
10243f31c649SGarrett Wollman 		cal_usec += 1000000;
10253f31c649SGarrett Wollman 		cal_sec--;
10263f31c649SGarrett Wollman 	}
10273f31c649SGarrett Wollman 	pps_time = *tvp;
10283f31c649SGarrett Wollman 
10293f31c649SGarrett Wollman 	/*
10303f31c649SGarrett Wollman 	 * Check for lost interrupts, noise, excessive jitter and
10313f31c649SGarrett Wollman 	 * excessive frequency error. The number of timer ticks during
10323f31c649SGarrett Wollman 	 * the interval may vary +-1 tick. Add to this a margin of one
10333f31c649SGarrett Wollman 	 * tick for the PPS signal jitter and maximum frequency
10343f31c649SGarrett Wollman 	 * deviation. If the limits are exceeded, the calibration
10353f31c649SGarrett Wollman 	 * interval is reset to the minimum and we start over.
10363f31c649SGarrett Wollman 	 */
10373f31c649SGarrett Wollman 	u_usec = (long)tick << 1;
10383f31c649SGarrett Wollman 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
10393f31c649SGarrett Wollman 	    || (cal_sec == 0 && cal_usec < u_usec))
10403f31c649SGarrett Wollman 	    || v_usec > ntp_pll.tolerance || v_usec < -ntp_pll.tolerance) {
10413f31c649SGarrett Wollman 		ntp_pll.jitcnt++;
10423f31c649SGarrett Wollman 		ntp_pll.shift = NTP_PLL.SHIFT;
10433f31c649SGarrett Wollman 		pps_dispinc = PPS_DISPINC;
10443f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
10453f31c649SGarrett Wollman 		return;
10463f31c649SGarrett Wollman 	}
10473f31c649SGarrett Wollman 
10483f31c649SGarrett Wollman 	/*
10493f31c649SGarrett Wollman 	 * A three-stage median filter is used to help deglitch the pps
10503f31c649SGarrett Wollman 	 * signal. The median sample becomes the offset estimate; the
10513f31c649SGarrett Wollman 	 * difference between the other two samples becomes the
10523f31c649SGarrett Wollman 	 * dispersion estimate.
10533f31c649SGarrett Wollman 	 */
10543f31c649SGarrett Wollman 	pps_mf[2] = pps_mf[1];
10553f31c649SGarrett Wollman 	pps_mf[1] = pps_mf[0];
10563f31c649SGarrett Wollman 	pps_mf[0] = v_usec;
10573f31c649SGarrett Wollman 	if (pps_mf[0] > pps_mf[1]) {
10583f31c649SGarrett Wollman 		if (pps_mf[1] > pps_mf[2]) {
10593f31c649SGarrett Wollman 			u_usec = pps_mf[1];		/* 0 1 2 */
10603f31c649SGarrett Wollman 			v_usec = pps_mf[0] - pps_mf[2];
10613f31c649SGarrett Wollman 		} else if (pps_mf[2] > pps_mf[0]) {
10623f31c649SGarrett Wollman 			u_usec = pps_mf[0];		/* 2 0 1 */
10633f31c649SGarrett Wollman 			v_usec = pps_mf[2] - pps_mf[1];
10643f31c649SGarrett Wollman 		} else {
10653f31c649SGarrett Wollman 			u_usec = pps_mf[2];		/* 0 2 1 */
10663f31c649SGarrett Wollman 			v_usec = pps_mf[0] - pps_mf[1];
10673f31c649SGarrett Wollman 		}
10683f31c649SGarrett Wollman 	} else {
10693f31c649SGarrett Wollman 		if (pps_mf[1] < pps_mf[2]) {
10703f31c649SGarrett Wollman 			u_usec = pps_mf[1];		/* 2 1 0 */
10713f31c649SGarrett Wollman 			v_usec = pps_mf[2] - pps_mf[0];
10723f31c649SGarrett Wollman 		} else  if (pps_mf[2] < pps_mf[0]) {
10733f31c649SGarrett Wollman 			u_usec = pps_mf[0];		/* 1 0 2 */
10743f31c649SGarrett Wollman 			v_usec = pps_mf[1] - pps_mf[2];
10753f31c649SGarrett Wollman 		} else {
10763f31c649SGarrett Wollman 			u_usec = pps_mf[2];		/* 1 2 0 */
10773f31c649SGarrett Wollman 			v_usec = pps_mf[1] - pps_mf[0];
10783f31c649SGarrett Wollman 		}
10793f31c649SGarrett Wollman 	}
10803f31c649SGarrett Wollman 
10813f31c649SGarrett Wollman 	/*
10823f31c649SGarrett Wollman 	 * Here the dispersion average is updated. If it is less than
10833f31c649SGarrett Wollman 	 * the threshold pps_dispmax, the frequency average is updated
10843f31c649SGarrett Wollman 	 * as well, but clamped to the tolerance.
10853f31c649SGarrett Wollman 	 */
10863f31c649SGarrett Wollman 	v_usec = (v_usec >> 1) - ntp_pll.disp;
10873f31c649SGarrett Wollman 	if (v_usec < 0)
10883f31c649SGarrett Wollman 		ntp_pll.disp -= -v_usec >> PPS_AVG;
10893f31c649SGarrett Wollman 	else
10903f31c649SGarrett Wollman 		ntp_pll.disp += v_usec >> PPS_AVG;
10913f31c649SGarrett Wollman 	if (ntp_pll.disp > pps_dispmax) {
10923f31c649SGarrett Wollman 		ntp_pll.discnt++;
10933f31c649SGarrett Wollman 		return;
10943f31c649SGarrett Wollman 	}
10953f31c649SGarrett Wollman 	if (u_usec < 0) {
10963f31c649SGarrett Wollman 		ntp_pll.ybar -= -u_usec >> PPS_AVG;
10973f31c649SGarrett Wollman 		if (ntp_pll.ybar < -ntp_pll.tolerance)
10983f31c649SGarrett Wollman 			ntp_pll.ybar = -ntp_pll.tolerance;
10993f31c649SGarrett Wollman 		u_usec = -u_usec;
11003f31c649SGarrett Wollman 	} else {
11013f31c649SGarrett Wollman 		ntp_pll.ybar += u_usec >> PPS_AVG;
11023f31c649SGarrett Wollman 		if (ntp_pll.ybar > ntp_pll.tolerance)
11033f31c649SGarrett Wollman 			ntp_pll.ybar = ntp_pll.tolerance;
11043f31c649SGarrett Wollman 	}
11053f31c649SGarrett Wollman 
11063f31c649SGarrett Wollman 	/*
11073f31c649SGarrett Wollman 	 * Here the calibration interval is adjusted. If the maximum
11083f31c649SGarrett Wollman 	 * time difference is greater than tick/4, reduce the interval
11093f31c649SGarrett Wollman 	 * by half. If this is not the case for four consecutive
11103f31c649SGarrett Wollman 	 * intervals, double the interval.
11113f31c649SGarrett Wollman 	 */
11123f31c649SGarrett Wollman 	if (u_usec << ntp_pll.shift > bigtick >> 2) {
11133f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
11143f31c649SGarrett Wollman 		if (ntp_pll.shift > NTP_PLL.SHIFT) {
11153f31c649SGarrett Wollman 			ntp_pll.shift--;
11163f31c649SGarrett Wollman 			pps_dispinc <<= 1;
11173f31c649SGarrett Wollman 		}
11183f31c649SGarrett Wollman 	} else if (ntp_pll.intcnt >= 4) {
11193f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
11203f31c649SGarrett Wollman 		if (ntp_pll.shift < NTP_PLL.SHIFTMAX) {
11213f31c649SGarrett Wollman 			ntp_pll.shift++;
11223f31c649SGarrett Wollman 			pps_dispinc >>= 1;
11233f31c649SGarrett Wollman 		}
11243f31c649SGarrett Wollman 	} else
11253f31c649SGarrett Wollman 		ntp_pll.intcnt++;
11263f31c649SGarrett Wollman }
11273f31c649SGarrett Wollman #endif /* PPS_SYNC */
1128