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