kern_ntptime.c revision 219028
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 219028 2011-02-25 10:11:01Z netchild $");
35116182Sobrien
3644666Sphk#include "opt_ntp.h"
3744666Sphk
382858Swollman#include <sys/param.h>
392858Swollman#include <sys/systm.h>
4012221Sbde#include <sys/sysproto.h>
41207360Savg#include <sys/eventhandler.h>
422858Swollman#include <sys/kernel.h>
43164033Srwatson#include <sys/priv.h>
442858Swollman#include <sys/proc.h>
4582717Sdillon#include <sys/lock.h>
4682717Sdillon#include <sys/mutex.h>
4744574Sphk#include <sys/time.h>
482858Swollman#include <sys/timex.h>
4958377Sphk#include <sys/timetc.h>
5036941Sphk#include <sys/timepps.h>
51144445Sjhb#include <sys/syscallsubr.h>
522858Swollman#include <sys/sysctl.h>
532858Swollman
54219028Snetchild#ifdef PPS_SYNC
55219028SnetchildFEATURE(pps_sync, "Support usage of external PPS signal by kernel PLL");
56219028Snetchild#endif
57219028Snetchild
582858Swollman/*
5944574Sphk * Single-precision macros for 64-bit machines
6044574Sphk */
61126974Sphktypedef int64_t l_fp;
6244574Sphk#define L_ADD(v, u)	((v) += (u))
6344574Sphk#define L_SUB(v, u)	((v) -= (u))
64126974Sphk#define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
6544574Sphk#define L_NEG(v)	((v) = -(v))
6644574Sphk#define L_RSHIFT(v, n) \
6744574Sphk	do { \
6844574Sphk		if ((v) < 0) \
6944574Sphk			(v) = -(-(v) >> (n)); \
7044574Sphk		else \
7144574Sphk			(v) = (v) >> (n); \
7244574Sphk	} while (0)
7344574Sphk#define L_MPY(v, a)	((v) *= (a))
7444574Sphk#define L_CLR(v)	((v) = 0)
7544574Sphk#define L_ISNEG(v)	((v) < 0)
76126974Sphk#define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
7744574Sphk#define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
7844574Sphk
7944574Sphk/*
8044574Sphk * Generic NTP kernel interface
8132513Sphk *
8244574Sphk * These routines constitute the Network Time Protocol (NTP) interfaces
8344574Sphk * for user and daemon application programs. The ntp_gettime() routine
8444574Sphk * provides the time, maximum error (synch distance) and estimated error
8544574Sphk * (dispersion) to client user application programs. The ntp_adjtime()
8644574Sphk * routine is used by the NTP daemon to adjust the system clock to an
8744574Sphk * externally derived time. The time offset and related variables set by
8844574Sphk * this routine are used by other routines in this module to adjust the
8944574Sphk * phase and frequency of the clock discipline loop which controls the
9044574Sphk * system clock.
9132513Sphk *
9245294Sphk * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
9344574Sphk * defined), the time at each tick interrupt is derived directly from
9444574Sphk * the kernel time variable. When the kernel time is reckoned in
9545294Sphk * microseconds, (NTP_NANO undefined), the time is derived from the
9645294Sphk * kernel time variable together with a variable representing the
9745294Sphk * leftover nanoseconds at the last tick interrupt. In either case, the
9845294Sphk * current nanosecond time is reckoned from these values plus an
9945294Sphk * interpolated value derived by the clock routines in another
10045294Sphk * architecture-specific module. The interpolation can use either a
10145294Sphk * dedicated counter or a processor cycle counter (PCC) implemented in
10245294Sphk * some architectures.
10332513Sphk *
10444574Sphk * Note that all routines must run at priority splclock or higher.
10544574Sphk */
10644574Sphk/*
10744574Sphk * Phase/frequency-lock loop (PLL/FLL) definitions
10832513Sphk *
10944574Sphk * The nanosecond clock discipline uses two variable types, time
11044574Sphk * variables and frequency variables. Both types are represented as 64-
11144574Sphk * bit fixed-point quantities with the decimal point between two 32-bit
11244574Sphk * halves. On a 32-bit machine, each half is represented as a single
11344574Sphk * word and mathematical operations are done using multiple-precision
11444574Sphk * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
11544574Sphk * used.
11632513Sphk *
11744574Sphk * A time variable is a signed 64-bit fixed-point number in ns and
11844574Sphk * fraction. It represents the remaining time offset to be amortized
11944574Sphk * over succeeding tick interrupts. The maximum time offset is about
12045294Sphk * 0.5 s and the resolution is about 2.3e-10 ns.
12132513Sphk *
12244574Sphk *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
12344574Sphk *  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
12444574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12544574Sphk * |s s s|			 ns				   |
12644574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12744574Sphk * |			    fraction				   |
12844574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12932513Sphk *
13044574Sphk * A frequency variable is a signed 64-bit fixed-point number in ns/s
13144574Sphk * and fraction. It represents the ns and fraction to be added to the
13244574Sphk * kernel time variable at each second. The maximum frequency offset is
13345294Sphk * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
13432513Sphk *
13544574Sphk *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
13644574Sphk *  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
13744574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
13844574Sphk * |s s s s s s s s s s s s s|	          ns/s			   |
13944574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
14044574Sphk * |			    fraction				   |
14144574Sphk * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1422858Swollman */
14332513Sphk/*
14432513Sphk * The following variables establish the state of the PLL/FLL and the
14544574Sphk * residual time and frequency offset of the local clock.
14632513Sphk */
14744574Sphk#define SHIFT_PLL	4		/* PLL loop gain (shift) */
14844574Sphk#define SHIFT_FLL	2		/* FLL loop gain (shift) */
14932513Sphk
15044574Sphkstatic int time_state = TIME_OK;	/* clock state */
15144574Sphkstatic int time_status = STA_UNSYNC;	/* clock status bits */
15265432Sphkstatic long time_tai;			/* TAI offset (s) */
15365432Sphkstatic long time_monitor;		/* last time offset scaled (ns) */
15444574Sphkstatic long time_constant;		/* poll interval (shift) (s) */
15544574Sphkstatic long time_precision = 1;		/* clock precision (ns) */
15644574Sphkstatic long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
15744574Sphkstatic long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
15844574Sphkstatic long time_reftime;		/* time at last adjustment (s) */
15944574Sphkstatic l_fp time_offset;		/* time offset (ns) */
16044574Sphkstatic l_fp time_freq;			/* frequency offset (ns/s) */
16165432Sphkstatic l_fp time_adj;			/* tick adjust (ns/s) */
16244574Sphk
16394754Sphkstatic int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
16494754Sphk
1652858Swollman#ifdef PPS_SYNC
1662858Swollman/*
16744574Sphk * The following variables are used when a pulse-per-second (PPS) signal
16844574Sphk * is available and connected via a modem control lead. They establish
16944574Sphk * the engineering parameters of the clock discipline loop when
17044574Sphk * controlled by the PPS signal.
1712858Swollman */
17244574Sphk#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
17375540Sjhay#define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
17450656Sphk#define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
17544574Sphk#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
17644574Sphk#define PPS_VALID	120		/* PPS signal watchdog max (s) */
17750656Sphk#define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
17850656Sphk#define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
17932513Sphk
18050656Sphkstatic struct timespec pps_tf[3];	/* phase median filter */
18144574Sphkstatic l_fp pps_freq;			/* scaled frequency offset (ns/s) */
18245294Sphkstatic long pps_fcount;			/* frequency accumulator */
18350656Sphkstatic long pps_jitter;			/* nominal jitter (ns) */
18450656Sphkstatic long pps_stabil;			/* nominal stability (scaled ns/s) */
18544574Sphkstatic long pps_lastsec;		/* time at last calibration (s) */
18644574Sphkstatic int pps_valid;			/* signal watchdog counter */
18744574Sphkstatic int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
18850656Sphkstatic int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
18944574Sphkstatic int pps_intcnt;			/* wander counter */
19044574Sphk
19132513Sphk/*
19232513Sphk * PPS signal quality monitors
19332513Sphk */
19444574Sphkstatic long pps_calcnt;			/* calibration intervals */
19544574Sphkstatic long pps_jitcnt;			/* jitter limit exceeded */
19644574Sphkstatic long pps_stbcnt;			/* stability limit exceeded */
19744574Sphkstatic long pps_errcnt;			/* calibration errors */
1982858Swollman#endif /* PPS_SYNC */
19932513Sphk/*
20044574Sphk * End of phase/frequency-lock loop (PLL/FLL) definitions
20132513Sphk */
20232513Sphk
20344574Sphkstatic void ntp_init(void);
20444574Sphkstatic void hardupdate(long offset);
205137873Smarksstatic void ntp_gettime1(struct ntptimeval *ntvp);
206207359Savgstatic int ntp_is_time_error(void);
20732513Sphk
208207359Savgstatic int
209207359Savgntp_is_time_error(void)
2102858Swollman{
2112858Swollman	/*
21244574Sphk	 * Status word error decode. If any of these conditions occur,
21344574Sphk	 * an error is returned, instead of the status word. Most
21444574Sphk	 * applications will care only about the fact the system clock
21544574Sphk	 * may not be trusted, not about the details.
2162858Swollman	 *
2172858Swollman	 * Hardware or software error
2182858Swollman	 */
21944574Sphk	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
2202858Swollman
2212858Swollman	/*
22244574Sphk	 * PPS signal lost when either time or frequency synchronization
22344574Sphk	 * requested
2242858Swollman	 */
22544574Sphk	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
22644574Sphk	    !(time_status & STA_PPSSIGNAL)) ||
2272858Swollman
2282858Swollman	/*
22944574Sphk	 * PPS jitter exceeded when time synchronization requested
2302858Swollman	 */
23144574Sphk	    (time_status & STA_PPSTIME &&
23244574Sphk	    time_status & STA_PPSJITTER) ||
2332858Swollman
2342858Swollman	/*
23544574Sphk	 * PPS wander exceeded or calibration error when frequency
23644574Sphk	 * synchronization requested
2372858Swollman	 */
23844574Sphk	    (time_status & STA_PPSFREQ &&
23944574Sphk	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
240207359Savg		return (1);
241207359Savg
242207359Savg	return (0);
243207359Savg}
244207359Savg
245207359Savgstatic void
246207359Savgntp_gettime1(struct ntptimeval *ntvp)
247207359Savg{
248207359Savg	struct timespec atv;	/* nanosecond time */
249207359Savg
250207359Savg	GIANT_REQUIRED;
251207359Savg
252207359Savg	nanotime(&atv);
253207359Savg	ntvp->time.tv_sec = atv.tv_sec;
254207359Savg	ntvp->time.tv_nsec = atv.tv_nsec;
255207359Savg	ntvp->maxerror = time_maxerror;
256207359Savg	ntvp->esterror = time_esterror;
257207359Savg	ntvp->tai = time_tai;
258207359Savg	ntvp->time_state = time_state;
259207359Savg
260207359Savg	if (ntp_is_time_error())
261137873Smarks		ntvp->time_state = TIME_ERROR;
2622858Swollman}
2632858Swollman
264137879Smarks/*
265137879Smarks * ntp_gettime() - NTP user application interface
266137879Smarks *
267167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
268167232Srwatson * the TAI offset is returned in the ntvtimeval.tai structure member.
269137879Smarks */
270137873Smarks#ifndef _SYS_SYSPROTO_H_
271137873Smarksstruct ntp_gettime_args {
272137873Smarks	struct ntptimeval *ntvp;
273137873Smarks};
274137873Smarks#endif
275137873Smarks/* ARGSUSED */
276137873Smarksint
277137873Smarksntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
278137873Smarks{
279137873Smarks	struct ntptimeval ntv;
280137873Smarks
281146722Srwatson	mtx_lock(&Giant);
282137873Smarks	ntp_gettime1(&ntv);
283146722Srwatson	mtx_unlock(&Giant);
284137873Smarks
285165969Simp	td->td_retval[0] = ntv.time_state;
286137873Smarks	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
287137873Smarks}
288137873Smarks
289137873Smarksstatic int
290137873Smarksntp_sysctl(SYSCTL_HANDLER_ARGS)
291137873Smarks{
292137873Smarks	struct ntptimeval ntv;	/* temporary structure */
293137873Smarks
294137873Smarks	ntp_gettime1(&ntv);
295137873Smarks
296137873Smarks	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
297137873Smarks}
298137873Smarks
29944574SphkSYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
30044574SphkSYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
30112623Sphk	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
30212279Sphk
30350663Sphk#ifdef PPS_SYNC
30450656SphkSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
30555413SphkSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
306217368SmdfSYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
307217368Smdf    &time_monitor, 0, "");
30856458Sphk
30956458SphkSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", "");
31056458SphkSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD, &time_freq, sizeof(time_freq), "I", "");
31150663Sphk#endif
312167232Srwatson
3132858Swollman/*
3142858Swollman * ntp_adjtime() - NTP daemon application interface
31544574Sphk *
316167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
317167232Srwatson * the timex.constant structure member has a dual purpose to set the time
318167232Srwatson * constant and to set the TAI offset.
3192858Swollman */
32012221Sbde#ifndef _SYS_SYSPROTO_H_
3212858Swollmanstruct ntp_adjtime_args {
32244574Sphk	struct timex *tp;
3232858Swollman};
32412221Sbde#endif
3252858Swollman
3262858Swollmanint
32783366Sjulianntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
3282858Swollman{
32944574Sphk	struct timex ntv;	/* temporary structure */
33045294Sphk	long freq;		/* frequency ns/s) */
33144574Sphk	int modes;		/* mode bits from structure */
33244574Sphk	int s;			/* caller priority */
3332858Swollman	int error;
3342858Swollman
3352858Swollman	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
3362858Swollman	if (error)
33744574Sphk		return(error);
3382858Swollman
3392858Swollman	/*
3402858Swollman	 * Update selected clock variables - only the superuser can
3412858Swollman	 * change anything. Note that there is no error checking here on
3422858Swollman	 * the assumption the superuser should know what it is doing.
34365432Sphk	 * Note that either the time constant or TAI offset are loaded
34475540Sjhay	 * from the ntv.constant member, depending on the mode bits. If
34575540Sjhay	 * the STA_PLL bit in the status word is cleared, the state and
34675540Sjhay	 * status words are reset to the initial values at boot.
3472858Swollman	 */
34882717Sdillon	mtx_lock(&Giant);
3492858Swollman	modes = ntv.modes;
35044776Sphk	if (modes)
351164033Srwatson		error = priv_check(td, PRIV_NTP_ADJTIME);
35244574Sphk	if (error)
35382717Sdillon		goto done2;
3542858Swollman	s = splclock();
3552858Swollman	if (modes & MOD_MAXERROR)
3562858Swollman		time_maxerror = ntv.maxerror;
3572858Swollman	if (modes & MOD_ESTERROR)
3582858Swollman		time_esterror = ntv.esterror;
3592858Swollman	if (modes & MOD_STATUS) {
36075540Sjhay		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
36175540Sjhay			time_state = TIME_OK;
36275540Sjhay			time_status = STA_UNSYNC;
36375540Sjhay#ifdef PPS_SYNC
36475540Sjhay			pps_shift = PPS_FAVG;
36575540Sjhay#endif /* PPS_SYNC */
36675540Sjhay		}
3672858Swollman		time_status &= STA_RONLY;
3682858Swollman		time_status |= ntv.status & ~STA_RONLY;
3692858Swollman	}
37045294Sphk	if (modes & MOD_TIMECONST) {
37145294Sphk		if (ntv.constant < 0)
37245294Sphk			time_constant = 0;
37345294Sphk		else if (ntv.constant > MAXTC)
37445294Sphk			time_constant = MAXTC;
37545294Sphk		else
37645294Sphk			time_constant = ntv.constant;
37745294Sphk	}
37865432Sphk	if (modes & MOD_TAI) {
37965432Sphk		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
38065432Sphk			time_tai = ntv.constant;
38165432Sphk	}
38250656Sphk#ifdef PPS_SYNC
38350656Sphk	if (modes & MOD_PPSMAX) {
38450656Sphk		if (ntv.shift < PPS_FAVG)
38550656Sphk			pps_shiftmax = PPS_FAVG;
38650656Sphk		else if (ntv.shift > PPS_FAVGMAX)
38750656Sphk			pps_shiftmax = PPS_FAVGMAX;
38850656Sphk		else
38950656Sphk			pps_shiftmax = ntv.shift;
39050656Sphk	}
39150656Sphk#endif /* PPS_SYNC */
39244574Sphk	if (modes & MOD_NANO)
39344574Sphk		time_status |= STA_NANO;
39444574Sphk	if (modes & MOD_MICRO)
39544574Sphk		time_status &= ~STA_NANO;
39644574Sphk	if (modes & MOD_CLKB)
39744574Sphk		time_status |= STA_CLK;
39844574Sphk	if (modes & MOD_CLKA)
39944574Sphk		time_status &= ~STA_CLK;
40075540Sjhay	if (modes & MOD_FREQUENCY) {
40175540Sjhay		freq = (ntv.freq * 1000LL) >> 16;
40275540Sjhay		if (freq > MAXFREQ)
40375540Sjhay			L_LINT(time_freq, MAXFREQ);
40475540Sjhay		else if (freq < -MAXFREQ)
40575540Sjhay			L_LINT(time_freq, -MAXFREQ);
406126974Sphk		else {
407126974Sphk			/*
408126974Sphk			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
409126974Sphk			 * time_freq is [ns/s * 2^32]
410126974Sphk			 */
411126974Sphk			time_freq = ntv.freq * 1000LL * 65536LL;
412126974Sphk		}
41375540Sjhay#ifdef PPS_SYNC
41475540Sjhay		pps_freq = time_freq;
41575540Sjhay#endif /* PPS_SYNC */
41675540Sjhay	}
417124937Sphk	if (modes & MOD_OFFSET) {
418124937Sphk		if (time_status & STA_NANO)
419124937Sphk			hardupdate(ntv.offset);
420124937Sphk		else
421124937Sphk			hardupdate(ntv.offset * 1000);
422124937Sphk	}
4232858Swollman
4242858Swollman	/*
42565432Sphk	 * Retrieve all clock variables. Note that the TAI offset is
42665432Sphk	 * returned only by ntp_gettime();
4272858Swollman	 */
42844574Sphk	if (time_status & STA_NANO)
42994740Sphk		ntv.offset = L_GINT(time_offset);
4302858Swollman	else
43194740Sphk		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
43245295Sphk	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
4332858Swollman	ntv.maxerror = time_maxerror;
4342858Swollman	ntv.esterror = time_esterror;
4352858Swollman	ntv.status = time_status;
43645294Sphk	ntv.constant = time_constant;
43744574Sphk	if (time_status & STA_NANO)
43844574Sphk		ntv.precision = time_precision;
43944574Sphk	else
44044574Sphk		ntv.precision = time_precision / 1000;
44144574Sphk	ntv.tolerance = MAXFREQ * SCALE_PPM;
4422858Swollman#ifdef PPS_SYNC
4432858Swollman	ntv.shift = pps_shift;
44445295Sphk	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
44544574Sphk	if (time_status & STA_NANO)
44644574Sphk		ntv.jitter = pps_jitter;
44744574Sphk	else
44844574Sphk		ntv.jitter = pps_jitter / 1000;
4492858Swollman	ntv.stabil = pps_stabil;
4502858Swollman	ntv.calcnt = pps_calcnt;
4512858Swollman	ntv.errcnt = pps_errcnt;
4522858Swollman	ntv.jitcnt = pps_jitcnt;
4532858Swollman	ntv.stbcnt = pps_stbcnt;
4542858Swollman#endif /* PPS_SYNC */
45544574Sphk	splx(s);
4562858Swollman
4572858Swollman	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
45844574Sphk	if (error)
45982717Sdillon		goto done2;
46044574Sphk
461207359Savg	if (ntp_is_time_error())
46283366Sjulian		td->td_retval[0] = TIME_ERROR;
463207359Savg	else
46483366Sjulian		td->td_retval[0] = time_state;
465207359Savg
46682717Sdillondone2:
46782717Sdillon	mtx_unlock(&Giant);
46845302Sphk	return (error);
46944574Sphk}
47044574Sphk
47144574Sphk/*
47244574Sphk * second_overflow() - called after ntp_tick_adjust()
47344574Sphk *
47444574Sphk * This routine is ordinarily called immediately following the above
47544574Sphk * routine ntp_tick_adjust(). While these two routines are normally
47644574Sphk * combined, they are separated here only for the purposes of
47744574Sphk * simulation.
47844574Sphk */
47944574Sphkvoid
48095529Sphkntp_update_second(int64_t *adjustment, time_t *newsec)
48144574Sphk{
48294754Sphk	int tickrate;
48365432Sphk	l_fp ftemp;		/* 32/64-bit temporary */
48444574Sphk
48550656Sphk	/*
48650656Sphk	 * On rollover of the second both the nanosecond and microsecond
48750656Sphk	 * clocks are updated and the state machine cranked as
48850656Sphk	 * necessary. The phase adjustment to be used for the next
48950656Sphk	 * second is calculated and the maximum error is increased by
49050656Sphk	 * the tolerance.
49150656Sphk	 */
49244574Sphk	time_maxerror += MAXFREQ / 1000;
49344574Sphk
49444574Sphk	/*
49544574Sphk	 * Leap second processing. If in leap-insert state at
49644574Sphk	 * the end of the day, the system clock is set back one
49744574Sphk	 * second; if in leap-delete state, the system clock is
49844574Sphk	 * set ahead one second. The nano_time() routine or
49944574Sphk	 * external clock driver will insure that reported time
50044574Sphk	 * is always monotonic.
50144574Sphk	 */
50244574Sphk	switch (time_state) {
50344574Sphk
5042858Swollman		/*
50544574Sphk		 * No warning.
5062858Swollman		 */
50744574Sphk		case TIME_OK:
50844574Sphk		if (time_status & STA_INS)
50944574Sphk			time_state = TIME_INS;
51044574Sphk		else if (time_status & STA_DEL)
51144574Sphk			time_state = TIME_DEL;
51244574Sphk		break;
51344574Sphk
51444574Sphk		/*
51544574Sphk		 * Insert second 23:59:60 following second
51644574Sphk		 * 23:59:59.
51744574Sphk		 */
51844574Sphk		case TIME_INS:
51944574Sphk		if (!(time_status & STA_INS))
52044574Sphk			time_state = TIME_OK;
52144574Sphk		else if ((*newsec) % 86400 == 0) {
52244574Sphk			(*newsec)--;
52344574Sphk			time_state = TIME_OOP;
524116838Simp			time_tai++;
52544574Sphk		}
52644574Sphk		break;
52744574Sphk
52844574Sphk		/*
52944574Sphk		 * Delete second 23:59:59.
53044574Sphk		 */
53144574Sphk		case TIME_DEL:
53244574Sphk		if (!(time_status & STA_DEL))
53344574Sphk			time_state = TIME_OK;
53444574Sphk		else if (((*newsec) + 1) % 86400 == 0) {
53544574Sphk			(*newsec)++;
53665432Sphk			time_tai--;
53744574Sphk			time_state = TIME_WAIT;
53844574Sphk		}
53944574Sphk		break;
54044574Sphk
54144574Sphk		/*
54244574Sphk		 * Insert second in progress.
54344574Sphk		 */
54444574Sphk		case TIME_OOP:
54565432Sphk			time_state = TIME_WAIT;
54644574Sphk		break;
54744574Sphk
54844574Sphk		/*
54944574Sphk		 * Wait for status bits to clear.
55044574Sphk		 */
55144574Sphk		case TIME_WAIT:
55244574Sphk		if (!(time_status & (STA_INS | STA_DEL)))
55344574Sphk			time_state = TIME_OK;
5542858Swollman	}
55544574Sphk
55644574Sphk	/*
55750656Sphk	 * Compute the total time adjustment for the next second
55850656Sphk	 * in ns. The offset is reduced by a factor depending on
55950656Sphk	 * whether the PPS signal is operating. Note that the
56050656Sphk	 * value is in effect scaled by the clock frequency,
56150656Sphk	 * since the adjustment is added at each tick interrupt.
56244574Sphk	 */
56365432Sphk	ftemp = time_offset;
56444574Sphk#ifdef PPS_SYNC
56565432Sphk	/* XXX even if PPS signal dies we should finish adjustment ? */
56665432Sphk	if (time_status & STA_PPSTIME && time_status &
56765673Sphk	    STA_PPSSIGNAL)
56865432Sphk		L_RSHIFT(ftemp, pps_shift);
56965432Sphk	else
57065432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57144574Sphk#else
57265432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57344574Sphk#endif /* PPS_SYNC */
57465432Sphk	time_adj = ftemp;
57565432Sphk	L_SUB(time_offset, ftemp);
57644574Sphk	L_ADD(time_adj, time_freq);
57794754Sphk
57894754Sphk	/*
57994754Sphk	 * Apply any correction from adjtime(2).  If more than one second
58094754Sphk	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
58194754Sphk	 * until the last second is slewed the final < 500 usecs.
58294754Sphk	 */
58394754Sphk	if (time_adjtime != 0) {
58494754Sphk		if (time_adjtime > 1000000)
58594754Sphk			tickrate = 5000;
58694754Sphk		else if (time_adjtime < -1000000)
58794754Sphk			tickrate = -5000;
58894754Sphk		else if (time_adjtime > 500)
58994754Sphk			tickrate = 500;
59094754Sphk		else if (time_adjtime < -500)
59194754Sphk			tickrate = -500;
592126974Sphk		else
59394754Sphk			tickrate = time_adjtime;
59494754Sphk		time_adjtime -= tickrate;
59594754Sphk		L_LINT(ftemp, tickrate * 1000);
59694754Sphk		L_ADD(time_adj, ftemp);
59794754Sphk	}
59895529Sphk	*adjustment = time_adj;
59994754Sphk
60044574Sphk#ifdef PPS_SYNC
60144574Sphk	if (pps_valid > 0)
60244574Sphk		pps_valid--;
60344574Sphk	else
60475540Sjhay		time_status &= ~STA_PPSSIGNAL;
60544574Sphk#endif /* PPS_SYNC */
6062858Swollman}
6072858Swollman
60844574Sphk/*
60944574Sphk * ntp_init() - initialize variables and structures
61044574Sphk *
61144574Sphk * This routine must be called after the kernel variables hz and tick
61244574Sphk * are set or changed and before the next tick interrupt. In this
61344574Sphk * particular implementation, these values are assumed set elsewhere in
61444574Sphk * the kernel. The design allows the clock frequency and tick interval
61544574Sphk * to be changed while the system is running. So, this routine should
61644574Sphk * probably be integrated with the code that does that.
61744574Sphk */
61844574Sphkstatic void
61944574Sphkntp_init()
62044574Sphk{
62144574Sphk
62244574Sphk	/*
62344574Sphk	 * The following variables are initialized only at startup. Only
62444574Sphk	 * those structures not cleared by the compiler need to be
62544574Sphk	 * initialized, and these only in the simulator. In the actual
62644574Sphk	 * kernel, any nonzero values here will quickly evaporate.
62744574Sphk	 */
62844574Sphk	L_CLR(time_offset);
62944574Sphk	L_CLR(time_freq);
63032513Sphk#ifdef PPS_SYNC
63150656Sphk	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
63250656Sphk	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
63350656Sphk	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
63444794Sphk	pps_fcount = 0;
63544574Sphk	L_CLR(pps_freq);
63644574Sphk#endif /* PPS_SYNC */
63744574Sphk}
6382858Swollman
639177253SrwatsonSYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
64032513Sphk
64144574Sphk/*
64244574Sphk * hardupdate() - local clock update
64344574Sphk *
64444574Sphk * This routine is called by ntp_adjtime() to update the local clock
64544574Sphk * phase and frequency. The implementation is of an adaptive-parameter,
64644574Sphk * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
64744574Sphk * time and frequency offset estimates for each call. If the kernel PPS
64844574Sphk * discipline code is configured (PPS_SYNC), the PPS signal itself
64944574Sphk * determines the new time offset, instead of the calling argument.
65044574Sphk * Presumably, calls to ntp_adjtime() occur only when the caller
65144574Sphk * believes the local clock is valid within some bound (+-128 ms with
65244574Sphk * NTP). If the caller's time is far different than the PPS time, an
65344574Sphk * argument will ensue, and it's not clear who will lose.
65444574Sphk *
65544574Sphk * For uncompensated quartz crystal oscillators and nominal update
65644574Sphk * intervals less than 256 s, operation should be in phase-lock mode,
65744574Sphk * where the loop is disciplined to phase. For update intervals greater
65844574Sphk * than 1024 s, operation should be in frequency-lock mode, where the
65944574Sphk * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
66044574Sphk * is selected by the STA_MODE status bit.
66144574Sphk */
66244574Sphkstatic void
66344574Sphkhardupdate(offset)
66444574Sphk	long offset;		/* clock offset (ns) */
66544574Sphk{
66665432Sphk	long mtemp;
66744574Sphk	l_fp ftemp;
66832513Sphk
66944574Sphk	/*
67044574Sphk	 * Select how the phase is to be controlled and from which
67144574Sphk	 * source. If the PPS signal is present and enabled to
67244574Sphk	 * discipline the time, the PPS offset is used; otherwise, the
67344574Sphk	 * argument offset is used.
67444574Sphk	 */
67550656Sphk	if (!(time_status & STA_PLL))
67650656Sphk		return;
67765432Sphk	if (!(time_status & STA_PPSTIME && time_status &
67865432Sphk	    STA_PPSSIGNAL)) {
67965432Sphk		if (offset > MAXPHASE)
68065432Sphk			time_monitor = MAXPHASE;
68165432Sphk		else if (offset < -MAXPHASE)
68265432Sphk			time_monitor = -MAXPHASE;
68365432Sphk		else
68465432Sphk			time_monitor = offset;
68565432Sphk		L_LINT(time_offset, time_monitor);
68665432Sphk	}
68732513Sphk
68844574Sphk	/*
68944574Sphk	 * Select how the frequency is to be controlled and in which
69044574Sphk	 * mode (PLL or FLL). If the PPS signal is present and enabled
69144574Sphk	 * to discipline the frequency, the PPS frequency is used;
69244574Sphk	 * otherwise, the argument offset is used to compute it.
69344574Sphk	 */
69444574Sphk	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
69544574Sphk		time_reftime = time_second;
69644574Sphk		return;
69744574Sphk	}
69844574Sphk	if (time_status & STA_FREQHOLD || time_reftime == 0)
69944574Sphk		time_reftime = time_second;
70044574Sphk	mtemp = time_second - time_reftime;
70165432Sphk	L_LINT(ftemp, time_monitor);
70250656Sphk	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
70350656Sphk	L_MPY(ftemp, mtemp);
70450656Sphk	L_ADD(time_freq, ftemp);
70550656Sphk	time_status &= ~STA_MODE;
70665432Sphk	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
70765432Sphk	    MAXSEC)) {
70865432Sphk		L_LINT(ftemp, (time_monitor << 4) / mtemp);
70944574Sphk		L_RSHIFT(ftemp, SHIFT_FLL + 4);
71044574Sphk		L_ADD(time_freq, ftemp);
71144574Sphk		time_status |= STA_MODE;
71244574Sphk	}
71344574Sphk	time_reftime = time_second;
71444574Sphk	if (L_GINT(time_freq) > MAXFREQ)
71544574Sphk		L_LINT(time_freq, MAXFREQ);
71644574Sphk	else if (L_GINT(time_freq) < -MAXFREQ)
71744574Sphk		L_LINT(time_freq, -MAXFREQ);
71844574Sphk}
71944574Sphk
72044574Sphk#ifdef PPS_SYNC
72132513Sphk/*
72232513Sphk * hardpps() - discipline CPU clock oscillator to external PPS signal
72332513Sphk *
72432513Sphk * This routine is called at each PPS interrupt in order to discipline
72565432Sphk * the CPU clock oscillator to the PPS signal. There are two independent
72665432Sphk * first-order feedback loops, one for the phase, the other for the
72765432Sphk * frequency. The phase loop measures and grooms the PPS phase offset
72865432Sphk * and leaves it in a handy spot for the seconds overflow routine. The
72965432Sphk * frequency loop averages successive PPS phase differences and
73065432Sphk * calculates the PPS frequency offset, which is also processed by the
73165432Sphk * seconds overflow routine. The code requires the caller to capture the
73265432Sphk * time and architecture-dependent hardware counter values in
73365432Sphk * nanoseconds at the on-time PPS signal transition.
73432513Sphk *
73544574Sphk * Note that, on some Unix systems this routine runs at an interrupt
73632513Sphk * priority level higher than the timer interrupt routine hardclock().
73732513Sphk * Therefore, the variables used are distinct from the hardclock()
73844574Sphk * variables, except for the actual time and frequency variables, which
73944574Sphk * are determined by this routine and updated atomically.
74032513Sphk */
74132513Sphkvoid
74244574Sphkhardpps(tsp, nsec)
74344574Sphk	struct timespec *tsp;	/* time at PPS */
74444574Sphk	long nsec;		/* hardware counter at PPS */
74532513Sphk{
74665432Sphk	long u_sec, u_nsec, v_nsec; /* temps */
74744574Sphk	l_fp ftemp;
74832513Sphk
74932513Sphk	/*
75065432Sphk	 * The signal is first processed by a range gate and frequency
75165432Sphk	 * discriminator. The range gate rejects noise spikes outside
75265432Sphk	 * the range +-500 us. The frequency discriminator rejects input
75365432Sphk	 * signals with apparent frequency outside the range 1 +-500
75465432Sphk	 * PPM. If two hits occur in the same second, we ignore the
75565432Sphk	 * later hit; if not and a hit occurs outside the range gate,
75665432Sphk	 * keep the later hit for later comparison, but do not process
75765432Sphk	 * it.
75832513Sphk	 */
75944574Sphk	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
76044574Sphk	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
76144574Sphk	pps_valid = PPS_VALID;
76244574Sphk	u_sec = tsp->tv_sec;
76344574Sphk	u_nsec = tsp->tv_nsec;
76444574Sphk	if (u_nsec >= (NANOSECOND >> 1)) {
76544574Sphk		u_nsec -= NANOSECOND;
76644574Sphk		u_sec++;
76744574Sphk	}
76850656Sphk	v_nsec = u_nsec - pps_tf[0].tv_nsec;
76975540Sjhay	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
77075540Sjhay	    MAXFREQ)
77144574Sphk		return;
77244574Sphk	pps_tf[2] = pps_tf[1];
77344574Sphk	pps_tf[1] = pps_tf[0];
77450656Sphk	pps_tf[0].tv_sec = u_sec;
77550656Sphk	pps_tf[0].tv_nsec = u_nsec;
77632513Sphk
77732513Sphk	/*
77844574Sphk	 * Compute the difference between the current and previous
77944574Sphk	 * counter values. If the difference exceeds 0.5 s, assume it
78044574Sphk	 * has wrapped around, so correct 1.0 s. If the result exceeds
78144574Sphk	 * the tick interval, the sample point has crossed a tick
78244574Sphk	 * boundary during the last second, so correct the tick. Very
78344574Sphk	 * intricate.
78444574Sphk	 */
78544666Sphk	u_nsec = nsec;
78644574Sphk	if (u_nsec > (NANOSECOND >> 1))
78744574Sphk		u_nsec -= NANOSECOND;
78844574Sphk	else if (u_nsec < -(NANOSECOND >> 1))
78944574Sphk		u_nsec += NANOSECOND;
79044794Sphk	pps_fcount += u_nsec;
79175540Sjhay	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
79244574Sphk		return;
79344574Sphk	time_status &= ~STA_PPSJITTER;
79444574Sphk
79544574Sphk	/*
79644574Sphk	 * A three-stage median filter is used to help denoise the PPS
79732513Sphk	 * time. The median sample becomes the time offset estimate; the
79832513Sphk	 * difference between the other two samples becomes the time
79932513Sphk	 * dispersion (jitter) estimate.
80032513Sphk	 */
80150656Sphk	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
80250656Sphk		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
80350656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
80450656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
80550656Sphk		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
80650656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
80750656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
80844574Sphk		} else {
80950656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
81050656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
81144574Sphk		}
81244574Sphk	} else {
81350656Sphk		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
81450656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
81550656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
81665673Sphk		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
81750656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
81850656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
81944574Sphk		} else {
82050656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
82150656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
82244574Sphk		}
82344574Sphk	}
82432513Sphk
82532513Sphk	/*
82665673Sphk	 * Nominal jitter is due to PPS signal noise and interrupt
82765432Sphk	 * latency. If it exceeds the popcorn threshold, the sample is
82865432Sphk	 * discarded. otherwise, if so enabled, the time offset is
82965432Sphk	 * updated. We can tolerate a modest loss of data here without
83065432Sphk	 * much degrading time accuracy.
83132513Sphk	 */
83250656Sphk	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
83344574Sphk		time_status |= STA_PPSJITTER;
83444574Sphk		pps_jitcnt++;
83544574Sphk	} else if (time_status & STA_PPSTIME) {
83665432Sphk		time_monitor = -v_nsec;
83765432Sphk		L_LINT(time_offset, time_monitor);
83832513Sphk	}
83944574Sphk	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
84050656Sphk	u_sec = pps_tf[0].tv_sec - pps_lastsec;
84144574Sphk	if (u_sec < (1 << pps_shift))
84244574Sphk		return;
84344574Sphk
84432513Sphk	/*
84544574Sphk	 * At the end of the calibration interval the difference between
84644574Sphk	 * the first and last counter values becomes the scaled
84744574Sphk	 * frequency. It will later be divided by the length of the
84844574Sphk	 * interval to determine the frequency update. If the frequency
84944574Sphk	 * exceeds a sanity threshold, or if the actual calibration
85044574Sphk	 * interval is not equal to the expected length, the data are
85144574Sphk	 * discarded. We can tolerate a modest loss of data here without
85265432Sphk	 * much degrading frequency accuracy.
85332513Sphk	 */
85444574Sphk	pps_calcnt++;
85544794Sphk	v_nsec = -pps_fcount;
85650656Sphk	pps_lastsec = pps_tf[0].tv_sec;
85744794Sphk	pps_fcount = 0;
85844574Sphk	u_nsec = MAXFREQ << pps_shift;
85944574Sphk	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
86044574Sphk	    pps_shift)) {
86144574Sphk		time_status |= STA_PPSERROR;
86232513Sphk		pps_errcnt++;
86332513Sphk		return;
86432513Sphk	}
86532513Sphk
86632513Sphk	/*
86750656Sphk	 * Here the raw frequency offset and wander (stability) is
86850656Sphk	 * calculated. If the wander is less than the wander threshold
86950656Sphk	 * for four consecutive averaging intervals, the interval is
87050656Sphk	 * doubled; if it is greater than the threshold for four
87150656Sphk	 * consecutive intervals, the interval is halved. The scaled
87250656Sphk	 * frequency offset is converted to frequency offset. The
87350656Sphk	 * stability metric is calculated as the average of recent
87450656Sphk	 * frequency changes, but is used only for performance
87544574Sphk	 * monitoring.
87632513Sphk	 */
87744574Sphk	L_LINT(ftemp, v_nsec);
87844574Sphk	L_RSHIFT(ftemp, pps_shift);
87944574Sphk	L_SUB(ftemp, pps_freq);
88044574Sphk	u_nsec = L_GINT(ftemp);
88150656Sphk	if (u_nsec > PPS_MAXWANDER) {
88250656Sphk		L_LINT(ftemp, PPS_MAXWANDER);
88344574Sphk		pps_intcnt--;
88444574Sphk		time_status |= STA_PPSWANDER;
88532513Sphk		pps_stbcnt++;
88650656Sphk	} else if (u_nsec < -PPS_MAXWANDER) {
88750656Sphk		L_LINT(ftemp, -PPS_MAXWANDER);
88844574Sphk		pps_intcnt--;
88932513Sphk		time_status |= STA_PPSWANDER;
89044574Sphk		pps_stbcnt++;
89144574Sphk	} else {
89244574Sphk		pps_intcnt++;
89332513Sphk	}
89465432Sphk	if (pps_intcnt >= 4) {
89544574Sphk		pps_intcnt = 4;
89650656Sphk		if (pps_shift < pps_shiftmax) {
89744574Sphk			pps_shift++;
89844574Sphk			pps_intcnt = 0;
89932513Sphk		}
90065432Sphk	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
90144574Sphk		pps_intcnt = -4;
90244574Sphk		if (pps_shift > PPS_FAVG) {
90344574Sphk			pps_shift--;
90444574Sphk			pps_intcnt = 0;
90544574Sphk		}
90632513Sphk	}
90744574Sphk	if (u_nsec < 0)
90844574Sphk		u_nsec = -u_nsec;
90944574Sphk	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
91032513Sphk
91132513Sphk	/*
91250656Sphk	 * The PPS frequency is recalculated and clamped to the maximum
91350656Sphk	 * MAXFREQ. If enabled, the system clock frequency is updated as
91450656Sphk	 * well.
91532513Sphk	 */
91644574Sphk	L_ADD(pps_freq, ftemp);
91744574Sphk	u_nsec = L_GINT(pps_freq);
91844574Sphk	if (u_nsec > MAXFREQ)
91944574Sphk		L_LINT(pps_freq, MAXFREQ);
92044574Sphk	else if (u_nsec < -MAXFREQ)
92144574Sphk		L_LINT(pps_freq, -MAXFREQ);
92265432Sphk	if (time_status & STA_PPSFREQ)
92344574Sphk		time_freq = pps_freq;
92432513Sphk}
92532513Sphk#endif /* PPS_SYNC */
92694754Sphk
92794754Sphk#ifndef _SYS_SYSPROTO_H_
92894754Sphkstruct adjtime_args {
92994754Sphk	struct timeval *delta;
93094754Sphk	struct timeval *olddelta;
93194754Sphk};
93294754Sphk#endif
93394754Sphk/* ARGSUSED */
93494754Sphkint
93594754Sphkadjtime(struct thread *td, struct adjtime_args *uap)
93694754Sphk{
937144445Sjhb	struct timeval delta, olddelta, *deltap;
938144445Sjhb	int error;
939144445Sjhb
940144445Sjhb	if (uap->delta) {
941144445Sjhb		error = copyin(uap->delta, &delta, sizeof(delta));
942144445Sjhb		if (error)
943144445Sjhb			return (error);
944144445Sjhb		deltap = &delta;
945144445Sjhb	} else
946144445Sjhb		deltap = NULL;
947144445Sjhb	error = kern_adjtime(td, deltap, &olddelta);
948144445Sjhb	if (uap->olddelta && error == 0)
949144445Sjhb		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
950144445Sjhb	return (error);
951144445Sjhb}
952144445Sjhb
953144445Sjhbint
954144445Sjhbkern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
955144445Sjhb{
95694754Sphk	struct timeval atv;
95794754Sphk	int error;
95894754Sphk
95994754Sphk	mtx_lock(&Giant);
960144445Sjhb	if (olddelta) {
96194754Sphk		atv.tv_sec = time_adjtime / 1000000;
96294754Sphk		atv.tv_usec = time_adjtime % 1000000;
96394754Sphk		if (atv.tv_usec < 0) {
96494754Sphk			atv.tv_usec += 1000000;
96594754Sphk			atv.tv_sec--;
96694754Sphk		}
967144445Sjhb		*olddelta = atv;
96894754Sphk	}
969170732Srwatson	if (delta) {
970170732Srwatson		if ((error = priv_check(td, PRIV_ADJTIME))) {
971170732Srwatson			mtx_unlock(&Giant);
972170732Srwatson			return (error);
973170732Srwatson		}
974144445Sjhb		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
975144445Sjhb		    delta->tv_usec;
976170732Srwatson	}
97794754Sphk	mtx_unlock(&Giant);
978170732Srwatson	return (0);
97994754Sphk}
98094754Sphk
981207360Savgstatic struct callout resettodr_callout;
982207360Savgstatic int resettodr_period = 1800;
983207360Savg
984207360Savgstatic void
985207360Savgperiodic_resettodr(void *arg __unused)
986207360Savg{
987207360Savg
988207360Savg	if (!ntp_is_time_error()) {
989207360Savg		mtx_lock(&Giant);
990207360Savg		resettodr();
991207360Savg		mtx_unlock(&Giant);
992207360Savg	}
993207360Savg	if (resettodr_period > 0)
994207360Savg		callout_schedule(&resettodr_callout, resettodr_period * hz);
995207360Savg}
996207360Savg
997207360Savgstatic void
998207360Savgshutdown_resettodr(void *arg __unused, int howto __unused)
999207360Savg{
1000207360Savg
1001207360Savg	callout_drain(&resettodr_callout);
1002207360Savg	if (resettodr_period > 0 && !ntp_is_time_error()) {
1003207360Savg		mtx_lock(&Giant);
1004207360Savg		resettodr();
1005207360Savg		mtx_unlock(&Giant);
1006207360Savg	}
1007207360Savg}
1008207360Savg
1009207360Savgstatic int
1010207360Savgsysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
1011207360Savg{
1012207360Savg	int error;
1013207360Savg
1014207360Savg	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1015207360Savg	if (error || !req->newptr)
1016207360Savg		return (error);
1017207360Savg	if (resettodr_period == 0)
1018207360Savg		callout_stop(&resettodr_callout);
1019207360Savg	else
1020207360Savg		callout_reset(&resettodr_callout, resettodr_period * hz,
1021207360Savg		    periodic_resettodr, NULL);
1022207360Savg	return (0);
1023207360Savg}
1024207360Savg
1025207360SavgSYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT|CTLFLAG_RW,
1026207360Savg	&resettodr_period, 1800, sysctl_resettodr_period, "I",
1027207360Savg	"Save system time to RTC with this period (in seconds)");
1028207360SavgTUNABLE_INT("machdep.rtc_save_period", &resettodr_period);
1029207360Savg
1030207360Savgstatic void
1031207360Savgstart_periodic_resettodr(void *arg __unused)
1032207360Savg{
1033207360Savg
1034207360Savg	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
1035207360Savg	    SHUTDOWN_PRI_FIRST);
1036207360Savg	callout_init(&resettodr_callout, 1);
1037207360Savg	if (resettodr_period == 0)
1038207360Savg		return;
1039207360Savg	callout_reset(&resettodr_callout, resettodr_period * hz,
1040207360Savg	    periodic_resettodr, NULL);
1041207360Savg}
1042207360Savg
1043213305SavgSYSINIT(periodic_resettodr, SI_SUB_RUN_SCHEDULER, SI_ORDER_MIDDLE,
1044207360Savg	start_periodic_resettodr, NULL);
1045