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: releng/11.0/sys/kern/kern_ntptime.c 302252 2016-06-28 16:43:23Z kib $");
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) */
158285424Sianstatic long time_reftime;		/* uptime 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
165302252Skibstatic struct mtx ntpadj_lock;
166302252SkibMTX_SYSINIT(ntpadj, &ntpadj_lock, "ntpadj",
1672858Swollman#ifdef PPS_SYNC
168302252Skib    MTX_SPIN
169302252Skib#else
170302252Skib    MTX_DEF
171302252Skib#endif
172302252Skib);
173302252Skib
1742858Swollman/*
175302252Skib * When PPS_SYNC is defined, hardpps() function is provided which can
176302252Skib * be legitimately called from interrupt filters.  Due to this, use
177302252Skib * spinlock for ntptime state protection, otherwise sleepable mutex is
178302252Skib * adequate.
179302252Skib */
180302252Skib#ifdef PPS_SYNC
181302252Skib#define	NTPADJ_LOCK()		mtx_lock_spin(&ntpadj_lock)
182302252Skib#define	NTPADJ_UNLOCK()		mtx_unlock_spin(&ntpadj_lock)
183302252Skib#else
184302252Skib#define	NTPADJ_LOCK()		mtx_lock(&ntpadj_lock)
185302252Skib#define	NTPADJ_UNLOCK()		mtx_unlock(&ntpadj_lock)
186302252Skib#endif
187302252Skib#define	NTPADJ_ASSERT_LOCKED()	mtx_assert(&ntpadj_lock, MA_OWNED)
188302252Skib
189302252Skib#ifdef PPS_SYNC
190302252Skib/*
19144574Sphk * The following variables are used when a pulse-per-second (PPS) signal
19244574Sphk * is available and connected via a modem control lead. They establish
19344574Sphk * the engineering parameters of the clock discipline loop when
19444574Sphk * controlled by the PPS signal.
1952858Swollman */
19644574Sphk#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
19775540Sjhay#define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
19850656Sphk#define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
19944574Sphk#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
20044574Sphk#define PPS_VALID	120		/* PPS signal watchdog max (s) */
20150656Sphk#define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
20250656Sphk#define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
20332513Sphk
20450656Sphkstatic struct timespec pps_tf[3];	/* phase median filter */
20544574Sphkstatic l_fp pps_freq;			/* scaled frequency offset (ns/s) */
20645294Sphkstatic long pps_fcount;			/* frequency accumulator */
20750656Sphkstatic long pps_jitter;			/* nominal jitter (ns) */
20850656Sphkstatic long pps_stabil;			/* nominal stability (scaled ns/s) */
20944574Sphkstatic long pps_lastsec;		/* time at last calibration (s) */
21044574Sphkstatic int pps_valid;			/* signal watchdog counter */
21144574Sphkstatic int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
21250656Sphkstatic int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
21344574Sphkstatic int pps_intcnt;			/* wander counter */
21444574Sphk
21532513Sphk/*
21632513Sphk * PPS signal quality monitors
21732513Sphk */
21844574Sphkstatic long pps_calcnt;			/* calibration intervals */
21944574Sphkstatic long pps_jitcnt;			/* jitter limit exceeded */
22044574Sphkstatic long pps_stbcnt;			/* stability limit exceeded */
22144574Sphkstatic long pps_errcnt;			/* calibration errors */
2222858Swollman#endif /* PPS_SYNC */
22332513Sphk/*
22444574Sphk * End of phase/frequency-lock loop (PLL/FLL) definitions
22532513Sphk */
22632513Sphk
22744574Sphkstatic void ntp_init(void);
22844574Sphkstatic void hardupdate(long offset);
229137873Smarksstatic void ntp_gettime1(struct ntptimeval *ntvp);
230302252Skibstatic bool ntp_is_time_error(int tsl);
23132513Sphk
232302252Skibstatic bool
233302252Skibntp_is_time_error(int tsl)
2342858Swollman{
235302252Skib
2362858Swollman	/*
23744574Sphk	 * Status word error decode. If any of these conditions occur,
23844574Sphk	 * an error is returned, instead of the status word. Most
23944574Sphk	 * applications will care only about the fact the system clock
24044574Sphk	 * may not be trusted, not about the details.
2412858Swollman	 *
2422858Swollman	 * Hardware or software error
2432858Swollman	 */
244302252Skib	if ((tsl & (STA_UNSYNC | STA_CLOCKERR)) ||
2452858Swollman
2462858Swollman	/*
24744574Sphk	 * PPS signal lost when either time or frequency synchronization
24844574Sphk	 * requested
2492858Swollman	 */
250302252Skib	    (tsl & (STA_PPSFREQ | STA_PPSTIME) &&
251302252Skib	    !(tsl & STA_PPSSIGNAL)) ||
2522858Swollman
2532858Swollman	/*
25444574Sphk	 * PPS jitter exceeded when time synchronization requested
2552858Swollman	 */
256302252Skib	    (tsl & STA_PPSTIME && tsl & STA_PPSJITTER) ||
2572858Swollman
2582858Swollman	/*
25944574Sphk	 * PPS wander exceeded or calibration error when frequency
26044574Sphk	 * synchronization requested
2612858Swollman	 */
262302252Skib	    (tsl & STA_PPSFREQ &&
263302252Skib	    tsl & (STA_PPSWANDER | STA_PPSERROR)))
264302252Skib		return (true);
265207359Savg
266302252Skib	return (false);
267207359Savg}
268207359Savg
269207359Savgstatic void
270207359Savgntp_gettime1(struct ntptimeval *ntvp)
271207359Savg{
272207359Savg	struct timespec atv;	/* nanosecond time */
273207359Savg
274302252Skib	NTPADJ_ASSERT_LOCKED();
275207359Savg
276207359Savg	nanotime(&atv);
277207359Savg	ntvp->time.tv_sec = atv.tv_sec;
278207359Savg	ntvp->time.tv_nsec = atv.tv_nsec;
279207359Savg	ntvp->maxerror = time_maxerror;
280207359Savg	ntvp->esterror = time_esterror;
281207359Savg	ntvp->tai = time_tai;
282207359Savg	ntvp->time_state = time_state;
283207359Savg
284302252Skib	if (ntp_is_time_error(time_status))
285137873Smarks		ntvp->time_state = TIME_ERROR;
2862858Swollman}
2872858Swollman
288137879Smarks/*
289137879Smarks * ntp_gettime() - NTP user application interface
290137879Smarks *
291167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
292167232Srwatson * the TAI offset is returned in the ntvtimeval.tai structure member.
293137879Smarks */
294137873Smarks#ifndef _SYS_SYSPROTO_H_
295137873Smarksstruct ntp_gettime_args {
296137873Smarks	struct ntptimeval *ntvp;
297137873Smarks};
298137873Smarks#endif
299137873Smarks/* ARGSUSED */
300137873Smarksint
301225617Skmacysys_ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
302137873Smarks{
303137873Smarks	struct ntptimeval ntv;
304137873Smarks
305302252Skib	NTPADJ_LOCK();
306137873Smarks	ntp_gettime1(&ntv);
307302252Skib	NTPADJ_UNLOCK();
308137873Smarks
309165969Simp	td->td_retval[0] = ntv.time_state;
310137873Smarks	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
311137873Smarks}
312137873Smarks
313137873Smarksstatic int
314137873Smarksntp_sysctl(SYSCTL_HANDLER_ARGS)
315137873Smarks{
316137873Smarks	struct ntptimeval ntv;	/* temporary structure */
317137873Smarks
318302252Skib	NTPADJ_LOCK();
319137873Smarks	ntp_gettime1(&ntv);
320302252Skib	NTPADJ_UNLOCK();
321137873Smarks
322137873Smarks	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
323137873Smarks}
324137873Smarks
32544574SphkSYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
326302252SkibSYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE | CTLFLAG_RD |
327302252Skib    CTLFLAG_MPSAFE, 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval",
328302252Skib    "");
32912279Sphk
33050663Sphk#ifdef PPS_SYNC
331228449SeadlerSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
332228449Seadler    &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
333228449SeadlerSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
334228449Seadler    &pps_shift, 0, "Interval duration (sec) (shift)");
335217368SmdfSYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
336228449Seadler    &time_monitor, 0, "Last time offset scaled (ns)");
33756458Sphk
338302252SkibSYSCTL_S64(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
339302252Skib    &pps_freq, 0,
340302252Skib    "Scaled frequency offset (ns/sec)");
341302252SkibSYSCTL_S64(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
342302252Skib    &time_freq, 0,
343302252Skib    "Frequency offset (ns/sec)");
34450663Sphk#endif
345167232Srwatson
3462858Swollman/*
3472858Swollman * ntp_adjtime() - NTP daemon application interface
34844574Sphk *
349167232Srwatson * See the timex.h header file for synopsis and API description.  Note that
350167232Srwatson * the timex.constant structure member has a dual purpose to set the time
351167232Srwatson * constant and to set the TAI offset.
3522858Swollman */
35312221Sbde#ifndef _SYS_SYSPROTO_H_
3542858Swollmanstruct ntp_adjtime_args {
35544574Sphk	struct timex *tp;
3562858Swollman};
35712221Sbde#endif
3582858Swollman
3592858Swollmanint
360225617Skmacysys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
3612858Swollman{
36244574Sphk	struct timex ntv;	/* temporary structure */
36345294Sphk	long freq;		/* frequency ns/s) */
36444574Sphk	int modes;		/* mode bits from structure */
365302252Skib	int error, retval;
3662858Swollman
3672858Swollman	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
3682858Swollman	if (error)
369302252Skib		return (error);
3702858Swollman
3712858Swollman	/*
3722858Swollman	 * Update selected clock variables - only the superuser can
3732858Swollman	 * change anything. Note that there is no error checking here on
3742858Swollman	 * the assumption the superuser should know what it is doing.
37565432Sphk	 * Note that either the time constant or TAI offset are loaded
37675540Sjhay	 * from the ntv.constant member, depending on the mode bits. If
37775540Sjhay	 * the STA_PLL bit in the status word is cleared, the state and
37875540Sjhay	 * status words are reset to the initial values at boot.
3792858Swollman	 */
3802858Swollman	modes = ntv.modes;
38144776Sphk	if (modes)
382164033Srwatson		error = priv_check(td, PRIV_NTP_ADJTIME);
383302252Skib	if (error != 0)
384302252Skib		return (error);
385302252Skib	NTPADJ_LOCK();
3862858Swollman	if (modes & MOD_MAXERROR)
3872858Swollman		time_maxerror = ntv.maxerror;
3882858Swollman	if (modes & MOD_ESTERROR)
3892858Swollman		time_esterror = ntv.esterror;
3902858Swollman	if (modes & MOD_STATUS) {
39175540Sjhay		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
39275540Sjhay			time_state = TIME_OK;
39375540Sjhay			time_status = STA_UNSYNC;
39475540Sjhay#ifdef PPS_SYNC
39575540Sjhay			pps_shift = PPS_FAVG;
39675540Sjhay#endif /* PPS_SYNC */
39775540Sjhay		}
3982858Swollman		time_status &= STA_RONLY;
3992858Swollman		time_status |= ntv.status & ~STA_RONLY;
4002858Swollman	}
40145294Sphk	if (modes & MOD_TIMECONST) {
40245294Sphk		if (ntv.constant < 0)
40345294Sphk			time_constant = 0;
40445294Sphk		else if (ntv.constant > MAXTC)
40545294Sphk			time_constant = MAXTC;
40645294Sphk		else
40745294Sphk			time_constant = ntv.constant;
40845294Sphk	}
40965432Sphk	if (modes & MOD_TAI) {
41065432Sphk		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
41165432Sphk			time_tai = ntv.constant;
41265432Sphk	}
41350656Sphk#ifdef PPS_SYNC
41450656Sphk	if (modes & MOD_PPSMAX) {
41550656Sphk		if (ntv.shift < PPS_FAVG)
41650656Sphk			pps_shiftmax = PPS_FAVG;
41750656Sphk		else if (ntv.shift > PPS_FAVGMAX)
41850656Sphk			pps_shiftmax = PPS_FAVGMAX;
41950656Sphk		else
42050656Sphk			pps_shiftmax = ntv.shift;
42150656Sphk	}
42250656Sphk#endif /* PPS_SYNC */
42344574Sphk	if (modes & MOD_NANO)
42444574Sphk		time_status |= STA_NANO;
42544574Sphk	if (modes & MOD_MICRO)
42644574Sphk		time_status &= ~STA_NANO;
42744574Sphk	if (modes & MOD_CLKB)
42844574Sphk		time_status |= STA_CLK;
42944574Sphk	if (modes & MOD_CLKA)
43044574Sphk		time_status &= ~STA_CLK;
43175540Sjhay	if (modes & MOD_FREQUENCY) {
43275540Sjhay		freq = (ntv.freq * 1000LL) >> 16;
43375540Sjhay		if (freq > MAXFREQ)
43475540Sjhay			L_LINT(time_freq, MAXFREQ);
43575540Sjhay		else if (freq < -MAXFREQ)
43675540Sjhay			L_LINT(time_freq, -MAXFREQ);
437126974Sphk		else {
438126974Sphk			/*
439126974Sphk			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
440126974Sphk			 * time_freq is [ns/s * 2^32]
441126974Sphk			 */
442126974Sphk			time_freq = ntv.freq * 1000LL * 65536LL;
443126974Sphk		}
44475540Sjhay#ifdef PPS_SYNC
44575540Sjhay		pps_freq = time_freq;
44675540Sjhay#endif /* PPS_SYNC */
44775540Sjhay	}
448124937Sphk	if (modes & MOD_OFFSET) {
449124937Sphk		if (time_status & STA_NANO)
450124937Sphk			hardupdate(ntv.offset);
451124937Sphk		else
452124937Sphk			hardupdate(ntv.offset * 1000);
453124937Sphk	}
4542858Swollman
4552858Swollman	/*
45665432Sphk	 * Retrieve all clock variables. Note that the TAI offset is
45765432Sphk	 * returned only by ntp_gettime();
4582858Swollman	 */
45944574Sphk	if (time_status & STA_NANO)
46094740Sphk		ntv.offset = L_GINT(time_offset);
4612858Swollman	else
46294740Sphk		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
46345295Sphk	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
4642858Swollman	ntv.maxerror = time_maxerror;
4652858Swollman	ntv.esterror = time_esterror;
4662858Swollman	ntv.status = time_status;
46745294Sphk	ntv.constant = time_constant;
46844574Sphk	if (time_status & STA_NANO)
46944574Sphk		ntv.precision = time_precision;
47044574Sphk	else
47144574Sphk		ntv.precision = time_precision / 1000;
47244574Sphk	ntv.tolerance = MAXFREQ * SCALE_PPM;
4732858Swollman#ifdef PPS_SYNC
4742858Swollman	ntv.shift = pps_shift;
47545295Sphk	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
47644574Sphk	if (time_status & STA_NANO)
47744574Sphk		ntv.jitter = pps_jitter;
47844574Sphk	else
47944574Sphk		ntv.jitter = pps_jitter / 1000;
4802858Swollman	ntv.stabil = pps_stabil;
4812858Swollman	ntv.calcnt = pps_calcnt;
4822858Swollman	ntv.errcnt = pps_errcnt;
4832858Swollman	ntv.jitcnt = pps_jitcnt;
4842858Swollman	ntv.stbcnt = pps_stbcnt;
4852858Swollman#endif /* PPS_SYNC */
486302252Skib	retval = ntp_is_time_error(time_status) ? TIME_ERROR : time_state;
487302252Skib	NTPADJ_UNLOCK();
4882858Swollman
4892858Swollman	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
490302252Skib	if (error == 0)
491302252Skib		td->td_retval[0] = retval;
49245302Sphk	return (error);
49344574Sphk}
49444574Sphk
49544574Sphk/*
49644574Sphk * second_overflow() - called after ntp_tick_adjust()
49744574Sphk *
49844574Sphk * This routine is ordinarily called immediately following the above
49944574Sphk * routine ntp_tick_adjust(). While these two routines are normally
50044574Sphk * combined, they are separated here only for the purposes of
50144574Sphk * simulation.
50244574Sphk */
50344574Sphkvoid
50495529Sphkntp_update_second(int64_t *adjustment, time_t *newsec)
50544574Sphk{
50694754Sphk	int tickrate;
50765432Sphk	l_fp ftemp;		/* 32/64-bit temporary */
50844574Sphk
50950656Sphk	/*
51050656Sphk	 * On rollover of the second both the nanosecond and microsecond
51150656Sphk	 * clocks are updated and the state machine cranked as
51250656Sphk	 * necessary. The phase adjustment to be used for the next
51350656Sphk	 * second is calculated and the maximum error is increased by
51450656Sphk	 * the tolerance.
51550656Sphk	 */
51644574Sphk	time_maxerror += MAXFREQ / 1000;
51744574Sphk
51844574Sphk	/*
51944574Sphk	 * Leap second processing. If in leap-insert state at
52044574Sphk	 * the end of the day, the system clock is set back one
52144574Sphk	 * second; if in leap-delete state, the system clock is
52244574Sphk	 * set ahead one second. The nano_time() routine or
52344574Sphk	 * external clock driver will insure that reported time
52444574Sphk	 * is always monotonic.
52544574Sphk	 */
52644574Sphk	switch (time_state) {
52744574Sphk
5282858Swollman		/*
52944574Sphk		 * No warning.
5302858Swollman		 */
53144574Sphk		case TIME_OK:
53244574Sphk		if (time_status & STA_INS)
53344574Sphk			time_state = TIME_INS;
53444574Sphk		else if (time_status & STA_DEL)
53544574Sphk			time_state = TIME_DEL;
53644574Sphk		break;
53744574Sphk
53844574Sphk		/*
53944574Sphk		 * Insert second 23:59:60 following second
54044574Sphk		 * 23:59:59.
54144574Sphk		 */
54244574Sphk		case TIME_INS:
54344574Sphk		if (!(time_status & STA_INS))
54444574Sphk			time_state = TIME_OK;
54544574Sphk		else if ((*newsec) % 86400 == 0) {
54644574Sphk			(*newsec)--;
54744574Sphk			time_state = TIME_OOP;
548116838Simp			time_tai++;
54944574Sphk		}
55044574Sphk		break;
55144574Sphk
55244574Sphk		/*
55344574Sphk		 * Delete second 23:59:59.
55444574Sphk		 */
55544574Sphk		case TIME_DEL:
55644574Sphk		if (!(time_status & STA_DEL))
55744574Sphk			time_state = TIME_OK;
55844574Sphk		else if (((*newsec) + 1) % 86400 == 0) {
55944574Sphk			(*newsec)++;
56065432Sphk			time_tai--;
56144574Sphk			time_state = TIME_WAIT;
56244574Sphk		}
56344574Sphk		break;
56444574Sphk
56544574Sphk		/*
56644574Sphk		 * Insert second in progress.
56744574Sphk		 */
56844574Sphk		case TIME_OOP:
56965432Sphk			time_state = TIME_WAIT;
57044574Sphk		break;
57144574Sphk
57244574Sphk		/*
57344574Sphk		 * Wait for status bits to clear.
57444574Sphk		 */
57544574Sphk		case TIME_WAIT:
57644574Sphk		if (!(time_status & (STA_INS | STA_DEL)))
57744574Sphk			time_state = TIME_OK;
5782858Swollman	}
57944574Sphk
58044574Sphk	/*
58150656Sphk	 * Compute the total time adjustment for the next second
58250656Sphk	 * in ns. The offset is reduced by a factor depending on
58350656Sphk	 * whether the PPS signal is operating. Note that the
58450656Sphk	 * value is in effect scaled by the clock frequency,
58550656Sphk	 * since the adjustment is added at each tick interrupt.
58644574Sphk	 */
58765432Sphk	ftemp = time_offset;
58844574Sphk#ifdef PPS_SYNC
58965432Sphk	/* XXX even if PPS signal dies we should finish adjustment ? */
59065432Sphk	if (time_status & STA_PPSTIME && time_status &
59165673Sphk	    STA_PPSSIGNAL)
59265432Sphk		L_RSHIFT(ftemp, pps_shift);
59365432Sphk	else
59465432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59544574Sphk#else
59665432Sphk		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59744574Sphk#endif /* PPS_SYNC */
59865432Sphk	time_adj = ftemp;
59965432Sphk	L_SUB(time_offset, ftemp);
60044574Sphk	L_ADD(time_adj, time_freq);
60194754Sphk
60294754Sphk	/*
60394754Sphk	 * Apply any correction from adjtime(2).  If more than one second
60494754Sphk	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
60594754Sphk	 * until the last second is slewed the final < 500 usecs.
60694754Sphk	 */
60794754Sphk	if (time_adjtime != 0) {
60894754Sphk		if (time_adjtime > 1000000)
60994754Sphk			tickrate = 5000;
61094754Sphk		else if (time_adjtime < -1000000)
61194754Sphk			tickrate = -5000;
61294754Sphk		else if (time_adjtime > 500)
61394754Sphk			tickrate = 500;
61494754Sphk		else if (time_adjtime < -500)
61594754Sphk			tickrate = -500;
616126974Sphk		else
61794754Sphk			tickrate = time_adjtime;
61894754Sphk		time_adjtime -= tickrate;
61994754Sphk		L_LINT(ftemp, tickrate * 1000);
62094754Sphk		L_ADD(time_adj, ftemp);
62194754Sphk	}
62295529Sphk	*adjustment = time_adj;
62394754Sphk
62444574Sphk#ifdef PPS_SYNC
62544574Sphk	if (pps_valid > 0)
62644574Sphk		pps_valid--;
62744574Sphk	else
62875540Sjhay		time_status &= ~STA_PPSSIGNAL;
62944574Sphk#endif /* PPS_SYNC */
6302858Swollman}
6312858Swollman
63244574Sphk/*
63344574Sphk * ntp_init() - initialize variables and structures
63444574Sphk *
63544574Sphk * This routine must be called after the kernel variables hz and tick
63644574Sphk * are set or changed and before the next tick interrupt. In this
63744574Sphk * particular implementation, these values are assumed set elsewhere in
63844574Sphk * the kernel. The design allows the clock frequency and tick interval
63944574Sphk * to be changed while the system is running. So, this routine should
64044574Sphk * probably be integrated with the code that does that.
64144574Sphk */
64244574Sphkstatic void
643302252Skibntp_init(void)
64444574Sphk{
64544574Sphk
64644574Sphk	/*
64744574Sphk	 * The following variables are initialized only at startup. Only
64844574Sphk	 * those structures not cleared by the compiler need to be
64944574Sphk	 * initialized, and these only in the simulator. In the actual
65044574Sphk	 * kernel, any nonzero values here will quickly evaporate.
65144574Sphk	 */
65244574Sphk	L_CLR(time_offset);
65344574Sphk	L_CLR(time_freq);
65432513Sphk#ifdef PPS_SYNC
65550656Sphk	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
65650656Sphk	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
65750656Sphk	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
65844794Sphk	pps_fcount = 0;
65944574Sphk	L_CLR(pps_freq);
66044574Sphk#endif /* PPS_SYNC */
66144574Sphk}
6622858Swollman
663177253SrwatsonSYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
66432513Sphk
66544574Sphk/*
66644574Sphk * hardupdate() - local clock update
66744574Sphk *
66844574Sphk * This routine is called by ntp_adjtime() to update the local clock
66944574Sphk * phase and frequency. The implementation is of an adaptive-parameter,
67044574Sphk * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
67144574Sphk * time and frequency offset estimates for each call. If the kernel PPS
67244574Sphk * discipline code is configured (PPS_SYNC), the PPS signal itself
67344574Sphk * determines the new time offset, instead of the calling argument.
67444574Sphk * Presumably, calls to ntp_adjtime() occur only when the caller
67544574Sphk * believes the local clock is valid within some bound (+-128 ms with
67644574Sphk * NTP). If the caller's time is far different than the PPS time, an
67744574Sphk * argument will ensue, and it's not clear who will lose.
67844574Sphk *
67944574Sphk * For uncompensated quartz crystal oscillators and nominal update
68044574Sphk * intervals less than 256 s, operation should be in phase-lock mode,
68144574Sphk * where the loop is disciplined to phase. For update intervals greater
68244574Sphk * than 1024 s, operation should be in frequency-lock mode, where the
68344574Sphk * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
68444574Sphk * is selected by the STA_MODE status bit.
68544574Sphk */
68644574Sphkstatic void
68744574Sphkhardupdate(offset)
68844574Sphk	long offset;		/* clock offset (ns) */
68944574Sphk{
69065432Sphk	long mtemp;
69144574Sphk	l_fp ftemp;
69232513Sphk
693302252Skib	NTPADJ_ASSERT_LOCKED();
694302252Skib
69544574Sphk	/*
69644574Sphk	 * Select how the phase is to be controlled and from which
69744574Sphk	 * source. If the PPS signal is present and enabled to
69844574Sphk	 * discipline the time, the PPS offset is used; otherwise, the
69944574Sphk	 * argument offset is used.
70044574Sphk	 */
70150656Sphk	if (!(time_status & STA_PLL))
70250656Sphk		return;
70365432Sphk	if (!(time_status & STA_PPSTIME && time_status &
70465432Sphk	    STA_PPSSIGNAL)) {
70565432Sphk		if (offset > MAXPHASE)
70665432Sphk			time_monitor = MAXPHASE;
70765432Sphk		else if (offset < -MAXPHASE)
70865432Sphk			time_monitor = -MAXPHASE;
70965432Sphk		else
71065432Sphk			time_monitor = offset;
71165432Sphk		L_LINT(time_offset, time_monitor);
71265432Sphk	}
71332513Sphk
71444574Sphk	/*
71544574Sphk	 * Select how the frequency is to be controlled and in which
71644574Sphk	 * mode (PLL or FLL). If the PPS signal is present and enabled
71744574Sphk	 * to discipline the frequency, the PPS frequency is used;
71844574Sphk	 * otherwise, the argument offset is used to compute it.
71944574Sphk	 */
72044574Sphk	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
721285424Sian		time_reftime = time_uptime;
72244574Sphk		return;
72344574Sphk	}
72444574Sphk	if (time_status & STA_FREQHOLD || time_reftime == 0)
725285424Sian		time_reftime = time_uptime;
726285424Sian	mtemp = time_uptime - time_reftime;
72765432Sphk	L_LINT(ftemp, time_monitor);
72850656Sphk	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
72950656Sphk	L_MPY(ftemp, mtemp);
73050656Sphk	L_ADD(time_freq, ftemp);
73150656Sphk	time_status &= ~STA_MODE;
73265432Sphk	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
73365432Sphk	    MAXSEC)) {
73465432Sphk		L_LINT(ftemp, (time_monitor << 4) / mtemp);
73544574Sphk		L_RSHIFT(ftemp, SHIFT_FLL + 4);
73644574Sphk		L_ADD(time_freq, ftemp);
73744574Sphk		time_status |= STA_MODE;
73844574Sphk	}
739285424Sian	time_reftime = time_uptime;
74044574Sphk	if (L_GINT(time_freq) > MAXFREQ)
74144574Sphk		L_LINT(time_freq, MAXFREQ);
74244574Sphk	else if (L_GINT(time_freq) < -MAXFREQ)
74344574Sphk		L_LINT(time_freq, -MAXFREQ);
74444574Sphk}
74544574Sphk
74644574Sphk#ifdef PPS_SYNC
74732513Sphk/*
74832513Sphk * hardpps() - discipline CPU clock oscillator to external PPS signal
74932513Sphk *
75032513Sphk * This routine is called at each PPS interrupt in order to discipline
75165432Sphk * the CPU clock oscillator to the PPS signal. There are two independent
75265432Sphk * first-order feedback loops, one for the phase, the other for the
75365432Sphk * frequency. The phase loop measures and grooms the PPS phase offset
75465432Sphk * and leaves it in a handy spot for the seconds overflow routine. The
75565432Sphk * frequency loop averages successive PPS phase differences and
75665432Sphk * calculates the PPS frequency offset, which is also processed by the
75765432Sphk * seconds overflow routine. The code requires the caller to capture the
75865432Sphk * time and architecture-dependent hardware counter values in
75965432Sphk * nanoseconds at the on-time PPS signal transition.
76032513Sphk *
76144574Sphk * Note that, on some Unix systems this routine runs at an interrupt
76232513Sphk * priority level higher than the timer interrupt routine hardclock().
76332513Sphk * Therefore, the variables used are distinct from the hardclock()
76444574Sphk * variables, except for the actual time and frequency variables, which
76544574Sphk * are determined by this routine and updated atomically.
76632513Sphk */
76732513Sphkvoid
76844574Sphkhardpps(tsp, nsec)
76944574Sphk	struct timespec *tsp;	/* time at PPS */
77044574Sphk	long nsec;		/* hardware counter at PPS */
77132513Sphk{
77265432Sphk	long u_sec, u_nsec, v_nsec; /* temps */
77344574Sphk	l_fp ftemp;
77432513Sphk
775302252Skib	NTPADJ_LOCK();
776302252Skib
77732513Sphk	/*
77865432Sphk	 * The signal is first processed by a range gate and frequency
77965432Sphk	 * discriminator. The range gate rejects noise spikes outside
78065432Sphk	 * the range +-500 us. The frequency discriminator rejects input
78165432Sphk	 * signals with apparent frequency outside the range 1 +-500
78265432Sphk	 * PPM. If two hits occur in the same second, we ignore the
78365432Sphk	 * later hit; if not and a hit occurs outside the range gate,
78465432Sphk	 * keep the later hit for later comparison, but do not process
78565432Sphk	 * it.
78632513Sphk	 */
78744574Sphk	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
78844574Sphk	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
78944574Sphk	pps_valid = PPS_VALID;
79044574Sphk	u_sec = tsp->tv_sec;
79144574Sphk	u_nsec = tsp->tv_nsec;
79244574Sphk	if (u_nsec >= (NANOSECOND >> 1)) {
79344574Sphk		u_nsec -= NANOSECOND;
79444574Sphk		u_sec++;
79544574Sphk	}
79650656Sphk	v_nsec = u_nsec - pps_tf[0].tv_nsec;
797302252Skib	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND - MAXFREQ)
798302252Skib		goto out;
79944574Sphk	pps_tf[2] = pps_tf[1];
80044574Sphk	pps_tf[1] = pps_tf[0];
80150656Sphk	pps_tf[0].tv_sec = u_sec;
80250656Sphk	pps_tf[0].tv_nsec = u_nsec;
80332513Sphk
80432513Sphk	/*
80544574Sphk	 * Compute the difference between the current and previous
80644574Sphk	 * counter values. If the difference exceeds 0.5 s, assume it
80744574Sphk	 * has wrapped around, so correct 1.0 s. If the result exceeds
80844574Sphk	 * the tick interval, the sample point has crossed a tick
80944574Sphk	 * boundary during the last second, so correct the tick. Very
81044574Sphk	 * intricate.
81144574Sphk	 */
81244666Sphk	u_nsec = nsec;
81344574Sphk	if (u_nsec > (NANOSECOND >> 1))
81444574Sphk		u_nsec -= NANOSECOND;
81544574Sphk	else if (u_nsec < -(NANOSECOND >> 1))
81644574Sphk		u_nsec += NANOSECOND;
81744794Sphk	pps_fcount += u_nsec;
81875540Sjhay	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
819302252Skib		goto out;
82044574Sphk	time_status &= ~STA_PPSJITTER;
82144574Sphk
82244574Sphk	/*
82344574Sphk	 * A three-stage median filter is used to help denoise the PPS
82432513Sphk	 * time. The median sample becomes the time offset estimate; the
82532513Sphk	 * difference between the other two samples becomes the time
82632513Sphk	 * dispersion (jitter) estimate.
82732513Sphk	 */
82850656Sphk	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
82950656Sphk		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
83050656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
83150656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
83250656Sphk		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
83350656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
83450656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
83544574Sphk		} else {
83650656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
83750656Sphk			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
83844574Sphk		}
83944574Sphk	} else {
84050656Sphk		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
84150656Sphk			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
84250656Sphk			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
84365673Sphk		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
84450656Sphk			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
84550656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
84644574Sphk		} else {
84750656Sphk			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
84850656Sphk			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
84944574Sphk		}
85044574Sphk	}
85132513Sphk
85232513Sphk	/*
85365673Sphk	 * Nominal jitter is due to PPS signal noise and interrupt
85465432Sphk	 * latency. If it exceeds the popcorn threshold, the sample is
85565432Sphk	 * discarded. otherwise, if so enabled, the time offset is
85665432Sphk	 * updated. We can tolerate a modest loss of data here without
85765432Sphk	 * much degrading time accuracy.
858239320Simp	 *
859239320Simp	 * The measurements being checked here were made with the system
860239320Simp	 * timecounter, so the popcorn threshold is not allowed to fall below
861239320Simp	 * the number of nanoseconds in two ticks of the timecounter.  For a
862239320Simp	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
863239320Simp	 * to avoid a nonsensical threshold of zero.
864239320Simp	*/
865302252Skib	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
866239320Simp	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
86744574Sphk		time_status |= STA_PPSJITTER;
86844574Sphk		pps_jitcnt++;
86944574Sphk	} else if (time_status & STA_PPSTIME) {
87065432Sphk		time_monitor = -v_nsec;
87165432Sphk		L_LINT(time_offset, time_monitor);
87232513Sphk	}
87344574Sphk	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
87450656Sphk	u_sec = pps_tf[0].tv_sec - pps_lastsec;
87544574Sphk	if (u_sec < (1 << pps_shift))
876302252Skib		goto out;
87744574Sphk
87832513Sphk	/*
87944574Sphk	 * At the end of the calibration interval the difference between
88044574Sphk	 * the first and last counter values becomes the scaled
88144574Sphk	 * frequency. It will later be divided by the length of the
88244574Sphk	 * interval to determine the frequency update. If the frequency
88344574Sphk	 * exceeds a sanity threshold, or if the actual calibration
88444574Sphk	 * interval is not equal to the expected length, the data are
88544574Sphk	 * discarded. We can tolerate a modest loss of data here without
88665432Sphk	 * much degrading frequency accuracy.
88732513Sphk	 */
88844574Sphk	pps_calcnt++;
88944794Sphk	v_nsec = -pps_fcount;
89050656Sphk	pps_lastsec = pps_tf[0].tv_sec;
89144794Sphk	pps_fcount = 0;
89244574Sphk	u_nsec = MAXFREQ << pps_shift;
893302252Skib	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 << pps_shift)) {
89444574Sphk		time_status |= STA_PPSERROR;
89532513Sphk		pps_errcnt++;
896302252Skib		goto out;
89732513Sphk	}
89832513Sphk
89932513Sphk	/*
90050656Sphk	 * Here the raw frequency offset and wander (stability) is
90150656Sphk	 * calculated. If the wander is less than the wander threshold
90250656Sphk	 * for four consecutive averaging intervals, the interval is
90350656Sphk	 * doubled; if it is greater than the threshold for four
90450656Sphk	 * consecutive intervals, the interval is halved. The scaled
90550656Sphk	 * frequency offset is converted to frequency offset. The
90650656Sphk	 * stability metric is calculated as the average of recent
90750656Sphk	 * frequency changes, but is used only for performance
90844574Sphk	 * monitoring.
90932513Sphk	 */
91044574Sphk	L_LINT(ftemp, v_nsec);
91144574Sphk	L_RSHIFT(ftemp, pps_shift);
91244574Sphk	L_SUB(ftemp, pps_freq);
91344574Sphk	u_nsec = L_GINT(ftemp);
91450656Sphk	if (u_nsec > PPS_MAXWANDER) {
91550656Sphk		L_LINT(ftemp, PPS_MAXWANDER);
91644574Sphk		pps_intcnt--;
91744574Sphk		time_status |= STA_PPSWANDER;
91832513Sphk		pps_stbcnt++;
91950656Sphk	} else if (u_nsec < -PPS_MAXWANDER) {
92050656Sphk		L_LINT(ftemp, -PPS_MAXWANDER);
92144574Sphk		pps_intcnt--;
92232513Sphk		time_status |= STA_PPSWANDER;
92344574Sphk		pps_stbcnt++;
92444574Sphk	} else {
92544574Sphk		pps_intcnt++;
92632513Sphk	}
92765432Sphk	if (pps_intcnt >= 4) {
92844574Sphk		pps_intcnt = 4;
92950656Sphk		if (pps_shift < pps_shiftmax) {
93044574Sphk			pps_shift++;
93144574Sphk			pps_intcnt = 0;
93232513Sphk		}
93365432Sphk	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
93444574Sphk		pps_intcnt = -4;
93544574Sphk		if (pps_shift > PPS_FAVG) {
93644574Sphk			pps_shift--;
93744574Sphk			pps_intcnt = 0;
93844574Sphk		}
93932513Sphk	}
94044574Sphk	if (u_nsec < 0)
94144574Sphk		u_nsec = -u_nsec;
94244574Sphk	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
94332513Sphk
94432513Sphk	/*
94550656Sphk	 * The PPS frequency is recalculated and clamped to the maximum
94650656Sphk	 * MAXFREQ. If enabled, the system clock frequency is updated as
94750656Sphk	 * well.
94832513Sphk	 */
94944574Sphk	L_ADD(pps_freq, ftemp);
95044574Sphk	u_nsec = L_GINT(pps_freq);
95144574Sphk	if (u_nsec > MAXFREQ)
95244574Sphk		L_LINT(pps_freq, MAXFREQ);
95344574Sphk	else if (u_nsec < -MAXFREQ)
95444574Sphk		L_LINT(pps_freq, -MAXFREQ);
95565432Sphk	if (time_status & STA_PPSFREQ)
95644574Sphk		time_freq = pps_freq;
957302252Skib
958302252Skibout:
959302252Skib	NTPADJ_UNLOCK();
96032513Sphk}
96132513Sphk#endif /* PPS_SYNC */
96294754Sphk
96394754Sphk#ifndef _SYS_SYSPROTO_H_
96494754Sphkstruct adjtime_args {
96594754Sphk	struct timeval *delta;
96694754Sphk	struct timeval *olddelta;
96794754Sphk};
96894754Sphk#endif
96994754Sphk/* ARGSUSED */
97094754Sphkint
971225617Skmacysys_adjtime(struct thread *td, struct adjtime_args *uap)
97294754Sphk{
973144445Sjhb	struct timeval delta, olddelta, *deltap;
974144445Sjhb	int error;
975144445Sjhb
976144445Sjhb	if (uap->delta) {
977144445Sjhb		error = copyin(uap->delta, &delta, sizeof(delta));
978144445Sjhb		if (error)
979144445Sjhb			return (error);
980144445Sjhb		deltap = &delta;
981144445Sjhb	} else
982144445Sjhb		deltap = NULL;
983144445Sjhb	error = kern_adjtime(td, deltap, &olddelta);
984144445Sjhb	if (uap->olddelta && error == 0)
985144445Sjhb		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
986144445Sjhb	return (error);
987144445Sjhb}
988144445Sjhb
989144445Sjhbint
990144445Sjhbkern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
991144445Sjhb{
99294754Sphk	struct timeval atv;
993302252Skib	int64_t ltr, ltw;
99494754Sphk	int error;
99594754Sphk
996302252Skib	if (delta != NULL) {
997302252Skib		error = priv_check(td, PRIV_ADJTIME);
998302252Skib		if (error != 0)
999302252Skib			return (error);
1000302252Skib		ltw = (int64_t)delta->tv_sec * 1000000 + delta->tv_usec;
1001302252Skib	}
1002302252Skib	NTPADJ_LOCK();
1003302252Skib	ltr = time_adjtime;
1004302252Skib	if (delta != NULL)
1005302252Skib		time_adjtime = ltw;
1006302252Skib	NTPADJ_UNLOCK();
1007302252Skib	if (olddelta != NULL) {
1008302252Skib		atv.tv_sec = ltr / 1000000;
1009302252Skib		atv.tv_usec = ltr % 1000000;
101094754Sphk		if (atv.tv_usec < 0) {
101194754Sphk			atv.tv_usec += 1000000;
101294754Sphk			atv.tv_sec--;
101394754Sphk		}
1014144445Sjhb		*olddelta = atv;
101594754Sphk	}
1016170732Srwatson	return (0);
101794754Sphk}
101894754Sphk
1019207360Savgstatic struct callout resettodr_callout;
1020207360Savgstatic int resettodr_period = 1800;
1021207360Savg
1022207360Savgstatic void
1023207360Savgperiodic_resettodr(void *arg __unused)
1024207360Savg{
1025207360Savg
1026302252Skib	/*
1027302252Skib	 * Read of time_status is lock-less, which is fine since
1028302252Skib	 * ntp_is_time_error() operates on the consistent read value.
1029302252Skib	 */
1030302252Skib	if (!ntp_is_time_error(time_status))
1031207360Savg		resettodr();
1032207360Savg	if (resettodr_period > 0)
1033207360Savg		callout_schedule(&resettodr_callout, resettodr_period * hz);
1034207360Savg}
1035207360Savg
1036207360Savgstatic void
1037207360Savgshutdown_resettodr(void *arg __unused, int howto __unused)
1038207360Savg{
1039207360Savg
1040207360Savg	callout_drain(&resettodr_callout);
1041302252Skib	/* Another unlocked read of time_status */
1042302252Skib	if (resettodr_period > 0 && !ntp_is_time_error(time_status))
1043207360Savg		resettodr();
1044207360Savg}
1045207360Savg
1046207360Savgstatic int
1047207360Savgsysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
1048207360Savg{
1049207360Savg	int error;
1050207360Savg
1051207360Savg	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1052207360Savg	if (error || !req->newptr)
1053207360Savg		return (error);
1054267992Shselasky	if (cold)
1055267992Shselasky		goto done;
1056207360Savg	if (resettodr_period == 0)
1057207360Savg		callout_stop(&resettodr_callout);
1058207360Savg	else
1059207360Savg		callout_reset(&resettodr_callout, resettodr_period * hz,
1060207360Savg		    periodic_resettodr, NULL);
1061267992Shselaskydone:
1062207360Savg	return (0);
1063207360Savg}
1064207360Savg
1065302252SkibSYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT | CTLFLAG_RWTUN |
1066302252Skib    CTLFLAG_MPSAFE, &resettodr_period, 1800, sysctl_resettodr_period, "I",
1067302252Skib    "Save system time to RTC with this period (in seconds)");
1068207360Savg
1069207360Savgstatic void
1070207360Savgstart_periodic_resettodr(void *arg __unused)
1071207360Savg{
1072207360Savg
1073207360Savg	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
1074207360Savg	    SHUTDOWN_PRI_FIRST);
1075207360Savg	callout_init(&resettodr_callout, 1);
1076207360Savg	if (resettodr_period == 0)
1077207360Savg		return;
1078207360Savg	callout_reset(&resettodr_callout, resettodr_period * hz,
1079207360Savg	    periodic_resettodr, NULL);
1080207360Savg}
1081207360Savg
1082253604SavgSYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
1083207360Savg	start_periodic_resettodr, NULL);
1084