xref: /freebsd/sys/kern/kern_clock.c (revision 6976af69e8e9387103b7fe3d2537396a8863421c)
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
396976af69SBruce Evans  * $Id: kern_clock.c,v 1.10 1994/10/16 03:52:12 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;
918478cabaSGarrett Wollman int dk_ndrive = 0;
928478cabaSGarrett Wollman char dk_names[DK_NDRIVE][DK_NAMELEN];
93f23b4c91SGarrett Wollman 
94f23b4c91SGarrett Wollman long tk_cancc;
95f23b4c91SGarrett Wollman long tk_nin;
96f23b4c91SGarrett Wollman long tk_nout;
97f23b4c91SGarrett Wollman long tk_rawcc;
98f23b4c91SGarrett Wollman 
99df8bae1dSRodney W. Grimes /*
100df8bae1dSRodney W. Grimes  * Clock handling routines.
101df8bae1dSRodney W. Grimes  *
102df8bae1dSRodney W. Grimes  * This code is written to operate with two timers that run independently of
103df8bae1dSRodney W. Grimes  * each other.  The main clock, running hz times per second, is used to keep
104df8bae1dSRodney W. Grimes  * track of real time.  The second timer handles kernel and user profiling,
105df8bae1dSRodney W. Grimes  * and does resource use estimation.  If the second timer is programmable,
106df8bae1dSRodney W. Grimes  * it is randomized to avoid aliasing between the two clocks.  For example,
107df8bae1dSRodney W. Grimes  * the randomization prevents an adversary from always giving up the cpu
108df8bae1dSRodney W. Grimes  * just before its quantum expires.  Otherwise, it would never accumulate
109df8bae1dSRodney W. Grimes  * cpu ticks.  The mean frequency of the second timer is stathz.
110df8bae1dSRodney W. Grimes  *
111df8bae1dSRodney W. Grimes  * If no second timer exists, stathz will be zero; in this case we drive
112df8bae1dSRodney W. Grimes  * profiling and statistics off the main clock.  This WILL NOT be accurate;
113df8bae1dSRodney W. Grimes  * do not do it unless absolutely necessary.
114df8bae1dSRodney W. Grimes  *
115df8bae1dSRodney W. Grimes  * The statistics clock may (or may not) be run at a higher rate while
116df8bae1dSRodney W. Grimes  * profiling.  This profile clock runs at profhz.  We require that profhz
117df8bae1dSRodney W. Grimes  * be an integral multiple of stathz.
118df8bae1dSRodney W. Grimes  *
119df8bae1dSRodney W. Grimes  * If the statistics clock is running fast, it must be divided by the ratio
120df8bae1dSRodney W. Grimes  * profhz/stathz for statistics.  (For profiling, every tick counts.)
121df8bae1dSRodney W. Grimes  */
122df8bae1dSRodney W. Grimes 
123df8bae1dSRodney W. Grimes /*
124df8bae1dSRodney W. Grimes  * TODO:
125df8bae1dSRodney W. Grimes  *	allocate more timeout table slots when table overflows.
126df8bae1dSRodney W. Grimes  */
127df8bae1dSRodney W. Grimes 
128df8bae1dSRodney W. Grimes /*
129df8bae1dSRodney W. Grimes  * Bump a timeval by a small number of usec's.
130df8bae1dSRodney W. Grimes  */
131df8bae1dSRodney W. Grimes #define BUMPTIME(t, usec) { \
132df8bae1dSRodney W. Grimes 	register volatile struct timeval *tp = (t); \
133df8bae1dSRodney W. Grimes 	register long us; \
134df8bae1dSRodney W. Grimes  \
135df8bae1dSRodney W. Grimes 	tp->tv_usec = us = tp->tv_usec + (usec); \
136df8bae1dSRodney W. Grimes 	if (us >= 1000000) { \
137df8bae1dSRodney W. Grimes 		tp->tv_usec = us - 1000000; \
138df8bae1dSRodney W. Grimes 		tp->tv_sec++; \
139df8bae1dSRodney W. Grimes 	} \
140df8bae1dSRodney W. Grimes }
141df8bae1dSRodney W. Grimes 
142df8bae1dSRodney W. Grimes int	stathz;
143df8bae1dSRodney W. Grimes int	profhz;
144df8bae1dSRodney W. Grimes int	profprocs;
145df8bae1dSRodney W. Grimes int	ticks;
146df8bae1dSRodney W. Grimes static int psdiv, pscnt;	/* prof => stat divider */
147df8bae1dSRodney W. Grimes int	psratio;		/* ratio: prof / stat */
148df8bae1dSRodney W. Grimes 
149df8bae1dSRodney W. Grimes volatile struct	timeval time;
150df8bae1dSRodney W. Grimes volatile struct	timeval mono_time;
151df8bae1dSRodney W. Grimes 
152df8bae1dSRodney W. Grimes /*
1533f31c649SGarrett Wollman  * Phase-lock loop (PLL) definitions
1543f31c649SGarrett Wollman  *
1553f31c649SGarrett Wollman  * The following variables are read and set by the ntp_adjtime() system
1563f31c649SGarrett Wollman  * call.
1573f31c649SGarrett Wollman  *
1583f31c649SGarrett Wollman  * time_state shows the state of the system clock, with values defined
1593f31c649SGarrett Wollman  * in the timex.h header file.
1603f31c649SGarrett Wollman  *
1613f31c649SGarrett Wollman  * time_status shows the status of the system clock, with bits defined
1623f31c649SGarrett Wollman  * in the timex.h header file.
1633f31c649SGarrett Wollman  *
1643f31c649SGarrett Wollman  * time_offset is used by the PLL to adjust the system time in small
1653f31c649SGarrett Wollman  * increments.
1663f31c649SGarrett Wollman  *
1673f31c649SGarrett Wollman  * time_constant determines the bandwidth or "stiffness" of the PLL.
1683f31c649SGarrett Wollman  *
1693f31c649SGarrett Wollman  * time_tolerance determines maximum frequency error or tolerance of the
1703f31c649SGarrett Wollman  * CPU clock oscillator and is a property of the architecture; however,
1713f31c649SGarrett Wollman  * in principle it could change as result of the presence of external
1723f31c649SGarrett Wollman  * discipline signals, for instance.
1733f31c649SGarrett Wollman  *
1743f31c649SGarrett Wollman  * time_precision is usually equal to the kernel tick variable; however,
1753f31c649SGarrett Wollman  * in cases where a precision clock counter or external clock is
1763f31c649SGarrett Wollman  * available, the resolution can be much less than this and depend on
1773f31c649SGarrett Wollman  * whether the external clock is working or not.
1783f31c649SGarrett Wollman  *
1793f31c649SGarrett Wollman  * time_maxerror is initialized by a ntp_adjtime() call and increased by
1803f31c649SGarrett Wollman  * the kernel once each second to reflect the maximum error
1813f31c649SGarrett Wollman  * bound growth.
1823f31c649SGarrett Wollman  *
1833f31c649SGarrett Wollman  * time_esterror is set and read by the ntp_adjtime() call, but
1843f31c649SGarrett Wollman  * otherwise not used by the kernel.
1853f31c649SGarrett Wollman  */
1863f31c649SGarrett Wollman int time_status = STA_UNSYNC;	/* clock status bits */
1873f31c649SGarrett Wollman int time_state = TIME_OK;	/* clock state */
1883f31c649SGarrett Wollman long time_offset = 0;		/* time offset (us) */
1893f31c649SGarrett Wollman long time_constant = 0;		/* pll time constant */
1903f31c649SGarrett Wollman long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
1913f31c649SGarrett Wollman long time_precision = 1;	/* clock precision (us) */
1923f31c649SGarrett Wollman long time_maxerror = MAXPHASE;	/* maximum error (us) */
1933f31c649SGarrett Wollman long time_esterror = MAXPHASE;	/* estimated error (us) */
1943f31c649SGarrett Wollman 
1953f31c649SGarrett Wollman /*
1963f31c649SGarrett Wollman  * The following variables establish the state of the PLL and the
1973f31c649SGarrett Wollman  * residual time and frequency offset of the local clock. The scale
1983f31c649SGarrett Wollman  * factors are defined in the timex.h header file.
1993f31c649SGarrett Wollman  *
2003f31c649SGarrett Wollman  * time_phase and time_freq are the phase increment and the frequency
2013f31c649SGarrett Wollman  * increment, respectively, of the kernel time variable at each tick of
2023f31c649SGarrett Wollman  * the clock.
2033f31c649SGarrett Wollman  *
2043f31c649SGarrett Wollman  * time_freq is set via ntp_adjtime() from a value stored in a file when
2053f31c649SGarrett Wollman  * the synchronization daemon is first started. Its value is retrieved
2063f31c649SGarrett Wollman  * via ntp_adjtime() and written to the file about once per hour by the
2073f31c649SGarrett Wollman  * daemon.
2083f31c649SGarrett Wollman  *
2093f31c649SGarrett Wollman  * time_adj is the adjustment added to the value of tick at each timer
2103f31c649SGarrett Wollman  * interrupt and is recomputed at each timer interrupt.
2113f31c649SGarrett Wollman  *
2123f31c649SGarrett Wollman  * time_reftime is the second's portion of the system time on the last
2133f31c649SGarrett Wollman  * call to ntp_adjtime(). It is used to adjust the time_freq variable
2143f31c649SGarrett Wollman  * and to increase the time_maxerror as the time since last update
2153f31c649SGarrett Wollman  * increases.
2163f31c649SGarrett Wollman  */
2173f31c649SGarrett Wollman long time_phase = 0;		/* phase offset (scaled us) */
2183f31c649SGarrett Wollman long time_freq = 0;		/* frequency offset (scaled ppm) */
2193f31c649SGarrett Wollman long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
2203f31c649SGarrett Wollman long time_reftime = 0;		/* time at last adjustment (s) */
2213f31c649SGarrett Wollman 
2223f31c649SGarrett Wollman #ifdef PPS_SYNC
2233f31c649SGarrett Wollman /*
2243f31c649SGarrett Wollman  * The following variables are used only if the if the kernel PPS
2253f31c649SGarrett Wollman  * discipline code is configured (PPS_SYNC). The scale factors are
2263f31c649SGarrett Wollman  * defined in the timex.h header file.
2273f31c649SGarrett Wollman  *
2283f31c649SGarrett Wollman  * pps_time contains the time at each calibration interval, as read by
2293f31c649SGarrett Wollman  * microtime().
2303f31c649SGarrett Wollman  *
2313f31c649SGarrett Wollman  * pps_offset is the time offset produced by the time median filter
2323f31c649SGarrett Wollman  * pps_tf[], while pps_jitter is the dispersion measured by this
2333f31c649SGarrett Wollman  * filter.
2343f31c649SGarrett Wollman  *
2353f31c649SGarrett Wollman  * pps_freq is the frequency offset produced by the frequency median
2363f31c649SGarrett Wollman  * filter pps_ff[], while pps_stabil is the dispersion measured by
2373f31c649SGarrett Wollman  * this filter.
2383f31c649SGarrett Wollman  *
2393f31c649SGarrett Wollman  * pps_usec is latched from a high resolution counter or external clock
2403f31c649SGarrett Wollman  * at pps_time. Here we want the hardware counter contents only, not the
2413f31c649SGarrett Wollman  * contents plus the time_tv.usec as usual.
2423f31c649SGarrett Wollman  *
2433f31c649SGarrett Wollman  * pps_valid counts the number of seconds since the last PPS update. It
2443f31c649SGarrett Wollman  * is used as a watchdog timer to disable the PPS discipline should the
2453f31c649SGarrett Wollman  * PPS signal be lost.
2463f31c649SGarrett Wollman  *
2473f31c649SGarrett Wollman  * pps_glitch counts the number of seconds since the beginning of an
2483f31c649SGarrett Wollman  * offset burst more than tick/2 from current nominal offset. It is used
2493f31c649SGarrett Wollman  * mainly to suppress error bursts due to priority conflicts between the
2503f31c649SGarrett Wollman  * PPS interrupt and timer interrupt.
2513f31c649SGarrett Wollman  *
2523f31c649SGarrett Wollman  * pps_count counts the seconds of the calibration interval, the
2533f31c649SGarrett Wollman  * duration of which is pps_shift in powers of two.
2543f31c649SGarrett Wollman  *
2553f31c649SGarrett Wollman  * pps_intcnt counts the calibration intervals for use in the interval-
2563f31c649SGarrett Wollman  * adaptation algorithm. It's just too complicated for words.
2573f31c649SGarrett Wollman  */
2583f31c649SGarrett Wollman struct timeval pps_time;	/* kernel time at last interval */
2593f31c649SGarrett Wollman long pps_offset = 0;		/* pps time offset (us) */
2603f31c649SGarrett Wollman long pps_jitter = MAXTIME;	/* pps time dispersion (jitter) (us) */
2613f31c649SGarrett Wollman long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
2623f31c649SGarrett Wollman long pps_freq = 0;		/* frequency offset (scaled ppm) */
2633f31c649SGarrett Wollman long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
2643f31c649SGarrett Wollman long pps_ff[] = {0, 0, 0};	/* frequency offset median filter */
2653f31c649SGarrett Wollman long pps_usec = 0;		/* microsec counter at last interval */
2663f31c649SGarrett Wollman long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
2673f31c649SGarrett Wollman int pps_glitch = 0;		/* pps signal glitch counter */
2683f31c649SGarrett Wollman int pps_count = 0;		/* calibration interval counter (s) */
2693f31c649SGarrett Wollman int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
2703f31c649SGarrett Wollman int pps_intcnt = 0;		/* intervals at current duration */
2713f31c649SGarrett Wollman 
2723f31c649SGarrett Wollman /*
2733f31c649SGarrett Wollman  * PPS signal quality monitors
2743f31c649SGarrett Wollman  *
2753f31c649SGarrett Wollman  * pps_jitcnt counts the seconds that have been discarded because the
2763f31c649SGarrett Wollman  * jitter measured by the time median filter exceeds the limit MAXTIME
2773f31c649SGarrett Wollman  * (100 us).
2783f31c649SGarrett Wollman  *
2793f31c649SGarrett Wollman  * pps_calcnt counts the frequency calibration intervals, which are
2803f31c649SGarrett Wollman  * variable from 4 s to 256 s.
2813f31c649SGarrett Wollman  *
2823f31c649SGarrett Wollman  * pps_errcnt counts the calibration intervals which have been discarded
2833f31c649SGarrett Wollman  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
2843f31c649SGarrett Wollman  * calibration interval jitter exceeds two ticks.
2853f31c649SGarrett Wollman  *
2863f31c649SGarrett Wollman  * pps_stbcnt counts the calibration intervals that have been discarded
2873f31c649SGarrett Wollman  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
2883f31c649SGarrett Wollman  */
2893f31c649SGarrett Wollman long pps_jitcnt = 0;		/* jitter limit exceeded */
2903f31c649SGarrett Wollman long pps_calcnt = 0;		/* calibration intervals */
2913f31c649SGarrett Wollman long pps_errcnt = 0;		/* calibration errors */
2923f31c649SGarrett Wollman long pps_stbcnt = 0;		/* stability limit exceeded */
2933f31c649SGarrett Wollman #endif /* PPS_SYNC */
2943f31c649SGarrett Wollman 
2953f31c649SGarrett Wollman /* XXX none of this stuff works under FreeBSD */
2963f31c649SGarrett Wollman #ifdef EXT_CLOCK
2973f31c649SGarrett Wollman /*
2983f31c649SGarrett Wollman  * External clock definitions
2993f31c649SGarrett Wollman  *
3003f31c649SGarrett Wollman  * The following definitions and declarations are used only if an
3013f31c649SGarrett Wollman  * external clock (HIGHBALL or TPRO) is configured on the system.
3023f31c649SGarrett Wollman  */
3033f31c649SGarrett Wollman #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
3043f31c649SGarrett Wollman 
3053f31c649SGarrett Wollman /*
3063f31c649SGarrett Wollman  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
3073f31c649SGarrett Wollman  * interrupt and decremented once each second.
3083f31c649SGarrett Wollman  */
3093f31c649SGarrett Wollman int clock_count = 0;		/* CPU clock counter */
3103f31c649SGarrett Wollman 
3113f31c649SGarrett Wollman #ifdef HIGHBALL
3123f31c649SGarrett Wollman /*
3133f31c649SGarrett Wollman  * The clock_offset and clock_cpu variables are used by the HIGHBALL
3143f31c649SGarrett Wollman  * interface. The clock_offset variable defines the offset between
3153f31c649SGarrett Wollman  * system time and the HIGBALL counters. The clock_cpu variable contains
3163f31c649SGarrett Wollman  * the offset between the system clock and the HIGHBALL clock for use in
3173f31c649SGarrett Wollman  * disciplining the kernel time variable.
3183f31c649SGarrett Wollman  */
3193f31c649SGarrett Wollman extern struct timeval clock_offset; /* Highball clock offset */
3203f31c649SGarrett Wollman long clock_cpu = 0;		/* CPU clock adjust */
3213f31c649SGarrett Wollman #endif /* HIGHBALL */
3223f31c649SGarrett Wollman #endif /* EXT_CLOCK */
3233f31c649SGarrett Wollman 
3243f31c649SGarrett Wollman /*
3253f31c649SGarrett Wollman  * hardupdate() - local clock update
3263f31c649SGarrett Wollman  *
3273f31c649SGarrett Wollman  * This routine is called by ntp_adjtime() to update the local clock
3283f31c649SGarrett Wollman  * phase and frequency. This is used to implement an adaptive-parameter,
3293f31c649SGarrett Wollman  * first-order, type-II phase-lock loop. The code computes new time and
3303f31c649SGarrett Wollman  * frequency offsets each time it is called. The hardclock() routine
3313f31c649SGarrett Wollman  * amortizes these offsets at each tick interrupt. If the kernel PPS
3323f31c649SGarrett Wollman  * discipline code is configured (PPS_SYNC), the PPS signal itself
3333f31c649SGarrett Wollman  * determines the new time offset, instead of the calling argument.
3343f31c649SGarrett Wollman  * Presumably, calls to ntp_adjtime() occur only when the caller
3353f31c649SGarrett Wollman  * believes the local clock is valid within some bound (+-128 ms with
3363f31c649SGarrett Wollman  * NTP). If the caller's time is far different than the PPS time, an
3373f31c649SGarrett Wollman  * argument will ensue, and it's not clear who will lose.
3383f31c649SGarrett Wollman  *
3393f31c649SGarrett Wollman  * For default SHIFT_UPDATE = 12, the offset is limited to +-512 ms, the
3403f31c649SGarrett Wollman  * maximum interval between updates is 4096 s and the maximum frequency
3413f31c649SGarrett Wollman  * offset is +-31.25 ms/s.
3423f31c649SGarrett Wollman  *
3433f31c649SGarrett Wollman  * Note: splclock() is in effect.
3443f31c649SGarrett Wollman  */
3453f31c649SGarrett Wollman void
3463f31c649SGarrett Wollman hardupdate(offset)
3473f31c649SGarrett Wollman 	long offset;
3483f31c649SGarrett Wollman {
3493f31c649SGarrett Wollman 	long ltemp, mtemp;
3503f31c649SGarrett Wollman 
3513f31c649SGarrett Wollman 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
3523f31c649SGarrett Wollman 		return;
3533f31c649SGarrett Wollman 	ltemp = offset;
3543f31c649SGarrett Wollman #ifdef PPS_SYNC
3553f31c649SGarrett Wollman 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
3563f31c649SGarrett Wollman 		ltemp = pps_offset;
3573f31c649SGarrett Wollman #endif /* PPS_SYNC */
3583f31c649SGarrett Wollman 	if (ltemp > MAXPHASE)
3593f31c649SGarrett Wollman 		time_offset = MAXPHASE << SHIFT_UPDATE;
3603f31c649SGarrett Wollman 	else if (ltemp < -MAXPHASE)
3613f31c649SGarrett Wollman 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
3623f31c649SGarrett Wollman 	else
3633f31c649SGarrett Wollman 		time_offset = ltemp << SHIFT_UPDATE;
3643f31c649SGarrett Wollman 	mtemp = time.tv_sec - time_reftime;
3653f31c649SGarrett Wollman 	time_reftime = time.tv_sec;
3663f31c649SGarrett Wollman 	if (mtemp > MAXSEC)
3673f31c649SGarrett Wollman 		mtemp = 0;
3683f31c649SGarrett Wollman 
3693f31c649SGarrett Wollman 	/* ugly multiply should be replaced */
3703f31c649SGarrett Wollman 	if (ltemp < 0)
3713f31c649SGarrett Wollman 		time_freq -= (-ltemp * mtemp) >> (time_constant +
3723f31c649SGarrett Wollman 		    time_constant + SHIFT_KF - SHIFT_USEC);
3733f31c649SGarrett Wollman 	else
3743f31c649SGarrett Wollman 		time_freq += (ltemp * mtemp) >> (time_constant +
3753f31c649SGarrett Wollman 		    time_constant + SHIFT_KF - SHIFT_USEC);
3763f31c649SGarrett Wollman 	if (time_freq > time_tolerance)
3773f31c649SGarrett Wollman 		time_freq = time_tolerance;
3783f31c649SGarrett Wollman 	else if (time_freq < -time_tolerance)
3793f31c649SGarrett Wollman 		time_freq = -time_tolerance;
3803f31c649SGarrett Wollman }
3813f31c649SGarrett Wollman 
3823f31c649SGarrett Wollman 
3833f31c649SGarrett Wollman 
3843f31c649SGarrett Wollman /*
385df8bae1dSRodney W. Grimes  * Initialize clock frequencies and start both clocks running.
386df8bae1dSRodney W. Grimes  */
387df8bae1dSRodney W. Grimes void
388df8bae1dSRodney W. Grimes initclocks()
389df8bae1dSRodney W. Grimes {
390df8bae1dSRodney W. Grimes 	register int i;
391df8bae1dSRodney W. Grimes 
392df8bae1dSRodney W. Grimes 	/*
393df8bae1dSRodney W. Grimes 	 * Set divisors to 1 (normal case) and let the machine-specific
394df8bae1dSRodney W. Grimes 	 * code do its bit.
395df8bae1dSRodney W. Grimes 	 */
396df8bae1dSRodney W. Grimes 	psdiv = pscnt = 1;
397df8bae1dSRodney W. Grimes 	cpu_initclocks();
398df8bae1dSRodney W. Grimes 
399df8bae1dSRodney W. Grimes 	/*
400df8bae1dSRodney W. Grimes 	 * Compute profhz/stathz, and fix profhz if needed.
401df8bae1dSRodney W. Grimes 	 */
402df8bae1dSRodney W. Grimes 	i = stathz ? stathz : hz;
403df8bae1dSRodney W. Grimes 	if (profhz == 0)
404df8bae1dSRodney W. Grimes 		profhz = i;
405df8bae1dSRodney W. Grimes 	psratio = profhz / i;
406df8bae1dSRodney W. Grimes }
407df8bae1dSRodney W. Grimes 
408df8bae1dSRodney W. Grimes /*
409df8bae1dSRodney W. Grimes  * The real-time timer, interrupting hz times per second.
410df8bae1dSRodney W. Grimes  */
411df8bae1dSRodney W. Grimes void
412df8bae1dSRodney W. Grimes hardclock(frame)
413df8bae1dSRodney W. Grimes 	register struct clockframe *frame;
414df8bae1dSRodney W. Grimes {
415df8bae1dSRodney W. Grimes 	register struct callout *p1;
416df8bae1dSRodney W. Grimes 	register struct proc *p;
417bb56ec4aSPoul-Henning Kamp 	register int needsoft;
418df8bae1dSRodney W. Grimes 	extern int tickdelta;
419df8bae1dSRodney W. Grimes 	extern long timedelta;
420df8bae1dSRodney W. Grimes 
421df8bae1dSRodney W. Grimes 	/*
422df8bae1dSRodney W. Grimes 	 * Update real-time timeout queue.
423df8bae1dSRodney W. Grimes 	 * At front of queue are some number of events which are ``due''.
424df8bae1dSRodney W. Grimes 	 * The time to these is <= 0 and if negative represents the
425df8bae1dSRodney W. Grimes 	 * number of ticks which have passed since it was supposed to happen.
426df8bae1dSRodney W. Grimes 	 * The rest of the q elements (times > 0) are events yet to happen,
427df8bae1dSRodney W. Grimes 	 * where the time for each is given as a delta from the previous.
428df8bae1dSRodney W. Grimes 	 * Decrementing just the first of these serves to decrement the time
429df8bae1dSRodney W. Grimes 	 * to all events.
430df8bae1dSRodney W. Grimes 	 */
431df8bae1dSRodney W. Grimes 	needsoft = 0;
432df8bae1dSRodney W. Grimes 	for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
433df8bae1dSRodney W. Grimes 		if (--p1->c_time > 0)
434df8bae1dSRodney W. Grimes 			break;
435df8bae1dSRodney W. Grimes 		needsoft = 1;
436df8bae1dSRodney W. Grimes 		if (p1->c_time == 0)
437df8bae1dSRodney W. Grimes 			break;
438df8bae1dSRodney W. Grimes 	}
439df8bae1dSRodney W. Grimes 
440df8bae1dSRodney W. Grimes 	p = curproc;
441df8bae1dSRodney W. Grimes 	if (p) {
442df8bae1dSRodney W. Grimes 		register struct pstats *pstats;
443df8bae1dSRodney W. Grimes 
444df8bae1dSRodney W. Grimes 		/*
445df8bae1dSRodney W. Grimes 		 * Run current process's virtual and profile time, as needed.
446df8bae1dSRodney W. Grimes 		 */
447df8bae1dSRodney W. Grimes 		pstats = p->p_stats;
448df8bae1dSRodney W. Grimes 		if (CLKF_USERMODE(frame) &&
449df8bae1dSRodney W. Grimes 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
450df8bae1dSRodney W. Grimes 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
451df8bae1dSRodney W. Grimes 			psignal(p, SIGVTALRM);
452df8bae1dSRodney W. Grimes 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
453df8bae1dSRodney W. Grimes 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
454df8bae1dSRodney W. Grimes 			psignal(p, SIGPROF);
455df8bae1dSRodney W. Grimes 	}
456df8bae1dSRodney W. Grimes 
457df8bae1dSRodney W. Grimes 	/*
458df8bae1dSRodney W. Grimes 	 * If no separate statistics clock is available, run it from here.
459df8bae1dSRodney W. Grimes 	 */
460df8bae1dSRodney W. Grimes 	if (stathz == 0)
461df8bae1dSRodney W. Grimes 		statclock(frame);
462df8bae1dSRodney W. Grimes 
463df8bae1dSRodney W. Grimes 	/*
4643f31c649SGarrett Wollman 	 * Increment the time-of-day.
465df8bae1dSRodney W. Grimes 	 */
466df8bae1dSRodney W. Grimes 	ticks++;
4673f31c649SGarrett Wollman 	{
4683f31c649SGarrett Wollman 		int time_update;
4693f31c649SGarrett Wollman 		struct timeval newtime = time;
4703f31c649SGarrett Wollman 		long ltemp;
4713f31c649SGarrett Wollman 
4723f31c649SGarrett Wollman 		if (timedelta == 0) {
4733f31c649SGarrett Wollman 			time_update = tick;
4743f31c649SGarrett Wollman 		} else {
4753f31c649SGarrett Wollman 			time_update = tick + tickdelta;
476df8bae1dSRodney W. Grimes 			timedelta -= tickdelta;
477df8bae1dSRodney W. Grimes 		}
4783f31c649SGarrett Wollman 		BUMPTIME(&mono_time, time_update);
4793f31c649SGarrett Wollman 
4803f31c649SGarrett Wollman 		/*
4813f31c649SGarrett Wollman 		 * Compute the phase adjustment. If the low-order bits
4823f31c649SGarrett Wollman 		 * (time_phase) of the update overflow, bump the high-order bits
4833f31c649SGarrett Wollman 		 * (time_update).
4843f31c649SGarrett Wollman 		 */
4853f31c649SGarrett Wollman 		time_phase += time_adj;
4863f31c649SGarrett Wollman 		if (time_phase <= -FINEUSEC) {
4873f31c649SGarrett Wollman 		  ltemp = -time_phase >> SHIFT_SCALE;
4883f31c649SGarrett Wollman 		  time_phase += ltemp << SHIFT_SCALE;
4893f31c649SGarrett Wollman 		  time_update -= ltemp;
4903f31c649SGarrett Wollman 		}
4913f31c649SGarrett Wollman 		else if (time_phase >= FINEUSEC) {
4923f31c649SGarrett Wollman 		  ltemp = time_phase >> SHIFT_SCALE;
4933f31c649SGarrett Wollman 		  time_phase -= ltemp << SHIFT_SCALE;
4943f31c649SGarrett Wollman 		  time_update += ltemp;
4953f31c649SGarrett Wollman 		}
4963f31c649SGarrett Wollman 
4973f31c649SGarrett Wollman 		newtime.tv_usec += time_update;
4983f31c649SGarrett Wollman 		/*
4993f31c649SGarrett Wollman 		 * On rollover of the second the phase adjustment to be used for
5003f31c649SGarrett Wollman 		 * the next second is calculated. Also, the maximum error is
5013f31c649SGarrett Wollman 		 * increased by the tolerance. If the PPS frequency discipline
5023f31c649SGarrett Wollman 		 * code is present, the phase is increased to compensate for the
5033f31c649SGarrett Wollman 		 * CPU clock oscillator frequency error.
5043f31c649SGarrett Wollman 		 *
5053f31c649SGarrett Wollman 		 * With SHIFT_SCALE = 23, the maximum frequency adjustment is
5063f31c649SGarrett Wollman 		 * +-256 us per tick, or 25.6 ms/s at a clock frequency of 100
5073f31c649SGarrett Wollman 		 * Hz. The time contribution is shifted right a minimum of two
5083f31c649SGarrett Wollman 		 * bits, while the frequency contribution is a right shift.
5093f31c649SGarrett Wollman 		 * Thus, overflow is prevented if the frequency contribution is
5103f31c649SGarrett Wollman 		 * limited to half the maximum or 15.625 ms/s.
5113f31c649SGarrett Wollman 		 */
5123f31c649SGarrett Wollman 		if (newtime.tv_usec >= 1000000) {
5133f31c649SGarrett Wollman 		  newtime.tv_usec -= 1000000;
5143f31c649SGarrett Wollman 		  newtime.tv_sec++;
5153f31c649SGarrett Wollman 		  time_maxerror += time_tolerance >> SHIFT_USEC;
5163f31c649SGarrett Wollman 		  if (time_offset < 0) {
5173f31c649SGarrett Wollman 		    ltemp = -time_offset >>
5183f31c649SGarrett Wollman 		      (SHIFT_KG + time_constant);
5193f31c649SGarrett Wollman 		    time_offset += ltemp;
5203f31c649SGarrett Wollman 		    time_adj = -ltemp <<
5213f31c649SGarrett Wollman 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
5223f31c649SGarrett Wollman 		  } else {
5233f31c649SGarrett Wollman 		    ltemp = time_offset >>
5243f31c649SGarrett Wollman 		      (SHIFT_KG + time_constant);
5253f31c649SGarrett Wollman 		    time_offset -= ltemp;
5263f31c649SGarrett Wollman 		    time_adj = ltemp <<
5273f31c649SGarrett Wollman 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
5283f31c649SGarrett Wollman 		  }
5293f31c649SGarrett Wollman #ifdef PPS_SYNC
5303f31c649SGarrett Wollman 		  /*
5313f31c649SGarrett Wollman 		   * Gnaw on the watchdog counter and update the frequency
5323f31c649SGarrett Wollman 		   * computed by the pll and the PPS signal.
5333f31c649SGarrett Wollman 		   */
5343f31c649SGarrett Wollman 		  pps_valid++;
5353f31c649SGarrett Wollman 		  if (pps_valid == PPS_VALID) {
5363f31c649SGarrett Wollman 		    pps_jitter = MAXTIME;
5373f31c649SGarrett Wollman 		    pps_stabil = MAXFREQ;
5383f31c649SGarrett Wollman 		    time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
5393f31c649SGarrett Wollman 				     STA_PPSWANDER | STA_PPSERROR);
5403f31c649SGarrett Wollman 		  }
5413f31c649SGarrett Wollman 		  ltemp = time_freq + pps_freq;
5423f31c649SGarrett Wollman #else
5433f31c649SGarrett Wollman 		  ltemp = time_freq;
5443f31c649SGarrett Wollman #endif /* PPS_SYNC */
5453f31c649SGarrett Wollman 		  if (ltemp < 0)
5463f31c649SGarrett Wollman 		    time_adj -= -ltemp >>
5473f31c649SGarrett Wollman 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
5483f31c649SGarrett Wollman 		  else
5493f31c649SGarrett Wollman 		    time_adj += ltemp >>
5503f31c649SGarrett Wollman 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
5513f31c649SGarrett Wollman 
5523f31c649SGarrett Wollman 		  /*
5533f31c649SGarrett Wollman 		   * When the CPU clock oscillator frequency is not a
5543f31c649SGarrett Wollman 		   * power of two in Hz, the SHIFT_HZ is only an
5553f31c649SGarrett Wollman 		   * approximate scale factor. In the SunOS kernel, this
5563f31c649SGarrett Wollman 		   * results in a PLL gain factor of 1/1.28 = 0.78 what it
5573f31c649SGarrett Wollman 		   * should be. In the following code the overall gain is
5583f31c649SGarrett Wollman 		   * increased by a factor of 1.25, which results in a
5593f31c649SGarrett Wollman 		   * residual error less than 3 percent.
5603f31c649SGarrett Wollman 		   */
5613f31c649SGarrett Wollman 		  /* Same thing applies for FreeBSD --GAW */
5623f31c649SGarrett Wollman 		  if (hz == 100) {
5633f31c649SGarrett Wollman 		    if (time_adj < 0)
5643f31c649SGarrett Wollman 		      time_adj -= -time_adj >> 2;
5653f31c649SGarrett Wollman 		    else
5663f31c649SGarrett Wollman 		      time_adj += time_adj >> 2;
5673f31c649SGarrett Wollman 		  }
5683f31c649SGarrett Wollman 
5693f31c649SGarrett Wollman 		  /* XXX - this is really bogus, but can't be fixed until
5703f31c649SGarrett Wollman 		     xntpd's idea of the system clock is fixed to know how
5713f31c649SGarrett Wollman 		     the user wants leap seconds handled; in the mean time,
5723f31c649SGarrett Wollman 		     we assume that users of NTP are running without proper
5733f31c649SGarrett Wollman 		     leap second support (this is now the default anyway) */
5743f31c649SGarrett Wollman 		  /*
5753f31c649SGarrett Wollman 		   * Leap second processing. If in leap-insert state at
5763f31c649SGarrett Wollman 		   * the end of the day, the system clock is set back one
5773f31c649SGarrett Wollman 		   * second; if in leap-delete state, the system clock is
5783f31c649SGarrett Wollman 		   * set ahead one second. The microtime() routine or
5793f31c649SGarrett Wollman 		   * external clock driver will insure that reported time
5803f31c649SGarrett Wollman 		   * is always monotonic. The ugly divides should be
5813f31c649SGarrett Wollman 		   * replaced.
5823f31c649SGarrett Wollman 		   */
5833f31c649SGarrett Wollman 		  switch (time_state) {
5843f31c649SGarrett Wollman 
5853f31c649SGarrett Wollman 		  case TIME_OK:
5863f31c649SGarrett Wollman 		    if (time_status & STA_INS)
5873f31c649SGarrett Wollman 		      time_state = TIME_INS;
5883f31c649SGarrett Wollman 		    else if (time_status & STA_DEL)
5893f31c649SGarrett Wollman 		      time_state = TIME_DEL;
5903f31c649SGarrett Wollman 		    break;
5913f31c649SGarrett Wollman 
5923f31c649SGarrett Wollman 		  case TIME_INS:
5933f31c649SGarrett Wollman 		    if (newtime.tv_sec % 86400 == 0) {
5943f31c649SGarrett Wollman 		      newtime.tv_sec--;
5953f31c649SGarrett Wollman 		      time_state = TIME_OOP;
5963f31c649SGarrett Wollman 		    }
5973f31c649SGarrett Wollman 		    break;
5983f31c649SGarrett Wollman 
5993f31c649SGarrett Wollman 		  case TIME_DEL:
6003f31c649SGarrett Wollman 		    if ((newtime.tv_sec + 1) % 86400 == 0) {
6013f31c649SGarrett Wollman 		      newtime.tv_sec++;
6023f31c649SGarrett Wollman 		      time_state = TIME_WAIT;
6033f31c649SGarrett Wollman 		    }
6043f31c649SGarrett Wollman 		    break;
6053f31c649SGarrett Wollman 
6063f31c649SGarrett Wollman 		  case TIME_OOP:
6073f31c649SGarrett Wollman 		    time_state = TIME_WAIT;
6083f31c649SGarrett Wollman 		    break;
6093f31c649SGarrett Wollman 
6103f31c649SGarrett Wollman 		  case TIME_WAIT:
6113f31c649SGarrett Wollman 		    if (!(time_status & (STA_INS | STA_DEL)))
6123f31c649SGarrett Wollman 		      time_state = TIME_OK;
6133f31c649SGarrett Wollman 		  }
6143f31c649SGarrett Wollman 		}
6153f31c649SGarrett Wollman 		CPU_CLOCKUPDATE(&time, &newtime);
6163f31c649SGarrett Wollman 	}
617df8bae1dSRodney W. Grimes 
618df8bae1dSRodney W. Grimes 	/*
619df8bae1dSRodney W. Grimes 	 * Process callouts at a very low cpu priority, so we don't keep the
620df8bae1dSRodney W. Grimes 	 * relatively high clock interrupt priority any longer than necessary.
621df8bae1dSRodney W. Grimes 	 */
622df8bae1dSRodney W. Grimes 	if (needsoft) {
623df8bae1dSRodney W. Grimes 		if (CLKF_BASEPRI(frame)) {
624df8bae1dSRodney W. Grimes 			/*
625df8bae1dSRodney W. Grimes 			 * Save the overhead of a software interrupt;
626df8bae1dSRodney W. Grimes 			 * it will happen as soon as we return, so do it now.
627df8bae1dSRodney W. Grimes 			 */
628df8bae1dSRodney W. Grimes 			(void)splsoftclock();
629df8bae1dSRodney W. Grimes 			softclock();
630df8bae1dSRodney W. Grimes 		} else
631df8bae1dSRodney W. Grimes 			setsoftclock();
632df8bae1dSRodney W. Grimes 	}
633df8bae1dSRodney W. Grimes }
634df8bae1dSRodney W. Grimes 
635df8bae1dSRodney W. Grimes /*
636df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
637df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
638df8bae1dSRodney W. Grimes  */
639df8bae1dSRodney W. Grimes /*ARGSUSED*/
640df8bae1dSRodney W. Grimes void
641df8bae1dSRodney W. Grimes softclock()
642df8bae1dSRodney W. Grimes {
643df8bae1dSRodney W. Grimes 	register struct callout *c;
644df8bae1dSRodney W. Grimes 	register void *arg;
645df8bae1dSRodney W. Grimes 	register void (*func) __P((void *));
646df8bae1dSRodney W. Grimes 	register int s;
647df8bae1dSRodney W. Grimes 
648df8bae1dSRodney W. Grimes 	s = splhigh();
649df8bae1dSRodney W. Grimes 	while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
650df8bae1dSRodney W. Grimes 		func = c->c_func;
651df8bae1dSRodney W. Grimes 		arg = c->c_arg;
652df8bae1dSRodney W. Grimes 		calltodo.c_next = c->c_next;
653df8bae1dSRodney W. Grimes 		c->c_next = callfree;
654df8bae1dSRodney W. Grimes 		callfree = c;
655df8bae1dSRodney W. Grimes 		splx(s);
656df8bae1dSRodney W. Grimes 		(*func)(arg);
657df8bae1dSRodney W. Grimes 		(void) splhigh();
658df8bae1dSRodney W. Grimes 	}
659df8bae1dSRodney W. Grimes 	splx(s);
660df8bae1dSRodney W. Grimes }
661df8bae1dSRodney W. Grimes 
662df8bae1dSRodney W. Grimes /*
663df8bae1dSRodney W. Grimes  * timeout --
664df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
665df8bae1dSRodney W. Grimes  *
666df8bae1dSRodney W. Grimes  * untimeout --
667df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
668df8bae1dSRodney W. Grimes  *
669df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
670df8bae1dSRodney W. Grimes  *	implementation differs from that one in that no identification
671df8bae1dSRodney W. Grimes  *	value is returned from timeout, rather, the original arguments
672df8bae1dSRodney W. Grimes  *	to timeout are used to identify entries for untimeout.
673df8bae1dSRodney W. Grimes  */
674df8bae1dSRodney W. Grimes void
675df8bae1dSRodney W. Grimes timeout(ftn, arg, ticks)
676f23b4c91SGarrett Wollman 	timeout_t ftn;
677df8bae1dSRodney W. Grimes 	void *arg;
678df8bae1dSRodney W. Grimes 	register int ticks;
679df8bae1dSRodney W. Grimes {
680df8bae1dSRodney W. Grimes 	register struct callout *new, *p, *t;
681df8bae1dSRodney W. Grimes 	register int s;
682df8bae1dSRodney W. Grimes 
683df8bae1dSRodney W. Grimes 	if (ticks <= 0)
684df8bae1dSRodney W. Grimes 		ticks = 1;
685df8bae1dSRodney W. Grimes 
686df8bae1dSRodney W. Grimes 	/* Lock out the clock. */
687df8bae1dSRodney W. Grimes 	s = splhigh();
688df8bae1dSRodney W. Grimes 
689df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
690df8bae1dSRodney W. Grimes 	if (callfree == NULL)
691df8bae1dSRodney W. Grimes 		panic("timeout table full");
692df8bae1dSRodney W. Grimes 	new = callfree;
693df8bae1dSRodney W. Grimes 	callfree = new->c_next;
694df8bae1dSRodney W. Grimes 	new->c_arg = arg;
695df8bae1dSRodney W. Grimes 	new->c_func = ftn;
696df8bae1dSRodney W. Grimes 
697df8bae1dSRodney W. Grimes 	/*
698df8bae1dSRodney W. Grimes 	 * The time for each event is stored as a difference from the time
699df8bae1dSRodney W. Grimes 	 * of the previous event on the queue.  Walk the queue, correcting
700df8bae1dSRodney W. Grimes 	 * the ticks argument for queue entries passed.  Correct the ticks
701df8bae1dSRodney W. Grimes 	 * value for the queue entry immediately after the insertion point
702df8bae1dSRodney W. Grimes 	 * as well.  Watch out for negative c_time values; these represent
703df8bae1dSRodney W. Grimes 	 * overdue events.
704df8bae1dSRodney W. Grimes 	 */
705df8bae1dSRodney W. Grimes 	for (p = &calltodo;
706df8bae1dSRodney W. Grimes 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
707df8bae1dSRodney W. Grimes 		if (t->c_time > 0)
708df8bae1dSRodney W. Grimes 			ticks -= t->c_time;
709df8bae1dSRodney W. Grimes 	new->c_time = ticks;
710df8bae1dSRodney W. Grimes 	if (t != NULL)
711df8bae1dSRodney W. Grimes 		t->c_time -= ticks;
712df8bae1dSRodney W. Grimes 
713df8bae1dSRodney W. Grimes 	/* Insert the new entry into the queue. */
714df8bae1dSRodney W. Grimes 	p->c_next = new;
715df8bae1dSRodney W. Grimes 	new->c_next = t;
716df8bae1dSRodney W. Grimes 	splx(s);
717df8bae1dSRodney W. Grimes }
718df8bae1dSRodney W. Grimes 
719df8bae1dSRodney W. Grimes void
720df8bae1dSRodney W. Grimes untimeout(ftn, arg)
721f23b4c91SGarrett Wollman 	timeout_t ftn;
722df8bae1dSRodney W. Grimes 	void *arg;
723df8bae1dSRodney W. Grimes {
724df8bae1dSRodney W. Grimes 	register struct callout *p, *t;
725df8bae1dSRodney W. Grimes 	register int s;
726df8bae1dSRodney W. Grimes 
727df8bae1dSRodney W. Grimes 	s = splhigh();
728df8bae1dSRodney W. Grimes 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
729df8bae1dSRodney W. Grimes 		if (t->c_func == ftn && t->c_arg == arg) {
730df8bae1dSRodney W. Grimes 			/* Increment next entry's tick count. */
731df8bae1dSRodney W. Grimes 			if (t->c_next && t->c_time > 0)
732df8bae1dSRodney W. Grimes 				t->c_next->c_time += t->c_time;
733df8bae1dSRodney W. Grimes 
734df8bae1dSRodney W. Grimes 			/* Move entry from callout queue to callfree queue. */
735df8bae1dSRodney W. Grimes 			p->c_next = t->c_next;
736df8bae1dSRodney W. Grimes 			t->c_next = callfree;
737df8bae1dSRodney W. Grimes 			callfree = t;
738df8bae1dSRodney W. Grimes 			break;
739df8bae1dSRodney W. Grimes 		}
740df8bae1dSRodney W. Grimes 	splx(s);
741df8bae1dSRodney W. Grimes }
742df8bae1dSRodney W. Grimes 
743df8bae1dSRodney W. Grimes /*
744df8bae1dSRodney W. Grimes  * Compute number of hz until specified time.  Used to
745df8bae1dSRodney W. Grimes  * compute third argument to timeout() from an absolute time.
746df8bae1dSRodney W. Grimes  */
747df8bae1dSRodney W. Grimes int
748df8bae1dSRodney W. Grimes hzto(tv)
749df8bae1dSRodney W. Grimes 	struct timeval *tv;
750df8bae1dSRodney W. Grimes {
7516976af69SBruce Evans 	register unsigned long ticks;
7526976af69SBruce Evans 	register long sec, usec;
753df8bae1dSRodney W. Grimes 	int s;
754df8bae1dSRodney W. Grimes 
755df8bae1dSRodney W. Grimes 	/*
7566976af69SBruce Evans 	 * If the number of usecs in the whole seconds part of the time
7576976af69SBruce Evans 	 * difference fits in a long, then the total number of usecs will
7586976af69SBruce Evans 	 * fit in an unsigned long.  Compute the total and convert it to
7596976af69SBruce Evans 	 * ticks, rounding up and adding 1 to allow for the current tick
7606976af69SBruce Evans 	 * to expire.  Rounding also depends on unsigned long arithmetic
7616976af69SBruce Evans 	 * to avoid overflow.
762df8bae1dSRodney W. Grimes 	 *
7636976af69SBruce Evans 	 * Otherwise, if the number of ticks in the whole seconds part of
7646976af69SBruce Evans 	 * the time difference fits in a long, then convert the parts to
7656976af69SBruce Evans 	 * ticks separately and add, using similar rounding methods and
7666976af69SBruce Evans 	 * overflow avoidance.  This method would work in the previous
7676976af69SBruce Evans 	 * case but it is slightly slower and assumes that hz is integral.
7686976af69SBruce Evans 	 *
7696976af69SBruce Evans 	 * Otherwise, round the time difference down to the maximum
7706976af69SBruce Evans 	 * representable value.
7716976af69SBruce Evans 	 *
7726976af69SBruce Evans 	 * If ints have 32 bits, then the maximum value for any timeout in
7736976af69SBruce Evans 	 * 10ms ticks is 248 days.
774df8bae1dSRodney W. Grimes 	 */
7756976af69SBruce Evans 	s = splclock();
776df8bae1dSRodney W. Grimes 	sec = tv->tv_sec - time.tv_sec;
7776976af69SBruce Evans 	usec = tv->tv_usec - time.tv_usec;
778df8bae1dSRodney W. Grimes 	splx(s);
7796976af69SBruce Evans 	if (usec < 0) {
7806976af69SBruce Evans 		sec--;
7816976af69SBruce Evans 		usec += 1000000;
7826976af69SBruce Evans 	}
7836976af69SBruce Evans 	if (sec < 0) {
7846976af69SBruce Evans #ifdef DIAGNOSTIC
7856976af69SBruce Evans 		printf("hzto: negative time difference %ld sec %ld usec\n",
7866976af69SBruce Evans 		       sec, usec);
7876976af69SBruce Evans #endif
7886976af69SBruce Evans 		ticks = 1;
7896976af69SBruce Evans 	} else if (sec <= LONG_MAX / 1000000)
7906976af69SBruce Evans 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
7916976af69SBruce Evans 			/ tick + 1;
7926976af69SBruce Evans 	else if (sec <= LONG_MAX / hz)
7936976af69SBruce Evans 		ticks = sec * hz
7946976af69SBruce Evans 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
7956976af69SBruce Evans 	else
7966976af69SBruce Evans 		ticks = LONG_MAX;
7976976af69SBruce Evans 	if (ticks > INT_MAX)
7986976af69SBruce Evans 		ticks = INT_MAX;
799df8bae1dSRodney W. Grimes 	return (ticks);
800df8bae1dSRodney W. Grimes }
801df8bae1dSRodney W. Grimes 
802df8bae1dSRodney W. Grimes /*
803df8bae1dSRodney W. Grimes  * Start profiling on a process.
804df8bae1dSRodney W. Grimes  *
805df8bae1dSRodney W. Grimes  * Kernel profiling passes proc0 which never exits and hence
806df8bae1dSRodney W. Grimes  * keeps the profile clock running constantly.
807df8bae1dSRodney W. Grimes  */
808df8bae1dSRodney W. Grimes void
809df8bae1dSRodney W. Grimes startprofclock(p)
810df8bae1dSRodney W. Grimes 	register struct proc *p;
811df8bae1dSRodney W. Grimes {
812df8bae1dSRodney W. Grimes 	int s;
813df8bae1dSRodney W. Grimes 
814df8bae1dSRodney W. Grimes 	if ((p->p_flag & P_PROFIL) == 0) {
815df8bae1dSRodney W. Grimes 		p->p_flag |= P_PROFIL;
816df8bae1dSRodney W. Grimes 		if (++profprocs == 1 && stathz != 0) {
817df8bae1dSRodney W. Grimes 			s = splstatclock();
818df8bae1dSRodney W. Grimes 			psdiv = pscnt = psratio;
819df8bae1dSRodney W. Grimes 			setstatclockrate(profhz);
820df8bae1dSRodney W. Grimes 			splx(s);
821df8bae1dSRodney W. Grimes 		}
822df8bae1dSRodney W. Grimes 	}
823df8bae1dSRodney W. Grimes }
824df8bae1dSRodney W. Grimes 
825df8bae1dSRodney W. Grimes /*
826df8bae1dSRodney W. Grimes  * Stop profiling on a process.
827df8bae1dSRodney W. Grimes  */
828df8bae1dSRodney W. Grimes void
829df8bae1dSRodney W. Grimes stopprofclock(p)
830df8bae1dSRodney W. Grimes 	register struct proc *p;
831df8bae1dSRodney W. Grimes {
832df8bae1dSRodney W. Grimes 	int s;
833df8bae1dSRodney W. Grimes 
834df8bae1dSRodney W. Grimes 	if (p->p_flag & P_PROFIL) {
835df8bae1dSRodney W. Grimes 		p->p_flag &= ~P_PROFIL;
836df8bae1dSRodney W. Grimes 		if (--profprocs == 0 && stathz != 0) {
837df8bae1dSRodney W. Grimes 			s = splstatclock();
838df8bae1dSRodney W. Grimes 			psdiv = pscnt = 1;
839df8bae1dSRodney W. Grimes 			setstatclockrate(stathz);
840df8bae1dSRodney W. Grimes 			splx(s);
841df8bae1dSRodney W. Grimes 		}
842df8bae1dSRodney W. Grimes 	}
843df8bae1dSRodney W. Grimes }
844df8bae1dSRodney W. Grimes 
845df8bae1dSRodney W. Grimes /*
846df8bae1dSRodney W. Grimes  * Statistics clock.  Grab profile sample, and if divider reaches 0,
847df8bae1dSRodney W. Grimes  * do process and kernel statistics.
848df8bae1dSRodney W. Grimes  */
849df8bae1dSRodney W. Grimes void
850df8bae1dSRodney W. Grimes statclock(frame)
851df8bae1dSRodney W. Grimes 	register struct clockframe *frame;
852df8bae1dSRodney W. Grimes {
853df8bae1dSRodney W. Grimes #ifdef GPROF
854df8bae1dSRodney W. Grimes 	register struct gmonparam *g;
855df8bae1dSRodney W. Grimes #endif
8568a129caeSDavid Greenman 	register struct proc *p = curproc;
857df8bae1dSRodney W. Grimes 	register int i;
858df8bae1dSRodney W. Grimes 
8598a129caeSDavid Greenman 	if (p) {
8608a129caeSDavid Greenman 		struct pstats *pstats;
8618a129caeSDavid Greenman 		struct rusage *ru;
8628a129caeSDavid Greenman 		struct vmspace *vm;
8638a129caeSDavid Greenman 
8648a129caeSDavid Greenman 		/* bump the resource usage of integral space use */
8658a129caeSDavid Greenman 		if ((pstats = p->p_stats) && (ru = &pstats->p_ru) && (vm = p->p_vmspace)) {
8668a129caeSDavid Greenman 			ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024;
8678a129caeSDavid Greenman 			ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024;
8688a129caeSDavid Greenman 			ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024;
8698a129caeSDavid Greenman 			if ((vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024) >
8708a129caeSDavid Greenman 			    ru->ru_maxrss) {
8718a129caeSDavid Greenman 				ru->ru_maxrss =
8728a129caeSDavid Greenman 				    vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024;
8738a129caeSDavid Greenman 			}
8748a129caeSDavid Greenman         	}
8758a129caeSDavid Greenman 	}
8768a129caeSDavid Greenman 
877df8bae1dSRodney W. Grimes 	if (CLKF_USERMODE(frame)) {
878df8bae1dSRodney W. Grimes 		if (p->p_flag & P_PROFIL)
879df8bae1dSRodney W. Grimes 			addupc_intr(p, CLKF_PC(frame), 1);
880df8bae1dSRodney W. Grimes 		if (--pscnt > 0)
881df8bae1dSRodney W. Grimes 			return;
882df8bae1dSRodney W. Grimes 		/*
883df8bae1dSRodney W. Grimes 		 * Came from user mode; CPU was in user state.
884df8bae1dSRodney W. Grimes 		 * If this process is being profiled record the tick.
885df8bae1dSRodney W. Grimes 		 */
886df8bae1dSRodney W. Grimes 		p->p_uticks++;
887df8bae1dSRodney W. Grimes 		if (p->p_nice > NZERO)
888df8bae1dSRodney W. Grimes 			cp_time[CP_NICE]++;
889df8bae1dSRodney W. Grimes 		else
890df8bae1dSRodney W. Grimes 			cp_time[CP_USER]++;
891df8bae1dSRodney W. Grimes 	} else {
892df8bae1dSRodney W. Grimes #ifdef GPROF
893df8bae1dSRodney W. Grimes 		/*
894df8bae1dSRodney W. Grimes 		 * Kernel statistics are just like addupc_intr, only easier.
895df8bae1dSRodney W. Grimes 		 */
896df8bae1dSRodney W. Grimes 		g = &_gmonparam;
897df8bae1dSRodney W. Grimes 		if (g->state == GMON_PROF_ON) {
898df8bae1dSRodney W. Grimes 			i = CLKF_PC(frame) - g->lowpc;
899df8bae1dSRodney W. Grimes 			if (i < g->textsize) {
900df8bae1dSRodney W. Grimes 				i /= HISTFRACTION * sizeof(*g->kcount);
901df8bae1dSRodney W. Grimes 				g->kcount[i]++;
902df8bae1dSRodney W. Grimes 			}
903df8bae1dSRodney W. Grimes 		}
904df8bae1dSRodney W. Grimes #endif
905df8bae1dSRodney W. Grimes 		if (--pscnt > 0)
906df8bae1dSRodney W. Grimes 			return;
907df8bae1dSRodney W. Grimes 		/*
908df8bae1dSRodney W. Grimes 		 * Came from kernel mode, so we were:
909df8bae1dSRodney W. Grimes 		 * - handling an interrupt,
910df8bae1dSRodney W. Grimes 		 * - doing syscall or trap work on behalf of the current
911df8bae1dSRodney W. Grimes 		 *   user process, or
912df8bae1dSRodney W. Grimes 		 * - spinning in the idle loop.
913df8bae1dSRodney W. Grimes 		 * Whichever it is, charge the time as appropriate.
914df8bae1dSRodney W. Grimes 		 * Note that we charge interrupts to the current process,
915df8bae1dSRodney W. Grimes 		 * regardless of whether they are ``for'' that process,
916df8bae1dSRodney W. Grimes 		 * so that we know how much of its real time was spent
917df8bae1dSRodney W. Grimes 		 * in ``non-process'' (i.e., interrupt) work.
918df8bae1dSRodney W. Grimes 		 */
919df8bae1dSRodney W. Grimes 		if (CLKF_INTR(frame)) {
920df8bae1dSRodney W. Grimes 			if (p != NULL)
921df8bae1dSRodney W. Grimes 				p->p_iticks++;
922df8bae1dSRodney W. Grimes 			cp_time[CP_INTR]++;
923df8bae1dSRodney W. Grimes 		} else if (p != NULL) {
924df8bae1dSRodney W. Grimes 			p->p_sticks++;
925df8bae1dSRodney W. Grimes 			cp_time[CP_SYS]++;
926df8bae1dSRodney W. Grimes 		} else
927df8bae1dSRodney W. Grimes 			cp_time[CP_IDLE]++;
928df8bae1dSRodney W. Grimes 	}
929df8bae1dSRodney W. Grimes 	pscnt = psdiv;
930df8bae1dSRodney W. Grimes 
931df8bae1dSRodney W. Grimes 	/*
932df8bae1dSRodney W. Grimes 	 * We maintain statistics shown by user-level statistics
933df8bae1dSRodney W. Grimes 	 * programs:  the amount of time in each cpu state, and
934df8bae1dSRodney W. Grimes 	 * the amount of time each of DK_NDRIVE ``drives'' is busy.
935df8bae1dSRodney W. Grimes 	 *
936df8bae1dSRodney W. Grimes 	 * XXX	should either run linked list of drives, or (better)
937df8bae1dSRodney W. Grimes 	 *	grab timestamps in the start & done code.
938df8bae1dSRodney W. Grimes 	 */
939df8bae1dSRodney W. Grimes 	for (i = 0; i < DK_NDRIVE; i++)
940df8bae1dSRodney W. Grimes 		if (dk_busy & (1 << i))
941df8bae1dSRodney W. Grimes 			dk_time[i]++;
942df8bae1dSRodney W. Grimes 
943df8bae1dSRodney W. Grimes 	/*
944df8bae1dSRodney W. Grimes 	 * We adjust the priority of the current process.  The priority of
945df8bae1dSRodney W. Grimes 	 * a process gets worse as it accumulates CPU time.  The cpu usage
946df8bae1dSRodney W. Grimes 	 * estimator (p_estcpu) is increased here.  The formula for computing
947df8bae1dSRodney W. Grimes 	 * priorities (in kern_synch.c) will compute a different value each
948df8bae1dSRodney W. Grimes 	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
949df8bae1dSRodney W. Grimes 	 * quite quickly when the process is running (linearly), and decays
950df8bae1dSRodney W. Grimes 	 * away exponentially, at a rate which is proportionally slower when
951df8bae1dSRodney W. Grimes 	 * the system is busy.  The basic principal is that the system will
952df8bae1dSRodney W. Grimes 	 * 90% forget that the process used a lot of CPU time in 5 * loadav
953df8bae1dSRodney W. Grimes 	 * seconds.  This causes the system to favor processes which haven't
954df8bae1dSRodney W. Grimes 	 * run much recently, and to round-robin among other processes.
955df8bae1dSRodney W. Grimes 	 */
956df8bae1dSRodney W. Grimes 	if (p != NULL) {
957df8bae1dSRodney W. Grimes 		p->p_cpticks++;
958df8bae1dSRodney W. Grimes 		if (++p->p_estcpu == 0)
959df8bae1dSRodney W. Grimes 			p->p_estcpu--;
960df8bae1dSRodney W. Grimes 		if ((p->p_estcpu & 3) == 0) {
961df8bae1dSRodney W. Grimes 			resetpriority(p);
962df8bae1dSRodney W. Grimes 			if (p->p_priority >= PUSER)
963df8bae1dSRodney W. Grimes 				p->p_priority = p->p_usrpri;
964df8bae1dSRodney W. Grimes 		}
965df8bae1dSRodney W. Grimes 	}
966df8bae1dSRodney W. Grimes }
967df8bae1dSRodney W. Grimes 
968df8bae1dSRodney W. Grimes /*
969df8bae1dSRodney W. Grimes  * Return information about system clocks.
970df8bae1dSRodney W. Grimes  */
97126f9a767SRodney W. Grimes int
972df8bae1dSRodney W. Grimes sysctl_clockrate(where, sizep)
973df8bae1dSRodney W. Grimes 	register char *where;
974df8bae1dSRodney W. Grimes 	size_t *sizep;
975df8bae1dSRodney W. Grimes {
976df8bae1dSRodney W. Grimes 	struct clockinfo clkinfo;
977df8bae1dSRodney W. Grimes 
978df8bae1dSRodney W. Grimes 	/*
979df8bae1dSRodney W. Grimes 	 * Construct clockinfo structure.
980df8bae1dSRodney W. Grimes 	 */
981df8bae1dSRodney W. Grimes 	clkinfo.hz = hz;
982df8bae1dSRodney W. Grimes 	clkinfo.tick = tick;
983df8bae1dSRodney W. Grimes 	clkinfo.profhz = profhz;
984df8bae1dSRodney W. Grimes 	clkinfo.stathz = stathz ? stathz : hz;
985df8bae1dSRodney W. Grimes 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
986df8bae1dSRodney W. Grimes }
9873f31c649SGarrett Wollman 
9883f31c649SGarrett Wollman /*#ifdef PPS_SYNC*/
9893f31c649SGarrett Wollman #if 0
9903f31c649SGarrett Wollman /* This code is completely bogus; if anybody ever wants to use it, get
9913f31c649SGarrett Wollman  * the current version from Dave Mills. */
9923f31c649SGarrett Wollman 
9933f31c649SGarrett Wollman /*
9943f31c649SGarrett Wollman  * hardpps() - discipline CPU clock oscillator to external pps signal
9953f31c649SGarrett Wollman  *
9963f31c649SGarrett Wollman  * This routine is called at each PPS interrupt in order to discipline
9973f31c649SGarrett Wollman  * the CPU clock oscillator to the PPS signal. It integrates successive
9983f31c649SGarrett Wollman  * phase differences between the two oscillators and calculates the
9993f31c649SGarrett Wollman  * frequency offset. This is used in hardclock() to discipline the CPU
10003f31c649SGarrett Wollman  * clock oscillator so that intrinsic frequency error is cancelled out.
10013f31c649SGarrett Wollman  * The code requires the caller to capture the time and hardware
10023f31c649SGarrett Wollman  * counter value at the designated PPS signal transition.
10033f31c649SGarrett Wollman  */
10043f31c649SGarrett Wollman void
10053f31c649SGarrett Wollman hardpps(tvp, usec)
10063f31c649SGarrett Wollman 	struct timeval *tvp;		/* time at PPS */
10073f31c649SGarrett Wollman 	long usec;			/* hardware counter at PPS */
10083f31c649SGarrett Wollman {
10093f31c649SGarrett Wollman 	long u_usec, v_usec, bigtick;
10103f31c649SGarrett Wollman 	long cal_sec, cal_usec;
10113f31c649SGarrett Wollman 
10123f31c649SGarrett Wollman 	/*
10133f31c649SGarrett Wollman 	 * During the calibration interval adjust the starting time when
10143f31c649SGarrett Wollman 	 * the tick overflows. At the end of the interval compute the
10153f31c649SGarrett Wollman 	 * duration of the interval and the difference of the hardware
10163f31c649SGarrett Wollman 	 * counters at the beginning and end of the interval. This code
10173f31c649SGarrett Wollman 	 * is deliciously complicated by the fact valid differences may
10183f31c649SGarrett Wollman 	 * exceed the value of tick when using long calibration
10193f31c649SGarrett Wollman 	 * intervals and small ticks. Note that the counter can be
10203f31c649SGarrett Wollman 	 * greater than tick if caught at just the wrong instant, but
10213f31c649SGarrett Wollman 	 * the values returned and used here are correct.
10223f31c649SGarrett Wollman 	 */
10233f31c649SGarrett Wollman 	bigtick = (long)tick << SHIFT_USEC;
10243f31c649SGarrett Wollman 	pps_usec -= ntp_pll.ybar;
10253f31c649SGarrett Wollman 	if (pps_usec >= bigtick)
10263f31c649SGarrett Wollman 		pps_usec -= bigtick;
10273f31c649SGarrett Wollman 	if (pps_usec < 0)
10283f31c649SGarrett Wollman 		pps_usec += bigtick;
10293f31c649SGarrett Wollman 	pps_time.tv_sec++;
10303f31c649SGarrett Wollman 	pps_count++;
10313f31c649SGarrett Wollman 	if (pps_count < (1 << pps_shift))
10323f31c649SGarrett Wollman 		return;
10333f31c649SGarrett Wollman 	pps_count = 0;
10343f31c649SGarrett Wollman 	ntp_pll.calcnt++;
10353f31c649SGarrett Wollman 	u_usec = usec << SHIFT_USEC;
10363f31c649SGarrett Wollman 	v_usec = pps_usec - u_usec;
10373f31c649SGarrett Wollman 	if (v_usec >= bigtick >> 1)
10383f31c649SGarrett Wollman 		v_usec -= bigtick;
10393f31c649SGarrett Wollman 	if (v_usec < -(bigtick >> 1))
10403f31c649SGarrett Wollman 		v_usec += bigtick;
10413f31c649SGarrett Wollman 	if (v_usec < 0)
10423f31c649SGarrett Wollman 		v_usec = -(-v_usec >> ntp_pll.shift);
10433f31c649SGarrett Wollman 	else
10443f31c649SGarrett Wollman 		v_usec = v_usec >> ntp_pll.shift;
10453f31c649SGarrett Wollman 	pps_usec = u_usec;
10463f31c649SGarrett Wollman 	cal_sec = tvp->tv_sec;
10473f31c649SGarrett Wollman 	cal_usec = tvp->tv_usec;
10483f31c649SGarrett Wollman 	cal_sec -= pps_time.tv_sec;
10493f31c649SGarrett Wollman 	cal_usec -= pps_time.tv_usec;
10503f31c649SGarrett Wollman 	if (cal_usec < 0) {
10513f31c649SGarrett Wollman 		cal_usec += 1000000;
10523f31c649SGarrett Wollman 		cal_sec--;
10533f31c649SGarrett Wollman 	}
10543f31c649SGarrett Wollman 	pps_time = *tvp;
10553f31c649SGarrett Wollman 
10563f31c649SGarrett Wollman 	/*
10573f31c649SGarrett Wollman 	 * Check for lost interrupts, noise, excessive jitter and
10583f31c649SGarrett Wollman 	 * excessive frequency error. The number of timer ticks during
10593f31c649SGarrett Wollman 	 * the interval may vary +-1 tick. Add to this a margin of one
10603f31c649SGarrett Wollman 	 * tick for the PPS signal jitter and maximum frequency
10613f31c649SGarrett Wollman 	 * deviation. If the limits are exceeded, the calibration
10623f31c649SGarrett Wollman 	 * interval is reset to the minimum and we start over.
10633f31c649SGarrett Wollman 	 */
10643f31c649SGarrett Wollman 	u_usec = (long)tick << 1;
10653f31c649SGarrett Wollman 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
10663f31c649SGarrett Wollman 	    || (cal_sec == 0 && cal_usec < u_usec))
10673f31c649SGarrett Wollman 	    || v_usec > ntp_pll.tolerance || v_usec < -ntp_pll.tolerance) {
10683f31c649SGarrett Wollman 		ntp_pll.jitcnt++;
10693f31c649SGarrett Wollman 		ntp_pll.shift = NTP_PLL.SHIFT;
10703f31c649SGarrett Wollman 		pps_dispinc = PPS_DISPINC;
10713f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
10723f31c649SGarrett Wollman 		return;
10733f31c649SGarrett Wollman 	}
10743f31c649SGarrett Wollman 
10753f31c649SGarrett Wollman 	/*
10763f31c649SGarrett Wollman 	 * A three-stage median filter is used to help deglitch the pps
10773f31c649SGarrett Wollman 	 * signal. The median sample becomes the offset estimate; the
10783f31c649SGarrett Wollman 	 * difference between the other two samples becomes the
10793f31c649SGarrett Wollman 	 * dispersion estimate.
10803f31c649SGarrett Wollman 	 */
10813f31c649SGarrett Wollman 	pps_mf[2] = pps_mf[1];
10823f31c649SGarrett Wollman 	pps_mf[1] = pps_mf[0];
10833f31c649SGarrett Wollman 	pps_mf[0] = v_usec;
10843f31c649SGarrett Wollman 	if (pps_mf[0] > pps_mf[1]) {
10853f31c649SGarrett Wollman 		if (pps_mf[1] > pps_mf[2]) {
10863f31c649SGarrett Wollman 			u_usec = pps_mf[1];		/* 0 1 2 */
10873f31c649SGarrett Wollman 			v_usec = pps_mf[0] - pps_mf[2];
10883f31c649SGarrett Wollman 		} else if (pps_mf[2] > pps_mf[0]) {
10893f31c649SGarrett Wollman 			u_usec = pps_mf[0];		/* 2 0 1 */
10903f31c649SGarrett Wollman 			v_usec = pps_mf[2] - pps_mf[1];
10913f31c649SGarrett Wollman 		} else {
10923f31c649SGarrett Wollman 			u_usec = pps_mf[2];		/* 0 2 1 */
10933f31c649SGarrett Wollman 			v_usec = pps_mf[0] - pps_mf[1];
10943f31c649SGarrett Wollman 		}
10953f31c649SGarrett Wollman 	} else {
10963f31c649SGarrett Wollman 		if (pps_mf[1] < pps_mf[2]) {
10973f31c649SGarrett Wollman 			u_usec = pps_mf[1];		/* 2 1 0 */
10983f31c649SGarrett Wollman 			v_usec = pps_mf[2] - pps_mf[0];
10993f31c649SGarrett Wollman 		} else  if (pps_mf[2] < pps_mf[0]) {
11003f31c649SGarrett Wollman 			u_usec = pps_mf[0];		/* 1 0 2 */
11013f31c649SGarrett Wollman 			v_usec = pps_mf[1] - pps_mf[2];
11023f31c649SGarrett Wollman 		} else {
11033f31c649SGarrett Wollman 			u_usec = pps_mf[2];		/* 1 2 0 */
11043f31c649SGarrett Wollman 			v_usec = pps_mf[1] - pps_mf[0];
11053f31c649SGarrett Wollman 		}
11063f31c649SGarrett Wollman 	}
11073f31c649SGarrett Wollman 
11083f31c649SGarrett Wollman 	/*
11093f31c649SGarrett Wollman 	 * Here the dispersion average is updated. If it is less than
11103f31c649SGarrett Wollman 	 * the threshold pps_dispmax, the frequency average is updated
11113f31c649SGarrett Wollman 	 * as well, but clamped to the tolerance.
11123f31c649SGarrett Wollman 	 */
11133f31c649SGarrett Wollman 	v_usec = (v_usec >> 1) - ntp_pll.disp;
11143f31c649SGarrett Wollman 	if (v_usec < 0)
11153f31c649SGarrett Wollman 		ntp_pll.disp -= -v_usec >> PPS_AVG;
11163f31c649SGarrett Wollman 	else
11173f31c649SGarrett Wollman 		ntp_pll.disp += v_usec >> PPS_AVG;
11183f31c649SGarrett Wollman 	if (ntp_pll.disp > pps_dispmax) {
11193f31c649SGarrett Wollman 		ntp_pll.discnt++;
11203f31c649SGarrett Wollman 		return;
11213f31c649SGarrett Wollman 	}
11223f31c649SGarrett Wollman 	if (u_usec < 0) {
11233f31c649SGarrett Wollman 		ntp_pll.ybar -= -u_usec >> PPS_AVG;
11243f31c649SGarrett Wollman 		if (ntp_pll.ybar < -ntp_pll.tolerance)
11253f31c649SGarrett Wollman 			ntp_pll.ybar = -ntp_pll.tolerance;
11263f31c649SGarrett Wollman 		u_usec = -u_usec;
11273f31c649SGarrett Wollman 	} else {
11283f31c649SGarrett Wollman 		ntp_pll.ybar += u_usec >> PPS_AVG;
11293f31c649SGarrett Wollman 		if (ntp_pll.ybar > ntp_pll.tolerance)
11303f31c649SGarrett Wollman 			ntp_pll.ybar = ntp_pll.tolerance;
11313f31c649SGarrett Wollman 	}
11323f31c649SGarrett Wollman 
11333f31c649SGarrett Wollman 	/*
11343f31c649SGarrett Wollman 	 * Here the calibration interval is adjusted. If the maximum
11353f31c649SGarrett Wollman 	 * time difference is greater than tick/4, reduce the interval
11363f31c649SGarrett Wollman 	 * by half. If this is not the case for four consecutive
11373f31c649SGarrett Wollman 	 * intervals, double the interval.
11383f31c649SGarrett Wollman 	 */
11393f31c649SGarrett Wollman 	if (u_usec << ntp_pll.shift > bigtick >> 2) {
11403f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
11413f31c649SGarrett Wollman 		if (ntp_pll.shift > NTP_PLL.SHIFT) {
11423f31c649SGarrett Wollman 			ntp_pll.shift--;
11433f31c649SGarrett Wollman 			pps_dispinc <<= 1;
11443f31c649SGarrett Wollman 		}
11453f31c649SGarrett Wollman 	} else if (ntp_pll.intcnt >= 4) {
11463f31c649SGarrett Wollman 		ntp_pll.intcnt = 0;
11473f31c649SGarrett Wollman 		if (ntp_pll.shift < NTP_PLL.SHIFTMAX) {
11483f31c649SGarrett Wollman 			ntp_pll.shift++;
11493f31c649SGarrett Wollman 			pps_dispinc >>= 1;
11503f31c649SGarrett Wollman 		}
11513f31c649SGarrett Wollman 	} else
11523f31c649SGarrett Wollman 		ntp_pll.intcnt++;
11533f31c649SGarrett Wollman }
11543f31c649SGarrett Wollman #endif /* PPS_SYNC */
1155