xref: /freebsd/sys/kern/kern_ntptime.c (revision be2535b0a6e624f275abe9ee405fc19a0b096b6f)
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 
288fb441a88SKonstantin Belousov 	memset(&ntv, 0, sizeof(ntv));
289fb441a88SKonstantin Belousov 
2904493f659SKonstantin Belousov 	NTP_LOCK();
291932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
2924493f659SKonstantin Belousov 	NTP_UNLOCK();
293932cfd41SMark Santcroos 
294fe18f385SWarner Losh 	td->td_retval[0] = ntv.time_state;
295932cfd41SMark Santcroos 	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
296932cfd41SMark Santcroos }
297932cfd41SMark Santcroos 
298932cfd41SMark Santcroos static int
299932cfd41SMark Santcroos ntp_sysctl(SYSCTL_HANDLER_ARGS)
300932cfd41SMark Santcroos {
301932cfd41SMark Santcroos 	struct ntptimeval ntv;	/* temporary structure */
302932cfd41SMark Santcroos 
303c7dc361dSMark Johnston 	memset(&ntv, 0, sizeof(ntv));
304c7dc361dSMark Johnston 
3054493f659SKonstantin Belousov 	NTP_LOCK();
306932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
3074493f659SKonstantin Belousov 	NTP_UNLOCK();
308932cfd41SMark Santcroos 
309932cfd41SMark Santcroos 	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
310c68996e2SPoul-Henning Kamp }
311c68996e2SPoul-Henning Kamp 
3127029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
3137029da5cSPawel Biernacki     "");
314364c516cSKonstantin Belousov SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE | CTLFLAG_RD |
315364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval",
316364c516cSKonstantin Belousov     "");
317c68996e2SPoul-Henning Kamp 
3185968e18bSPoul-Henning Kamp #ifdef PPS_SYNC
3193eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
3203eb9ab52SEitan Adler     &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
3213eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
3223eb9ab52SEitan Adler     &pps_shift, 0, "Interval duration (sec) (shift)");
323240577c2SMatthew D Fleming SYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
3243eb9ab52SEitan Adler     &time_monitor, 0, "Last time offset scaled (ns)");
3257fd299cbSPoul-Henning Kamp 
326364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
327364c516cSKonstantin Belousov     &pps_freq, 0,
328364c516cSKonstantin Belousov     "Scaled frequency offset (ns/sec)");
329364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
330364c516cSKonstantin Belousov     &time_freq, 0,
331364c516cSKonstantin Belousov     "Frequency offset (ns/sec)");
3325968e18bSPoul-Henning Kamp #endif
333873fbcd7SRobert Watson 
334c68996e2SPoul-Henning Kamp /*
335c68996e2SPoul-Henning Kamp  * ntp_adjtime() - NTP daemon application interface
336c68996e2SPoul-Henning Kamp  *
337873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
338873fbcd7SRobert Watson  * the timex.constant structure member has a dual purpose to set the time
339873fbcd7SRobert Watson  * constant and to set the TAI offset.
340c68996e2SPoul-Henning Kamp  */
341c68996e2SPoul-Henning Kamp int
342*be2535b0SKonstantin Belousov kern_ntp_adjtime(struct thread *td, struct timex *ntv, int *retvalp)
343c68996e2SPoul-Henning Kamp {
344f425c1f6SPoul-Henning Kamp 	long freq;		/* frequency ns/s) */
345c68996e2SPoul-Henning Kamp 	int modes;		/* mode bits from structure */
346364c516cSKonstantin Belousov 	int error, retval;
347c68996e2SPoul-Henning Kamp 
348c68996e2SPoul-Henning Kamp 	/*
349c68996e2SPoul-Henning Kamp 	 * Update selected clock variables - only the superuser can
350c68996e2SPoul-Henning Kamp 	 * change anything. Note that there is no error checking here on
351c68996e2SPoul-Henning Kamp 	 * the assumption the superuser should know what it is doing.
35297804a5cSPoul-Henning Kamp 	 * Note that either the time constant or TAI offset are loaded
35324dbea46SJohn Hay 	 * from the ntv.constant member, depending on the mode bits. If
35424dbea46SJohn Hay 	 * the STA_PLL bit in the status word is cleared, the state and
35524dbea46SJohn Hay 	 * status words are reset to the initial values at boot.
356c68996e2SPoul-Henning Kamp 	 */
357*be2535b0SKonstantin Belousov 	modes = ntv->modes;
358*be2535b0SKonstantin Belousov 	error = 0;
359fafbe352SPoul-Henning Kamp 	if (modes)
360acd3428bSRobert Watson 		error = priv_check(td, PRIV_NTP_ADJTIME);
361364c516cSKonstantin Belousov 	if (error != 0)
362364c516cSKonstantin Belousov 		return (error);
3634493f659SKonstantin Belousov 	NTP_LOCK();
364c68996e2SPoul-Henning Kamp 	if (modes & MOD_MAXERROR)
365*be2535b0SKonstantin Belousov 		time_maxerror = ntv->maxerror;
366c68996e2SPoul-Henning Kamp 	if (modes & MOD_ESTERROR)
367*be2535b0SKonstantin Belousov 		time_esterror = ntv->esterror;
368c68996e2SPoul-Henning Kamp 	if (modes & MOD_STATUS) {
369*be2535b0SKonstantin Belousov 		if (time_status & STA_PLL && !(ntv->status & STA_PLL)) {
37024dbea46SJohn Hay 			time_state = TIME_OK;
37124dbea46SJohn Hay 			time_status = STA_UNSYNC;
37224dbea46SJohn Hay #ifdef PPS_SYNC
37324dbea46SJohn Hay 			pps_shift = PPS_FAVG;
37424dbea46SJohn Hay #endif /* PPS_SYNC */
37524dbea46SJohn Hay 		}
376c68996e2SPoul-Henning Kamp 		time_status &= STA_RONLY;
377*be2535b0SKonstantin Belousov 		time_status |= ntv->status & ~STA_RONLY;
378c68996e2SPoul-Henning Kamp 	}
379f425c1f6SPoul-Henning Kamp 	if (modes & MOD_TIMECONST) {
380*be2535b0SKonstantin Belousov 		if (ntv->constant < 0)
381f425c1f6SPoul-Henning Kamp 			time_constant = 0;
382*be2535b0SKonstantin Belousov 		else if (ntv->constant > MAXTC)
383f425c1f6SPoul-Henning Kamp 			time_constant = MAXTC;
384f425c1f6SPoul-Henning Kamp 		else
385*be2535b0SKonstantin Belousov 			time_constant = ntv->constant;
386f425c1f6SPoul-Henning Kamp 	}
38797804a5cSPoul-Henning Kamp 	if (modes & MOD_TAI) {
388*be2535b0SKonstantin Belousov 		if (ntv->constant > 0) /* XXX zero & negative numbers ? */
389*be2535b0SKonstantin Belousov 			time_tai = ntv->constant;
39097804a5cSPoul-Henning Kamp 	}
39182e84c5bSPoul-Henning Kamp #ifdef PPS_SYNC
39282e84c5bSPoul-Henning Kamp 	if (modes & MOD_PPSMAX) {
393*be2535b0SKonstantin Belousov 		if (ntv->shift < PPS_FAVG)
39482e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVG;
395*be2535b0SKonstantin Belousov 		else if (ntv->shift > PPS_FAVGMAX)
39682e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVGMAX;
39782e84c5bSPoul-Henning Kamp 		else
398*be2535b0SKonstantin Belousov 			pps_shiftmax = ntv->shift;
39982e84c5bSPoul-Henning Kamp 	}
40082e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
401c68996e2SPoul-Henning Kamp 	if (modes & MOD_NANO)
402c68996e2SPoul-Henning Kamp 		time_status |= STA_NANO;
403c68996e2SPoul-Henning Kamp 	if (modes & MOD_MICRO)
404c68996e2SPoul-Henning Kamp 		time_status &= ~STA_NANO;
405c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKB)
406c68996e2SPoul-Henning Kamp 		time_status |= STA_CLK;
407c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKA)
408c68996e2SPoul-Henning Kamp 		time_status &= ~STA_CLK;
40924dbea46SJohn Hay 	if (modes & MOD_FREQUENCY) {
410*be2535b0SKonstantin Belousov 		freq = (ntv->freq * 1000LL) >> 16;
41124dbea46SJohn Hay 		if (freq > MAXFREQ)
41224dbea46SJohn Hay 			L_LINT(time_freq, MAXFREQ);
41324dbea46SJohn Hay 		else if (freq < -MAXFREQ)
41424dbea46SJohn Hay 			L_LINT(time_freq, -MAXFREQ);
415bcfe6d8bSPoul-Henning Kamp 		else {
416bcfe6d8bSPoul-Henning Kamp 			/*
417*be2535b0SKonstantin Belousov 			 * ntv->freq is [PPM * 2^16] = [us/s * 2^16]
418bcfe6d8bSPoul-Henning Kamp 			 * time_freq is [ns/s * 2^32]
419bcfe6d8bSPoul-Henning Kamp 			 */
420*be2535b0SKonstantin Belousov 			time_freq = ntv->freq * 1000LL * 65536LL;
421bcfe6d8bSPoul-Henning Kamp 		}
42224dbea46SJohn Hay #ifdef PPS_SYNC
42324dbea46SJohn Hay 		pps_freq = time_freq;
42424dbea46SJohn Hay #endif /* PPS_SYNC */
42524dbea46SJohn Hay 	}
426551260fcSPoul-Henning Kamp 	if (modes & MOD_OFFSET) {
427551260fcSPoul-Henning Kamp 		if (time_status & STA_NANO)
428*be2535b0SKonstantin Belousov 			hardupdate(ntv->offset);
429551260fcSPoul-Henning Kamp 		else
430*be2535b0SKonstantin Belousov 			hardupdate(ntv->offset * 1000);
431551260fcSPoul-Henning Kamp 	}
432c68996e2SPoul-Henning Kamp 
433c68996e2SPoul-Henning Kamp 	/*
43497804a5cSPoul-Henning Kamp 	 * Retrieve all clock variables. Note that the TAI offset is
43597804a5cSPoul-Henning Kamp 	 * returned only by ntp_gettime();
436c68996e2SPoul-Henning Kamp 	 */
437c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
438*be2535b0SKonstantin Belousov 		ntv->offset = L_GINT(time_offset);
439c68996e2SPoul-Henning Kamp 	else
440*be2535b0SKonstantin Belousov 		ntv->offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
441*be2535b0SKonstantin Belousov 	ntv->freq = L_GINT((time_freq / 1000LL) << 16);
442*be2535b0SKonstantin Belousov 	ntv->maxerror = time_maxerror;
443*be2535b0SKonstantin Belousov 	ntv->esterror = time_esterror;
444*be2535b0SKonstantin Belousov 	ntv->status = time_status;
445*be2535b0SKonstantin Belousov 	ntv->constant = time_constant;
446c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
447*be2535b0SKonstantin Belousov 		ntv->precision = time_precision;
448c68996e2SPoul-Henning Kamp 	else
449*be2535b0SKonstantin Belousov 		ntv->precision = time_precision / 1000;
450*be2535b0SKonstantin Belousov 	ntv->tolerance = MAXFREQ * SCALE_PPM;
451c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
452*be2535b0SKonstantin Belousov 	ntv->shift = pps_shift;
453*be2535b0SKonstantin Belousov 	ntv->ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
454c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
455*be2535b0SKonstantin Belousov 		ntv->jitter = pps_jitter;
456c68996e2SPoul-Henning Kamp 	else
457*be2535b0SKonstantin Belousov 		ntv->jitter = pps_jitter / 1000;
458*be2535b0SKonstantin Belousov 	ntv->stabil = pps_stabil;
459*be2535b0SKonstantin Belousov 	ntv->calcnt = pps_calcnt;
460*be2535b0SKonstantin Belousov 	ntv->errcnt = pps_errcnt;
461*be2535b0SKonstantin Belousov 	ntv->jitcnt = pps_jitcnt;
462*be2535b0SKonstantin Belousov 	ntv->stbcnt = pps_stbcnt;
463c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
464364c516cSKonstantin Belousov 	retval = ntp_is_time_error(time_status) ? TIME_ERROR : time_state;
4654493f659SKonstantin Belousov 	NTP_UNLOCK();
466c68996e2SPoul-Henning Kamp 
467*be2535b0SKonstantin Belousov 	*retvalp = retval;
468*be2535b0SKonstantin Belousov 	return (0);
469*be2535b0SKonstantin Belousov }
470*be2535b0SKonstantin Belousov 
471*be2535b0SKonstantin Belousov #ifndef _SYS_SYSPROTO_H_
472*be2535b0SKonstantin Belousov struct ntp_adjtime_args {
473*be2535b0SKonstantin Belousov 	struct timex *tp;
474*be2535b0SKonstantin Belousov };
475*be2535b0SKonstantin Belousov #endif
476*be2535b0SKonstantin Belousov 
477*be2535b0SKonstantin Belousov int
478*be2535b0SKonstantin Belousov sys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
479*be2535b0SKonstantin Belousov {
480*be2535b0SKonstantin Belousov 	struct timex ntv;
481*be2535b0SKonstantin Belousov 	int error, retval;
482*be2535b0SKonstantin Belousov 
483*be2535b0SKonstantin Belousov 	error = copyin(uap->tp, &ntv, sizeof(ntv));
484*be2535b0SKonstantin Belousov 	if (error == 0) {
485*be2535b0SKonstantin Belousov 		error = kern_ntp_adjtime(td, &ntv, &retval);
486*be2535b0SKonstantin Belousov 		if (error == 0) {
487*be2535b0SKonstantin Belousov 			error = copyout(&ntv, uap->tp, sizeof(ntv));
488364c516cSKonstantin Belousov 			if (error == 0)
489364c516cSKonstantin Belousov 				td->td_retval[0] = retval;
490*be2535b0SKonstantin Belousov 		}
491*be2535b0SKonstantin Belousov 	}
492a5088017SPoul-Henning Kamp 	return (error);
493c68996e2SPoul-Henning Kamp }
494c68996e2SPoul-Henning Kamp 
495c68996e2SPoul-Henning Kamp /*
496c68996e2SPoul-Henning Kamp  * second_overflow() - called after ntp_tick_adjust()
497c68996e2SPoul-Henning Kamp  *
498c68996e2SPoul-Henning Kamp  * This routine is ordinarily called immediately following the above
499c68996e2SPoul-Henning Kamp  * routine ntp_tick_adjust(). While these two routines are normally
500c68996e2SPoul-Henning Kamp  * combined, they are separated here only for the purposes of
501c68996e2SPoul-Henning Kamp  * simulation.
502c68996e2SPoul-Henning Kamp  */
503c68996e2SPoul-Henning Kamp void
504b4a1d0deSPoul-Henning Kamp ntp_update_second(int64_t *adjustment, time_t *newsec)
505c68996e2SPoul-Henning Kamp {
506e1d970f1SPoul-Henning Kamp 	int tickrate;
50797804a5cSPoul-Henning Kamp 	l_fp ftemp;		/* 32/64-bit temporary */
508c68996e2SPoul-Henning Kamp 
5094493f659SKonstantin Belousov 	NTP_LOCK();
5104493f659SKonstantin Belousov 
51182e84c5bSPoul-Henning Kamp 	/*
51282e84c5bSPoul-Henning Kamp 	 * On rollover of the second both the nanosecond and microsecond
51382e84c5bSPoul-Henning Kamp 	 * clocks are updated and the state machine cranked as
51482e84c5bSPoul-Henning Kamp 	 * necessary. The phase adjustment to be used for the next
51582e84c5bSPoul-Henning Kamp 	 * second is calculated and the maximum error is increased by
51682e84c5bSPoul-Henning Kamp 	 * the tolerance.
51782e84c5bSPoul-Henning Kamp 	 */
518c68996e2SPoul-Henning Kamp 	time_maxerror += MAXFREQ / 1000;
519c68996e2SPoul-Henning Kamp 
520c68996e2SPoul-Henning Kamp 	/*
521c68996e2SPoul-Henning Kamp 	 * Leap second processing. If in leap-insert state at
522c68996e2SPoul-Henning Kamp 	 * the end of the day, the system clock is set back one
523c68996e2SPoul-Henning Kamp 	 * second; if in leap-delete state, the system clock is
524c68996e2SPoul-Henning Kamp 	 * set ahead one second. The nano_time() routine or
525c68996e2SPoul-Henning Kamp 	 * external clock driver will insure that reported time
526c68996e2SPoul-Henning Kamp 	 * is always monotonic.
527c68996e2SPoul-Henning Kamp 	 */
528c68996e2SPoul-Henning Kamp 	switch (time_state) {
529c68996e2SPoul-Henning Kamp 		/*
530c68996e2SPoul-Henning Kamp 		 * No warning.
531c68996e2SPoul-Henning Kamp 		 */
532c68996e2SPoul-Henning Kamp 		case TIME_OK:
533c68996e2SPoul-Henning Kamp 		if (time_status & STA_INS)
534c68996e2SPoul-Henning Kamp 			time_state = TIME_INS;
535c68996e2SPoul-Henning Kamp 		else if (time_status & STA_DEL)
536c68996e2SPoul-Henning Kamp 			time_state = TIME_DEL;
537c68996e2SPoul-Henning Kamp 		break;
538c68996e2SPoul-Henning Kamp 
539c68996e2SPoul-Henning Kamp 		/*
540c68996e2SPoul-Henning Kamp 		 * Insert second 23:59:60 following second
541c68996e2SPoul-Henning Kamp 		 * 23:59:59.
542c68996e2SPoul-Henning Kamp 		 */
543c68996e2SPoul-Henning Kamp 		case TIME_INS:
544c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_INS))
545c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
546c68996e2SPoul-Henning Kamp 		else if ((*newsec) % 86400 == 0) {
547c68996e2SPoul-Henning Kamp 			(*newsec)--;
548c68996e2SPoul-Henning Kamp 			time_state = TIME_OOP;
549eac3c62bSWarner Losh 			time_tai++;
550c68996e2SPoul-Henning Kamp 		}
551c68996e2SPoul-Henning Kamp 		break;
552c68996e2SPoul-Henning Kamp 
553c68996e2SPoul-Henning Kamp 		/*
554c68996e2SPoul-Henning Kamp 		 * Delete second 23:59:59.
555c68996e2SPoul-Henning Kamp 		 */
556c68996e2SPoul-Henning Kamp 		case TIME_DEL:
557c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_DEL))
558c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
559c68996e2SPoul-Henning Kamp 		else if (((*newsec) + 1) % 86400 == 0) {
560c68996e2SPoul-Henning Kamp 			(*newsec)++;
56197804a5cSPoul-Henning Kamp 			time_tai--;
562c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
563c68996e2SPoul-Henning Kamp 		}
564c68996e2SPoul-Henning Kamp 		break;
565c68996e2SPoul-Henning Kamp 
566c68996e2SPoul-Henning Kamp 		/*
567c68996e2SPoul-Henning Kamp 		 * Insert second in progress.
568c68996e2SPoul-Henning Kamp 		 */
569c68996e2SPoul-Henning Kamp 		case TIME_OOP:
570c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
571c68996e2SPoul-Henning Kamp 		break;
572c68996e2SPoul-Henning Kamp 
573c68996e2SPoul-Henning Kamp 		/*
574c68996e2SPoul-Henning Kamp 		 * Wait for status bits to clear.
575c68996e2SPoul-Henning Kamp 		 */
576c68996e2SPoul-Henning Kamp 		case TIME_WAIT:
577c68996e2SPoul-Henning Kamp 		if (!(time_status & (STA_INS | STA_DEL)))
578c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
579c68996e2SPoul-Henning Kamp 	}
580c68996e2SPoul-Henning Kamp 
581c68996e2SPoul-Henning Kamp 	/*
58282e84c5bSPoul-Henning Kamp 	 * Compute the total time adjustment for the next second
58382e84c5bSPoul-Henning Kamp 	 * in ns. The offset is reduced by a factor depending on
58482e84c5bSPoul-Henning Kamp 	 * whether the PPS signal is operating. Note that the
58582e84c5bSPoul-Henning Kamp 	 * value is in effect scaled by the clock frequency,
58682e84c5bSPoul-Henning Kamp 	 * since the adjustment is added at each tick interrupt.
587c68996e2SPoul-Henning Kamp 	 */
58897804a5cSPoul-Henning Kamp 	ftemp = time_offset;
589c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
59097804a5cSPoul-Henning Kamp 	/* XXX even if PPS signal dies we should finish adjustment ? */
59197804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSTIME && time_status &
59297804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)
59397804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, pps_shift);
59497804a5cSPoul-Henning Kamp 	else
59597804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59682e84c5bSPoul-Henning Kamp #else
59797804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59882e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
59997804a5cSPoul-Henning Kamp 	time_adj = ftemp;
60097804a5cSPoul-Henning Kamp 	L_SUB(time_offset, ftemp);
601c68996e2SPoul-Henning Kamp 	L_ADD(time_adj, time_freq);
602e1d970f1SPoul-Henning Kamp 
603e1d970f1SPoul-Henning Kamp 	/*
604e1d970f1SPoul-Henning Kamp 	 * Apply any correction from adjtime(2).  If more than one second
605e1d970f1SPoul-Henning Kamp 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500 PPM)
606e1d970f1SPoul-Henning Kamp 	 * until the last second is slewed the final < 500 usecs.
607e1d970f1SPoul-Henning Kamp 	 */
608e1d970f1SPoul-Henning Kamp 	if (time_adjtime != 0) {
609e1d970f1SPoul-Henning Kamp 		if (time_adjtime > 1000000)
610e1d970f1SPoul-Henning Kamp 			tickrate = 5000;
611e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -1000000)
612e1d970f1SPoul-Henning Kamp 			tickrate = -5000;
613e1d970f1SPoul-Henning Kamp 		else if (time_adjtime > 500)
614e1d970f1SPoul-Henning Kamp 			tickrate = 500;
615e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -500)
616e1d970f1SPoul-Henning Kamp 			tickrate = -500;
617e1d970f1SPoul-Henning Kamp 		else
618bcfe6d8bSPoul-Henning Kamp 			tickrate = time_adjtime;
619e1d970f1SPoul-Henning Kamp 		time_adjtime -= tickrate;
620e1d970f1SPoul-Henning Kamp 		L_LINT(ftemp, tickrate * 1000);
621e1d970f1SPoul-Henning Kamp 		L_ADD(time_adj, ftemp);
622e1d970f1SPoul-Henning Kamp 	}
623b4a1d0deSPoul-Henning Kamp 	*adjustment = time_adj;
624e1d970f1SPoul-Henning Kamp 
625c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
626c68996e2SPoul-Henning Kamp 	if (pps_valid > 0)
627c68996e2SPoul-Henning Kamp 		pps_valid--;
628c68996e2SPoul-Henning Kamp 	else
62924dbea46SJohn Hay 		time_status &= ~STA_PPSSIGNAL;
630c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
6314493f659SKonstantin Belousov 
6324493f659SKonstantin Belousov 	NTP_UNLOCK();
633c68996e2SPoul-Henning Kamp }
634c68996e2SPoul-Henning Kamp 
635c68996e2SPoul-Henning Kamp /*
636c68996e2SPoul-Henning Kamp  * ntp_init() - initialize variables and structures
637c68996e2SPoul-Henning Kamp  *
638c68996e2SPoul-Henning Kamp  * This routine must be called after the kernel variables hz and tick
639c68996e2SPoul-Henning Kamp  * are set or changed and before the next tick interrupt. In this
640c68996e2SPoul-Henning Kamp  * particular implementation, these values are assumed set elsewhere in
641c68996e2SPoul-Henning Kamp  * the kernel. The design allows the clock frequency and tick interval
642c68996e2SPoul-Henning Kamp  * to be changed while the system is running. So, this routine should
643c68996e2SPoul-Henning Kamp  * probably be integrated with the code that does that.
644c68996e2SPoul-Henning Kamp  */
645c68996e2SPoul-Henning Kamp static void
646364c516cSKonstantin Belousov ntp_init(void)
647c68996e2SPoul-Henning Kamp {
648c68996e2SPoul-Henning Kamp 
649c68996e2SPoul-Henning Kamp 	/*
650c68996e2SPoul-Henning Kamp 	 * The following variables are initialized only at startup. Only
651c68996e2SPoul-Henning Kamp 	 * those structures not cleared by the compiler need to be
652c68996e2SPoul-Henning Kamp 	 * initialized, and these only in the simulator. In the actual
653c68996e2SPoul-Henning Kamp 	 * kernel, any nonzero values here will quickly evaporate.
654c68996e2SPoul-Henning Kamp 	 */
655c68996e2SPoul-Henning Kamp 	L_CLR(time_offset);
656c68996e2SPoul-Henning Kamp 	L_CLR(time_freq);
657c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
65882e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
65982e84c5bSPoul-Henning Kamp 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
66082e84c5bSPoul-Henning Kamp 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
661f425c1f6SPoul-Henning Kamp 	pps_fcount = 0;
662c68996e2SPoul-Henning Kamp 	L_CLR(pps_freq);
663c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
664c68996e2SPoul-Henning Kamp }
665c68996e2SPoul-Henning Kamp 
666237fdd78SRobert Watson SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
6676f70df15SPoul-Henning Kamp 
6686f70df15SPoul-Henning Kamp /*
6696f70df15SPoul-Henning Kamp  * hardupdate() - local clock update
6706f70df15SPoul-Henning Kamp  *
6716f70df15SPoul-Henning Kamp  * This routine is called by ntp_adjtime() to update the local clock
6726f70df15SPoul-Henning Kamp  * phase and frequency. The implementation is of an adaptive-parameter,
6736f70df15SPoul-Henning Kamp  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
6746f70df15SPoul-Henning Kamp  * time and frequency offset estimates for each call. If the kernel PPS
6756f70df15SPoul-Henning Kamp  * discipline code is configured (PPS_SYNC), the PPS signal itself
6766f70df15SPoul-Henning Kamp  * determines the new time offset, instead of the calling argument.
6776f70df15SPoul-Henning Kamp  * Presumably, calls to ntp_adjtime() occur only when the caller
6786f70df15SPoul-Henning Kamp  * believes the local clock is valid within some bound (+-128 ms with
6796f70df15SPoul-Henning Kamp  * NTP). If the caller's time is far different than the PPS time, an
6806f70df15SPoul-Henning Kamp  * argument will ensue, and it's not clear who will lose.
6816f70df15SPoul-Henning Kamp  *
682c68996e2SPoul-Henning Kamp  * For uncompensated quartz crystal oscillators and nominal update
683c68996e2SPoul-Henning Kamp  * intervals less than 256 s, operation should be in phase-lock mode,
684c68996e2SPoul-Henning Kamp  * where the loop is disciplined to phase. For update intervals greater
685c68996e2SPoul-Henning Kamp  * than 1024 s, operation should be in frequency-lock mode, where the
686c68996e2SPoul-Henning Kamp  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
687c68996e2SPoul-Henning Kamp  * is selected by the STA_MODE status bit.
6886f70df15SPoul-Henning Kamp  */
6896f70df15SPoul-Henning Kamp static void
690c68996e2SPoul-Henning Kamp hardupdate(offset)
691c68996e2SPoul-Henning Kamp 	long offset;		/* clock offset (ns) */
6926f70df15SPoul-Henning Kamp {
69397804a5cSPoul-Henning Kamp 	long mtemp;
694c68996e2SPoul-Henning Kamp 	l_fp ftemp;
6956f70df15SPoul-Henning Kamp 
6964493f659SKonstantin Belousov 	NTP_ASSERT_LOCKED();
697364c516cSKonstantin Belousov 
698c68996e2SPoul-Henning Kamp 	/*
699c68996e2SPoul-Henning Kamp 	 * Select how the phase is to be controlled and from which
700c68996e2SPoul-Henning Kamp 	 * source. If the PPS signal is present and enabled to
701c68996e2SPoul-Henning Kamp 	 * discipline the time, the PPS offset is used; otherwise, the
702c68996e2SPoul-Henning Kamp 	 * argument offset is used.
703c68996e2SPoul-Henning Kamp 	 */
70482e84c5bSPoul-Henning Kamp 	if (!(time_status & STA_PLL))
70582e84c5bSPoul-Henning Kamp 		return;
70697804a5cSPoul-Henning Kamp 	if (!(time_status & STA_PPSTIME && time_status &
70797804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)) {
70897804a5cSPoul-Henning Kamp 		if (offset > MAXPHASE)
70997804a5cSPoul-Henning Kamp 			time_monitor = MAXPHASE;
71097804a5cSPoul-Henning Kamp 		else if (offset < -MAXPHASE)
71197804a5cSPoul-Henning Kamp 			time_monitor = -MAXPHASE;
71297804a5cSPoul-Henning Kamp 		else
71397804a5cSPoul-Henning Kamp 			time_monitor = offset;
71497804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
71597804a5cSPoul-Henning Kamp 	}
7166f70df15SPoul-Henning Kamp 
7176f70df15SPoul-Henning Kamp 	/*
718c68996e2SPoul-Henning Kamp 	 * Select how the frequency is to be controlled and in which
719c68996e2SPoul-Henning Kamp 	 * mode (PLL or FLL). If the PPS signal is present and enabled
720c68996e2SPoul-Henning Kamp 	 * to discipline the frequency, the PPS frequency is used;
721c68996e2SPoul-Henning Kamp 	 * otherwise, the argument offset is used to compute it.
7226f70df15SPoul-Henning Kamp 	 */
723c68996e2SPoul-Henning Kamp 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
724969fc29eSIan Lepore 		time_reftime = time_uptime;
725c68996e2SPoul-Henning Kamp 		return;
726c68996e2SPoul-Henning Kamp 	}
7276f70df15SPoul-Henning Kamp 	if (time_status & STA_FREQHOLD || time_reftime == 0)
728969fc29eSIan Lepore 		time_reftime = time_uptime;
729969fc29eSIan Lepore 	mtemp = time_uptime - time_reftime;
73097804a5cSPoul-Henning Kamp 	L_LINT(ftemp, time_monitor);
731c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
732c68996e2SPoul-Henning Kamp 	L_MPY(ftemp, mtemp);
733c68996e2SPoul-Henning Kamp 	L_ADD(time_freq, ftemp);
734c68996e2SPoul-Henning Kamp 	time_status &= ~STA_MODE;
73597804a5cSPoul-Henning Kamp 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
73697804a5cSPoul-Henning Kamp 	    MAXSEC)) {
73797804a5cSPoul-Henning Kamp 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
73882e84c5bSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
73982e84c5bSPoul-Henning Kamp 		L_ADD(time_freq, ftemp);
74082e84c5bSPoul-Henning Kamp 		time_status |= STA_MODE;
741c68996e2SPoul-Henning Kamp 	}
742969fc29eSIan Lepore 	time_reftime = time_uptime;
743c68996e2SPoul-Henning Kamp 	if (L_GINT(time_freq) > MAXFREQ)
744c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, MAXFREQ);
745c68996e2SPoul-Henning Kamp 	else if (L_GINT(time_freq) < -MAXFREQ)
746c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, -MAXFREQ);
7473f31c649SGarrett Wollman }
7483f31c649SGarrett Wollman 
7496f70df15SPoul-Henning Kamp #ifdef PPS_SYNC
7506f70df15SPoul-Henning Kamp /*
7516f70df15SPoul-Henning Kamp  * hardpps() - discipline CPU clock oscillator to external PPS signal
7526f70df15SPoul-Henning Kamp  *
7536f70df15SPoul-Henning Kamp  * This routine is called at each PPS interrupt in order to discipline
75497804a5cSPoul-Henning Kamp  * the CPU clock oscillator to the PPS signal. There are two independent
75597804a5cSPoul-Henning Kamp  * first-order feedback loops, one for the phase, the other for the
75697804a5cSPoul-Henning Kamp  * frequency. The phase loop measures and grooms the PPS phase offset
75797804a5cSPoul-Henning Kamp  * and leaves it in a handy spot for the seconds overflow routine. The
75897804a5cSPoul-Henning Kamp  * frequency loop averages successive PPS phase differences and
75997804a5cSPoul-Henning Kamp  * calculates the PPS frequency offset, which is also processed by the
76097804a5cSPoul-Henning Kamp  * seconds overflow routine. The code requires the caller to capture the
76197804a5cSPoul-Henning Kamp  * time and architecture-dependent hardware counter values in
76297804a5cSPoul-Henning Kamp  * nanoseconds at the on-time PPS signal transition.
7636f70df15SPoul-Henning Kamp  *
764c68996e2SPoul-Henning Kamp  * Note that, on some Unix systems this routine runs at an interrupt
7656f70df15SPoul-Henning Kamp  * priority level higher than the timer interrupt routine hardclock().
7666f70df15SPoul-Henning Kamp  * Therefore, the variables used are distinct from the hardclock()
767c68996e2SPoul-Henning Kamp  * variables, except for the actual time and frequency variables, which
768c68996e2SPoul-Henning Kamp  * are determined by this routine and updated atomically.
769f27ac8e2SEd Maste  *
770f27ac8e2SEd Maste  * tsp  - time at PPS
771f27ac8e2SEd Maste  * nsec - hardware counter at PPS
7726f70df15SPoul-Henning Kamp  */
7736f70df15SPoul-Henning Kamp void
774f27ac8e2SEd Maste hardpps(struct timespec *tsp, long nsec)
7756f70df15SPoul-Henning Kamp {
77697804a5cSPoul-Henning Kamp 	long u_sec, u_nsec, v_nsec; /* temps */
777c68996e2SPoul-Henning Kamp 	l_fp ftemp;
7786f70df15SPoul-Henning Kamp 
7794493f659SKonstantin Belousov 	NTP_LOCK();
780364c516cSKonstantin Belousov 
7816f70df15SPoul-Henning Kamp 	/*
78297804a5cSPoul-Henning Kamp 	 * The signal is first processed by a range gate and frequency
78397804a5cSPoul-Henning Kamp 	 * discriminator. The range gate rejects noise spikes outside
78497804a5cSPoul-Henning Kamp 	 * the range +-500 us. The frequency discriminator rejects input
78597804a5cSPoul-Henning Kamp 	 * signals with apparent frequency outside the range 1 +-500
78697804a5cSPoul-Henning Kamp 	 * PPM. If two hits occur in the same second, we ignore the
78797804a5cSPoul-Henning Kamp 	 * later hit; if not and a hit occurs outside the range gate,
78897804a5cSPoul-Henning Kamp 	 * keep the later hit for later comparison, but do not process
78997804a5cSPoul-Henning Kamp 	 * it.
7906f70df15SPoul-Henning Kamp 	 */
791c68996e2SPoul-Henning Kamp 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
792c68996e2SPoul-Henning Kamp 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
793c68996e2SPoul-Henning Kamp 	pps_valid = PPS_VALID;
794c68996e2SPoul-Henning Kamp 	u_sec = tsp->tv_sec;
795c68996e2SPoul-Henning Kamp 	u_nsec = tsp->tv_nsec;
796c68996e2SPoul-Henning Kamp 	if (u_nsec >= (NANOSECOND >> 1)) {
797c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
798c68996e2SPoul-Henning Kamp 		u_sec++;
7996f70df15SPoul-Henning Kamp 	}
80082e84c5bSPoul-Henning Kamp 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
801364c516cSKonstantin Belousov 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND - MAXFREQ)
802364c516cSKonstantin Belousov 		goto out;
803c68996e2SPoul-Henning Kamp 	pps_tf[2] = pps_tf[1];
804c68996e2SPoul-Henning Kamp 	pps_tf[1] = pps_tf[0];
80582e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = u_sec;
80682e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_nsec = u_nsec;
8076f70df15SPoul-Henning Kamp 
8086f70df15SPoul-Henning Kamp 	/*
809c68996e2SPoul-Henning Kamp 	 * Compute the difference between the current and previous
810c68996e2SPoul-Henning Kamp 	 * counter values. If the difference exceeds 0.5 s, assume it
811c68996e2SPoul-Henning Kamp 	 * has wrapped around, so correct 1.0 s. If the result exceeds
812c68996e2SPoul-Henning Kamp 	 * the tick interval, the sample point has crossed a tick
813c68996e2SPoul-Henning Kamp 	 * boundary during the last second, so correct the tick. Very
814c68996e2SPoul-Henning Kamp 	 * intricate.
815c68996e2SPoul-Henning Kamp 	 */
81632c20357SPoul-Henning Kamp 	u_nsec = nsec;
817c68996e2SPoul-Henning Kamp 	if (u_nsec > (NANOSECOND >> 1))
818c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
819c68996e2SPoul-Henning Kamp 	else if (u_nsec < -(NANOSECOND >> 1))
820c68996e2SPoul-Henning Kamp 		u_nsec += NANOSECOND;
821884ab557SPoul-Henning Kamp 	pps_fcount += u_nsec;
82224dbea46SJohn Hay 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
823364c516cSKonstantin Belousov 		goto out;
824c68996e2SPoul-Henning Kamp 	time_status &= ~STA_PPSJITTER;
825c68996e2SPoul-Henning Kamp 
826c68996e2SPoul-Henning Kamp 	/*
827c68996e2SPoul-Henning Kamp 	 * A three-stage median filter is used to help denoise the PPS
8286f70df15SPoul-Henning Kamp 	 * time. The median sample becomes the time offset estimate; the
8296f70df15SPoul-Henning Kamp 	 * difference between the other two samples becomes the time
8306f70df15SPoul-Henning Kamp 	 * dispersion (jitter) estimate.
8316f70df15SPoul-Henning Kamp 	 */
83282e84c5bSPoul-Henning Kamp 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
83382e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
83482e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
83582e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
83682e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
83782e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
83882e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
8396f70df15SPoul-Henning Kamp 		} else {
84082e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
84182e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
842c68996e2SPoul-Henning Kamp 		}
843c68996e2SPoul-Henning Kamp 	} else {
84482e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
84582e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
84682e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
84782e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
84882e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
84982e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
850c68996e2SPoul-Henning Kamp 		} else {
85182e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
85282e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
8536f70df15SPoul-Henning Kamp 		}
8546f70df15SPoul-Henning Kamp 	}
8556f70df15SPoul-Henning Kamp 
8566f70df15SPoul-Henning Kamp 	/*
857c68996e2SPoul-Henning Kamp 	 * Nominal jitter is due to PPS signal noise and interrupt
85897804a5cSPoul-Henning Kamp 	 * latency. If it exceeds the popcorn threshold, the sample is
85997804a5cSPoul-Henning Kamp 	 * discarded. otherwise, if so enabled, the time offset is
86097804a5cSPoul-Henning Kamp 	 * updated. We can tolerate a modest loss of data here without
86197804a5cSPoul-Henning Kamp 	 * much degrading time accuracy.
86279f1fdb8SWarner Losh 	 *
86379f1fdb8SWarner Losh 	 * The measurements being checked here were made with the system
86479f1fdb8SWarner Losh 	 * timecounter, so the popcorn threshold is not allowed to fall below
86579f1fdb8SWarner Losh 	 * the number of nanoseconds in two ticks of the timecounter.  For a
86679f1fdb8SWarner Losh 	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
86779f1fdb8SWarner Losh 	 * to avoid a nonsensical threshold of zero.
8686f70df15SPoul-Henning Kamp 	*/
86979f1fdb8SWarner Losh 	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
87079f1fdb8SWarner Losh 	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
871c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSJITTER;
872c68996e2SPoul-Henning Kamp 		pps_jitcnt++;
873c68996e2SPoul-Henning Kamp 	} else if (time_status & STA_PPSTIME) {
87497804a5cSPoul-Henning Kamp 		time_monitor = -v_nsec;
87597804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
876c68996e2SPoul-Henning Kamp 	}
877c68996e2SPoul-Henning Kamp 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
87882e84c5bSPoul-Henning Kamp 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
879c68996e2SPoul-Henning Kamp 	if (u_sec < (1 << pps_shift))
880364c516cSKonstantin Belousov 		goto out;
881c68996e2SPoul-Henning Kamp 
882c68996e2SPoul-Henning Kamp 	/*
883c68996e2SPoul-Henning Kamp 	 * At the end of the calibration interval the difference between
884c68996e2SPoul-Henning Kamp 	 * the first and last counter values becomes the scaled
885c68996e2SPoul-Henning Kamp 	 * frequency. It will later be divided by the length of the
886c68996e2SPoul-Henning Kamp 	 * interval to determine the frequency update. If the frequency
887c68996e2SPoul-Henning Kamp 	 * exceeds a sanity threshold, or if the actual calibration
888c68996e2SPoul-Henning Kamp 	 * interval is not equal to the expected length, the data are
889c68996e2SPoul-Henning Kamp 	 * discarded. We can tolerate a modest loss of data here without
89097804a5cSPoul-Henning Kamp 	 * much degrading frequency accuracy.
891c68996e2SPoul-Henning Kamp 	 */
892c68996e2SPoul-Henning Kamp 	pps_calcnt++;
893884ab557SPoul-Henning Kamp 	v_nsec = -pps_fcount;
89482e84c5bSPoul-Henning Kamp 	pps_lastsec = pps_tf[0].tv_sec;
895884ab557SPoul-Henning Kamp 	pps_fcount = 0;
896c68996e2SPoul-Henning Kamp 	u_nsec = MAXFREQ << pps_shift;
897364c516cSKonstantin Belousov 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 << pps_shift)) {
898c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSERROR;
899c68996e2SPoul-Henning Kamp 		pps_errcnt++;
900364c516cSKonstantin Belousov 		goto out;
901c68996e2SPoul-Henning Kamp 	}
902c68996e2SPoul-Henning Kamp 
903c68996e2SPoul-Henning Kamp 	/*
90482e84c5bSPoul-Henning Kamp 	 * Here the raw frequency offset and wander (stability) is
90582e84c5bSPoul-Henning Kamp 	 * calculated. If the wander is less than the wander threshold
90682e84c5bSPoul-Henning Kamp 	 * for four consecutive averaging intervals, the interval is
90782e84c5bSPoul-Henning Kamp 	 * doubled; if it is greater than the threshold for four
90882e84c5bSPoul-Henning Kamp 	 * consecutive intervals, the interval is halved. The scaled
90982e84c5bSPoul-Henning Kamp 	 * frequency offset is converted to frequency offset. The
91082e84c5bSPoul-Henning Kamp 	 * stability metric is calculated as the average of recent
91182e84c5bSPoul-Henning Kamp 	 * frequency changes, but is used only for performance
912c68996e2SPoul-Henning Kamp 	 * monitoring.
913c68996e2SPoul-Henning Kamp 	 */
914c68996e2SPoul-Henning Kamp 	L_LINT(ftemp, v_nsec);
915c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, pps_shift);
916c68996e2SPoul-Henning Kamp 	L_SUB(ftemp, pps_freq);
917c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(ftemp);
91882e84c5bSPoul-Henning Kamp 	if (u_nsec > PPS_MAXWANDER) {
91982e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, PPS_MAXWANDER);
920c68996e2SPoul-Henning Kamp 		pps_intcnt--;
921c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
922c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
92382e84c5bSPoul-Henning Kamp 	} else if (u_nsec < -PPS_MAXWANDER) {
92482e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, -PPS_MAXWANDER);
925c68996e2SPoul-Henning Kamp 		pps_intcnt--;
926c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
927c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
928c68996e2SPoul-Henning Kamp 	} else {
9296f70df15SPoul-Henning Kamp 		pps_intcnt++;
9306f70df15SPoul-Henning Kamp 	}
93197804a5cSPoul-Henning Kamp 	if (pps_intcnt >= 4) {
932c68996e2SPoul-Henning Kamp 		pps_intcnt = 4;
93382e84c5bSPoul-Henning Kamp 		if (pps_shift < pps_shiftmax) {
934c68996e2SPoul-Henning Kamp 			pps_shift++;
935c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
936c68996e2SPoul-Henning Kamp 		}
93797804a5cSPoul-Henning Kamp 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
938c68996e2SPoul-Henning Kamp 		pps_intcnt = -4;
939c68996e2SPoul-Henning Kamp 		if (pps_shift > PPS_FAVG) {
940c68996e2SPoul-Henning Kamp 			pps_shift--;
941c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
942c68996e2SPoul-Henning Kamp 		}
943c68996e2SPoul-Henning Kamp 	}
944c68996e2SPoul-Henning Kamp 	if (u_nsec < 0)
945c68996e2SPoul-Henning Kamp 		u_nsec = -u_nsec;
946c68996e2SPoul-Henning Kamp 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
9479ada5a50SPoul-Henning Kamp 
948c68996e2SPoul-Henning Kamp 	/*
94982e84c5bSPoul-Henning Kamp 	 * The PPS frequency is recalculated and clamped to the maximum
95082e84c5bSPoul-Henning Kamp 	 * MAXFREQ. If enabled, the system clock frequency is updated as
95182e84c5bSPoul-Henning Kamp 	 * well.
952c68996e2SPoul-Henning Kamp 	 */
953c68996e2SPoul-Henning Kamp 	L_ADD(pps_freq, ftemp);
954c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(pps_freq);
955c68996e2SPoul-Henning Kamp 	if (u_nsec > MAXFREQ)
956c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, MAXFREQ);
957c68996e2SPoul-Henning Kamp 	else if (u_nsec < -MAXFREQ)
958c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, -MAXFREQ);
95997804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSFREQ)
960c68996e2SPoul-Henning Kamp 		time_freq = pps_freq;
961364c516cSKonstantin Belousov 
962364c516cSKonstantin Belousov out:
9634493f659SKonstantin Belousov 	NTP_UNLOCK();
964c68996e2SPoul-Henning Kamp }
9656f70df15SPoul-Henning Kamp #endif /* PPS_SYNC */
966e1d970f1SPoul-Henning Kamp 
967e1d970f1SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
968e1d970f1SPoul-Henning Kamp struct adjtime_args {
969e1d970f1SPoul-Henning Kamp 	struct timeval *delta;
970e1d970f1SPoul-Henning Kamp 	struct timeval *olddelta;
971e1d970f1SPoul-Henning Kamp };
972e1d970f1SPoul-Henning Kamp #endif
973e1d970f1SPoul-Henning Kamp /* ARGSUSED */
974e1d970f1SPoul-Henning Kamp int
9758451d0ddSKip Macy sys_adjtime(struct thread *td, struct adjtime_args *uap)
976e1d970f1SPoul-Henning Kamp {
977b88ec951SJohn Baldwin 	struct timeval delta, olddelta, *deltap;
978b88ec951SJohn Baldwin 	int error;
979b88ec951SJohn Baldwin 
980b88ec951SJohn Baldwin 	if (uap->delta) {
981b88ec951SJohn Baldwin 		error = copyin(uap->delta, &delta, sizeof(delta));
982b88ec951SJohn Baldwin 		if (error)
983b88ec951SJohn Baldwin 			return (error);
984b88ec951SJohn Baldwin 		deltap = &delta;
985b88ec951SJohn Baldwin 	} else
986b88ec951SJohn Baldwin 		deltap = NULL;
987b88ec951SJohn Baldwin 	error = kern_adjtime(td, deltap, &olddelta);
988b88ec951SJohn Baldwin 	if (uap->olddelta && error == 0)
989b88ec951SJohn Baldwin 		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
990b88ec951SJohn Baldwin 	return (error);
991b88ec951SJohn Baldwin }
992b88ec951SJohn Baldwin 
993b88ec951SJohn Baldwin int
994b88ec951SJohn Baldwin kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
995b88ec951SJohn Baldwin {
996e1d970f1SPoul-Henning Kamp 	struct timeval atv;
997364c516cSKonstantin Belousov 	int64_t ltr, ltw;
998e1d970f1SPoul-Henning Kamp 	int error;
999e1d970f1SPoul-Henning Kamp 
1000364c516cSKonstantin Belousov 	if (delta != NULL) {
1001364c516cSKonstantin Belousov 		error = priv_check(td, PRIV_ADJTIME);
1002364c516cSKonstantin Belousov 		if (error != 0)
1003364c516cSKonstantin Belousov 			return (error);
1004364c516cSKonstantin Belousov 		ltw = (int64_t)delta->tv_sec * 1000000 + delta->tv_usec;
1005364c516cSKonstantin Belousov 	}
10064493f659SKonstantin Belousov 	NTP_LOCK();
1007364c516cSKonstantin Belousov 	ltr = time_adjtime;
1008364c516cSKonstantin Belousov 	if (delta != NULL)
1009364c516cSKonstantin Belousov 		time_adjtime = ltw;
10104493f659SKonstantin Belousov 	NTP_UNLOCK();
1011364c516cSKonstantin Belousov 	if (olddelta != NULL) {
1012364c516cSKonstantin Belousov 		atv.tv_sec = ltr / 1000000;
1013364c516cSKonstantin Belousov 		atv.tv_usec = ltr % 1000000;
1014e1d970f1SPoul-Henning Kamp 		if (atv.tv_usec < 0) {
1015e1d970f1SPoul-Henning Kamp 			atv.tv_usec += 1000000;
1016e1d970f1SPoul-Henning Kamp 			atv.tv_sec--;
1017e1d970f1SPoul-Henning Kamp 		}
1018b88ec951SJohn Baldwin 		*olddelta = atv;
1019e1d970f1SPoul-Henning Kamp 	}
1020b4be6ef2SRobert Watson 	return (0);
1021b4be6ef2SRobert Watson }
1022e1d970f1SPoul-Henning Kamp 
10235c7e270fSAndriy Gapon static struct callout resettodr_callout;
10245c7e270fSAndriy Gapon static int resettodr_period = 1800;
10255c7e270fSAndriy Gapon 
10265c7e270fSAndriy Gapon static void
10275c7e270fSAndriy Gapon periodic_resettodr(void *arg __unused)
10285c7e270fSAndriy Gapon {
10295c7e270fSAndriy Gapon 
1030364c516cSKonstantin Belousov 	/*
1031364c516cSKonstantin Belousov 	 * Read of time_status is lock-less, which is fine since
1032364c516cSKonstantin Belousov 	 * ntp_is_time_error() operates on the consistent read value.
1033364c516cSKonstantin Belousov 	 */
1034364c516cSKonstantin Belousov 	if (!ntp_is_time_error(time_status))
10355c7e270fSAndriy Gapon 		resettodr();
10365c7e270fSAndriy Gapon 	if (resettodr_period > 0)
10375c7e270fSAndriy Gapon 		callout_schedule(&resettodr_callout, resettodr_period * hz);
10385c7e270fSAndriy Gapon }
10395c7e270fSAndriy Gapon 
10405c7e270fSAndriy Gapon static void
10415c7e270fSAndriy Gapon shutdown_resettodr(void *arg __unused, int howto __unused)
10425c7e270fSAndriy Gapon {
10435c7e270fSAndriy Gapon 
10445c7e270fSAndriy Gapon 	callout_drain(&resettodr_callout);
1045364c516cSKonstantin Belousov 	/* Another unlocked read of time_status */
1046364c516cSKonstantin Belousov 	if (resettodr_period > 0 && !ntp_is_time_error(time_status))
10475c7e270fSAndriy Gapon 		resettodr();
10485c7e270fSAndriy Gapon }
10495c7e270fSAndriy Gapon 
10505c7e270fSAndriy Gapon static int
10515c7e270fSAndriy Gapon sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
10525c7e270fSAndriy Gapon {
10535c7e270fSAndriy Gapon 	int error;
10545c7e270fSAndriy Gapon 
10555c7e270fSAndriy Gapon 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
10565c7e270fSAndriy Gapon 	if (error || !req->newptr)
10575c7e270fSAndriy Gapon 		return (error);
1058af3b2549SHans Petter Selasky 	if (cold)
1059af3b2549SHans Petter Selasky 		goto done;
10605c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10615c7e270fSAndriy Gapon 		callout_stop(&resettodr_callout);
10625c7e270fSAndriy Gapon 	else
10635c7e270fSAndriy Gapon 		callout_reset(&resettodr_callout, resettodr_period * hz,
10645c7e270fSAndriy Gapon 		    periodic_resettodr, NULL);
1065af3b2549SHans Petter Selasky done:
10665c7e270fSAndriy Gapon 	return (0);
10675c7e270fSAndriy Gapon }
10685c7e270fSAndriy Gapon 
1069364c516cSKonstantin Belousov SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT | CTLFLAG_RWTUN |
1070364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, &resettodr_period, 1800, sysctl_resettodr_period, "I",
10715c7e270fSAndriy Gapon     "Save system time to RTC with this period (in seconds)");
10725c7e270fSAndriy Gapon 
10735c7e270fSAndriy Gapon static void
10745c7e270fSAndriy Gapon start_periodic_resettodr(void *arg __unused)
10755c7e270fSAndriy Gapon {
10765c7e270fSAndriy Gapon 
10775c7e270fSAndriy Gapon 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
10785c7e270fSAndriy Gapon 	    SHUTDOWN_PRI_FIRST);
10795c7e270fSAndriy Gapon 	callout_init(&resettodr_callout, 1);
10805c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10815c7e270fSAndriy Gapon 		return;
10825c7e270fSAndriy Gapon 	callout_reset(&resettodr_callout, resettodr_period * hz,
10835c7e270fSAndriy Gapon 	    periodic_resettodr, NULL);
10845c7e270fSAndriy Gapon }
10855c7e270fSAndriy Gapon 
1086785797c3SAndriy Gapon SYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
10875c7e270fSAndriy Gapon 	start_periodic_resettodr, NULL);
1088