kern_ntptime.c revision 177253
1139804Simp/*-
2139804Simp ***********************************************************************
344574Sphk *								       *
475540Sjhay * Copyright (c) David L. Mills 1993-2001			       *
544574Sphk *								       *
644574Sphk * Permission to use, copy, modify, and distribute this software and   *
744574Sphk * its documentation for any purpose and without fee is hereby	       *
844574Sphk * granted, provided that the above copyright notice appears in all    *
944574Sphk * copies and that both the copyright notice and this permission       *
1044574Sphk * notice appear in supporting documentation, and that the name	       *
1144574Sphk * University of Delaware not be used in advertising or publicity      *
1244574Sphk * pertaining to distribution of the software without specific,	       *
1344574Sphk * written prior permission. The University of Delaware makes no       *
1444574Sphk * representations about the suitability this software for any	       *
1544574Sphk * purpose. It is provided "as is" without express or implied	       *
1644574Sphk * warranty.							       *
1744574Sphk *								       *
1844574Sphk **********************************************************************/
192858Swollman
202858Swollman/*
2144574Sphk * Adapted from the original sources for FreeBSD and timecounters by:
2244666Sphk * Poul-Henning Kamp <phk@FreeBSD.org>.
232858Swollman *
2444574Sphk * The 32bit version of the "LP" macros seems a bit past its "sell by"
2544574Sphk * date so I have retained only the 64bit version and included it directly
2644574Sphk * in this file.
2721101Sjhay *
2844574Sphk * Only minor changes done to interface with the timecounters over in
2944574Sphk * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
3044574Sphk * confusing and/or plain wrong in that context.
312858Swollman */
3232925Seivind
33116182Sobrien#include <sys/cdefs.h>
34116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/kern_ntptime.c 177253 2008-03-16 10:58:09Z rwatson $");
35116182Sobrien
3644666Sphk#include "opt_ntp.h"
3744666Sphk
382858Swollman#include <sys/param.h>
392858Swollman#include <sys/systm.h>
4012221Sbde#include <sys/sysproto.h>
412858Swollman#include <sys/kernel.h>
42164033Srwatson#include <sys/priv.h>
432858Swollman#include <sys/proc.h>
4482717Sdillon#include <sys/lock.h>
4582717Sdillon#include <sys/mutex.h>
4644574Sphk#include <sys/time.h>
472858Swollman#include <sys/timex.h>
4858377Sphk#include <sys/timetc.h>
4936941Sphk#include <sys/timepps.h>
50144445Sjhb#include <sys/syscallsubr.h>
512858Swollman#include <sys/sysctl.h>
522858Swollman
532858Swollman/*
5444574Sphk * Single-precision macros for 64-bit machines
5544574Sphk */
56126974Sphktypedef int64_t l_fp;
5744574Sphk#define L_ADD(v, u)	((v) += (u))
5844574Sphk#define L_SUB(v, u)	((v) -= (u))
59126974Sphk#define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
6044574Sphk#define L_NEG(v)	((v) = -(v))
6144574Sphk#define L_RSHIFT(v, n) \
6244574Sphk	do { \
6344574Sphk		if ((v) < 0) \
6444574Sphk			(v) = -(-(v) >> (n)); \
6544574Sphk		else \
6644574Sphk			(v) = (v) >> (n); \
6744574Sphk	} while (0)
6844574Sphk#define L_MPY(v, a)	((v) *= (a))
6944574Sphk#define L_CLR(v)	((v) = 0)
7044574Sphk#define L_ISNEG(v)	((v) < 0)
71126974Sphk#define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
7244574Sphk#define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
7344574Sphk
7444574Sphk/*
7544574Sphk * Generic NTP kernel interface
7632513Sphk *
7744574Sphk * These routines constitute the Network Time Protocol (NTP) interfaces
7844574Sphk * for user and daemon application programs. The ntp_gettime() routine
7944574Sphk * provides the time, maximum error (synch distance) and estimated error
8044574Sphk * (dispersion) to client user application programs. The ntp_adjtime()
8144574Sphk * routine is used by the NTP daemon to adjust the system clock to an
8244574Sphk * externally derived time. The time offset and related variables set by
8344574Sphk * this routine are used by other routines in this module to adjust the
8444574Sphk * phase and frequency of the clock discipline loop which controls the
8544574Sphk * system clock.
8632513Sphk *
8745294Sphk * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
8844574Sphk * defined), the time at each tick interrupt is derived directly from
8944574Sphk * the kernel time variable. When the kernel time is reckoned in
9045294Sphk * microseconds, (NTP_NANO undefined), the time is derived from the
9145294Sphk * kernel time variable together with a variable representing the
9245294Sphk * leftover nanoseconds at the last tick interrupt. In either case, the
9345294Sphk * current nanosecond time is reckoned from these values plus an
9445294Sphk * interpolated value derived by the clock routines in another
9545294Sphk * architecture-specific module. The interpolation can use either a
9645294Sphk * dedicated counter or a processor cycle counter (PCC) implemented in
9745294Sphk * some architectures.
9832513Sphk *
9944574Sphk * Note that all routines must run at priority splclock or higher.
10044574Sphk */
10144574Sphk/*
10244574Sphk * Phase/frequency-lock loop (PLL/FLL) definitions
10332513Sphk *
10444574Sphk * The nanosecond clock discipline uses two variable types, time
10544574Sphk * variables and frequency variables. Both types are represented as 64-
10644574Sphk * bit fixed-point quantities with the decimal point between two 32-bit
10744574Sphk * halves. On a 32-bit machine, each half is represented as a single
10844574Sphk * word and mathematical operations are done using multiple-precision
10944574Sphk * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
11044574Sphk * used.
11132513Sphk *
11244574Sphk * A time variable is a signed 64-bit fixed-point number in ns and
11344574Sphk * fraction. It represents the remaining time offset to be amortized
11444574Sphk * over succeeding tick interrupts. The maximum time offset is about
11545294Sphk * 0.5 s and the resolution is about 2.3e-10 ns.
11632513Sphk *
11744574Sphk *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
11844574Sphk *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
11944574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12044574Sphk * |s s s|			 ns				   |
12144574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12244574Sphk * |			    fraction				   |
12344574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12432513Sphk *
12544574Sphk * A frequency variable is a signed 64-bit fixed-point number in ns/s
12644574Sphk * and fraction. It represents the ns and fraction to be added to the
12744574Sphk * kernel time variable at each second. The maximum frequency offset is
12845294Sphk * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
12932513Sphk *
13044574Sphk *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
13144574Sphk *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
13244574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
13344574Sphk * |s s s s s s s s s s s s s|	          ns/s			   |
13444574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
13544574Sphk * |			    fraction				   |
13644574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1372858Swollman */
13832513Sphk/*
13932513Sphk * The following variables establish the state of the PLL/FLL and the
14044574Sphk * residual time and frequency offset of the local clock.
14132513Sphk */
14244574Sphk#define SHIFT_PLL	4		/* PLL loop gain (shift) */
14344574Sphk#define SHIFT_FLL	2		/* FLL loop gain (shift) */
14432513Sphk
14544574Sphkstatic int time_state = TIME_OK;	/* clock state */
14644574Sphkstatic int time_status = STA_UNSYNC;	/* clock status bits */
14765432Sphkstatic long time_tai;			/* TAI offset (s) */
14865432Sphkstatic long time_monitor;		/* last time offset scaled (ns) */
14944574Sphkstatic long time_constant;		/* poll interval (shift) (s) */
15044574Sphkstatic long time_precision = 1;		/* clock precision (ns) */
15144574Sphkstatic long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
15244574Sphkstatic long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
15344574Sphkstatic long time_reftime;		/* time at last adjustment (s) */
15444574Sphkstatic l_fp time_offset;		/* time offset (ns) */
15544574Sphkstatic l_fp time_freq;			/* frequency offset (ns/s) */
15665432Sphkstatic l_fp time_adj;			/* tick adjust (ns/s) */
15744574Sphk
15894754Sphkstatic int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
15994754Sphk
1602858Swollman#ifdef PPS_SYNC
1612858Swollman/*
16244574Sphk * The following variables are used when a pulse-per-second (PPS) signal
16344574Sphk * is available and connected via a modem control lead. They establish
16444574Sphk * the engineering parameters of the clock discipline loop when
16544574Sphk * controlled by the PPS signal.
1662858Swollman */
16744574Sphk#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
16875540Sjhay#define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
16950656Sphk#define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
17044574Sphk#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
17144574Sphk#define PPS_VALID	120		/* PPS signal watchdog max (s) */
17250656Sphk#define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
17350656Sphk#define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
17432513Sphk
17550656Sphkstatic struct timespec pps_tf[3];	/* phase median filter */
17644574Sphkstatic l_fp pps_freq;			/* scaled frequency offset (ns/s) */
17745294Sphkstatic long pps_fcount;			/* frequency accumulator */
17850656Sphkstatic long pps_jitter;			/* nominal jitter (ns) */
17950656Sphkstatic long pps_stabil;			/* nominal stability (scaled ns/s) */
18044574Sphkstatic long pps_lastsec;		/* time at last calibration (s) */
18144574Sphkstatic int pps_valid;			/* signal watchdog counter */
18244574Sphkstatic int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
18350656Sphkstatic int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
18444574Sphkstatic int pps_intcnt;			/* wander counter */
18544574Sphk
18632513Sphk/*
18732513Sphk * PPS signal quality monitors
18832513Sphk */
18944574Sphkstatic long pps_calcnt;			/* calibration intervals */
19044574Sphkstatic long pps_jitcnt;			/* jitter limit exceeded */
19144574Sphkstatic long pps_stbcnt;			/* stability limit exceeded */
19244574Sphkstatic long pps_errcnt;			/* calibration errors */
1932858Swollman#endif /* PPS_SYNC */
19432513Sphk/*
19544574Sphk * End of phase/frequency-lock loop (PLL/FLL) definitions
19632513Sphk */
19732513Sphk
19844574Sphkstatic void ntp_init(void);
19944574Sphkstatic void hardupdate(long offset);
200137873Smarksstatic void ntp_gettime1(struct ntptimeval *ntvp);
20132513Sphk
202137873Smarksstatic void
203137873Smarksntp_gettime1(struct ntptimeval *ntvp)
2042858Swollman{
20544574Sphk	struct timespec atv;	/* nanosecond time */
2062858Swollman
207146722Srwatson	GIANT_REQUIRED;
208146722Srwatson
20944574Sphk	nanotime(&atv);
210137873Smarks	ntvp->time.tv_sec = atv.tv_sec;
211137873Smarks	ntvp->time.tv_nsec = atv.tv_nsec;
212137873Smarks	ntvp->maxerror = time_maxerror;
213137873Smarks	ntvp->esterror = time_esterror;
214137873Smarks	ntvp->tai = time_tai;
215137873Smarks	ntvp->time_state = time_state;
2162858Swollman
2172858Swollman	/*
21844574Sphk	 * Status word error decode. If any of these conditions occur,
21944574Sphk	 * an error is returned, instead of the status word. Most
22044574Sphk	 * applications will care only about the fact the system clock
22144574Sphk	 * may not be trusted, not about the details.
2222858Swollman	 *
2232858Swollman	 * Hardware or software error
2242858Swollman	 */
22544574Sphk	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
2262858Swollman
2272858Swollman	/*
22844574Sphk	 * PPS signal lost when either time or frequency synchronization
22944574Sphk	 * requested
2302858Swollman	 */
23144574Sphk	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
23244574Sphk	    !(time_status & STA_PPSSIGNAL)) ||
2332858Swollman
2342858Swollman	/*
23544574Sphk	 * PPS jitter exceeded when time synchronization requested
2362858Swollman	 */
23744574Sphk	    (time_status & STA_PPSTIME &&
23844574Sphk	    time_status & STA_PPSJITTER) ||
2392858Swollman
2402858Swollman	/*
24144574Sphk	 * PPS wander exceeded or calibration error when frequency
24244574Sphk	 * synchronization requested
2432858Swollman	 */
24444574Sphk	    (time_status & STA_PPSFREQ &&
24544574Sphk	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
246137873Smarks		ntvp->time_state = TIME_ERROR;
2472858Swollman}
2482858Swollman
249137879Smarks/*
250137879Smarks * ntp_gettime() - NTP user application interface
251137879Smarks *
252167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
253167232Srwatson * the TAI offset is returned in the ntvtimeval.tai structure member.
254137879Smarks */
255137873Smarks#ifndef _SYS_SYSPROTO_H_
256137873Smarksstruct ntp_gettime_args {
257137873Smarks	struct ntptimeval *ntvp;
258137873Smarks};
259137873Smarks#endif
260137873Smarks/* ARGSUSED */
261137873Smarksint
262137873Smarksntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
263137873Smarks{
264137873Smarks	struct ntptimeval ntv;
265137873Smarks
266146722Srwatson	mtx_lock(&Giant);
267137873Smarks	ntp_gettime1(&ntv);
268146722Srwatson	mtx_unlock(&Giant);
269137873Smarks
270165969Simp	td->td_retval[0] = ntv.time_state;
271137873Smarks	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
272137873Smarks}
273137873Smarks
274137873Smarksstatic int
275137873Smarksntp_sysctl(SYSCTL_HANDLER_ARGS)
276137873Smarks{
277137873Smarks	struct ntptimeval ntv;	/* temporary structure */
278137873Smarks
279137873Smarks	ntp_gettime1(&ntv);
280137873Smarks
281137873Smarks	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
282137873Smarks}
283137873Smarks
28444574SphkSYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
28544574SphkSYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
28612623Sphk	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
28712279Sphk
28850663Sphk#ifdef PPS_SYNC
28950656SphkSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
29055413SphkSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
29165673SphkSYSCTL_INT(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD, &time_monitor, 0, "");
29256458Sphk
29356458SphkSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", "");
29456458SphkSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD, &time_freq, sizeof(time_freq), "I", "");
29550663Sphk#endif
296167232Srwatson
2972858Swollman/*
2982858Swollman * ntp_adjtime() - NTP daemon application interface
29944574Sphk *
300167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
301167232Srwatson * the timex.constant structure member has a dual purpose to set the time
302167232Srwatson * constant and to set the TAI offset.
3032858Swollman */
30412221Sbde#ifndef _SYS_SYSPROTO_H_
3052858Swollmanstruct ntp_adjtime_args {
30644574Sphk	struct timex *tp;
3072858Swollman};
30812221Sbde#endif
3092858Swollman
3102858Swollmanint
31183366Sjulianntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
3122858Swollman{
31344574Sphk	struct timex ntv;	/* temporary structure */
31445294Sphk	long freq;		/* frequency ns/s) */
31544574Sphk	int modes;		/* mode bits from structure */
31644574Sphk	int s;			/* caller priority */
3172858Swollman	int error;
3182858Swollman
3192858Swollman	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
3202858Swollman	if (error)
32144574Sphk		return(error);
3222858Swollman
3232858Swollman	/*
3242858Swollman	 * Update selected clock variables - only the superuser can
3252858Swollman	 * change anything. Note that there is no error checking here on
3262858Swollman	 * the assumption the superuser should know what it is doing.
32765432Sphk	 * Note that either the time constant or TAI offset are loaded
32875540Sjhay	 * from the ntv.constant member, depending on the mode bits. If
32975540Sjhay	 * the STA_PLL bit in the status word is cleared, the state and
33075540Sjhay	 * status words are reset to the initial values at boot.
3312858Swollman	 */
33282717Sdillon	mtx_lock(&Giant);
3332858Swollman	modes = ntv.modes;
33444776Sphk	if (modes)
335164033Srwatson		error = priv_check(td, PRIV_NTP_ADJTIME);
33644574Sphk	if (error)
33782717Sdillon		goto done2;
3382858Swollman	s = splclock();
3392858Swollman	if (modes & MOD_MAXERROR)
3402858Swollman		time_maxerror = ntv.maxerror;
3412858Swollman	if (modes & MOD_ESTERROR)
3422858Swollman		time_esterror = ntv.esterror;
3432858Swollman	if (modes & MOD_STATUS) {
34475540Sjhay		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
34575540Sjhay			time_state = TIME_OK;
34675540Sjhay			time_status = STA_UNSYNC;
34775540Sjhay#ifdef PPS_SYNC
34875540Sjhay			pps_shift = PPS_FAVG;
34975540Sjhay#endif /* PPS_SYNC */
35075540Sjhay		}
3512858Swollman		time_status &= STA_RONLY;
3522858Swollman		time_status |= ntv.status & ~STA_RONLY;
3532858Swollman	}
35445294Sphk	if (modes & MOD_TIMECONST) {
35545294Sphk		if (ntv.constant < 0)
35645294Sphk			time_constant = 0;
35745294Sphk		else if (ntv.constant > MAXTC)
35845294Sphk			time_constant = MAXTC;
35945294Sphk		else
36045294Sphk			time_constant = ntv.constant;
36145294Sphk	}
36265432Sphk	if (modes & MOD_TAI) {
36365432Sphk		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
36465432Sphk			time_tai = ntv.constant;
36565432Sphk	}
36650656Sphk#ifdef PPS_SYNC
36750656Sphk	if (modes & MOD_PPSMAX) {
36850656Sphk		if (ntv.shift < PPS_FAVG)
36950656Sphk			pps_shiftmax = PPS_FAVG;
37050656Sphk		else if (ntv.shift > PPS_FAVGMAX)
37150656Sphk			pps_shiftmax = PPS_FAVGMAX;
37250656Sphk		else
37350656Sphk			pps_shiftmax = ntv.shift;
37450656Sphk	}
37550656Sphk#endif /* PPS_SYNC */
37644574Sphk	if (modes & MOD_NANO)
37744574Sphk		time_status |= STA_NANO;
37844574Sphk	if (modes & MOD_MICRO)
37944574Sphk		time_status &= ~STA_NANO;
38044574Sphk	if (modes & MOD_CLKB)
38144574Sphk		time_status |= STA_CLK;
38244574Sphk	if (modes & MOD_CLKA)
38344574Sphk		time_status &= ~STA_CLK;
38475540Sjhay	if (modes & MOD_FREQUENCY) {
38575540Sjhay		freq = (ntv.freq * 1000LL) >> 16;
38675540Sjhay		if (freq > MAXFREQ)
38775540Sjhay			L_LINT(time_freq, MAXFREQ);
38875540Sjhay		else if (freq < -MAXFREQ)
38975540Sjhay			L_LINT(time_freq, -MAXFREQ);
390126974Sphk		else {
391126974Sphk			/*
392126974Sphk			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
393126974Sphk			 * time_freq is [ns/s * 2^32]
394126974Sphk			 */
395126974Sphk			time_freq = ntv.freq * 1000LL * 65536LL;
396126974Sphk		}
39775540Sjhay#ifdef PPS_SYNC
39875540Sjhay		pps_freq = time_freq;
39975540Sjhay#endif /* PPS_SYNC */
40075540Sjhay	}
401124937Sphk	if (modes & MOD_OFFSET) {
402124937Sphk		if (time_status & STA_NANO)
403124937Sphk			hardupdate(ntv.offset);
404124937Sphk		else
405124937Sphk			hardupdate(ntv.offset * 1000);
406124937Sphk	}
4072858Swollman
4082858Swollman	/*
40965432Sphk	 * Retrieve all clock variables. Note that the TAI offset is
41065432Sphk	 * returned only by ntp_gettime();
4112858Swollman	 */
41244574Sphk	if (time_status & STA_NANO)
41394740Sphk		ntv.offset = L_GINT(time_offset);
4142858Swollman	else
41594740Sphk		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
41645295Sphk	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
4172858Swollman	ntv.maxerror = time_maxerror;
4182858Swollman	ntv.esterror = time_esterror;
4192858Swollman	ntv.status = time_status;
42045294Sphk	ntv.constant = time_constant;
42144574Sphk	if (time_status & STA_NANO)
42244574Sphk		ntv.precision = time_precision;
42344574Sphk	else
42444574Sphk		ntv.precision = time_precision / 1000;
42544574Sphk	ntv.tolerance = MAXFREQ * SCALE_PPM;
4262858Swollman#ifdef PPS_SYNC
4272858Swollman	ntv.shift = pps_shift;
42845295Sphk	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
42944574Sphk	if (time_status & STA_NANO)
43044574Sphk		ntv.jitter = pps_jitter;
43144574Sphk	else
43244574Sphk		ntv.jitter = pps_jitter / 1000;
4332858Swollman	ntv.stabil = pps_stabil;
4342858Swollman	ntv.calcnt = pps_calcnt;
4352858Swollman	ntv.errcnt = pps_errcnt;
4362858Swollman	ntv.jitcnt = pps_jitcnt;
4372858Swollman	ntv.stbcnt = pps_stbcnt;
4382858Swollman#endif /* PPS_SYNC */
43944574Sphk	splx(s);
4402858Swollman
4412858Swollman	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
44244574Sphk	if (error)
44382717Sdillon		goto done2;
44444574Sphk
44544574Sphk	/*
44644574Sphk	 * Status word error decode. See comments in
44744574Sphk	 * ntp_gettime() routine.
44844574Sphk	 */
44944574Sphk	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
45044574Sphk	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
45144574Sphk	    !(time_status & STA_PPSSIGNAL)) ||
45244574Sphk	    (time_status & STA_PPSTIME &&
45344574Sphk	    time_status & STA_PPSJITTER) ||
45444574Sphk	    (time_status & STA_PPSFREQ &&
45582717Sdillon	    time_status & (STA_PPSWANDER | STA_PPSERROR))) {
45683366Sjulian		td->td_retval[0] = TIME_ERROR;
45782717Sdillon	} else {
45883366Sjulian		td->td_retval[0] = time_state;
45982717Sdillon	}
46082717Sdillondone2:
46182717Sdillon	mtx_unlock(&Giant);
46245302Sphk	return (error);
46344574Sphk}
46444574Sphk
46544574Sphk/*
46644574Sphk * second_overflow() - called after ntp_tick_adjust()
46744574Sphk *
46844574Sphk * This routine is ordinarily called immediately following the above
46944574Sphk * routine ntp_tick_adjust(). While these two routines are normally
47044574Sphk * combined, they are separated here only for the purposes of
47144574Sphk * simulation.
47244574Sphk */
47344574Sphkvoid
47495529Sphkntp_update_second(int64_t *adjustment, time_t *newsec)
47544574Sphk{
47694754Sphk	int tickrate;
47765432Sphk	l_fp ftemp;		/* 32/64-bit temporary */
47844574Sphk
47950656Sphk	/*
48050656Sphk	 * On rollover of the second both the nanosecond and microsecond
48150656Sphk	 * clocks are updated and the state machine cranked as
48250656Sphk	 * necessary. The phase adjustment to be used for the next
48350656Sphk	 * second is calculated and the maximum error is increased by
48450656Sphk	 * the tolerance.
48550656Sphk	 */
48644574Sphk	time_maxerror += MAXFREQ / 1000;
48744574Sphk
48844574Sphk	/*
48944574Sphk	 * Leap second processing. If in leap-insert state at
49044574Sphk	 * the end of the day, the system clock is set back one
49144574Sphk	 * second; if in leap-delete state, the system clock is
49244574Sphk	 * set ahead one second. The nano_time() routine or
49344574Sphk	 * external clock driver will insure that reported time
49444574Sphk	 * is always monotonic.
49544574Sphk	 */
49644574Sphk	switch (time_state) {
49744574Sphk
4982858Swollman		/*
49944574Sphk		 * No warning.
5002858Swollman		 */
50144574Sphk		case TIME_OK:
50244574Sphk		if (time_status & STA_INS)
50344574Sphk			time_state = TIME_INS;
50444574Sphk		else if (time_status & STA_DEL)
50544574Sphk			time_state = TIME_DEL;
50644574Sphk		break;
50744574Sphk
50844574Sphk		/*
50944574Sphk		 * Insert second 23:59:60 following second
51044574Sphk		 * 23:59:59.
51144574Sphk		 */
51244574Sphk		case TIME_INS:
51344574Sphk		if (!(time_status & STA_INS))
51444574Sphk			time_state = TIME_OK;
51544574Sphk		else if ((*newsec) % 86400 == 0) {
51644574Sphk			(*newsec)--;
51744574Sphk			time_state = TIME_OOP;
518116838Simp			time_tai++;
51944574Sphk		}
52044574Sphk		break;
52144574Sphk
52244574Sphk		/*
52344574Sphk		 * Delete second 23:59:59.
52444574Sphk		 */
52544574Sphk		case TIME_DEL:
52644574Sphk		if (!(time_status & STA_DEL))
52744574Sphk			time_state = TIME_OK;
52844574Sphk		else if (((*newsec) + 1) % 86400 == 0) {
52944574Sphk			(*newsec)++;
53065432Sphk			time_tai--;
53144574Sphk			time_state = TIME_WAIT;
53244574Sphk		}
53344574Sphk		break;
53444574Sphk
53544574Sphk		/*
53644574Sphk		 * Insert second in progress.
53744574Sphk		 */
53844574Sphk		case TIME_OOP:
53965432Sphk			time_state = TIME_WAIT;
54044574Sphk		break;
54144574Sphk
54244574Sphk		/*
54344574Sphk		 * Wait for status bits to clear.
54444574Sphk		 */
54544574Sphk		case TIME_WAIT:
54644574Sphk		if (!(time_status & (STA_INS | STA_DEL)))
54744574Sphk			time_state = TIME_OK;
5482858Swollman	}
54944574Sphk
55044574Sphk	/*
55150656Sphk	 * Compute the total time adjustment for the next second
55250656Sphk	 * in ns. The offset is reduced by a factor depending on
55350656Sphk	 * whether the PPS signal is operating. Note that the
55450656Sphk	 * value is in effect scaled by the clock frequency,
55550656Sphk	 * since the adjustment is added at each tick interrupt.
55644574Sphk	 */
55765432Sphk	ftemp = time_offset;
55844574Sphk#ifdef PPS_SYNC
55965432Sphk	/* XXX even if PPS signal dies we should finish adjustment ? */
56065432Sphk	if (time_status & STA_PPSTIME && time_status &
56165673Sphk	    STA_PPSSIGNAL)
56265432Sphk		L_RSHIFT(ftemp, pps_shift);
56365432Sphk	else
56465432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
56544574Sphk#else
56665432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
56744574Sphk#endif /* PPS_SYNC */
56865432Sphk	time_adj = ftemp;
56965432Sphk	L_SUB(time_offset, ftemp);
57044574Sphk	L_ADD(time_adj, time_freq);
57194754Sphk
57294754Sphk	/*
57394754Sphk	 * Apply any correction from adjtime(2).  If more than one second
57494754Sphk	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
57594754Sphk	 * until the last second is slewed the final < 500 usecs.
57694754Sphk	 */
57794754Sphk	if (time_adjtime != 0) {
57894754Sphk		if (time_adjtime > 1000000)
57994754Sphk			tickrate = 5000;
58094754Sphk		else if (time_adjtime < -1000000)
58194754Sphk			tickrate = -5000;
58294754Sphk		else if (time_adjtime > 500)
58394754Sphk			tickrate = 500;
58494754Sphk		else if (time_adjtime < -500)
58594754Sphk			tickrate = -500;
586126974Sphk		else
58794754Sphk			tickrate = time_adjtime;
58894754Sphk		time_adjtime -= tickrate;
58994754Sphk		L_LINT(ftemp, tickrate * 1000);
59094754Sphk		L_ADD(time_adj, ftemp);
59194754Sphk	}
59295529Sphk	*adjustment = time_adj;
59394754Sphk
59444574Sphk#ifdef PPS_SYNC
59544574Sphk	if (pps_valid > 0)
59644574Sphk		pps_valid--;
59744574Sphk	else
59875540Sjhay		time_status &= ~STA_PPSSIGNAL;
59944574Sphk#endif /* PPS_SYNC */
6002858Swollman}
6012858Swollman
60244574Sphk/*
60344574Sphk * ntp_init() - initialize variables and structures
60444574Sphk *
60544574Sphk * This routine must be called after the kernel variables hz and tick
60644574Sphk * are set or changed and before the next tick interrupt. In this
60744574Sphk * particular implementation, these values are assumed set elsewhere in
60844574Sphk * the kernel. The design allows the clock frequency and tick interval
60944574Sphk * to be changed while the system is running. So, this routine should
61044574Sphk * probably be integrated with the code that does that.
61144574Sphk */
61244574Sphkstatic void
61344574Sphkntp_init()
61444574Sphk{
61544574Sphk
61644574Sphk	/*
61744574Sphk	 * The following variables are initialized only at startup. Only
61844574Sphk	 * those structures not cleared by the compiler need to be
61944574Sphk	 * initialized, and these only in the simulator. In the actual
62044574Sphk	 * kernel, any nonzero values here will quickly evaporate.
62144574Sphk	 */
62244574Sphk	L_CLR(time_offset);
62344574Sphk	L_CLR(time_freq);
62432513Sphk#ifdef PPS_SYNC
62550656Sphk	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
62650656Sphk	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
62750656Sphk	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
62844794Sphk	pps_fcount = 0;
62944574Sphk	L_CLR(pps_freq);
63044574Sphk#endif /* PPS_SYNC */
63144574Sphk}
6322858Swollman
633177253SrwatsonSYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
63432513Sphk
63544574Sphk/*
63644574Sphk * hardupdate() - local clock update
63744574Sphk *
63844574Sphk * This routine is called by ntp_adjtime() to update the local clock
63944574Sphk * phase and frequency. The implementation is of an adaptive-parameter,
64044574Sphk * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
64144574Sphk * time and frequency offset estimates for each call. If the kernel PPS
64244574Sphk * discipline code is configured (PPS_SYNC), the PPS signal itself
64344574Sphk * determines the new time offset, instead of the calling argument.
64444574Sphk * Presumably, calls to ntp_adjtime() occur only when the caller
64544574Sphk * believes the local clock is valid within some bound (+-128 ms with
64644574Sphk * NTP). If the caller's time is far different than the PPS time, an
64744574Sphk * argument will ensue, and it's not clear who will lose.
64844574Sphk *
64944574Sphk * For uncompensated quartz crystal oscillators and nominal update
65044574Sphk * intervals less than 256 s, operation should be in phase-lock mode,
65144574Sphk * where the loop is disciplined to phase. For update intervals greater
65244574Sphk * than 1024 s, operation should be in frequency-lock mode, where the
65344574Sphk * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
65444574Sphk * is selected by the STA_MODE status bit.
65544574Sphk */
65644574Sphkstatic void
65744574Sphkhardupdate(offset)
65844574Sphk	long offset;		/* clock offset (ns) */
65944574Sphk{
66065432Sphk	long mtemp;
66144574Sphk	l_fp ftemp;
66232513Sphk
66344574Sphk	/*
66444574Sphk	 * Select how the phase is to be controlled and from which
66544574Sphk	 * source. If the PPS signal is present and enabled to
66644574Sphk	 * discipline the time, the PPS offset is used; otherwise, the
66744574Sphk	 * argument offset is used.
66844574Sphk	 */
66950656Sphk	if (!(time_status & STA_PLL))
67050656Sphk		return;
67165432Sphk	if (!(time_status & STA_PPSTIME && time_status &
67265432Sphk	    STA_PPSSIGNAL)) {
67365432Sphk		if (offset > MAXPHASE)
67465432Sphk			time_monitor = MAXPHASE;
67565432Sphk		else if (offset < -MAXPHASE)
67665432Sphk			time_monitor = -MAXPHASE;
67765432Sphk		else
67865432Sphk			time_monitor = offset;
67965432Sphk		L_LINT(time_offset, time_monitor);
68065432Sphk	}
68132513Sphk
68244574Sphk	/*
68344574Sphk	 * Select how the frequency is to be controlled and in which
68444574Sphk	 * mode (PLL or FLL). If the PPS signal is present and enabled
68544574Sphk	 * to discipline the frequency, the PPS frequency is used;
68644574Sphk	 * otherwise, the argument offset is used to compute it.
68744574Sphk	 */
68844574Sphk	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
68944574Sphk		time_reftime = time_second;
69044574Sphk		return;
69144574Sphk	}
69244574Sphk	if (time_status & STA_FREQHOLD || time_reftime == 0)
69344574Sphk		time_reftime = time_second;
69444574Sphk	mtemp = time_second - time_reftime;
69565432Sphk	L_LINT(ftemp, time_monitor);
69650656Sphk	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
69750656Sphk	L_MPY(ftemp, mtemp);
69850656Sphk	L_ADD(time_freq, ftemp);
69950656Sphk	time_status &= ~STA_MODE;
70065432Sphk	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
70165432Sphk	    MAXSEC)) {
70265432Sphk		L_LINT(ftemp, (time_monitor << 4) / mtemp);
70344574Sphk		L_RSHIFT(ftemp, SHIFT_FLL + 4);
70444574Sphk		L_ADD(time_freq, ftemp);
70544574Sphk		time_status |= STA_MODE;
70644574Sphk	}
70744574Sphk	time_reftime = time_second;
70844574Sphk	if (L_GINT(time_freq) > MAXFREQ)
70944574Sphk		L_LINT(time_freq, MAXFREQ);
71044574Sphk	else if (L_GINT(time_freq) < -MAXFREQ)
71144574Sphk		L_LINT(time_freq, -MAXFREQ);
71244574Sphk}
71344574Sphk
71444574Sphk#ifdef PPS_SYNC
71532513Sphk/*
71632513Sphk * hardpps() - discipline CPU clock oscillator to external PPS signal
71732513Sphk *
71832513Sphk * This routine is called at each PPS interrupt in order to discipline
71965432Sphk * the CPU clock oscillator to the PPS signal. There are two independent
72065432Sphk * first-order feedback loops, one for the phase, the other for the
72165432Sphk * frequency. The phase loop measures and grooms the PPS phase offset
72265432Sphk * and leaves it in a handy spot for the seconds overflow routine. The
72365432Sphk * frequency loop averages successive PPS phase differences and
72465432Sphk * calculates the PPS frequency offset, which is also processed by the
72565432Sphk * seconds overflow routine. The code requires the caller to capture the
72665432Sphk * time and architecture-dependent hardware counter values in
72765432Sphk * nanoseconds at the on-time PPS signal transition.
72832513Sphk *
72944574Sphk * Note that, on some Unix systems this routine runs at an interrupt
73032513Sphk * priority level higher than the timer interrupt routine hardclock().
73132513Sphk * Therefore, the variables used are distinct from the hardclock()
73244574Sphk * variables, except for the actual time and frequency variables, which
73344574Sphk * are determined by this routine and updated atomically.
73432513Sphk */
73532513Sphkvoid
73644574Sphkhardpps(tsp, nsec)
73744574Sphk	struct timespec *tsp;	/* time at PPS */
73844574Sphk	long nsec;		/* hardware counter at PPS */
73932513Sphk{
74065432Sphk	long u_sec, u_nsec, v_nsec; /* temps */
74144574Sphk	l_fp ftemp;
74232513Sphk
74332513Sphk	/*
74465432Sphk	 * The signal is first processed by a range gate and frequency
74565432Sphk	 * discriminator. The range gate rejects noise spikes outside
74665432Sphk	 * the range +-500 us. The frequency discriminator rejects input
74765432Sphk	 * signals with apparent frequency outside the range 1 +-500
74865432Sphk	 * PPM. If two hits occur in the same second, we ignore the
74965432Sphk	 * later hit; if not and a hit occurs outside the range gate,
75065432Sphk	 * keep the later hit for later comparison, but do not process
75165432Sphk	 * it.
75232513Sphk	 */
75344574Sphk	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
75444574Sphk	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
75544574Sphk	pps_valid = PPS_VALID;
75644574Sphk	u_sec = tsp->tv_sec;
75744574Sphk	u_nsec = tsp->tv_nsec;
75844574Sphk	if (u_nsec >= (NANOSECOND >> 1)) {
75944574Sphk		u_nsec -= NANOSECOND;
76044574Sphk		u_sec++;
76144574Sphk	}
76250656Sphk	v_nsec = u_nsec - pps_tf[0].tv_nsec;
76375540Sjhay	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
76475540Sjhay	    MAXFREQ)
76544574Sphk		return;
76644574Sphk	pps_tf[2] = pps_tf[1];
76744574Sphk	pps_tf[1] = pps_tf[0];
76850656Sphk	pps_tf[0].tv_sec = u_sec;
76950656Sphk	pps_tf[0].tv_nsec = u_nsec;
77032513Sphk
77132513Sphk	/*
77244574Sphk	 * Compute the difference between the current and previous
77344574Sphk	 * counter values. If the difference exceeds 0.5 s, assume it
77444574Sphk	 * has wrapped around, so correct 1.0 s. If the result exceeds
77544574Sphk	 * the tick interval, the sample point has crossed a tick
77644574Sphk	 * boundary during the last second, so correct the tick. Very
77744574Sphk	 * intricate.
77844574Sphk	 */
77944666Sphk	u_nsec = nsec;
78044574Sphk	if (u_nsec > (NANOSECOND >> 1))
78144574Sphk		u_nsec -= NANOSECOND;
78244574Sphk	else if (u_nsec < -(NANOSECOND >> 1))
78344574Sphk		u_nsec += NANOSECOND;
78444794Sphk	pps_fcount += u_nsec;
78575540Sjhay	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
78644574Sphk		return;
78744574Sphk	time_status &= ~STA_PPSJITTER;
78844574Sphk
78944574Sphk	/*
79044574Sphk	 * A three-stage median filter is used to help denoise the PPS
79132513Sphk	 * time. The median sample becomes the time offset estimate; the
79232513Sphk	 * difference between the other two samples becomes the time
79332513Sphk	 * dispersion (jitter) estimate.
79432513Sphk	 */
79550656Sphk	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
79650656Sphk		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
79750656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
79850656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
79950656Sphk		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
80050656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
80150656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
80244574Sphk		} else {
80350656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
80450656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
80544574Sphk		}
80644574Sphk	} else {
80750656Sphk		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
80850656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
80950656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
81065673Sphk		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
81150656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
81250656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
81344574Sphk		} else {
81450656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
81550656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
81644574Sphk		}
81744574Sphk	}
81832513Sphk
81932513Sphk	/*
82065673Sphk	 * Nominal jitter is due to PPS signal noise and interrupt
82165432Sphk	 * latency. If it exceeds the popcorn threshold, the sample is
82265432Sphk	 * discarded. otherwise, if so enabled, the time offset is
82365432Sphk	 * updated. We can tolerate a modest loss of data here without
82465432Sphk	 * much degrading time accuracy.
82532513Sphk	 */
82650656Sphk	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
82744574Sphk		time_status |= STA_PPSJITTER;
82844574Sphk		pps_jitcnt++;
82944574Sphk	} else if (time_status & STA_PPSTIME) {
83065432Sphk		time_monitor = -v_nsec;
83165432Sphk		L_LINT(time_offset, time_monitor);
83232513Sphk	}
83344574Sphk	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
83450656Sphk	u_sec = pps_tf[0].tv_sec - pps_lastsec;
83544574Sphk	if (u_sec < (1 << pps_shift))
83644574Sphk		return;
83744574Sphk
83832513Sphk	/*
83944574Sphk	 * At the end of the calibration interval the difference between
84044574Sphk	 * the first and last counter values becomes the scaled
84144574Sphk	 * frequency. It will later be divided by the length of the
84244574Sphk	 * interval to determine the frequency update. If the frequency
84344574Sphk	 * exceeds a sanity threshold, or if the actual calibration
84444574Sphk	 * interval is not equal to the expected length, the data are
84544574Sphk	 * discarded. We can tolerate a modest loss of data here without
84665432Sphk	 * much degrading frequency accuracy.
84732513Sphk	 */
84844574Sphk	pps_calcnt++;
84944794Sphk	v_nsec = -pps_fcount;
85050656Sphk	pps_lastsec = pps_tf[0].tv_sec;
85144794Sphk	pps_fcount = 0;
85244574Sphk	u_nsec = MAXFREQ << pps_shift;
85344574Sphk	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
85444574Sphk	    pps_shift)) {
85544574Sphk		time_status |= STA_PPSERROR;
85632513Sphk		pps_errcnt++;
85732513Sphk		return;
85832513Sphk	}
85932513Sphk
86032513Sphk	/*
86150656Sphk	 * Here the raw frequency offset and wander (stability) is
86250656Sphk	 * calculated. If the wander is less than the wander threshold
86350656Sphk	 * for four consecutive averaging intervals, the interval is
86450656Sphk	 * doubled; if it is greater than the threshold for four
86550656Sphk	 * consecutive intervals, the interval is halved. The scaled
86650656Sphk	 * frequency offset is converted to frequency offset. The
86750656Sphk	 * stability metric is calculated as the average of recent
86850656Sphk	 * frequency changes, but is used only for performance
86944574Sphk	 * monitoring.
87032513Sphk	 */
87144574Sphk	L_LINT(ftemp, v_nsec);
87244574Sphk	L_RSHIFT(ftemp, pps_shift);
87344574Sphk	L_SUB(ftemp, pps_freq);
87444574Sphk	u_nsec = L_GINT(ftemp);
87550656Sphk	if (u_nsec > PPS_MAXWANDER) {
87650656Sphk		L_LINT(ftemp, PPS_MAXWANDER);
87744574Sphk		pps_intcnt--;
87844574Sphk		time_status |= STA_PPSWANDER;
87932513Sphk		pps_stbcnt++;
88050656Sphk	} else if (u_nsec < -PPS_MAXWANDER) {
88150656Sphk		L_LINT(ftemp, -PPS_MAXWANDER);
88244574Sphk		pps_intcnt--;
88332513Sphk		time_status |= STA_PPSWANDER;
88444574Sphk		pps_stbcnt++;
88544574Sphk	} else {
88644574Sphk		pps_intcnt++;
88732513Sphk	}
88865432Sphk	if (pps_intcnt >= 4) {
88944574Sphk		pps_intcnt = 4;
89050656Sphk		if (pps_shift < pps_shiftmax) {
89144574Sphk			pps_shift++;
89244574Sphk			pps_intcnt = 0;
89332513Sphk		}
89465432Sphk	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
89544574Sphk		pps_intcnt = -4;
89644574Sphk		if (pps_shift > PPS_FAVG) {
89744574Sphk			pps_shift--;
89844574Sphk			pps_intcnt = 0;
89944574Sphk		}
90032513Sphk	}
90144574Sphk	if (u_nsec < 0)
90244574Sphk		u_nsec = -u_nsec;
90344574Sphk	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
90432513Sphk
90532513Sphk	/*
90650656Sphk	 * The PPS frequency is recalculated and clamped to the maximum
90750656Sphk	 * MAXFREQ. If enabled, the system clock frequency is updated as
90850656Sphk	 * well.
90932513Sphk	 */
91044574Sphk	L_ADD(pps_freq, ftemp);
91144574Sphk	u_nsec = L_GINT(pps_freq);
91244574Sphk	if (u_nsec > MAXFREQ)
91344574Sphk		L_LINT(pps_freq, MAXFREQ);
91444574Sphk	else if (u_nsec < -MAXFREQ)
91544574Sphk		L_LINT(pps_freq, -MAXFREQ);
91665432Sphk	if (time_status & STA_PPSFREQ)
91744574Sphk		time_freq = pps_freq;
91832513Sphk}
91932513Sphk#endif /* PPS_SYNC */
92094754Sphk
92194754Sphk#ifndef _SYS_SYSPROTO_H_
92294754Sphkstruct adjtime_args {
92394754Sphk	struct timeval *delta;
92494754Sphk	struct timeval *olddelta;
92594754Sphk};
92694754Sphk#endif
92794754Sphk/* ARGSUSED */
92894754Sphkint
92994754Sphkadjtime(struct thread *td, struct adjtime_args *uap)
93094754Sphk{
931144445Sjhb	struct timeval delta, olddelta, *deltap;
932144445Sjhb	int error;
933144445Sjhb
934144445Sjhb	if (uap->delta) {
935144445Sjhb		error = copyin(uap->delta, &delta, sizeof(delta));
936144445Sjhb		if (error)
937144445Sjhb			return (error);
938144445Sjhb		deltap = &delta;
939144445Sjhb	} else
940144445Sjhb		deltap = NULL;
941144445Sjhb	error = kern_adjtime(td, deltap, &olddelta);
942144445Sjhb	if (uap->olddelta && error == 0)
943144445Sjhb		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
944144445Sjhb	return (error);
945144445Sjhb}
946144445Sjhb
947144445Sjhbint
948144445Sjhbkern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
949144445Sjhb{
95094754Sphk	struct timeval atv;
95194754Sphk	int error;
95294754Sphk
95394754Sphk	mtx_lock(&Giant);
954144445Sjhb	if (olddelta) {
95594754Sphk		atv.tv_sec = time_adjtime / 1000000;
95694754Sphk		atv.tv_usec = time_adjtime % 1000000;
95794754Sphk		if (atv.tv_usec < 0) {
95894754Sphk			atv.tv_usec += 1000000;
95994754Sphk			atv.tv_sec--;
96094754Sphk		}
961144445Sjhb		*olddelta = atv;
96294754Sphk	}
963170732Srwatson	if (delta) {
964170732Srwatson		if ((error = priv_check(td, PRIV_ADJTIME))) {
965170732Srwatson			mtx_unlock(&Giant);
966170732Srwatson			return (error);
967170732Srwatson		}
968144445Sjhb		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
969144445Sjhb		    delta->tv_usec;
970170732Srwatson	}
97194754Sphk	mtx_unlock(&Giant);
972170732Srwatson	return (0);
97394754Sphk}
97494754Sphk
975