xref: /freebsd/sys/kern/kern_ntptime.c (revision f27ac8e297becff0ce9f8d18535b270b2d16df7e)
19454b2d8SWarner Losh /*-
29454b2d8SWarner Losh  ***********************************************************************
33f31c649SGarrett Wollman  *								       *
424dbea46SJohn Hay  * Copyright (c) David L. Mills 1993-2001			       *
53f31c649SGarrett Wollman  *								       *
6c68996e2SPoul-Henning Kamp  * Permission to use, copy, modify, and distribute this software and   *
7c68996e2SPoul-Henning Kamp  * its documentation for any purpose and without fee is hereby	       *
8c68996e2SPoul-Henning Kamp  * granted, provided that the above copyright notice appears in all    *
9c68996e2SPoul-Henning Kamp  * copies and that both the copyright notice and this permission       *
10c68996e2SPoul-Henning Kamp  * notice appear in supporting documentation, and that the name	       *
11c68996e2SPoul-Henning Kamp  * University of Delaware not be used in advertising or publicity      *
12c68996e2SPoul-Henning Kamp  * pertaining to distribution of the software without specific,	       *
13c68996e2SPoul-Henning Kamp  * written prior permission. The University of Delaware makes no       *
14c68996e2SPoul-Henning Kamp  * representations about the suitability this software for any	       *
15c68996e2SPoul-Henning Kamp  * purpose. It is provided "as is" without express or implied	       *
16c68996e2SPoul-Henning Kamp  * warranty.							       *
173f31c649SGarrett Wollman  *								       *
18c68996e2SPoul-Henning Kamp  **********************************************************************/
193f31c649SGarrett Wollman 
203f31c649SGarrett Wollman /*
21c68996e2SPoul-Henning Kamp  * Adapted from the original sources for FreeBSD and timecounters by:
2232c20357SPoul-Henning Kamp  * Poul-Henning Kamp <phk@FreeBSD.org>.
233f31c649SGarrett Wollman  *
24c68996e2SPoul-Henning Kamp  * The 32bit version of the "LP" macros seems a bit past its "sell by"
25c68996e2SPoul-Henning Kamp  * date so I have retained only the 64bit version and included it directly
26c68996e2SPoul-Henning Kamp  * in this file.
27885bd8e4SJohn Hay  *
28c68996e2SPoul-Henning Kamp  * Only minor changes done to interface with the timecounters over in
29c68996e2SPoul-Henning Kamp  * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
30c68996e2SPoul-Henning Kamp  * confusing and/or plain wrong in that context.
313f31c649SGarrett Wollman  */
32e0d781f3SEivind Eklund 
33677b542eSDavid E. O'Brien #include <sys/cdefs.h>
34677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
35677b542eSDavid E. O'Brien 
3632c20357SPoul-Henning Kamp #include "opt_ntp.h"
3732c20357SPoul-Henning Kamp 
383f31c649SGarrett Wollman #include <sys/param.h>
393f31c649SGarrett Wollman #include <sys/systm.h>
40d2d3e875SBruce Evans #include <sys/sysproto.h>
415c7e270fSAndriy Gapon #include <sys/eventhandler.h>
423f31c649SGarrett Wollman #include <sys/kernel.h>
43acd3428bSRobert Watson #include <sys/priv.h>
443f31c649SGarrett Wollman #include <sys/proc.h>
456f1e8c18SMatthew Dillon #include <sys/lock.h>
466f1e8c18SMatthew Dillon #include <sys/mutex.h>
47c68996e2SPoul-Henning Kamp #include <sys/time.h>
483f31c649SGarrett Wollman #include <sys/timex.h>
4991266b96SPoul-Henning Kamp #include <sys/timetc.h>
50938ee3ceSPoul-Henning Kamp #include <sys/timepps.h>
51b88ec951SJohn Baldwin #include <sys/syscallsubr.h>
523f31c649SGarrett Wollman #include <sys/sysctl.h>
533f31c649SGarrett Wollman 
54de5b1952SAlexander Leidinger #ifdef PPS_SYNC
55de5b1952SAlexander Leidinger FEATURE(pps_sync, "Support usage of external PPS signal by kernel PLL");
56de5b1952SAlexander Leidinger #endif
57de5b1952SAlexander Leidinger 
583f31c649SGarrett Wollman /*
59c68996e2SPoul-Henning Kamp  * Single-precision macros for 64-bit machines
603f31c649SGarrett Wollman  */
61bcfe6d8bSPoul-Henning Kamp typedef int64_t l_fp;
62c68996e2SPoul-Henning Kamp #define L_ADD(v, u)	((v) += (u))
63c68996e2SPoul-Henning Kamp #define L_SUB(v, u)	((v) -= (u))
64bcfe6d8bSPoul-Henning Kamp #define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
65c68996e2SPoul-Henning Kamp #define L_NEG(v)	((v) = -(v))
66c68996e2SPoul-Henning Kamp #define L_RSHIFT(v, n) \
67c68996e2SPoul-Henning Kamp 	do { \
68c68996e2SPoul-Henning Kamp 		if ((v) < 0) \
69c68996e2SPoul-Henning Kamp 			(v) = -(-(v) >> (n)); \
70c68996e2SPoul-Henning Kamp 		else \
71c68996e2SPoul-Henning Kamp 			(v) = (v) >> (n); \
72c68996e2SPoul-Henning Kamp 	} while (0)
73c68996e2SPoul-Henning Kamp #define L_MPY(v, a)	((v) *= (a))
74c68996e2SPoul-Henning Kamp #define L_CLR(v)	((v) = 0)
75c68996e2SPoul-Henning Kamp #define L_ISNEG(v)	((v) < 0)
76bcfe6d8bSPoul-Henning Kamp #define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
77c68996e2SPoul-Henning Kamp #define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
786f70df15SPoul-Henning Kamp 
796f70df15SPoul-Henning Kamp /*
80c68996e2SPoul-Henning Kamp  * Generic NTP kernel interface
816f70df15SPoul-Henning Kamp  *
82c68996e2SPoul-Henning Kamp  * These routines constitute the Network Time Protocol (NTP) interfaces
83c68996e2SPoul-Henning Kamp  * for user and daemon application programs. The ntp_gettime() routine
84c68996e2SPoul-Henning Kamp  * provides the time, maximum error (synch distance) and estimated error
85c68996e2SPoul-Henning Kamp  * (dispersion) to client user application programs. The ntp_adjtime()
86c68996e2SPoul-Henning Kamp  * routine is used by the NTP daemon to adjust the system clock to an
87c68996e2SPoul-Henning Kamp  * externally derived time. The time offset and related variables set by
88c68996e2SPoul-Henning Kamp  * this routine are used by other routines in this module to adjust the
89c68996e2SPoul-Henning Kamp  * phase and frequency of the clock discipline loop which controls the
90c68996e2SPoul-Henning Kamp  * system clock.
916f70df15SPoul-Henning Kamp  *
92f425c1f6SPoul-Henning Kamp  * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
93c68996e2SPoul-Henning Kamp  * defined), the time at each tick interrupt is derived directly from
94c68996e2SPoul-Henning Kamp  * the kernel time variable. When the kernel time is reckoned in
95f425c1f6SPoul-Henning Kamp  * microseconds, (NTP_NANO undefined), the time is derived from the
96f425c1f6SPoul-Henning Kamp  * kernel time variable together with a variable representing the
97f425c1f6SPoul-Henning Kamp  * leftover nanoseconds at the last tick interrupt. In either case, the
98f425c1f6SPoul-Henning Kamp  * current nanosecond time is reckoned from these values plus an
99f425c1f6SPoul-Henning Kamp  * interpolated value derived by the clock routines in another
100f425c1f6SPoul-Henning Kamp  * architecture-specific module. The interpolation can use either a
101f425c1f6SPoul-Henning Kamp  * dedicated counter or a processor cycle counter (PCC) implemented in
102f425c1f6SPoul-Henning Kamp  * some architectures.
1036f70df15SPoul-Henning Kamp  *
104c68996e2SPoul-Henning Kamp  * Note that all routines must run at priority splclock or higher.
1056f70df15SPoul-Henning Kamp  */
106c68996e2SPoul-Henning Kamp /*
107c68996e2SPoul-Henning Kamp  * Phase/frequency-lock loop (PLL/FLL) definitions
108c68996e2SPoul-Henning Kamp  *
109c68996e2SPoul-Henning Kamp  * The nanosecond clock discipline uses two variable types, time
110c68996e2SPoul-Henning Kamp  * variables and frequency variables. Both types are represented as 64-
111c68996e2SPoul-Henning Kamp  * bit fixed-point quantities with the decimal point between two 32-bit
112c68996e2SPoul-Henning Kamp  * halves. On a 32-bit machine, each half is represented as a single
113c68996e2SPoul-Henning Kamp  * word and mathematical operations are done using multiple-precision
114c68996e2SPoul-Henning Kamp  * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
115c68996e2SPoul-Henning Kamp  * used.
116c68996e2SPoul-Henning Kamp  *
117c68996e2SPoul-Henning Kamp  * A time variable is a signed 64-bit fixed-point number in ns and
118c68996e2SPoul-Henning Kamp  * fraction. It represents the remaining time offset to be amortized
119c68996e2SPoul-Henning Kamp  * over succeeding tick interrupts. The maximum time offset is about
120f425c1f6SPoul-Henning Kamp  * 0.5 s and the resolution is about 2.3e-10 ns.
121c68996e2SPoul-Henning Kamp  *
122c68996e2SPoul-Henning Kamp  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
123c68996e2SPoul-Henning Kamp  *  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
124c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
125c68996e2SPoul-Henning Kamp  * |s s s|			 ns				   |
126c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
127c68996e2SPoul-Henning Kamp  * |			    fraction				   |
128c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129c68996e2SPoul-Henning Kamp  *
130c68996e2SPoul-Henning Kamp  * A frequency variable is a signed 64-bit fixed-point number in ns/s
131c68996e2SPoul-Henning Kamp  * and fraction. It represents the ns and fraction to be added to the
132c68996e2SPoul-Henning Kamp  * kernel time variable at each second. The maximum frequency offset is
133f425c1f6SPoul-Henning Kamp  * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
134c68996e2SPoul-Henning Kamp  *
135c68996e2SPoul-Henning Kamp  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
136c68996e2SPoul-Henning Kamp  *  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
137c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
138c68996e2SPoul-Henning Kamp  * |s s s s s s s s s s s s s|	          ns/s			   |
139c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
140c68996e2SPoul-Henning Kamp  * |			    fraction				   |
141c68996e2SPoul-Henning Kamp  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
142c68996e2SPoul-Henning Kamp  */
143c68996e2SPoul-Henning Kamp /*
144c68996e2SPoul-Henning Kamp  * The following variables establish the state of the PLL/FLL and the
145c68996e2SPoul-Henning Kamp  * residual time and frequency offset of the local clock.
146c68996e2SPoul-Henning Kamp  */
147c68996e2SPoul-Henning Kamp #define SHIFT_PLL	4		/* PLL loop gain (shift) */
148c68996e2SPoul-Henning Kamp #define SHIFT_FLL	2		/* FLL loop gain (shift) */
149c68996e2SPoul-Henning Kamp 
150c68996e2SPoul-Henning Kamp static int time_state = TIME_OK;	/* clock state */
1516cedd609SLawrence Stewart int time_status = STA_UNSYNC;	/* clock status bits */
15297804a5cSPoul-Henning Kamp static long time_tai;			/* TAI offset (s) */
15397804a5cSPoul-Henning Kamp static long time_monitor;		/* last time offset scaled (ns) */
154c68996e2SPoul-Henning Kamp static long time_constant;		/* poll interval (shift) (s) */
155c68996e2SPoul-Henning Kamp static long time_precision = 1;		/* clock precision (ns) */
156c68996e2SPoul-Henning Kamp static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
1576cedd609SLawrence Stewart long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
158969fc29eSIan Lepore static long time_reftime;		/* uptime at last adjustment (s) */
159c68996e2SPoul-Henning Kamp static l_fp time_offset;		/* time offset (ns) */
160c68996e2SPoul-Henning Kamp static l_fp time_freq;			/* frequency offset (ns/s) */
16197804a5cSPoul-Henning Kamp static l_fp time_adj;			/* tick adjust (ns/s) */
1623f31c649SGarrett Wollman 
163e1d970f1SPoul-Henning Kamp static int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
164e1d970f1SPoul-Henning Kamp 
1654493f659SKonstantin Belousov static struct mtx ntp_lock;
1664493f659SKonstantin Belousov MTX_SYSINIT(ntp, &ntp_lock, "ntp", MTX_SPIN);
167364c516cSKonstantin Belousov 
1684493f659SKonstantin Belousov #define	NTP_LOCK()		mtx_lock_spin(&ntp_lock)
1694493f659SKonstantin Belousov #define	NTP_UNLOCK()		mtx_unlock_spin(&ntp_lock)
1704493f659SKonstantin Belousov #define	NTP_ASSERT_LOCKED()	mtx_assert(&ntp_lock, MA_OWNED)
171364c516cSKonstantin Belousov 
1723f31c649SGarrett Wollman #ifdef PPS_SYNC
1733f31c649SGarrett Wollman /*
174c68996e2SPoul-Henning Kamp  * The following variables are used when a pulse-per-second (PPS) signal
175c68996e2SPoul-Henning Kamp  * is available and connected via a modem control lead. They establish
176c68996e2SPoul-Henning Kamp  * the engineering parameters of the clock discipline loop when
177c68996e2SPoul-Henning Kamp  * controlled by the PPS signal.
1783f31c649SGarrett Wollman  */
179c68996e2SPoul-Henning Kamp #define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
18024dbea46SJohn Hay #define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
18182e84c5bSPoul-Henning Kamp #define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
182c68996e2SPoul-Henning Kamp #define PPS_PAVG	4		/* phase avg interval (s) (shift) */
183c68996e2SPoul-Henning Kamp #define PPS_VALID	120		/* PPS signal watchdog max (s) */
18482e84c5bSPoul-Henning Kamp #define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
18582e84c5bSPoul-Henning Kamp #define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
186c68996e2SPoul-Henning Kamp 
18782e84c5bSPoul-Henning Kamp static struct timespec pps_tf[3];	/* phase median filter */
188c68996e2SPoul-Henning Kamp static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
189f425c1f6SPoul-Henning Kamp static long pps_fcount;			/* frequency accumulator */
19082e84c5bSPoul-Henning Kamp static long pps_jitter;			/* nominal jitter (ns) */
19182e84c5bSPoul-Henning Kamp static long pps_stabil;			/* nominal stability (scaled ns/s) */
192c68996e2SPoul-Henning Kamp static long pps_lastsec;		/* time at last calibration (s) */
193c68996e2SPoul-Henning Kamp static int pps_valid;			/* signal watchdog counter */
194c68996e2SPoul-Henning Kamp static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
19582e84c5bSPoul-Henning Kamp static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
196c68996e2SPoul-Henning Kamp static int pps_intcnt;			/* wander counter */
1976f70df15SPoul-Henning Kamp 
1986f70df15SPoul-Henning Kamp /*
1996f70df15SPoul-Henning Kamp  * PPS signal quality monitors
2006f70df15SPoul-Henning Kamp  */
201c68996e2SPoul-Henning Kamp static long pps_calcnt;			/* calibration intervals */
202c68996e2SPoul-Henning Kamp static long pps_jitcnt;			/* jitter limit exceeded */
203c68996e2SPoul-Henning Kamp static long pps_stbcnt;			/* stability limit exceeded */
204c68996e2SPoul-Henning Kamp static long pps_errcnt;			/* calibration errors */
2053f31c649SGarrett Wollman #endif /* PPS_SYNC */
206c68996e2SPoul-Henning Kamp /*
207c68996e2SPoul-Henning Kamp  * End of phase/frequency-lock loop (PLL/FLL) definitions
208c68996e2SPoul-Henning Kamp  */
2093f31c649SGarrett Wollman 
210c68996e2SPoul-Henning Kamp static void ntp_init(void);
211c68996e2SPoul-Henning Kamp static void hardupdate(long offset);
212932cfd41SMark Santcroos static void ntp_gettime1(struct ntptimeval *ntvp);
213364c516cSKonstantin Belousov static bool ntp_is_time_error(int tsl);
214c68996e2SPoul-Henning Kamp 
215364c516cSKonstantin Belousov static bool
216364c516cSKonstantin Belousov ntp_is_time_error(int tsl)
217c68996e2SPoul-Henning Kamp {
218364c516cSKonstantin Belousov 
219c68996e2SPoul-Henning Kamp 	/*
220c68996e2SPoul-Henning Kamp 	 * Status word error decode. If any of these conditions occur,
221c68996e2SPoul-Henning Kamp 	 * an error is returned, instead of the status word. Most
222c68996e2SPoul-Henning Kamp 	 * applications will care only about the fact the system clock
223c68996e2SPoul-Henning Kamp 	 * may not be trusted, not about the details.
224c68996e2SPoul-Henning Kamp 	 *
225c68996e2SPoul-Henning Kamp 	 * Hardware or software error
226c68996e2SPoul-Henning Kamp 	 */
227364c516cSKonstantin Belousov 	if ((tsl & (STA_UNSYNC | STA_CLOCKERR)) ||
228c68996e2SPoul-Henning Kamp 
229c68996e2SPoul-Henning Kamp 	/*
230c68996e2SPoul-Henning Kamp 	 * PPS signal lost when either time or frequency synchronization
231c68996e2SPoul-Henning Kamp 	 * requested
232c68996e2SPoul-Henning Kamp 	 */
233364c516cSKonstantin Belousov 	    (tsl & (STA_PPSFREQ | STA_PPSTIME) &&
234364c516cSKonstantin Belousov 	    !(tsl & STA_PPSSIGNAL)) ||
235c68996e2SPoul-Henning Kamp 
236c68996e2SPoul-Henning Kamp 	/*
237c68996e2SPoul-Henning Kamp 	 * PPS jitter exceeded when time synchronization requested
238c68996e2SPoul-Henning Kamp 	 */
239364c516cSKonstantin Belousov 	    (tsl & STA_PPSTIME && tsl & STA_PPSJITTER) ||
240c68996e2SPoul-Henning Kamp 
241c68996e2SPoul-Henning Kamp 	/*
242c68996e2SPoul-Henning Kamp 	 * PPS wander exceeded or calibration error when frequency
243c68996e2SPoul-Henning Kamp 	 * synchronization requested
244c68996e2SPoul-Henning Kamp 	 */
245364c516cSKonstantin Belousov 	    (tsl & STA_PPSFREQ &&
246364c516cSKonstantin Belousov 	    tsl & (STA_PPSWANDER | STA_PPSERROR)))
247364c516cSKonstantin Belousov 		return (true);
2489a9ae42aSAndriy Gapon 
249364c516cSKonstantin Belousov 	return (false);
2509a9ae42aSAndriy Gapon }
2519a9ae42aSAndriy Gapon 
2529a9ae42aSAndriy Gapon static void
2539a9ae42aSAndriy Gapon ntp_gettime1(struct ntptimeval *ntvp)
2549a9ae42aSAndriy Gapon {
2559a9ae42aSAndriy Gapon 	struct timespec atv;	/* nanosecond time */
2569a9ae42aSAndriy Gapon 
2574493f659SKonstantin Belousov 	NTP_ASSERT_LOCKED();
2589a9ae42aSAndriy Gapon 
2599a9ae42aSAndriy Gapon 	nanotime(&atv);
2609a9ae42aSAndriy Gapon 	ntvp->time.tv_sec = atv.tv_sec;
2619a9ae42aSAndriy Gapon 	ntvp->time.tv_nsec = atv.tv_nsec;
2629a9ae42aSAndriy Gapon 	ntvp->maxerror = time_maxerror;
2639a9ae42aSAndriy Gapon 	ntvp->esterror = time_esterror;
2649a9ae42aSAndriy Gapon 	ntvp->tai = time_tai;
2659a9ae42aSAndriy Gapon 	ntvp->time_state = time_state;
2669a9ae42aSAndriy Gapon 
267364c516cSKonstantin Belousov 	if (ntp_is_time_error(time_status))
268932cfd41SMark Santcroos 		ntvp->time_state = TIME_ERROR;
269932cfd41SMark Santcroos }
270932cfd41SMark Santcroos 
2719b7fe7e4SMark Santcroos /*
2729b7fe7e4SMark Santcroos  * ntp_gettime() - NTP user application interface
2739b7fe7e4SMark Santcroos  *
274873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
275873fbcd7SRobert Watson  * the TAI offset is returned in the ntvtimeval.tai structure member.
2769b7fe7e4SMark Santcroos  */
277932cfd41SMark Santcroos #ifndef _SYS_SYSPROTO_H_
278932cfd41SMark Santcroos struct ntp_gettime_args {
279932cfd41SMark Santcroos 	struct ntptimeval *ntvp;
280932cfd41SMark Santcroos };
281932cfd41SMark Santcroos #endif
282932cfd41SMark Santcroos /* ARGSUSED */
283932cfd41SMark Santcroos int
2848451d0ddSKip Macy sys_ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
285932cfd41SMark Santcroos {
286932cfd41SMark Santcroos 	struct ntptimeval ntv;
287932cfd41SMark Santcroos 
2884493f659SKonstantin Belousov 	NTP_LOCK();
289932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
2904493f659SKonstantin Belousov 	NTP_UNLOCK();
291932cfd41SMark Santcroos 
292fe18f385SWarner Losh 	td->td_retval[0] = ntv.time_state;
293932cfd41SMark Santcroos 	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
294932cfd41SMark Santcroos }
295932cfd41SMark Santcroos 
296932cfd41SMark Santcroos static int
297932cfd41SMark Santcroos ntp_sysctl(SYSCTL_HANDLER_ARGS)
298932cfd41SMark Santcroos {
299932cfd41SMark Santcroos 	struct ntptimeval ntv;	/* temporary structure */
300932cfd41SMark Santcroos 
3014493f659SKonstantin Belousov 	NTP_LOCK();
302932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
3034493f659SKonstantin Belousov 	NTP_UNLOCK();
304932cfd41SMark Santcroos 
305932cfd41SMark Santcroos 	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
306c68996e2SPoul-Henning Kamp }
307c68996e2SPoul-Henning Kamp 
308c68996e2SPoul-Henning Kamp SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
309364c516cSKonstantin Belousov SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE | CTLFLAG_RD |
310364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval",
311364c516cSKonstantin Belousov     "");
312c68996e2SPoul-Henning Kamp 
3135968e18bSPoul-Henning Kamp #ifdef PPS_SYNC
3143eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
3153eb9ab52SEitan Adler     &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
3163eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
3173eb9ab52SEitan Adler     &pps_shift, 0, "Interval duration (sec) (shift)");
318240577c2SMatthew D Fleming SYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
3193eb9ab52SEitan Adler     &time_monitor, 0, "Last time offset scaled (ns)");
3207fd299cbSPoul-Henning Kamp 
321364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
322364c516cSKonstantin Belousov     &pps_freq, 0,
323364c516cSKonstantin Belousov     "Scaled frequency offset (ns/sec)");
324364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
325364c516cSKonstantin Belousov     &time_freq, 0,
326364c516cSKonstantin Belousov     "Frequency offset (ns/sec)");
3275968e18bSPoul-Henning Kamp #endif
328873fbcd7SRobert Watson 
329c68996e2SPoul-Henning Kamp /*
330c68996e2SPoul-Henning Kamp  * ntp_adjtime() - NTP daemon application interface
331c68996e2SPoul-Henning Kamp  *
332873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
333873fbcd7SRobert Watson  * the timex.constant structure member has a dual purpose to set the time
334873fbcd7SRobert Watson  * constant and to set the TAI offset.
335c68996e2SPoul-Henning Kamp  */
336c68996e2SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
337c68996e2SPoul-Henning Kamp struct ntp_adjtime_args {
338c68996e2SPoul-Henning Kamp 	struct timex *tp;
339c68996e2SPoul-Henning Kamp };
340c68996e2SPoul-Henning Kamp #endif
341c68996e2SPoul-Henning Kamp 
342c68996e2SPoul-Henning Kamp int
3438451d0ddSKip Macy sys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
344c68996e2SPoul-Henning Kamp {
345c68996e2SPoul-Henning Kamp 	struct timex ntv;	/* temporary structure */
346f425c1f6SPoul-Henning Kamp 	long freq;		/* frequency ns/s) */
347c68996e2SPoul-Henning Kamp 	int modes;		/* mode bits from structure */
348364c516cSKonstantin Belousov 	int error, retval;
349c68996e2SPoul-Henning Kamp 
350c68996e2SPoul-Henning Kamp 	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
351c68996e2SPoul-Henning Kamp 	if (error)
352c68996e2SPoul-Henning Kamp 		return (error);
353c68996e2SPoul-Henning Kamp 
354c68996e2SPoul-Henning Kamp 	/*
355c68996e2SPoul-Henning Kamp 	 * Update selected clock variables - only the superuser can
356c68996e2SPoul-Henning Kamp 	 * change anything. Note that there is no error checking here on
357c68996e2SPoul-Henning Kamp 	 * the assumption the superuser should know what it is doing.
35897804a5cSPoul-Henning Kamp 	 * Note that either the time constant or TAI offset are loaded
35924dbea46SJohn Hay 	 * from the ntv.constant member, depending on the mode bits. If
36024dbea46SJohn Hay 	 * the STA_PLL bit in the status word is cleared, the state and
36124dbea46SJohn Hay 	 * status words are reset to the initial values at boot.
362c68996e2SPoul-Henning Kamp 	 */
363c68996e2SPoul-Henning Kamp 	modes = ntv.modes;
364fafbe352SPoul-Henning Kamp 	if (modes)
365acd3428bSRobert Watson 		error = priv_check(td, PRIV_NTP_ADJTIME);
366364c516cSKonstantin Belousov 	if (error != 0)
367364c516cSKonstantin Belousov 		return (error);
3684493f659SKonstantin Belousov 	NTP_LOCK();
369c68996e2SPoul-Henning Kamp 	if (modes & MOD_MAXERROR)
370c68996e2SPoul-Henning Kamp 		time_maxerror = ntv.maxerror;
371c68996e2SPoul-Henning Kamp 	if (modes & MOD_ESTERROR)
372c68996e2SPoul-Henning Kamp 		time_esterror = ntv.esterror;
373c68996e2SPoul-Henning Kamp 	if (modes & MOD_STATUS) {
37424dbea46SJohn Hay 		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
37524dbea46SJohn Hay 			time_state = TIME_OK;
37624dbea46SJohn Hay 			time_status = STA_UNSYNC;
37724dbea46SJohn Hay #ifdef PPS_SYNC
37824dbea46SJohn Hay 			pps_shift = PPS_FAVG;
37924dbea46SJohn Hay #endif /* PPS_SYNC */
38024dbea46SJohn Hay 		}
381c68996e2SPoul-Henning Kamp 		time_status &= STA_RONLY;
382c68996e2SPoul-Henning Kamp 		time_status |= ntv.status & ~STA_RONLY;
383c68996e2SPoul-Henning Kamp 	}
384f425c1f6SPoul-Henning Kamp 	if (modes & MOD_TIMECONST) {
385f425c1f6SPoul-Henning Kamp 		if (ntv.constant < 0)
386f425c1f6SPoul-Henning Kamp 			time_constant = 0;
387f425c1f6SPoul-Henning Kamp 		else if (ntv.constant > MAXTC)
388f425c1f6SPoul-Henning Kamp 			time_constant = MAXTC;
389f425c1f6SPoul-Henning Kamp 		else
390c68996e2SPoul-Henning Kamp 			time_constant = ntv.constant;
391f425c1f6SPoul-Henning Kamp 	}
39297804a5cSPoul-Henning Kamp 	if (modes & MOD_TAI) {
39397804a5cSPoul-Henning Kamp 		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
39497804a5cSPoul-Henning Kamp 			time_tai = ntv.constant;
39597804a5cSPoul-Henning Kamp 	}
39682e84c5bSPoul-Henning Kamp #ifdef PPS_SYNC
39782e84c5bSPoul-Henning Kamp 	if (modes & MOD_PPSMAX) {
39882e84c5bSPoul-Henning Kamp 		if (ntv.shift < PPS_FAVG)
39982e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVG;
40082e84c5bSPoul-Henning Kamp 		else if (ntv.shift > PPS_FAVGMAX)
40182e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVGMAX;
40282e84c5bSPoul-Henning Kamp 		else
40382e84c5bSPoul-Henning Kamp 			pps_shiftmax = ntv.shift;
40482e84c5bSPoul-Henning Kamp 	}
40582e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
406c68996e2SPoul-Henning Kamp 	if (modes & MOD_NANO)
407c68996e2SPoul-Henning Kamp 		time_status |= STA_NANO;
408c68996e2SPoul-Henning Kamp 	if (modes & MOD_MICRO)
409c68996e2SPoul-Henning Kamp 		time_status &= ~STA_NANO;
410c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKB)
411c68996e2SPoul-Henning Kamp 		time_status |= STA_CLK;
412c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKA)
413c68996e2SPoul-Henning Kamp 		time_status &= ~STA_CLK;
41424dbea46SJohn Hay 	if (modes & MOD_FREQUENCY) {
41524dbea46SJohn Hay 		freq = (ntv.freq * 1000LL) >> 16;
41624dbea46SJohn Hay 		if (freq > MAXFREQ)
41724dbea46SJohn Hay 			L_LINT(time_freq, MAXFREQ);
41824dbea46SJohn Hay 		else if (freq < -MAXFREQ)
41924dbea46SJohn Hay 			L_LINT(time_freq, -MAXFREQ);
420bcfe6d8bSPoul-Henning Kamp 		else {
421bcfe6d8bSPoul-Henning Kamp 			/*
422bcfe6d8bSPoul-Henning Kamp 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
423bcfe6d8bSPoul-Henning Kamp 			 * time_freq is [ns/s * 2^32]
424bcfe6d8bSPoul-Henning Kamp 			 */
425bcfe6d8bSPoul-Henning Kamp 			time_freq = ntv.freq * 1000LL * 65536LL;
426bcfe6d8bSPoul-Henning Kamp 		}
42724dbea46SJohn Hay #ifdef PPS_SYNC
42824dbea46SJohn Hay 		pps_freq = time_freq;
42924dbea46SJohn Hay #endif /* PPS_SYNC */
43024dbea46SJohn Hay 	}
431551260fcSPoul-Henning Kamp 	if (modes & MOD_OFFSET) {
432551260fcSPoul-Henning Kamp 		if (time_status & STA_NANO)
433551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset);
434551260fcSPoul-Henning Kamp 		else
435551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset * 1000);
436551260fcSPoul-Henning Kamp 	}
437c68996e2SPoul-Henning Kamp 
438c68996e2SPoul-Henning Kamp 	/*
43997804a5cSPoul-Henning Kamp 	 * Retrieve all clock variables. Note that the TAI offset is
44097804a5cSPoul-Henning Kamp 	 * returned only by ntp_gettime();
441c68996e2SPoul-Henning Kamp 	 */
442c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
443b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset);
444c68996e2SPoul-Henning Kamp 	else
445b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
44634cffbe3SPoul-Henning Kamp 	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
447c68996e2SPoul-Henning Kamp 	ntv.maxerror = time_maxerror;
448c68996e2SPoul-Henning Kamp 	ntv.esterror = time_esterror;
449c68996e2SPoul-Henning Kamp 	ntv.status = time_status;
450f425c1f6SPoul-Henning Kamp 	ntv.constant = time_constant;
451c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
452c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision;
453c68996e2SPoul-Henning Kamp 	else
454c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision / 1000;
455c68996e2SPoul-Henning Kamp 	ntv.tolerance = MAXFREQ * SCALE_PPM;
456c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
457c68996e2SPoul-Henning Kamp 	ntv.shift = pps_shift;
45834cffbe3SPoul-Henning Kamp 	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
459c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
460c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter;
461c68996e2SPoul-Henning Kamp 	else
462c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter / 1000;
463c68996e2SPoul-Henning Kamp 	ntv.stabil = pps_stabil;
464c68996e2SPoul-Henning Kamp 	ntv.calcnt = pps_calcnt;
465c68996e2SPoul-Henning Kamp 	ntv.errcnt = pps_errcnt;
466c68996e2SPoul-Henning Kamp 	ntv.jitcnt = pps_jitcnt;
467c68996e2SPoul-Henning Kamp 	ntv.stbcnt = pps_stbcnt;
468c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
469364c516cSKonstantin Belousov 	retval = ntp_is_time_error(time_status) ? TIME_ERROR : time_state;
4704493f659SKonstantin Belousov 	NTP_UNLOCK();
471c68996e2SPoul-Henning Kamp 
472c68996e2SPoul-Henning Kamp 	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
473364c516cSKonstantin Belousov 	if (error == 0)
474364c516cSKonstantin Belousov 		td->td_retval[0] = retval;
475a5088017SPoul-Henning Kamp 	return (error);
476c68996e2SPoul-Henning Kamp }
477c68996e2SPoul-Henning Kamp 
478c68996e2SPoul-Henning Kamp /*
479c68996e2SPoul-Henning Kamp  * second_overflow() - called after ntp_tick_adjust()
480c68996e2SPoul-Henning Kamp  *
481c68996e2SPoul-Henning Kamp  * This routine is ordinarily called immediately following the above
482c68996e2SPoul-Henning Kamp  * routine ntp_tick_adjust(). While these two routines are normally
483c68996e2SPoul-Henning Kamp  * combined, they are separated here only for the purposes of
484c68996e2SPoul-Henning Kamp  * simulation.
485c68996e2SPoul-Henning Kamp  */
486c68996e2SPoul-Henning Kamp void
487b4a1d0deSPoul-Henning Kamp ntp_update_second(int64_t *adjustment, time_t *newsec)
488c68996e2SPoul-Henning Kamp {
489e1d970f1SPoul-Henning Kamp 	int tickrate;
49097804a5cSPoul-Henning Kamp 	l_fp ftemp;		/* 32/64-bit temporary */
491c68996e2SPoul-Henning Kamp 
4924493f659SKonstantin Belousov 	NTP_LOCK();
4934493f659SKonstantin Belousov 
49482e84c5bSPoul-Henning Kamp 	/*
49582e84c5bSPoul-Henning Kamp 	 * On rollover of the second both the nanosecond and microsecond
49682e84c5bSPoul-Henning Kamp 	 * clocks are updated and the state machine cranked as
49782e84c5bSPoul-Henning Kamp 	 * necessary. The phase adjustment to be used for the next
49882e84c5bSPoul-Henning Kamp 	 * second is calculated and the maximum error is increased by
49982e84c5bSPoul-Henning Kamp 	 * the tolerance.
50082e84c5bSPoul-Henning Kamp 	 */
501c68996e2SPoul-Henning Kamp 	time_maxerror += MAXFREQ / 1000;
502c68996e2SPoul-Henning Kamp 
503c68996e2SPoul-Henning Kamp 	/*
504c68996e2SPoul-Henning Kamp 	 * Leap second processing. If in leap-insert state at
505c68996e2SPoul-Henning Kamp 	 * the end of the day, the system clock is set back one
506c68996e2SPoul-Henning Kamp 	 * second; if in leap-delete state, the system clock is
507c68996e2SPoul-Henning Kamp 	 * set ahead one second. The nano_time() routine or
508c68996e2SPoul-Henning Kamp 	 * external clock driver will insure that reported time
509c68996e2SPoul-Henning Kamp 	 * is always monotonic.
510c68996e2SPoul-Henning Kamp 	 */
511c68996e2SPoul-Henning Kamp 	switch (time_state) {
512c68996e2SPoul-Henning Kamp 
513c68996e2SPoul-Henning Kamp 		/*
514c68996e2SPoul-Henning Kamp 		 * No warning.
515c68996e2SPoul-Henning Kamp 		 */
516c68996e2SPoul-Henning Kamp 		case TIME_OK:
517c68996e2SPoul-Henning Kamp 		if (time_status & STA_INS)
518c68996e2SPoul-Henning Kamp 			time_state = TIME_INS;
519c68996e2SPoul-Henning Kamp 		else if (time_status & STA_DEL)
520c68996e2SPoul-Henning Kamp 			time_state = TIME_DEL;
521c68996e2SPoul-Henning Kamp 		break;
522c68996e2SPoul-Henning Kamp 
523c68996e2SPoul-Henning Kamp 		/*
524c68996e2SPoul-Henning Kamp 		 * Insert second 23:59:60 following second
525c68996e2SPoul-Henning Kamp 		 * 23:59:59.
526c68996e2SPoul-Henning Kamp 		 */
527c68996e2SPoul-Henning Kamp 		case TIME_INS:
528c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_INS))
529c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
530c68996e2SPoul-Henning Kamp 		else if ((*newsec) % 86400 == 0) {
531c68996e2SPoul-Henning Kamp 			(*newsec)--;
532c68996e2SPoul-Henning Kamp 			time_state = TIME_OOP;
533eac3c62bSWarner Losh 			time_tai++;
534c68996e2SPoul-Henning Kamp 		}
535c68996e2SPoul-Henning Kamp 		break;
536c68996e2SPoul-Henning Kamp 
537c68996e2SPoul-Henning Kamp 		/*
538c68996e2SPoul-Henning Kamp 		 * Delete second 23:59:59.
539c68996e2SPoul-Henning Kamp 		 */
540c68996e2SPoul-Henning Kamp 		case TIME_DEL:
541c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_DEL))
542c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
543c68996e2SPoul-Henning Kamp 		else if (((*newsec) + 1) % 86400 == 0) {
544c68996e2SPoul-Henning Kamp 			(*newsec)++;
54597804a5cSPoul-Henning Kamp 			time_tai--;
546c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
547c68996e2SPoul-Henning Kamp 		}
548c68996e2SPoul-Henning Kamp 		break;
549c68996e2SPoul-Henning Kamp 
550c68996e2SPoul-Henning Kamp 		/*
551c68996e2SPoul-Henning Kamp 		 * Insert second in progress.
552c68996e2SPoul-Henning Kamp 		 */
553c68996e2SPoul-Henning Kamp 		case TIME_OOP:
554c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
555c68996e2SPoul-Henning Kamp 		break;
556c68996e2SPoul-Henning Kamp 
557c68996e2SPoul-Henning Kamp 		/*
558c68996e2SPoul-Henning Kamp 		 * Wait for status bits to clear.
559c68996e2SPoul-Henning Kamp 		 */
560c68996e2SPoul-Henning Kamp 		case TIME_WAIT:
561c68996e2SPoul-Henning Kamp 		if (!(time_status & (STA_INS | STA_DEL)))
562c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
563c68996e2SPoul-Henning Kamp 	}
564c68996e2SPoul-Henning Kamp 
565c68996e2SPoul-Henning Kamp 	/*
56682e84c5bSPoul-Henning Kamp 	 * Compute the total time adjustment for the next second
56782e84c5bSPoul-Henning Kamp 	 * in ns. The offset is reduced by a factor depending on
56882e84c5bSPoul-Henning Kamp 	 * whether the PPS signal is operating. Note that the
56982e84c5bSPoul-Henning Kamp 	 * value is in effect scaled by the clock frequency,
57082e84c5bSPoul-Henning Kamp 	 * since the adjustment is added at each tick interrupt.
571c68996e2SPoul-Henning Kamp 	 */
57297804a5cSPoul-Henning Kamp 	ftemp = time_offset;
573c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
57497804a5cSPoul-Henning Kamp 	/* XXX even if PPS signal dies we should finish adjustment ? */
57597804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSTIME && time_status &
57697804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)
57797804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, pps_shift);
57897804a5cSPoul-Henning Kamp 	else
57997804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
58082e84c5bSPoul-Henning Kamp #else
58197804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
58282e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
58397804a5cSPoul-Henning Kamp 	time_adj = ftemp;
58497804a5cSPoul-Henning Kamp 	L_SUB(time_offset, ftemp);
585c68996e2SPoul-Henning Kamp 	L_ADD(time_adj, time_freq);
586e1d970f1SPoul-Henning Kamp 
587e1d970f1SPoul-Henning Kamp 	/*
588e1d970f1SPoul-Henning Kamp 	 * Apply any correction from adjtime(2).  If more than one second
589e1d970f1SPoul-Henning Kamp 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
590e1d970f1SPoul-Henning Kamp 	 * until the last second is slewed the final < 500 usecs.
591e1d970f1SPoul-Henning Kamp 	 */
592e1d970f1SPoul-Henning Kamp 	if (time_adjtime != 0) {
593e1d970f1SPoul-Henning Kamp 		if (time_adjtime > 1000000)
594e1d970f1SPoul-Henning Kamp 			tickrate = 5000;
595e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -1000000)
596e1d970f1SPoul-Henning Kamp 			tickrate = -5000;
597e1d970f1SPoul-Henning Kamp 		else if (time_adjtime > 500)
598e1d970f1SPoul-Henning Kamp 			tickrate = 500;
599e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -500)
600e1d970f1SPoul-Henning Kamp 			tickrate = -500;
601e1d970f1SPoul-Henning Kamp 		else
602bcfe6d8bSPoul-Henning Kamp 			tickrate = time_adjtime;
603e1d970f1SPoul-Henning Kamp 		time_adjtime -= tickrate;
604e1d970f1SPoul-Henning Kamp 		L_LINT(ftemp, tickrate * 1000);
605e1d970f1SPoul-Henning Kamp 		L_ADD(time_adj, ftemp);
606e1d970f1SPoul-Henning Kamp 	}
607b4a1d0deSPoul-Henning Kamp 	*adjustment = time_adj;
608e1d970f1SPoul-Henning Kamp 
609c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
610c68996e2SPoul-Henning Kamp 	if (pps_valid > 0)
611c68996e2SPoul-Henning Kamp 		pps_valid--;
612c68996e2SPoul-Henning Kamp 	else
61324dbea46SJohn Hay 		time_status &= ~STA_PPSSIGNAL;
614c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
6154493f659SKonstantin Belousov 
6164493f659SKonstantin Belousov 	NTP_UNLOCK();
617c68996e2SPoul-Henning Kamp }
618c68996e2SPoul-Henning Kamp 
619c68996e2SPoul-Henning Kamp /*
620c68996e2SPoul-Henning Kamp  * ntp_init() - initialize variables and structures
621c68996e2SPoul-Henning Kamp  *
622c68996e2SPoul-Henning Kamp  * This routine must be called after the kernel variables hz and tick
623c68996e2SPoul-Henning Kamp  * are set or changed and before the next tick interrupt. In this
624c68996e2SPoul-Henning Kamp  * particular implementation, these values are assumed set elsewhere in
625c68996e2SPoul-Henning Kamp  * the kernel. The design allows the clock frequency and tick interval
626c68996e2SPoul-Henning Kamp  * to be changed while the system is running. So, this routine should
627c68996e2SPoul-Henning Kamp  * probably be integrated with the code that does that.
628c68996e2SPoul-Henning Kamp  */
629c68996e2SPoul-Henning Kamp static void
630364c516cSKonstantin Belousov ntp_init(void)
631c68996e2SPoul-Henning Kamp {
632c68996e2SPoul-Henning Kamp 
633c68996e2SPoul-Henning Kamp 	/*
634c68996e2SPoul-Henning Kamp 	 * The following variables are initialized only at startup. Only
635c68996e2SPoul-Henning Kamp 	 * those structures not cleared by the compiler need to be
636c68996e2SPoul-Henning Kamp 	 * initialized, and these only in the simulator. In the actual
637c68996e2SPoul-Henning Kamp 	 * kernel, any nonzero values here will quickly evaporate.
638c68996e2SPoul-Henning Kamp 	 */
639c68996e2SPoul-Henning Kamp 	L_CLR(time_offset);
640c68996e2SPoul-Henning Kamp 	L_CLR(time_freq);
641c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
64282e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
64382e84c5bSPoul-Henning Kamp 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
64482e84c5bSPoul-Henning Kamp 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
645f425c1f6SPoul-Henning Kamp 	pps_fcount = 0;
646c68996e2SPoul-Henning Kamp 	L_CLR(pps_freq);
647c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
648c68996e2SPoul-Henning Kamp }
649c68996e2SPoul-Henning Kamp 
650237fdd78SRobert Watson SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
6516f70df15SPoul-Henning Kamp 
6526f70df15SPoul-Henning Kamp /*
6536f70df15SPoul-Henning Kamp  * hardupdate() - local clock update
6546f70df15SPoul-Henning Kamp  *
6556f70df15SPoul-Henning Kamp  * This routine is called by ntp_adjtime() to update the local clock
6566f70df15SPoul-Henning Kamp  * phase and frequency. The implementation is of an adaptive-parameter,
6576f70df15SPoul-Henning Kamp  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
6586f70df15SPoul-Henning Kamp  * time and frequency offset estimates for each call. If the kernel PPS
6596f70df15SPoul-Henning Kamp  * discipline code is configured (PPS_SYNC), the PPS signal itself
6606f70df15SPoul-Henning Kamp  * determines the new time offset, instead of the calling argument.
6616f70df15SPoul-Henning Kamp  * Presumably, calls to ntp_adjtime() occur only when the caller
6626f70df15SPoul-Henning Kamp  * believes the local clock is valid within some bound (+-128 ms with
6636f70df15SPoul-Henning Kamp  * NTP). If the caller's time is far different than the PPS time, an
6646f70df15SPoul-Henning Kamp  * argument will ensue, and it's not clear who will lose.
6656f70df15SPoul-Henning Kamp  *
666c68996e2SPoul-Henning Kamp  * For uncompensated quartz crystal oscillators and nominal update
667c68996e2SPoul-Henning Kamp  * intervals less than 256 s, operation should be in phase-lock mode,
668c68996e2SPoul-Henning Kamp  * where the loop is disciplined to phase. For update intervals greater
669c68996e2SPoul-Henning Kamp  * than 1024 s, operation should be in frequency-lock mode, where the
670c68996e2SPoul-Henning Kamp  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
671c68996e2SPoul-Henning Kamp  * is selected by the STA_MODE status bit.
6726f70df15SPoul-Henning Kamp  */
6736f70df15SPoul-Henning Kamp static void
674c68996e2SPoul-Henning Kamp hardupdate(offset)
675c68996e2SPoul-Henning Kamp 	long offset;		/* clock offset (ns) */
6766f70df15SPoul-Henning Kamp {
67797804a5cSPoul-Henning Kamp 	long mtemp;
678c68996e2SPoul-Henning Kamp 	l_fp ftemp;
6796f70df15SPoul-Henning Kamp 
6804493f659SKonstantin Belousov 	NTP_ASSERT_LOCKED();
681364c516cSKonstantin Belousov 
682c68996e2SPoul-Henning Kamp 	/*
683c68996e2SPoul-Henning Kamp 	 * Select how the phase is to be controlled and from which
684c68996e2SPoul-Henning Kamp 	 * source. If the PPS signal is present and enabled to
685c68996e2SPoul-Henning Kamp 	 * discipline the time, the PPS offset is used; otherwise, the
686c68996e2SPoul-Henning Kamp 	 * argument offset is used.
687c68996e2SPoul-Henning Kamp 	 */
68882e84c5bSPoul-Henning Kamp 	if (!(time_status & STA_PLL))
68982e84c5bSPoul-Henning Kamp 		return;
69097804a5cSPoul-Henning Kamp 	if (!(time_status & STA_PPSTIME && time_status &
69197804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)) {
69297804a5cSPoul-Henning Kamp 		if (offset > MAXPHASE)
69397804a5cSPoul-Henning Kamp 			time_monitor = MAXPHASE;
69497804a5cSPoul-Henning Kamp 		else if (offset < -MAXPHASE)
69597804a5cSPoul-Henning Kamp 			time_monitor = -MAXPHASE;
69697804a5cSPoul-Henning Kamp 		else
69797804a5cSPoul-Henning Kamp 			time_monitor = offset;
69897804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
69997804a5cSPoul-Henning Kamp 	}
7006f70df15SPoul-Henning Kamp 
7016f70df15SPoul-Henning Kamp 	/*
702c68996e2SPoul-Henning Kamp 	 * Select how the frequency is to be controlled and in which
703c68996e2SPoul-Henning Kamp 	 * mode (PLL or FLL). If the PPS signal is present and enabled
704c68996e2SPoul-Henning Kamp 	 * to discipline the frequency, the PPS frequency is used;
705c68996e2SPoul-Henning Kamp 	 * otherwise, the argument offset is used to compute it.
7066f70df15SPoul-Henning Kamp 	 */
707c68996e2SPoul-Henning Kamp 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
708969fc29eSIan Lepore 		time_reftime = time_uptime;
709c68996e2SPoul-Henning Kamp 		return;
710c68996e2SPoul-Henning Kamp 	}
7116f70df15SPoul-Henning Kamp 	if (time_status & STA_FREQHOLD || time_reftime == 0)
712969fc29eSIan Lepore 		time_reftime = time_uptime;
713969fc29eSIan Lepore 	mtemp = time_uptime - time_reftime;
71497804a5cSPoul-Henning Kamp 	L_LINT(ftemp, time_monitor);
715c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
716c68996e2SPoul-Henning Kamp 	L_MPY(ftemp, mtemp);
717c68996e2SPoul-Henning Kamp 	L_ADD(time_freq, ftemp);
718c68996e2SPoul-Henning Kamp 	time_status &= ~STA_MODE;
71997804a5cSPoul-Henning Kamp 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
72097804a5cSPoul-Henning Kamp 	    MAXSEC)) {
72197804a5cSPoul-Henning Kamp 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
72282e84c5bSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
72382e84c5bSPoul-Henning Kamp 		L_ADD(time_freq, ftemp);
72482e84c5bSPoul-Henning Kamp 		time_status |= STA_MODE;
725c68996e2SPoul-Henning Kamp 	}
726969fc29eSIan Lepore 	time_reftime = time_uptime;
727c68996e2SPoul-Henning Kamp 	if (L_GINT(time_freq) > MAXFREQ)
728c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, MAXFREQ);
729c68996e2SPoul-Henning Kamp 	else if (L_GINT(time_freq) < -MAXFREQ)
730c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, -MAXFREQ);
7313f31c649SGarrett Wollman }
7323f31c649SGarrett Wollman 
7336f70df15SPoul-Henning Kamp #ifdef PPS_SYNC
7346f70df15SPoul-Henning Kamp /*
7356f70df15SPoul-Henning Kamp  * hardpps() - discipline CPU clock oscillator to external PPS signal
7366f70df15SPoul-Henning Kamp  *
7376f70df15SPoul-Henning Kamp  * This routine is called at each PPS interrupt in order to discipline
73897804a5cSPoul-Henning Kamp  * the CPU clock oscillator to the PPS signal. There are two independent
73997804a5cSPoul-Henning Kamp  * first-order feedback loops, one for the phase, the other for the
74097804a5cSPoul-Henning Kamp  * frequency. The phase loop measures and grooms the PPS phase offset
74197804a5cSPoul-Henning Kamp  * and leaves it in a handy spot for the seconds overflow routine. The
74297804a5cSPoul-Henning Kamp  * frequency loop averages successive PPS phase differences and
74397804a5cSPoul-Henning Kamp  * calculates the PPS frequency offset, which is also processed by the
74497804a5cSPoul-Henning Kamp  * seconds overflow routine. The code requires the caller to capture the
74597804a5cSPoul-Henning Kamp  * time and architecture-dependent hardware counter values in
74697804a5cSPoul-Henning Kamp  * nanoseconds at the on-time PPS signal transition.
7476f70df15SPoul-Henning Kamp  *
748c68996e2SPoul-Henning Kamp  * Note that, on some Unix systems this routine runs at an interrupt
7496f70df15SPoul-Henning Kamp  * priority level higher than the timer interrupt routine hardclock().
7506f70df15SPoul-Henning Kamp  * Therefore, the variables used are distinct from the hardclock()
751c68996e2SPoul-Henning Kamp  * variables, except for the actual time and frequency variables, which
752c68996e2SPoul-Henning Kamp  * are determined by this routine and updated atomically.
753*f27ac8e2SEd Maste  *
754*f27ac8e2SEd Maste  * tsp  - time at PPS
755*f27ac8e2SEd Maste  * nsec - hardware counter at PPS
7566f70df15SPoul-Henning Kamp  */
7576f70df15SPoul-Henning Kamp void
758*f27ac8e2SEd Maste hardpps(struct timespec *tsp, long nsec)
7596f70df15SPoul-Henning Kamp {
76097804a5cSPoul-Henning Kamp 	long u_sec, u_nsec, v_nsec; /* temps */
761c68996e2SPoul-Henning Kamp 	l_fp ftemp;
7626f70df15SPoul-Henning Kamp 
7634493f659SKonstantin Belousov 	NTP_LOCK();
764364c516cSKonstantin Belousov 
7656f70df15SPoul-Henning Kamp 	/*
76697804a5cSPoul-Henning Kamp 	 * The signal is first processed by a range gate and frequency
76797804a5cSPoul-Henning Kamp 	 * discriminator. The range gate rejects noise spikes outside
76897804a5cSPoul-Henning Kamp 	 * the range +-500 us. The frequency discriminator rejects input
76997804a5cSPoul-Henning Kamp 	 * signals with apparent frequency outside the range 1 +-500
77097804a5cSPoul-Henning Kamp 	 * PPM. If two hits occur in the same second, we ignore the
77197804a5cSPoul-Henning Kamp 	 * later hit; if not and a hit occurs outside the range gate,
77297804a5cSPoul-Henning Kamp 	 * keep the later hit for later comparison, but do not process
77397804a5cSPoul-Henning Kamp 	 * it.
7746f70df15SPoul-Henning Kamp 	 */
775c68996e2SPoul-Henning Kamp 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
776c68996e2SPoul-Henning Kamp 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
777c68996e2SPoul-Henning Kamp 	pps_valid = PPS_VALID;
778c68996e2SPoul-Henning Kamp 	u_sec = tsp->tv_sec;
779c68996e2SPoul-Henning Kamp 	u_nsec = tsp->tv_nsec;
780c68996e2SPoul-Henning Kamp 	if (u_nsec >= (NANOSECOND >> 1)) {
781c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
782c68996e2SPoul-Henning Kamp 		u_sec++;
7836f70df15SPoul-Henning Kamp 	}
78482e84c5bSPoul-Henning Kamp 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
785364c516cSKonstantin Belousov 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND - MAXFREQ)
786364c516cSKonstantin Belousov 		goto out;
787c68996e2SPoul-Henning Kamp 	pps_tf[2] = pps_tf[1];
788c68996e2SPoul-Henning Kamp 	pps_tf[1] = pps_tf[0];
78982e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = u_sec;
79082e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_nsec = u_nsec;
7916f70df15SPoul-Henning Kamp 
7926f70df15SPoul-Henning Kamp 	/*
793c68996e2SPoul-Henning Kamp 	 * Compute the difference between the current and previous
794c68996e2SPoul-Henning Kamp 	 * counter values. If the difference exceeds 0.5 s, assume it
795c68996e2SPoul-Henning Kamp 	 * has wrapped around, so correct 1.0 s. If the result exceeds
796c68996e2SPoul-Henning Kamp 	 * the tick interval, the sample point has crossed a tick
797c68996e2SPoul-Henning Kamp 	 * boundary during the last second, so correct the tick. Very
798c68996e2SPoul-Henning Kamp 	 * intricate.
799c68996e2SPoul-Henning Kamp 	 */
80032c20357SPoul-Henning Kamp 	u_nsec = nsec;
801c68996e2SPoul-Henning Kamp 	if (u_nsec > (NANOSECOND >> 1))
802c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
803c68996e2SPoul-Henning Kamp 	else if (u_nsec < -(NANOSECOND >> 1))
804c68996e2SPoul-Henning Kamp 		u_nsec += NANOSECOND;
805884ab557SPoul-Henning Kamp 	pps_fcount += u_nsec;
80624dbea46SJohn Hay 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
807364c516cSKonstantin Belousov 		goto out;
808c68996e2SPoul-Henning Kamp 	time_status &= ~STA_PPSJITTER;
809c68996e2SPoul-Henning Kamp 
810c68996e2SPoul-Henning Kamp 	/*
811c68996e2SPoul-Henning Kamp 	 * A three-stage median filter is used to help denoise the PPS
8126f70df15SPoul-Henning Kamp 	 * time. The median sample becomes the time offset estimate; the
8136f70df15SPoul-Henning Kamp 	 * difference between the other two samples becomes the time
8146f70df15SPoul-Henning Kamp 	 * dispersion (jitter) estimate.
8156f70df15SPoul-Henning Kamp 	 */
81682e84c5bSPoul-Henning Kamp 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
81782e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
81882e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
81982e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
82082e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
82182e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
82282e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
8236f70df15SPoul-Henning Kamp 		} else {
82482e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
82582e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
826c68996e2SPoul-Henning Kamp 		}
827c68996e2SPoul-Henning Kamp 	} else {
82882e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
82982e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
83082e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
83182e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
83282e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
83382e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
834c68996e2SPoul-Henning Kamp 		} else {
83582e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
83682e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
8376f70df15SPoul-Henning Kamp 		}
8386f70df15SPoul-Henning Kamp 	}
8396f70df15SPoul-Henning Kamp 
8406f70df15SPoul-Henning Kamp 	/*
841c68996e2SPoul-Henning Kamp 	 * Nominal jitter is due to PPS signal noise and interrupt
84297804a5cSPoul-Henning Kamp 	 * latency. If it exceeds the popcorn threshold, the sample is
84397804a5cSPoul-Henning Kamp 	 * discarded. otherwise, if so enabled, the time offset is
84497804a5cSPoul-Henning Kamp 	 * updated. We can tolerate a modest loss of data here without
84597804a5cSPoul-Henning Kamp 	 * much degrading time accuracy.
84679f1fdb8SWarner Losh 	 *
84779f1fdb8SWarner Losh 	 * The measurements being checked here were made with the system
84879f1fdb8SWarner Losh 	 * timecounter, so the popcorn threshold is not allowed to fall below
84979f1fdb8SWarner Losh 	 * the number of nanoseconds in two ticks of the timecounter.  For a
85079f1fdb8SWarner Losh 	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
85179f1fdb8SWarner Losh 	 * to avoid a nonsensical threshold of zero.
8526f70df15SPoul-Henning Kamp 	*/
85379f1fdb8SWarner Losh 	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
85479f1fdb8SWarner Losh 	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
855c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSJITTER;
856c68996e2SPoul-Henning Kamp 		pps_jitcnt++;
857c68996e2SPoul-Henning Kamp 	} else if (time_status & STA_PPSTIME) {
85897804a5cSPoul-Henning Kamp 		time_monitor = -v_nsec;
85997804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
860c68996e2SPoul-Henning Kamp 	}
861c68996e2SPoul-Henning Kamp 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
86282e84c5bSPoul-Henning Kamp 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
863c68996e2SPoul-Henning Kamp 	if (u_sec < (1 << pps_shift))
864364c516cSKonstantin Belousov 		goto out;
865c68996e2SPoul-Henning Kamp 
866c68996e2SPoul-Henning Kamp 	/*
867c68996e2SPoul-Henning Kamp 	 * At the end of the calibration interval the difference between
868c68996e2SPoul-Henning Kamp 	 * the first and last counter values becomes the scaled
869c68996e2SPoul-Henning Kamp 	 * frequency. It will later be divided by the length of the
870c68996e2SPoul-Henning Kamp 	 * interval to determine the frequency update. If the frequency
871c68996e2SPoul-Henning Kamp 	 * exceeds a sanity threshold, or if the actual calibration
872c68996e2SPoul-Henning Kamp 	 * interval is not equal to the expected length, the data are
873c68996e2SPoul-Henning Kamp 	 * discarded. We can tolerate a modest loss of data here without
87497804a5cSPoul-Henning Kamp 	 * much degrading frequency accuracy.
875c68996e2SPoul-Henning Kamp 	 */
876c68996e2SPoul-Henning Kamp 	pps_calcnt++;
877884ab557SPoul-Henning Kamp 	v_nsec = -pps_fcount;
87882e84c5bSPoul-Henning Kamp 	pps_lastsec = pps_tf[0].tv_sec;
879884ab557SPoul-Henning Kamp 	pps_fcount = 0;
880c68996e2SPoul-Henning Kamp 	u_nsec = MAXFREQ << pps_shift;
881364c516cSKonstantin Belousov 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 << pps_shift)) {
882c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSERROR;
883c68996e2SPoul-Henning Kamp 		pps_errcnt++;
884364c516cSKonstantin Belousov 		goto out;
885c68996e2SPoul-Henning Kamp 	}
886c68996e2SPoul-Henning Kamp 
887c68996e2SPoul-Henning Kamp 	/*
88882e84c5bSPoul-Henning Kamp 	 * Here the raw frequency offset and wander (stability) is
88982e84c5bSPoul-Henning Kamp 	 * calculated. If the wander is less than the wander threshold
89082e84c5bSPoul-Henning Kamp 	 * for four consecutive averaging intervals, the interval is
89182e84c5bSPoul-Henning Kamp 	 * doubled; if it is greater than the threshold for four
89282e84c5bSPoul-Henning Kamp 	 * consecutive intervals, the interval is halved. The scaled
89382e84c5bSPoul-Henning Kamp 	 * frequency offset is converted to frequency offset. The
89482e84c5bSPoul-Henning Kamp 	 * stability metric is calculated as the average of recent
89582e84c5bSPoul-Henning Kamp 	 * frequency changes, but is used only for performance
896c68996e2SPoul-Henning Kamp 	 * monitoring.
897c68996e2SPoul-Henning Kamp 	 */
898c68996e2SPoul-Henning Kamp 	L_LINT(ftemp, v_nsec);
899c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, pps_shift);
900c68996e2SPoul-Henning Kamp 	L_SUB(ftemp, pps_freq);
901c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(ftemp);
90282e84c5bSPoul-Henning Kamp 	if (u_nsec > PPS_MAXWANDER) {
90382e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, PPS_MAXWANDER);
904c68996e2SPoul-Henning Kamp 		pps_intcnt--;
905c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
906c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
90782e84c5bSPoul-Henning Kamp 	} else if (u_nsec < -PPS_MAXWANDER) {
90882e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, -PPS_MAXWANDER);
909c68996e2SPoul-Henning Kamp 		pps_intcnt--;
910c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
911c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
912c68996e2SPoul-Henning Kamp 	} else {
9136f70df15SPoul-Henning Kamp 		pps_intcnt++;
9146f70df15SPoul-Henning Kamp 	}
91597804a5cSPoul-Henning Kamp 	if (pps_intcnt >= 4) {
916c68996e2SPoul-Henning Kamp 		pps_intcnt = 4;
91782e84c5bSPoul-Henning Kamp 		if (pps_shift < pps_shiftmax) {
918c68996e2SPoul-Henning Kamp 			pps_shift++;
919c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
920c68996e2SPoul-Henning Kamp 		}
92197804a5cSPoul-Henning Kamp 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
922c68996e2SPoul-Henning Kamp 		pps_intcnt = -4;
923c68996e2SPoul-Henning Kamp 		if (pps_shift > PPS_FAVG) {
924c68996e2SPoul-Henning Kamp 			pps_shift--;
925c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
926c68996e2SPoul-Henning Kamp 		}
927c68996e2SPoul-Henning Kamp 	}
928c68996e2SPoul-Henning Kamp 	if (u_nsec < 0)
929c68996e2SPoul-Henning Kamp 		u_nsec = -u_nsec;
930c68996e2SPoul-Henning Kamp 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
9319ada5a50SPoul-Henning Kamp 
932c68996e2SPoul-Henning Kamp 	/*
93382e84c5bSPoul-Henning Kamp 	 * The PPS frequency is recalculated and clamped to the maximum
93482e84c5bSPoul-Henning Kamp 	 * MAXFREQ. If enabled, the system clock frequency is updated as
93582e84c5bSPoul-Henning Kamp 	 * well.
936c68996e2SPoul-Henning Kamp 	 */
937c68996e2SPoul-Henning Kamp 	L_ADD(pps_freq, ftemp);
938c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(pps_freq);
939c68996e2SPoul-Henning Kamp 	if (u_nsec > MAXFREQ)
940c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, MAXFREQ);
941c68996e2SPoul-Henning Kamp 	else if (u_nsec < -MAXFREQ)
942c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, -MAXFREQ);
94397804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSFREQ)
944c68996e2SPoul-Henning Kamp 		time_freq = pps_freq;
945364c516cSKonstantin Belousov 
946364c516cSKonstantin Belousov out:
9474493f659SKonstantin Belousov 	NTP_UNLOCK();
948c68996e2SPoul-Henning Kamp }
9496f70df15SPoul-Henning Kamp #endif /* PPS_SYNC */
950e1d970f1SPoul-Henning Kamp 
951e1d970f1SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
952e1d970f1SPoul-Henning Kamp struct adjtime_args {
953e1d970f1SPoul-Henning Kamp 	struct timeval *delta;
954e1d970f1SPoul-Henning Kamp 	struct timeval *olddelta;
955e1d970f1SPoul-Henning Kamp };
956e1d970f1SPoul-Henning Kamp #endif
957e1d970f1SPoul-Henning Kamp /* ARGSUSED */
958e1d970f1SPoul-Henning Kamp int
9598451d0ddSKip Macy sys_adjtime(struct thread *td, struct adjtime_args *uap)
960e1d970f1SPoul-Henning Kamp {
961b88ec951SJohn Baldwin 	struct timeval delta, olddelta, *deltap;
962b88ec951SJohn Baldwin 	int error;
963b88ec951SJohn Baldwin 
964b88ec951SJohn Baldwin 	if (uap->delta) {
965b88ec951SJohn Baldwin 		error = copyin(uap->delta, &delta, sizeof(delta));
966b88ec951SJohn Baldwin 		if (error)
967b88ec951SJohn Baldwin 			return (error);
968b88ec951SJohn Baldwin 		deltap = &delta;
969b88ec951SJohn Baldwin 	} else
970b88ec951SJohn Baldwin 		deltap = NULL;
971b88ec951SJohn Baldwin 	error = kern_adjtime(td, deltap, &olddelta);
972b88ec951SJohn Baldwin 	if (uap->olddelta && error == 0)
973b88ec951SJohn Baldwin 		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
974b88ec951SJohn Baldwin 	return (error);
975b88ec951SJohn Baldwin }
976b88ec951SJohn Baldwin 
977b88ec951SJohn Baldwin int
978b88ec951SJohn Baldwin kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
979b88ec951SJohn Baldwin {
980e1d970f1SPoul-Henning Kamp 	struct timeval atv;
981364c516cSKonstantin Belousov 	int64_t ltr, ltw;
982e1d970f1SPoul-Henning Kamp 	int error;
983e1d970f1SPoul-Henning Kamp 
984364c516cSKonstantin Belousov 	if (delta != NULL) {
985364c516cSKonstantin Belousov 		error = priv_check(td, PRIV_ADJTIME);
986364c516cSKonstantin Belousov 		if (error != 0)
987364c516cSKonstantin Belousov 			return (error);
988364c516cSKonstantin Belousov 		ltw = (int64_t)delta->tv_sec * 1000000 + delta->tv_usec;
989364c516cSKonstantin Belousov 	}
9904493f659SKonstantin Belousov 	NTP_LOCK();
991364c516cSKonstantin Belousov 	ltr = time_adjtime;
992364c516cSKonstantin Belousov 	if (delta != NULL)
993364c516cSKonstantin Belousov 		time_adjtime = ltw;
9944493f659SKonstantin Belousov 	NTP_UNLOCK();
995364c516cSKonstantin Belousov 	if (olddelta != NULL) {
996364c516cSKonstantin Belousov 		atv.tv_sec = ltr / 1000000;
997364c516cSKonstantin Belousov 		atv.tv_usec = ltr % 1000000;
998e1d970f1SPoul-Henning Kamp 		if (atv.tv_usec < 0) {
999e1d970f1SPoul-Henning Kamp 			atv.tv_usec += 1000000;
1000e1d970f1SPoul-Henning Kamp 			atv.tv_sec--;
1001e1d970f1SPoul-Henning Kamp 		}
1002b88ec951SJohn Baldwin 		*olddelta = atv;
1003e1d970f1SPoul-Henning Kamp 	}
1004b4be6ef2SRobert Watson 	return (0);
1005b4be6ef2SRobert Watson }
1006e1d970f1SPoul-Henning Kamp 
10075c7e270fSAndriy Gapon static struct callout resettodr_callout;
10085c7e270fSAndriy Gapon static int resettodr_period = 1800;
10095c7e270fSAndriy Gapon 
10105c7e270fSAndriy Gapon static void
10115c7e270fSAndriy Gapon periodic_resettodr(void *arg __unused)
10125c7e270fSAndriy Gapon {
10135c7e270fSAndriy Gapon 
1014364c516cSKonstantin Belousov 	/*
1015364c516cSKonstantin Belousov 	 * Read of time_status is lock-less, which is fine since
1016364c516cSKonstantin Belousov 	 * ntp_is_time_error() operates on the consistent read value.
1017364c516cSKonstantin Belousov 	 */
1018364c516cSKonstantin Belousov 	if (!ntp_is_time_error(time_status))
10195c7e270fSAndriy Gapon 		resettodr();
10205c7e270fSAndriy Gapon 	if (resettodr_period > 0)
10215c7e270fSAndriy Gapon 		callout_schedule(&resettodr_callout, resettodr_period * hz);
10225c7e270fSAndriy Gapon }
10235c7e270fSAndriy Gapon 
10245c7e270fSAndriy Gapon static void
10255c7e270fSAndriy Gapon shutdown_resettodr(void *arg __unused, int howto __unused)
10265c7e270fSAndriy Gapon {
10275c7e270fSAndriy Gapon 
10285c7e270fSAndriy Gapon 	callout_drain(&resettodr_callout);
1029364c516cSKonstantin Belousov 	/* Another unlocked read of time_status */
1030364c516cSKonstantin Belousov 	if (resettodr_period > 0 && !ntp_is_time_error(time_status))
10315c7e270fSAndriy Gapon 		resettodr();
10325c7e270fSAndriy Gapon }
10335c7e270fSAndriy Gapon 
10345c7e270fSAndriy Gapon static int
10355c7e270fSAndriy Gapon sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
10365c7e270fSAndriy Gapon {
10375c7e270fSAndriy Gapon 	int error;
10385c7e270fSAndriy Gapon 
10395c7e270fSAndriy Gapon 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
10405c7e270fSAndriy Gapon 	if (error || !req->newptr)
10415c7e270fSAndriy Gapon 		return (error);
1042af3b2549SHans Petter Selasky 	if (cold)
1043af3b2549SHans Petter Selasky 		goto done;
10445c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10455c7e270fSAndriy Gapon 		callout_stop(&resettodr_callout);
10465c7e270fSAndriy Gapon 	else
10475c7e270fSAndriy Gapon 		callout_reset(&resettodr_callout, resettodr_period * hz,
10485c7e270fSAndriy Gapon 		    periodic_resettodr, NULL);
1049af3b2549SHans Petter Selasky done:
10505c7e270fSAndriy Gapon 	return (0);
10515c7e270fSAndriy Gapon }
10525c7e270fSAndriy Gapon 
1053364c516cSKonstantin Belousov SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT | CTLFLAG_RWTUN |
1054364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, &resettodr_period, 1800, sysctl_resettodr_period, "I",
10555c7e270fSAndriy Gapon     "Save system time to RTC with this period (in seconds)");
10565c7e270fSAndriy Gapon 
10575c7e270fSAndriy Gapon static void
10585c7e270fSAndriy Gapon start_periodic_resettodr(void *arg __unused)
10595c7e270fSAndriy Gapon {
10605c7e270fSAndriy Gapon 
10615c7e270fSAndriy Gapon 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
10625c7e270fSAndriy Gapon 	    SHUTDOWN_PRI_FIRST);
10635c7e270fSAndriy Gapon 	callout_init(&resettodr_callout, 1);
10645c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10655c7e270fSAndriy Gapon 		return;
10665c7e270fSAndriy Gapon 	callout_reset(&resettodr_callout, resettodr_period * hz,
10675c7e270fSAndriy Gapon 	    periodic_resettodr, NULL);
10685c7e270fSAndriy Gapon }
10695c7e270fSAndriy Gapon 
1070785797c3SAndriy Gapon SYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
10715c7e270fSAndriy Gapon 	start_periodic_resettodr, NULL);
1072