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$");
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 */
151228856Slstewartint 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) */
157228856Slstewartlong 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
277225617Skmacysys_ntp_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
304228449SeadlerSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
305228449Seadler    &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
306228449SeadlerSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
307228449Seadler    &pps_shift, 0, "Interval duration (sec) (shift)");
308217368SmdfSYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
309228449Seadler    &time_monitor, 0, "Last time offset scaled (ns)");
31056458Sphk
311228449SeadlerSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD,
312228449Seadler    &pps_freq, sizeof(pps_freq), "I", "Scaled frequency offset (ns/sec)");
313228449SeadlerSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD,
314228449Seadler    &time_freq, sizeof(time_freq), "I", "Frequency offset (ns/sec)");
31550663Sphk#endif
316167232Srwatson
3172858Swollman/*
3182858Swollman * ntp_adjtime() - NTP daemon application interface
31944574Sphk *
320167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
321167232Srwatson * the timex.constant structure member has a dual purpose to set the time
322167232Srwatson * constant and to set the TAI offset.
3232858Swollman */
32412221Sbde#ifndef _SYS_SYSPROTO_H_
3252858Swollmanstruct ntp_adjtime_args {
32644574Sphk	struct timex *tp;
3272858Swollman};
32812221Sbde#endif
3292858Swollman
3302858Swollmanint
331225617Skmacysys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
3322858Swollman{
33344574Sphk	struct timex ntv;	/* temporary structure */
33445294Sphk	long freq;		/* frequency ns/s) */
33544574Sphk	int modes;		/* mode bits from structure */
33644574Sphk	int s;			/* caller priority */
3372858Swollman	int error;
3382858Swollman
3392858Swollman	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
3402858Swollman	if (error)
34144574Sphk		return(error);
3422858Swollman
3432858Swollman	/*
3442858Swollman	 * Update selected clock variables - only the superuser can
3452858Swollman	 * change anything. Note that there is no error checking here on
3462858Swollman	 * the assumption the superuser should know what it is doing.
34765432Sphk	 * Note that either the time constant or TAI offset are loaded
34875540Sjhay	 * from the ntv.constant member, depending on the mode bits. If
34975540Sjhay	 * the STA_PLL bit in the status word is cleared, the state and
35075540Sjhay	 * status words are reset to the initial values at boot.
3512858Swollman	 */
35282717Sdillon	mtx_lock(&Giant);
3532858Swollman	modes = ntv.modes;
35444776Sphk	if (modes)
355164033Srwatson		error = priv_check(td, PRIV_NTP_ADJTIME);
35644574Sphk	if (error)
35782717Sdillon		goto done2;
3582858Swollman	s = splclock();
3592858Swollman	if (modes & MOD_MAXERROR)
3602858Swollman		time_maxerror = ntv.maxerror;
3612858Swollman	if (modes & MOD_ESTERROR)
3622858Swollman		time_esterror = ntv.esterror;
3632858Swollman	if (modes & MOD_STATUS) {
36475540Sjhay		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
36575540Sjhay			time_state = TIME_OK;
36675540Sjhay			time_status = STA_UNSYNC;
36775540Sjhay#ifdef PPS_SYNC
36875540Sjhay			pps_shift = PPS_FAVG;
36975540Sjhay#endif /* PPS_SYNC */
37075540Sjhay		}
3712858Swollman		time_status &= STA_RONLY;
3722858Swollman		time_status |= ntv.status & ~STA_RONLY;
3732858Swollman	}
37445294Sphk	if (modes & MOD_TIMECONST) {
37545294Sphk		if (ntv.constant < 0)
37645294Sphk			time_constant = 0;
37745294Sphk		else if (ntv.constant > MAXTC)
37845294Sphk			time_constant = MAXTC;
37945294Sphk		else
38045294Sphk			time_constant = ntv.constant;
38145294Sphk	}
38265432Sphk	if (modes & MOD_TAI) {
38365432Sphk		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
38465432Sphk			time_tai = ntv.constant;
38565432Sphk	}
38650656Sphk#ifdef PPS_SYNC
38750656Sphk	if (modes & MOD_PPSMAX) {
38850656Sphk		if (ntv.shift < PPS_FAVG)
38950656Sphk			pps_shiftmax = PPS_FAVG;
39050656Sphk		else if (ntv.shift > PPS_FAVGMAX)
39150656Sphk			pps_shiftmax = PPS_FAVGMAX;
39250656Sphk		else
39350656Sphk			pps_shiftmax = ntv.shift;
39450656Sphk	}
39550656Sphk#endif /* PPS_SYNC */
39644574Sphk	if (modes & MOD_NANO)
39744574Sphk		time_status |= STA_NANO;
39844574Sphk	if (modes & MOD_MICRO)
39944574Sphk		time_status &= ~STA_NANO;
40044574Sphk	if (modes & MOD_CLKB)
40144574Sphk		time_status |= STA_CLK;
40244574Sphk	if (modes & MOD_CLKA)
40344574Sphk		time_status &= ~STA_CLK;
40475540Sjhay	if (modes & MOD_FREQUENCY) {
40575540Sjhay		freq = (ntv.freq * 1000LL) >> 16;
40675540Sjhay		if (freq > MAXFREQ)
40775540Sjhay			L_LINT(time_freq, MAXFREQ);
40875540Sjhay		else if (freq < -MAXFREQ)
40975540Sjhay			L_LINT(time_freq, -MAXFREQ);
410126974Sphk		else {
411126974Sphk			/*
412126974Sphk			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
413126974Sphk			 * time_freq is [ns/s * 2^32]
414126974Sphk			 */
415126974Sphk			time_freq = ntv.freq * 1000LL * 65536LL;
416126974Sphk		}
41775540Sjhay#ifdef PPS_SYNC
41875540Sjhay		pps_freq = time_freq;
41975540Sjhay#endif /* PPS_SYNC */
42075540Sjhay	}
421124937Sphk	if (modes & MOD_OFFSET) {
422124937Sphk		if (time_status & STA_NANO)
423124937Sphk			hardupdate(ntv.offset);
424124937Sphk		else
425124937Sphk			hardupdate(ntv.offset * 1000);
426124937Sphk	}
4272858Swollman
4282858Swollman	/*
42965432Sphk	 * Retrieve all clock variables. Note that the TAI offset is
43065432Sphk	 * returned only by ntp_gettime();
4312858Swollman	 */
43244574Sphk	if (time_status & STA_NANO)
43394740Sphk		ntv.offset = L_GINT(time_offset);
4342858Swollman	else
43594740Sphk		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
43645295Sphk	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
4372858Swollman	ntv.maxerror = time_maxerror;
4382858Swollman	ntv.esterror = time_esterror;
4392858Swollman	ntv.status = time_status;
44045294Sphk	ntv.constant = time_constant;
44144574Sphk	if (time_status & STA_NANO)
44244574Sphk		ntv.precision = time_precision;
44344574Sphk	else
44444574Sphk		ntv.precision = time_precision / 1000;
44544574Sphk	ntv.tolerance = MAXFREQ * SCALE_PPM;
4462858Swollman#ifdef PPS_SYNC
4472858Swollman	ntv.shift = pps_shift;
44845295Sphk	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
44944574Sphk	if (time_status & STA_NANO)
45044574Sphk		ntv.jitter = pps_jitter;
45144574Sphk	else
45244574Sphk		ntv.jitter = pps_jitter / 1000;
4532858Swollman	ntv.stabil = pps_stabil;
4542858Swollman	ntv.calcnt = pps_calcnt;
4552858Swollman	ntv.errcnt = pps_errcnt;
4562858Swollman	ntv.jitcnt = pps_jitcnt;
4572858Swollman	ntv.stbcnt = pps_stbcnt;
4582858Swollman#endif /* PPS_SYNC */
45944574Sphk	splx(s);
4602858Swollman
4612858Swollman	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
46244574Sphk	if (error)
46382717Sdillon		goto done2;
46444574Sphk
465207359Savg	if (ntp_is_time_error())
46683366Sjulian		td->td_retval[0] = TIME_ERROR;
467207359Savg	else
46883366Sjulian		td->td_retval[0] = time_state;
469207359Savg
47082717Sdillondone2:
47182717Sdillon	mtx_unlock(&Giant);
47245302Sphk	return (error);
47344574Sphk}
47444574Sphk
47544574Sphk/*
47644574Sphk * second_overflow() - called after ntp_tick_adjust()
47744574Sphk *
47844574Sphk * This routine is ordinarily called immediately following the above
47944574Sphk * routine ntp_tick_adjust(). While these two routines are normally
48044574Sphk * combined, they are separated here only for the purposes of
48144574Sphk * simulation.
48244574Sphk */
48344574Sphkvoid
48495529Sphkntp_update_second(int64_t *adjustment, time_t *newsec)
48544574Sphk{
48694754Sphk	int tickrate;
48765432Sphk	l_fp ftemp;		/* 32/64-bit temporary */
48844574Sphk
48950656Sphk	/*
49050656Sphk	 * On rollover of the second both the nanosecond and microsecond
49150656Sphk	 * clocks are updated and the state machine cranked as
49250656Sphk	 * necessary. The phase adjustment to be used for the next
49350656Sphk	 * second is calculated and the maximum error is increased by
49450656Sphk	 * the tolerance.
49550656Sphk	 */
49644574Sphk	time_maxerror += MAXFREQ / 1000;
49744574Sphk
49844574Sphk	/*
49944574Sphk	 * Leap second processing. If in leap-insert state at
50044574Sphk	 * the end of the day, the system clock is set back one
50144574Sphk	 * second; if in leap-delete state, the system clock is
50244574Sphk	 * set ahead one second. The nano_time() routine or
50344574Sphk	 * external clock driver will insure that reported time
50444574Sphk	 * is always monotonic.
50544574Sphk	 */
50644574Sphk	switch (time_state) {
50744574Sphk
5082858Swollman		/*
50944574Sphk		 * No warning.
5102858Swollman		 */
51144574Sphk		case TIME_OK:
51244574Sphk		if (time_status & STA_INS)
51344574Sphk			time_state = TIME_INS;
51444574Sphk		else if (time_status & STA_DEL)
51544574Sphk			time_state = TIME_DEL;
51644574Sphk		break;
51744574Sphk
51844574Sphk		/*
51944574Sphk		 * Insert second 23:59:60 following second
52044574Sphk		 * 23:59:59.
52144574Sphk		 */
52244574Sphk		case TIME_INS:
52344574Sphk		if (!(time_status & STA_INS))
52444574Sphk			time_state = TIME_OK;
52544574Sphk		else if ((*newsec) % 86400 == 0) {
52644574Sphk			(*newsec)--;
52744574Sphk			time_state = TIME_OOP;
528116838Simp			time_tai++;
52944574Sphk		}
53044574Sphk		break;
53144574Sphk
53244574Sphk		/*
53344574Sphk		 * Delete second 23:59:59.
53444574Sphk		 */
53544574Sphk		case TIME_DEL:
53644574Sphk		if (!(time_status & STA_DEL))
53744574Sphk			time_state = TIME_OK;
53844574Sphk		else if (((*newsec) + 1) % 86400 == 0) {
53944574Sphk			(*newsec)++;
54065432Sphk			time_tai--;
54144574Sphk			time_state = TIME_WAIT;
54244574Sphk		}
54344574Sphk		break;
54444574Sphk
54544574Sphk		/*
54644574Sphk		 * Insert second in progress.
54744574Sphk		 */
54844574Sphk		case TIME_OOP:
54965432Sphk			time_state = TIME_WAIT;
55044574Sphk		break;
55144574Sphk
55244574Sphk		/*
55344574Sphk		 * Wait for status bits to clear.
55444574Sphk		 */
55544574Sphk		case TIME_WAIT:
55644574Sphk		if (!(time_status & (STA_INS | STA_DEL)))
55744574Sphk			time_state = TIME_OK;
5582858Swollman	}
55944574Sphk
56044574Sphk	/*
56150656Sphk	 * Compute the total time adjustment for the next second
56250656Sphk	 * in ns. The offset is reduced by a factor depending on
56350656Sphk	 * whether the PPS signal is operating. Note that the
56450656Sphk	 * value is in effect scaled by the clock frequency,
56550656Sphk	 * since the adjustment is added at each tick interrupt.
56644574Sphk	 */
56765432Sphk	ftemp = time_offset;
56844574Sphk#ifdef PPS_SYNC
56965432Sphk	/* XXX even if PPS signal dies we should finish adjustment ? */
57065432Sphk	if (time_status & STA_PPSTIME && time_status &
57165673Sphk	    STA_PPSSIGNAL)
57265432Sphk		L_RSHIFT(ftemp, pps_shift);
57365432Sphk	else
57465432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57544574Sphk#else
57665432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57744574Sphk#endif /* PPS_SYNC */
57865432Sphk	time_adj = ftemp;
57965432Sphk	L_SUB(time_offset, ftemp);
58044574Sphk	L_ADD(time_adj, time_freq);
58194754Sphk
58294754Sphk	/*
58394754Sphk	 * Apply any correction from adjtime(2).  If more than one second
58494754Sphk	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
58594754Sphk	 * until the last second is slewed the final < 500 usecs.
58694754Sphk	 */
58794754Sphk	if (time_adjtime != 0) {
58894754Sphk		if (time_adjtime > 1000000)
58994754Sphk			tickrate = 5000;
59094754Sphk		else if (time_adjtime < -1000000)
59194754Sphk			tickrate = -5000;
59294754Sphk		else if (time_adjtime > 500)
59394754Sphk			tickrate = 500;
59494754Sphk		else if (time_adjtime < -500)
59594754Sphk			tickrate = -500;
596126974Sphk		else
59794754Sphk			tickrate = time_adjtime;
59894754Sphk		time_adjtime -= tickrate;
59994754Sphk		L_LINT(ftemp, tickrate * 1000);
60094754Sphk		L_ADD(time_adj, ftemp);
60194754Sphk	}
60295529Sphk	*adjustment = time_adj;
60394754Sphk
60444574Sphk#ifdef PPS_SYNC
60544574Sphk	if (pps_valid > 0)
60644574Sphk		pps_valid--;
60744574Sphk	else
60875540Sjhay		time_status &= ~STA_PPSSIGNAL;
60944574Sphk#endif /* PPS_SYNC */
6102858Swollman}
6112858Swollman
61244574Sphk/*
61344574Sphk * ntp_init() - initialize variables and structures
61444574Sphk *
61544574Sphk * This routine must be called after the kernel variables hz and tick
61644574Sphk * are set or changed and before the next tick interrupt. In this
61744574Sphk * particular implementation, these values are assumed set elsewhere in
61844574Sphk * the kernel. The design allows the clock frequency and tick interval
61944574Sphk * to be changed while the system is running. So, this routine should
62044574Sphk * probably be integrated with the code that does that.
62144574Sphk */
62244574Sphkstatic void
62344574Sphkntp_init()
62444574Sphk{
62544574Sphk
62644574Sphk	/*
62744574Sphk	 * The following variables are initialized only at startup. Only
62844574Sphk	 * those structures not cleared by the compiler need to be
62944574Sphk	 * initialized, and these only in the simulator. In the actual
63044574Sphk	 * kernel, any nonzero values here will quickly evaporate.
63144574Sphk	 */
63244574Sphk	L_CLR(time_offset);
63344574Sphk	L_CLR(time_freq);
63432513Sphk#ifdef PPS_SYNC
63550656Sphk	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
63650656Sphk	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
63750656Sphk	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
63844794Sphk	pps_fcount = 0;
63944574Sphk	L_CLR(pps_freq);
64044574Sphk#endif /* PPS_SYNC */
64144574Sphk}
6422858Swollman
643177253SrwatsonSYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
64432513Sphk
64544574Sphk/*
64644574Sphk * hardupdate() - local clock update
64744574Sphk *
64844574Sphk * This routine is called by ntp_adjtime() to update the local clock
64944574Sphk * phase and frequency. The implementation is of an adaptive-parameter,
65044574Sphk * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
65144574Sphk * time and frequency offset estimates for each call. If the kernel PPS
65244574Sphk * discipline code is configured (PPS_SYNC), the PPS signal itself
65344574Sphk * determines the new time offset, instead of the calling argument.
65444574Sphk * Presumably, calls to ntp_adjtime() occur only when the caller
65544574Sphk * believes the local clock is valid within some bound (+-128 ms with
65644574Sphk * NTP). If the caller's time is far different than the PPS time, an
65744574Sphk * argument will ensue, and it's not clear who will lose.
65844574Sphk *
65944574Sphk * For uncompensated quartz crystal oscillators and nominal update
66044574Sphk * intervals less than 256 s, operation should be in phase-lock mode,
66144574Sphk * where the loop is disciplined to phase. For update intervals greater
66244574Sphk * than 1024 s, operation should be in frequency-lock mode, where the
66344574Sphk * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
66444574Sphk * is selected by the STA_MODE status bit.
66544574Sphk */
66644574Sphkstatic void
66744574Sphkhardupdate(offset)
66844574Sphk	long offset;		/* clock offset (ns) */
66944574Sphk{
67065432Sphk	long mtemp;
67144574Sphk	l_fp ftemp;
67232513Sphk
67344574Sphk	/*
67444574Sphk	 * Select how the phase is to be controlled and from which
67544574Sphk	 * source. If the PPS signal is present and enabled to
67644574Sphk	 * discipline the time, the PPS offset is used; otherwise, the
67744574Sphk	 * argument offset is used.
67844574Sphk	 */
67950656Sphk	if (!(time_status & STA_PLL))
68050656Sphk		return;
68165432Sphk	if (!(time_status & STA_PPSTIME && time_status &
68265432Sphk	    STA_PPSSIGNAL)) {
68365432Sphk		if (offset > MAXPHASE)
68465432Sphk			time_monitor = MAXPHASE;
68565432Sphk		else if (offset < -MAXPHASE)
68665432Sphk			time_monitor = -MAXPHASE;
68765432Sphk		else
68865432Sphk			time_monitor = offset;
68965432Sphk		L_LINT(time_offset, time_monitor);
69065432Sphk	}
69132513Sphk
69244574Sphk	/*
69344574Sphk	 * Select how the frequency is to be controlled and in which
69444574Sphk	 * mode (PLL or FLL). If the PPS signal is present and enabled
69544574Sphk	 * to discipline the frequency, the PPS frequency is used;
69644574Sphk	 * otherwise, the argument offset is used to compute it.
69744574Sphk	 */
69844574Sphk	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
69944574Sphk		time_reftime = time_second;
70044574Sphk		return;
70144574Sphk	}
70244574Sphk	if (time_status & STA_FREQHOLD || time_reftime == 0)
70344574Sphk		time_reftime = time_second;
70444574Sphk	mtemp = time_second - time_reftime;
70565432Sphk	L_LINT(ftemp, time_monitor);
70650656Sphk	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
70750656Sphk	L_MPY(ftemp, mtemp);
70850656Sphk	L_ADD(time_freq, ftemp);
70950656Sphk	time_status &= ~STA_MODE;
71065432Sphk	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
71165432Sphk	    MAXSEC)) {
71265432Sphk		L_LINT(ftemp, (time_monitor << 4) / mtemp);
71344574Sphk		L_RSHIFT(ftemp, SHIFT_FLL + 4);
71444574Sphk		L_ADD(time_freq, ftemp);
71544574Sphk		time_status |= STA_MODE;
71644574Sphk	}
71744574Sphk	time_reftime = time_second;
71844574Sphk	if (L_GINT(time_freq) > MAXFREQ)
71944574Sphk		L_LINT(time_freq, MAXFREQ);
72044574Sphk	else if (L_GINT(time_freq) < -MAXFREQ)
72144574Sphk		L_LINT(time_freq, -MAXFREQ);
72244574Sphk}
72344574Sphk
72444574Sphk#ifdef PPS_SYNC
72532513Sphk/*
72632513Sphk * hardpps() - discipline CPU clock oscillator to external PPS signal
72732513Sphk *
72832513Sphk * This routine is called at each PPS interrupt in order to discipline
72965432Sphk * the CPU clock oscillator to the PPS signal. There are two independent
73065432Sphk * first-order feedback loops, one for the phase, the other for the
73165432Sphk * frequency. The phase loop measures and grooms the PPS phase offset
73265432Sphk * and leaves it in a handy spot for the seconds overflow routine. The
73365432Sphk * frequency loop averages successive PPS phase differences and
73465432Sphk * calculates the PPS frequency offset, which is also processed by the
73565432Sphk * seconds overflow routine. The code requires the caller to capture the
73665432Sphk * time and architecture-dependent hardware counter values in
73765432Sphk * nanoseconds at the on-time PPS signal transition.
73832513Sphk *
73944574Sphk * Note that, on some Unix systems this routine runs at an interrupt
74032513Sphk * priority level higher than the timer interrupt routine hardclock().
74132513Sphk * Therefore, the variables used are distinct from the hardclock()
74244574Sphk * variables, except for the actual time and frequency variables, which
74344574Sphk * are determined by this routine and updated atomically.
74432513Sphk */
74532513Sphkvoid
74644574Sphkhardpps(tsp, nsec)
74744574Sphk	struct timespec *tsp;	/* time at PPS */
74844574Sphk	long nsec;		/* hardware counter at PPS */
74932513Sphk{
75065432Sphk	long u_sec, u_nsec, v_nsec; /* temps */
75144574Sphk	l_fp ftemp;
75232513Sphk
75332513Sphk	/*
75465432Sphk	 * The signal is first processed by a range gate and frequency
75565432Sphk	 * discriminator. The range gate rejects noise spikes outside
75665432Sphk	 * the range +-500 us. The frequency discriminator rejects input
75765432Sphk	 * signals with apparent frequency outside the range 1 +-500
75865432Sphk	 * PPM. If two hits occur in the same second, we ignore the
75965432Sphk	 * later hit; if not and a hit occurs outside the range gate,
76065432Sphk	 * keep the later hit for later comparison, but do not process
76165432Sphk	 * it.
76232513Sphk	 */
76344574Sphk	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
76444574Sphk	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
76544574Sphk	pps_valid = PPS_VALID;
76644574Sphk	u_sec = tsp->tv_sec;
76744574Sphk	u_nsec = tsp->tv_nsec;
76844574Sphk	if (u_nsec >= (NANOSECOND >> 1)) {
76944574Sphk		u_nsec -= NANOSECOND;
77044574Sphk		u_sec++;
77144574Sphk	}
77250656Sphk	v_nsec = u_nsec - pps_tf[0].tv_nsec;
77375540Sjhay	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
77475540Sjhay	    MAXFREQ)
77544574Sphk		return;
77644574Sphk	pps_tf[2] = pps_tf[1];
77744574Sphk	pps_tf[1] = pps_tf[0];
77850656Sphk	pps_tf[0].tv_sec = u_sec;
77950656Sphk	pps_tf[0].tv_nsec = u_nsec;
78032513Sphk
78132513Sphk	/*
78244574Sphk	 * Compute the difference between the current and previous
78344574Sphk	 * counter values. If the difference exceeds 0.5 s, assume it
78444574Sphk	 * has wrapped around, so correct 1.0 s. If the result exceeds
78544574Sphk	 * the tick interval, the sample point has crossed a tick
78644574Sphk	 * boundary during the last second, so correct the tick. Very
78744574Sphk	 * intricate.
78844574Sphk	 */
78944666Sphk	u_nsec = nsec;
79044574Sphk	if (u_nsec > (NANOSECOND >> 1))
79144574Sphk		u_nsec -= NANOSECOND;
79244574Sphk	else if (u_nsec < -(NANOSECOND >> 1))
79344574Sphk		u_nsec += NANOSECOND;
79444794Sphk	pps_fcount += u_nsec;
79575540Sjhay	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
79644574Sphk		return;
79744574Sphk	time_status &= ~STA_PPSJITTER;
79844574Sphk
79944574Sphk	/*
80044574Sphk	 * A three-stage median filter is used to help denoise the PPS
80132513Sphk	 * time. The median sample becomes the time offset estimate; the
80232513Sphk	 * difference between the other two samples becomes the time
80332513Sphk	 * dispersion (jitter) estimate.
80432513Sphk	 */
80550656Sphk	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
80650656Sphk		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
80750656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
80850656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
80950656Sphk		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
81050656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
81150656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
81244574Sphk		} else {
81350656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
81450656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
81544574Sphk		}
81644574Sphk	} else {
81750656Sphk		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
81850656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
81950656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
82065673Sphk		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
82150656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
82250656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
82344574Sphk		} else {
82450656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
82550656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
82644574Sphk		}
82744574Sphk	}
82832513Sphk
82932513Sphk	/*
83065673Sphk	 * Nominal jitter is due to PPS signal noise and interrupt
83165432Sphk	 * latency. If it exceeds the popcorn threshold, the sample is
83265432Sphk	 * discarded. otherwise, if so enabled, the time offset is
83365432Sphk	 * updated. We can tolerate a modest loss of data here without
83465432Sphk	 * much degrading time accuracy.
835239320Simp	 *
836239320Simp	 * The measurements being checked here were made with the system
837239320Simp	 * timecounter, so the popcorn threshold is not allowed to fall below
838239320Simp	 * the number of nanoseconds in two ticks of the timecounter.  For a
839239320Simp	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
840239320Simp	 * to avoid a nonsensical threshold of zero.
841239320Simp	*/
842239320Simp	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
843239320Simp	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
84444574Sphk		time_status |= STA_PPSJITTER;
84544574Sphk		pps_jitcnt++;
84644574Sphk	} else if (time_status & STA_PPSTIME) {
84765432Sphk		time_monitor = -v_nsec;
84865432Sphk		L_LINT(time_offset, time_monitor);
84932513Sphk	}
85044574Sphk	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
85150656Sphk	u_sec = pps_tf[0].tv_sec - pps_lastsec;
85244574Sphk	if (u_sec < (1 << pps_shift))
85344574Sphk		return;
85444574Sphk
85532513Sphk	/*
85644574Sphk	 * At the end of the calibration interval the difference between
85744574Sphk	 * the first and last counter values becomes the scaled
85844574Sphk	 * frequency. It will later be divided by the length of the
85944574Sphk	 * interval to determine the frequency update. If the frequency
86044574Sphk	 * exceeds a sanity threshold, or if the actual calibration
86144574Sphk	 * interval is not equal to the expected length, the data are
86244574Sphk	 * discarded. We can tolerate a modest loss of data here without
86365432Sphk	 * much degrading frequency accuracy.
86432513Sphk	 */
86544574Sphk	pps_calcnt++;
86644794Sphk	v_nsec = -pps_fcount;
86750656Sphk	pps_lastsec = pps_tf[0].tv_sec;
86844794Sphk	pps_fcount = 0;
86944574Sphk	u_nsec = MAXFREQ << pps_shift;
87044574Sphk	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
87144574Sphk	    pps_shift)) {
87244574Sphk		time_status |= STA_PPSERROR;
87332513Sphk		pps_errcnt++;
87432513Sphk		return;
87532513Sphk	}
87632513Sphk
87732513Sphk	/*
87850656Sphk	 * Here the raw frequency offset and wander (stability) is
87950656Sphk	 * calculated. If the wander is less than the wander threshold
88050656Sphk	 * for four consecutive averaging intervals, the interval is
88150656Sphk	 * doubled; if it is greater than the threshold for four
88250656Sphk	 * consecutive intervals, the interval is halved. The scaled
88350656Sphk	 * frequency offset is converted to frequency offset. The
88450656Sphk	 * stability metric is calculated as the average of recent
88550656Sphk	 * frequency changes, but is used only for performance
88644574Sphk	 * monitoring.
88732513Sphk	 */
88844574Sphk	L_LINT(ftemp, v_nsec);
88944574Sphk	L_RSHIFT(ftemp, pps_shift);
89044574Sphk	L_SUB(ftemp, pps_freq);
89144574Sphk	u_nsec = L_GINT(ftemp);
89250656Sphk	if (u_nsec > PPS_MAXWANDER) {
89350656Sphk		L_LINT(ftemp, PPS_MAXWANDER);
89444574Sphk		pps_intcnt--;
89544574Sphk		time_status |= STA_PPSWANDER;
89632513Sphk		pps_stbcnt++;
89750656Sphk	} else if (u_nsec < -PPS_MAXWANDER) {
89850656Sphk		L_LINT(ftemp, -PPS_MAXWANDER);
89944574Sphk		pps_intcnt--;
90032513Sphk		time_status |= STA_PPSWANDER;
90144574Sphk		pps_stbcnt++;
90244574Sphk	} else {
90344574Sphk		pps_intcnt++;
90432513Sphk	}
90565432Sphk	if (pps_intcnt >= 4) {
90644574Sphk		pps_intcnt = 4;
90750656Sphk		if (pps_shift < pps_shiftmax) {
90844574Sphk			pps_shift++;
90944574Sphk			pps_intcnt = 0;
91032513Sphk		}
91165432Sphk	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
91244574Sphk		pps_intcnt = -4;
91344574Sphk		if (pps_shift > PPS_FAVG) {
91444574Sphk			pps_shift--;
91544574Sphk			pps_intcnt = 0;
91644574Sphk		}
91732513Sphk	}
91844574Sphk	if (u_nsec < 0)
91944574Sphk		u_nsec = -u_nsec;
92044574Sphk	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
92132513Sphk
92232513Sphk	/*
92350656Sphk	 * The PPS frequency is recalculated and clamped to the maximum
92450656Sphk	 * MAXFREQ. If enabled, the system clock frequency is updated as
92550656Sphk	 * well.
92632513Sphk	 */
92744574Sphk	L_ADD(pps_freq, ftemp);
92844574Sphk	u_nsec = L_GINT(pps_freq);
92944574Sphk	if (u_nsec > MAXFREQ)
93044574Sphk		L_LINT(pps_freq, MAXFREQ);
93144574Sphk	else if (u_nsec < -MAXFREQ)
93244574Sphk		L_LINT(pps_freq, -MAXFREQ);
93365432Sphk	if (time_status & STA_PPSFREQ)
93444574Sphk		time_freq = pps_freq;
93532513Sphk}
93632513Sphk#endif /* PPS_SYNC */
93794754Sphk
93894754Sphk#ifndef _SYS_SYSPROTO_H_
93994754Sphkstruct adjtime_args {
94094754Sphk	struct timeval *delta;
94194754Sphk	struct timeval *olddelta;
94294754Sphk};
94394754Sphk#endif
94494754Sphk/* ARGSUSED */
94594754Sphkint
946225617Skmacysys_adjtime(struct thread *td, struct adjtime_args *uap)
94794754Sphk{
948144445Sjhb	struct timeval delta, olddelta, *deltap;
949144445Sjhb	int error;
950144445Sjhb
951144445Sjhb	if (uap->delta) {
952144445Sjhb		error = copyin(uap->delta, &delta, sizeof(delta));
953144445Sjhb		if (error)
954144445Sjhb			return (error);
955144445Sjhb		deltap = &delta;
956144445Sjhb	} else
957144445Sjhb		deltap = NULL;
958144445Sjhb	error = kern_adjtime(td, deltap, &olddelta);
959144445Sjhb	if (uap->olddelta && error == 0)
960144445Sjhb		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
961144445Sjhb	return (error);
962144445Sjhb}
963144445Sjhb
964144445Sjhbint
965144445Sjhbkern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
966144445Sjhb{
96794754Sphk	struct timeval atv;
96894754Sphk	int error;
96994754Sphk
97094754Sphk	mtx_lock(&Giant);
971144445Sjhb	if (olddelta) {
97294754Sphk		atv.tv_sec = time_adjtime / 1000000;
97394754Sphk		atv.tv_usec = time_adjtime % 1000000;
97494754Sphk		if (atv.tv_usec < 0) {
97594754Sphk			atv.tv_usec += 1000000;
97694754Sphk			atv.tv_sec--;
97794754Sphk		}
978144445Sjhb		*olddelta = atv;
97994754Sphk	}
980170732Srwatson	if (delta) {
981170732Srwatson		if ((error = priv_check(td, PRIV_ADJTIME))) {
982170732Srwatson			mtx_unlock(&Giant);
983170732Srwatson			return (error);
984170732Srwatson		}
985144445Sjhb		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
986144445Sjhb		    delta->tv_usec;
987170732Srwatson	}
98894754Sphk	mtx_unlock(&Giant);
989170732Srwatson	return (0);
99094754Sphk}
99194754Sphk
992207360Savgstatic struct callout resettodr_callout;
993207360Savgstatic int resettodr_period = 1800;
994207360Savg
995207360Savgstatic void
996207360Savgperiodic_resettodr(void *arg __unused)
997207360Savg{
998207360Savg
999207360Savg	if (!ntp_is_time_error()) {
1000207360Savg		mtx_lock(&Giant);
1001207360Savg		resettodr();
1002207360Savg		mtx_unlock(&Giant);
1003207360Savg	}
1004207360Savg	if (resettodr_period > 0)
1005207360Savg		callout_schedule(&resettodr_callout, resettodr_period * hz);
1006207360Savg}
1007207360Savg
1008207360Savgstatic void
1009207360Savgshutdown_resettodr(void *arg __unused, int howto __unused)
1010207360Savg{
1011207360Savg
1012207360Savg	callout_drain(&resettodr_callout);
1013207360Savg	if (resettodr_period > 0 && !ntp_is_time_error()) {
1014207360Savg		mtx_lock(&Giant);
1015207360Savg		resettodr();
1016207360Savg		mtx_unlock(&Giant);
1017207360Savg	}
1018207360Savg}
1019207360Savg
1020207360Savgstatic int
1021207360Savgsysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
1022207360Savg{
1023207360Savg	int error;
1024207360Savg
1025207360Savg	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1026207360Savg	if (error || !req->newptr)
1027207360Savg		return (error);
1028207360Savg	if (resettodr_period == 0)
1029207360Savg		callout_stop(&resettodr_callout);
1030207360Savg	else
1031207360Savg		callout_reset(&resettodr_callout, resettodr_period * hz,
1032207360Savg		    periodic_resettodr, NULL);
1033207360Savg	return (0);
1034207360Savg}
1035207360Savg
1036207360SavgSYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT|CTLFLAG_RW,
1037207360Savg	&resettodr_period, 1800, sysctl_resettodr_period, "I",
1038207360Savg	"Save system time to RTC with this period (in seconds)");
1039207360SavgTUNABLE_INT("machdep.rtc_save_period", &resettodr_period);
1040207360Savg
1041207360Savgstatic void
1042207360Savgstart_periodic_resettodr(void *arg __unused)
1043207360Savg{
1044207360Savg
1045207360Savg	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
1046207360Savg	    SHUTDOWN_PRI_FIRST);
1047207360Savg	callout_init(&resettodr_callout, 1);
1048207360Savg	if (resettodr_period == 0)
1049207360Savg		return;
1050207360Savg	callout_reset(&resettodr_callout, resettodr_period * hz,
1051207360Savg	    periodic_resettodr, NULL);
1052207360Savg}
1053207360Savg
1054253604SavgSYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
1055207360Savg	start_periodic_resettodr, NULL);
1056