xref: /freebsd/sys/kern/kern_ntptime.c (revision c7c53e3ca6312c99a0e179e51357a1933de95b5a)
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 hardupdate(long offset);
211932cfd41SMark Santcroos static void ntp_gettime1(struct ntptimeval *ntvp);
212364c516cSKonstantin Belousov static bool ntp_is_time_error(int tsl);
213c68996e2SPoul-Henning Kamp 
214364c516cSKonstantin Belousov static bool
215364c516cSKonstantin Belousov ntp_is_time_error(int tsl)
216c68996e2SPoul-Henning Kamp {
217364c516cSKonstantin Belousov 
218c68996e2SPoul-Henning Kamp 	/*
219c68996e2SPoul-Henning Kamp 	 * Status word error decode. If any of these conditions occur,
220c68996e2SPoul-Henning Kamp 	 * an error is returned, instead of the status word. Most
221c68996e2SPoul-Henning Kamp 	 * applications will care only about the fact the system clock
222c68996e2SPoul-Henning Kamp 	 * may not be trusted, not about the details.
223c68996e2SPoul-Henning Kamp 	 *
224c68996e2SPoul-Henning Kamp 	 * Hardware or software error
225c68996e2SPoul-Henning Kamp 	 */
226364c516cSKonstantin Belousov 	if ((tsl & (STA_UNSYNC | STA_CLOCKERR)) ||
227c68996e2SPoul-Henning Kamp 
228c68996e2SPoul-Henning Kamp 	/*
229c68996e2SPoul-Henning Kamp 	 * PPS signal lost when either time or frequency synchronization
230c68996e2SPoul-Henning Kamp 	 * requested
231c68996e2SPoul-Henning Kamp 	 */
232364c516cSKonstantin Belousov 	    (tsl & (STA_PPSFREQ | STA_PPSTIME) &&
233364c516cSKonstantin Belousov 	    !(tsl & STA_PPSSIGNAL)) ||
234c68996e2SPoul-Henning Kamp 
235c68996e2SPoul-Henning Kamp 	/*
236c68996e2SPoul-Henning Kamp 	 * PPS jitter exceeded when time synchronization requested
237c68996e2SPoul-Henning Kamp 	 */
238364c516cSKonstantin Belousov 	    (tsl & STA_PPSTIME && tsl & STA_PPSJITTER) ||
239c68996e2SPoul-Henning Kamp 
240c68996e2SPoul-Henning Kamp 	/*
241c68996e2SPoul-Henning Kamp 	 * PPS wander exceeded or calibration error when frequency
242c68996e2SPoul-Henning Kamp 	 * synchronization requested
243c68996e2SPoul-Henning Kamp 	 */
244364c516cSKonstantin Belousov 	    (tsl & STA_PPSFREQ &&
245364c516cSKonstantin Belousov 	    tsl & (STA_PPSWANDER | STA_PPSERROR)))
246364c516cSKonstantin Belousov 		return (true);
2479a9ae42aSAndriy Gapon 
248364c516cSKonstantin Belousov 	return (false);
2499a9ae42aSAndriy Gapon }
2509a9ae42aSAndriy Gapon 
2519a9ae42aSAndriy Gapon static void
2529a9ae42aSAndriy Gapon ntp_gettime1(struct ntptimeval *ntvp)
2539a9ae42aSAndriy Gapon {
2549a9ae42aSAndriy Gapon 	struct timespec atv;	/* nanosecond time */
2559a9ae42aSAndriy Gapon 
2564493f659SKonstantin Belousov 	NTP_ASSERT_LOCKED();
2579a9ae42aSAndriy Gapon 
2589a9ae42aSAndriy Gapon 	nanotime(&atv);
2599a9ae42aSAndriy Gapon 	ntvp->time.tv_sec = atv.tv_sec;
2609a9ae42aSAndriy Gapon 	ntvp->time.tv_nsec = atv.tv_nsec;
2619a9ae42aSAndriy Gapon 	ntvp->maxerror = time_maxerror;
2629a9ae42aSAndriy Gapon 	ntvp->esterror = time_esterror;
2639a9ae42aSAndriy Gapon 	ntvp->tai = time_tai;
2649a9ae42aSAndriy Gapon 	ntvp->time_state = time_state;
2659a9ae42aSAndriy Gapon 
266364c516cSKonstantin Belousov 	if (ntp_is_time_error(time_status))
267932cfd41SMark Santcroos 		ntvp->time_state = TIME_ERROR;
268932cfd41SMark Santcroos }
269932cfd41SMark Santcroos 
2709b7fe7e4SMark Santcroos /*
2719b7fe7e4SMark Santcroos  * ntp_gettime() - NTP user application interface
2729b7fe7e4SMark Santcroos  *
273873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
274873fbcd7SRobert Watson  * the TAI offset is returned in the ntvtimeval.tai structure member.
2759b7fe7e4SMark Santcroos  */
276932cfd41SMark Santcroos #ifndef _SYS_SYSPROTO_H_
277932cfd41SMark Santcroos struct ntp_gettime_args {
278932cfd41SMark Santcroos 	struct ntptimeval *ntvp;
279932cfd41SMark Santcroos };
280932cfd41SMark Santcroos #endif
281932cfd41SMark Santcroos /* ARGSUSED */
282932cfd41SMark Santcroos int
2838451d0ddSKip Macy sys_ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
284932cfd41SMark Santcroos {
285932cfd41SMark Santcroos 	struct ntptimeval ntv;
286932cfd41SMark Santcroos 
287fb441a88SKonstantin Belousov 	memset(&ntv, 0, sizeof(ntv));
288fb441a88SKonstantin Belousov 
2894493f659SKonstantin Belousov 	NTP_LOCK();
290932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
2914493f659SKonstantin Belousov 	NTP_UNLOCK();
292932cfd41SMark Santcroos 
293fe18f385SWarner Losh 	td->td_retval[0] = ntv.time_state;
294932cfd41SMark Santcroos 	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
295932cfd41SMark Santcroos }
296932cfd41SMark Santcroos 
297932cfd41SMark Santcroos static int
298932cfd41SMark Santcroos ntp_sysctl(SYSCTL_HANDLER_ARGS)
299932cfd41SMark Santcroos {
300932cfd41SMark Santcroos 	struct ntptimeval ntv;	/* temporary structure */
301932cfd41SMark Santcroos 
302c7dc361dSMark Johnston 	memset(&ntv, 0, sizeof(ntv));
303c7dc361dSMark Johnston 
3044493f659SKonstantin Belousov 	NTP_LOCK();
305932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
3064493f659SKonstantin Belousov 	NTP_UNLOCK();
307932cfd41SMark Santcroos 
308932cfd41SMark Santcroos 	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
309c68996e2SPoul-Henning Kamp }
310c68996e2SPoul-Henning Kamp 
3117029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
3127029da5cSPawel Biernacki     "");
313364c516cSKonstantin Belousov SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE | CTLFLAG_RD |
314364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval",
315364c516cSKonstantin Belousov     "");
316c68996e2SPoul-Henning Kamp 
3175968e18bSPoul-Henning Kamp #ifdef PPS_SYNC
3183eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
3193eb9ab52SEitan Adler     &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
3203eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
3213eb9ab52SEitan Adler     &pps_shift, 0, "Interval duration (sec) (shift)");
322240577c2SMatthew D Fleming SYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
3233eb9ab52SEitan Adler     &time_monitor, 0, "Last time offset scaled (ns)");
3247fd299cbSPoul-Henning Kamp 
325364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
326364c516cSKonstantin Belousov     &pps_freq, 0,
327364c516cSKonstantin Belousov     "Scaled frequency offset (ns/sec)");
328364c516cSKonstantin Belousov SYSCTL_S64(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD | CTLFLAG_MPSAFE,
329364c516cSKonstantin Belousov     &time_freq, 0,
330364c516cSKonstantin Belousov     "Frequency offset (ns/sec)");
3315968e18bSPoul-Henning Kamp #endif
332873fbcd7SRobert Watson 
333c68996e2SPoul-Henning Kamp /*
334c68996e2SPoul-Henning Kamp  * ntp_adjtime() - NTP daemon application interface
335c68996e2SPoul-Henning Kamp  *
336873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
337873fbcd7SRobert Watson  * the timex.constant structure member has a dual purpose to set the time
338873fbcd7SRobert Watson  * constant and to set the TAI offset.
339c68996e2SPoul-Henning Kamp  */
340c68996e2SPoul-Henning Kamp int
341be2535b0SKonstantin Belousov kern_ntp_adjtime(struct thread *td, struct timex *ntv, int *retvalp)
342c68996e2SPoul-Henning Kamp {
343f425c1f6SPoul-Henning Kamp 	long freq;		/* frequency ns/s) */
344c68996e2SPoul-Henning Kamp 	int modes;		/* mode bits from structure */
345364c516cSKonstantin Belousov 	int error, retval;
346c68996e2SPoul-Henning Kamp 
347c68996e2SPoul-Henning Kamp 	/*
348c68996e2SPoul-Henning Kamp 	 * Update selected clock variables - only the superuser can
349c68996e2SPoul-Henning Kamp 	 * change anything. Note that there is no error checking here on
350c68996e2SPoul-Henning Kamp 	 * the assumption the superuser should know what it is doing.
35197804a5cSPoul-Henning Kamp 	 * Note that either the time constant or TAI offset are loaded
35224dbea46SJohn Hay 	 * from the ntv.constant member, depending on the mode bits. If
35324dbea46SJohn Hay 	 * the STA_PLL bit in the status word is cleared, the state and
35424dbea46SJohn Hay 	 * status words are reset to the initial values at boot.
355c68996e2SPoul-Henning Kamp 	 */
356be2535b0SKonstantin Belousov 	modes = ntv->modes;
357be2535b0SKonstantin Belousov 	error = 0;
358fafbe352SPoul-Henning Kamp 	if (modes)
359acd3428bSRobert Watson 		error = priv_check(td, PRIV_NTP_ADJTIME);
360364c516cSKonstantin Belousov 	if (error != 0)
361364c516cSKonstantin Belousov 		return (error);
3624493f659SKonstantin Belousov 	NTP_LOCK();
363c68996e2SPoul-Henning Kamp 	if (modes & MOD_MAXERROR)
364be2535b0SKonstantin Belousov 		time_maxerror = ntv->maxerror;
365c68996e2SPoul-Henning Kamp 	if (modes & MOD_ESTERROR)
366be2535b0SKonstantin Belousov 		time_esterror = ntv->esterror;
367c68996e2SPoul-Henning Kamp 	if (modes & MOD_STATUS) {
368be2535b0SKonstantin Belousov 		if (time_status & STA_PLL && !(ntv->status & STA_PLL)) {
36924dbea46SJohn Hay 			time_state = TIME_OK;
37024dbea46SJohn Hay 			time_status = STA_UNSYNC;
37124dbea46SJohn Hay #ifdef PPS_SYNC
37224dbea46SJohn Hay 			pps_shift = PPS_FAVG;
37324dbea46SJohn Hay #endif /* PPS_SYNC */
37424dbea46SJohn Hay 		}
375c68996e2SPoul-Henning Kamp 		time_status &= STA_RONLY;
376be2535b0SKonstantin Belousov 		time_status |= ntv->status & ~STA_RONLY;
377c68996e2SPoul-Henning Kamp 	}
378f425c1f6SPoul-Henning Kamp 	if (modes & MOD_TIMECONST) {
379be2535b0SKonstantin Belousov 		if (ntv->constant < 0)
380f425c1f6SPoul-Henning Kamp 			time_constant = 0;
381be2535b0SKonstantin Belousov 		else if (ntv->constant > MAXTC)
382f425c1f6SPoul-Henning Kamp 			time_constant = MAXTC;
383f425c1f6SPoul-Henning Kamp 		else
384be2535b0SKonstantin Belousov 			time_constant = ntv->constant;
385f425c1f6SPoul-Henning Kamp 	}
38697804a5cSPoul-Henning Kamp 	if (modes & MOD_TAI) {
387be2535b0SKonstantin Belousov 		if (ntv->constant > 0) /* XXX zero & negative numbers ? */
388be2535b0SKonstantin Belousov 			time_tai = ntv->constant;
38997804a5cSPoul-Henning Kamp 	}
39082e84c5bSPoul-Henning Kamp #ifdef PPS_SYNC
39182e84c5bSPoul-Henning Kamp 	if (modes & MOD_PPSMAX) {
392be2535b0SKonstantin Belousov 		if (ntv->shift < PPS_FAVG)
39382e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVG;
394be2535b0SKonstantin Belousov 		else if (ntv->shift > PPS_FAVGMAX)
39582e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVGMAX;
39682e84c5bSPoul-Henning Kamp 		else
397be2535b0SKonstantin Belousov 			pps_shiftmax = ntv->shift;
39882e84c5bSPoul-Henning Kamp 	}
39982e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
400c68996e2SPoul-Henning Kamp 	if (modes & MOD_NANO)
401c68996e2SPoul-Henning Kamp 		time_status |= STA_NANO;
402c68996e2SPoul-Henning Kamp 	if (modes & MOD_MICRO)
403c68996e2SPoul-Henning Kamp 		time_status &= ~STA_NANO;
404c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKB)
405c68996e2SPoul-Henning Kamp 		time_status |= STA_CLK;
406c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKA)
407c68996e2SPoul-Henning Kamp 		time_status &= ~STA_CLK;
40824dbea46SJohn Hay 	if (modes & MOD_FREQUENCY) {
409be2535b0SKonstantin Belousov 		freq = (ntv->freq * 1000LL) >> 16;
41024dbea46SJohn Hay 		if (freq > MAXFREQ)
41124dbea46SJohn Hay 			L_LINT(time_freq, MAXFREQ);
41224dbea46SJohn Hay 		else if (freq < -MAXFREQ)
41324dbea46SJohn Hay 			L_LINT(time_freq, -MAXFREQ);
414bcfe6d8bSPoul-Henning Kamp 		else {
415bcfe6d8bSPoul-Henning Kamp 			/*
416be2535b0SKonstantin Belousov 			 * ntv->freq is [PPM * 2^16] = [us/s * 2^16]
417bcfe6d8bSPoul-Henning Kamp 			 * time_freq is [ns/s * 2^32]
418bcfe6d8bSPoul-Henning Kamp 			 */
419be2535b0SKonstantin Belousov 			time_freq = ntv->freq * 1000LL * 65536LL;
420bcfe6d8bSPoul-Henning Kamp 		}
42124dbea46SJohn Hay #ifdef PPS_SYNC
42224dbea46SJohn Hay 		pps_freq = time_freq;
42324dbea46SJohn Hay #endif /* PPS_SYNC */
42424dbea46SJohn Hay 	}
425551260fcSPoul-Henning Kamp 	if (modes & MOD_OFFSET) {
426551260fcSPoul-Henning Kamp 		if (time_status & STA_NANO)
427be2535b0SKonstantin Belousov 			hardupdate(ntv->offset);
428551260fcSPoul-Henning Kamp 		else
429be2535b0SKonstantin Belousov 			hardupdate(ntv->offset * 1000);
430551260fcSPoul-Henning Kamp 	}
431c68996e2SPoul-Henning Kamp 
432c68996e2SPoul-Henning Kamp 	/*
43397804a5cSPoul-Henning Kamp 	 * Retrieve all clock variables. Note that the TAI offset is
43497804a5cSPoul-Henning Kamp 	 * returned only by ntp_gettime();
435c68996e2SPoul-Henning Kamp 	 */
436c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
437be2535b0SKonstantin Belousov 		ntv->offset = L_GINT(time_offset);
438c68996e2SPoul-Henning Kamp 	else
439be2535b0SKonstantin Belousov 		ntv->offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
440be2535b0SKonstantin Belousov 	ntv->freq = L_GINT((time_freq / 1000LL) << 16);
441be2535b0SKonstantin Belousov 	ntv->maxerror = time_maxerror;
442be2535b0SKonstantin Belousov 	ntv->esterror = time_esterror;
443be2535b0SKonstantin Belousov 	ntv->status = time_status;
444be2535b0SKonstantin Belousov 	ntv->constant = time_constant;
445c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
446be2535b0SKonstantin Belousov 		ntv->precision = time_precision;
447c68996e2SPoul-Henning Kamp 	else
448be2535b0SKonstantin Belousov 		ntv->precision = time_precision / 1000;
449be2535b0SKonstantin Belousov 	ntv->tolerance = MAXFREQ * SCALE_PPM;
450c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
451be2535b0SKonstantin Belousov 	ntv->shift = pps_shift;
452be2535b0SKonstantin Belousov 	ntv->ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
453c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
454be2535b0SKonstantin Belousov 		ntv->jitter = pps_jitter;
455c68996e2SPoul-Henning Kamp 	else
456be2535b0SKonstantin Belousov 		ntv->jitter = pps_jitter / 1000;
457be2535b0SKonstantin Belousov 	ntv->stabil = pps_stabil;
458be2535b0SKonstantin Belousov 	ntv->calcnt = pps_calcnt;
459be2535b0SKonstantin Belousov 	ntv->errcnt = pps_errcnt;
460be2535b0SKonstantin Belousov 	ntv->jitcnt = pps_jitcnt;
461be2535b0SKonstantin Belousov 	ntv->stbcnt = pps_stbcnt;
462c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
463364c516cSKonstantin Belousov 	retval = ntp_is_time_error(time_status) ? TIME_ERROR : time_state;
4644493f659SKonstantin Belousov 	NTP_UNLOCK();
465c68996e2SPoul-Henning Kamp 
466be2535b0SKonstantin Belousov 	*retvalp = retval;
467be2535b0SKonstantin Belousov 	return (0);
468be2535b0SKonstantin Belousov }
469be2535b0SKonstantin Belousov 
470be2535b0SKonstantin Belousov #ifndef _SYS_SYSPROTO_H_
471be2535b0SKonstantin Belousov struct ntp_adjtime_args {
472be2535b0SKonstantin Belousov 	struct timex *tp;
473be2535b0SKonstantin Belousov };
474be2535b0SKonstantin Belousov #endif
475be2535b0SKonstantin Belousov 
476be2535b0SKonstantin Belousov int
477be2535b0SKonstantin Belousov sys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
478be2535b0SKonstantin Belousov {
479be2535b0SKonstantin Belousov 	struct timex ntv;
480be2535b0SKonstantin Belousov 	int error, retval;
481be2535b0SKonstantin Belousov 
482be2535b0SKonstantin Belousov 	error = copyin(uap->tp, &ntv, sizeof(ntv));
483be2535b0SKonstantin Belousov 	if (error == 0) {
484be2535b0SKonstantin Belousov 		error = kern_ntp_adjtime(td, &ntv, &retval);
485be2535b0SKonstantin Belousov 		if (error == 0) {
486be2535b0SKonstantin Belousov 			error = copyout(&ntv, uap->tp, sizeof(ntv));
487364c516cSKonstantin Belousov 			if (error == 0)
488364c516cSKonstantin Belousov 				td->td_retval[0] = retval;
489be2535b0SKonstantin Belousov 		}
490be2535b0SKonstantin Belousov 	}
491a5088017SPoul-Henning Kamp 	return (error);
492c68996e2SPoul-Henning Kamp }
493c68996e2SPoul-Henning Kamp 
494c68996e2SPoul-Henning Kamp /*
495c68996e2SPoul-Henning Kamp  * second_overflow() - called after ntp_tick_adjust()
496c68996e2SPoul-Henning Kamp  *
497c68996e2SPoul-Henning Kamp  * This routine is ordinarily called immediately following the above
498c68996e2SPoul-Henning Kamp  * routine ntp_tick_adjust(). While these two routines are normally
499c68996e2SPoul-Henning Kamp  * combined, they are separated here only for the purposes of
500c68996e2SPoul-Henning Kamp  * simulation.
501c68996e2SPoul-Henning Kamp  */
502c68996e2SPoul-Henning Kamp void
503b4a1d0deSPoul-Henning Kamp ntp_update_second(int64_t *adjustment, time_t *newsec)
504c68996e2SPoul-Henning Kamp {
505e1d970f1SPoul-Henning Kamp 	int tickrate;
50697804a5cSPoul-Henning Kamp 	l_fp ftemp;		/* 32/64-bit temporary */
507c68996e2SPoul-Henning Kamp 
5084493f659SKonstantin Belousov 	NTP_LOCK();
5094493f659SKonstantin Belousov 
51082e84c5bSPoul-Henning Kamp 	/*
51182e84c5bSPoul-Henning Kamp 	 * On rollover of the second both the nanosecond and microsecond
51282e84c5bSPoul-Henning Kamp 	 * clocks are updated and the state machine cranked as
51382e84c5bSPoul-Henning Kamp 	 * necessary. The phase adjustment to be used for the next
51482e84c5bSPoul-Henning Kamp 	 * second is calculated and the maximum error is increased by
51582e84c5bSPoul-Henning Kamp 	 * the tolerance.
51682e84c5bSPoul-Henning Kamp 	 */
517c68996e2SPoul-Henning Kamp 	time_maxerror += MAXFREQ / 1000;
518c68996e2SPoul-Henning Kamp 
519c68996e2SPoul-Henning Kamp 	/*
520c68996e2SPoul-Henning Kamp 	 * Leap second processing. If in leap-insert state at
521c68996e2SPoul-Henning Kamp 	 * the end of the day, the system clock is set back one
522c68996e2SPoul-Henning Kamp 	 * second; if in leap-delete state, the system clock is
523c68996e2SPoul-Henning Kamp 	 * set ahead one second. The nano_time() routine or
524c68996e2SPoul-Henning Kamp 	 * external clock driver will insure that reported time
525c68996e2SPoul-Henning Kamp 	 * is always monotonic.
526c68996e2SPoul-Henning Kamp 	 */
527c68996e2SPoul-Henning Kamp 	switch (time_state) {
528c68996e2SPoul-Henning Kamp 		/*
529c68996e2SPoul-Henning Kamp 		 * No warning.
530c68996e2SPoul-Henning Kamp 		 */
531c68996e2SPoul-Henning Kamp 		case TIME_OK:
532c68996e2SPoul-Henning Kamp 		if (time_status & STA_INS)
533c68996e2SPoul-Henning Kamp 			time_state = TIME_INS;
534c68996e2SPoul-Henning Kamp 		else if (time_status & STA_DEL)
535c68996e2SPoul-Henning Kamp 			time_state = TIME_DEL;
536c68996e2SPoul-Henning Kamp 		break;
537c68996e2SPoul-Henning Kamp 
538c68996e2SPoul-Henning Kamp 		/*
539c68996e2SPoul-Henning Kamp 		 * Insert second 23:59:60 following second
540c68996e2SPoul-Henning Kamp 		 * 23:59:59.
541c68996e2SPoul-Henning Kamp 		 */
542c68996e2SPoul-Henning Kamp 		case TIME_INS:
543c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_INS))
544c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
545c68996e2SPoul-Henning Kamp 		else if ((*newsec) % 86400 == 0) {
546c68996e2SPoul-Henning Kamp 			(*newsec)--;
547c68996e2SPoul-Henning Kamp 			time_state = TIME_OOP;
548eac3c62bSWarner Losh 			time_tai++;
549c68996e2SPoul-Henning Kamp 		}
550c68996e2SPoul-Henning Kamp 		break;
551c68996e2SPoul-Henning Kamp 
552c68996e2SPoul-Henning Kamp 		/*
553c68996e2SPoul-Henning Kamp 		 * Delete second 23:59:59.
554c68996e2SPoul-Henning Kamp 		 */
555c68996e2SPoul-Henning Kamp 		case TIME_DEL:
556c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_DEL))
557c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
558c68996e2SPoul-Henning Kamp 		else if (((*newsec) + 1) % 86400 == 0) {
559c68996e2SPoul-Henning Kamp 			(*newsec)++;
56097804a5cSPoul-Henning Kamp 			time_tai--;
561c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
562c68996e2SPoul-Henning Kamp 		}
563c68996e2SPoul-Henning Kamp 		break;
564c68996e2SPoul-Henning Kamp 
565c68996e2SPoul-Henning Kamp 		/*
566c68996e2SPoul-Henning Kamp 		 * Insert second in progress.
567c68996e2SPoul-Henning Kamp 		 */
568c68996e2SPoul-Henning Kamp 		case TIME_OOP:
569c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
570c68996e2SPoul-Henning Kamp 		break;
571c68996e2SPoul-Henning Kamp 
572c68996e2SPoul-Henning Kamp 		/*
573c68996e2SPoul-Henning Kamp 		 * Wait for status bits to clear.
574c68996e2SPoul-Henning Kamp 		 */
575c68996e2SPoul-Henning Kamp 		case TIME_WAIT:
576c68996e2SPoul-Henning Kamp 		if (!(time_status & (STA_INS | STA_DEL)))
577c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
578c68996e2SPoul-Henning Kamp 	}
579c68996e2SPoul-Henning Kamp 
580c68996e2SPoul-Henning Kamp 	/*
58182e84c5bSPoul-Henning Kamp 	 * Compute the total time adjustment for the next second
58282e84c5bSPoul-Henning Kamp 	 * in ns. The offset is reduced by a factor depending on
58382e84c5bSPoul-Henning Kamp 	 * whether the PPS signal is operating. Note that the
58482e84c5bSPoul-Henning Kamp 	 * value is in effect scaled by the clock frequency,
58582e84c5bSPoul-Henning Kamp 	 * since the adjustment is added at each tick interrupt.
586c68996e2SPoul-Henning Kamp 	 */
58797804a5cSPoul-Henning Kamp 	ftemp = time_offset;
588c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
58997804a5cSPoul-Henning Kamp 	/* XXX even if PPS signal dies we should finish adjustment ? */
59097804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSTIME && time_status &
59197804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)
59297804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, pps_shift);
59397804a5cSPoul-Henning Kamp 	else
59497804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59582e84c5bSPoul-Henning Kamp #else
59697804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
59782e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
59897804a5cSPoul-Henning Kamp 	time_adj = ftemp;
59997804a5cSPoul-Henning Kamp 	L_SUB(time_offset, ftemp);
600c68996e2SPoul-Henning Kamp 	L_ADD(time_adj, time_freq);
601e1d970f1SPoul-Henning Kamp 
602e1d970f1SPoul-Henning Kamp 	/*
603e1d970f1SPoul-Henning Kamp 	 * Apply any correction from adjtime(2).  If more than one second
604e1d970f1SPoul-Henning Kamp 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500 PPM)
605e1d970f1SPoul-Henning Kamp 	 * until the last second is slewed the final < 500 usecs.
606e1d970f1SPoul-Henning Kamp 	 */
607e1d970f1SPoul-Henning Kamp 	if (time_adjtime != 0) {
608e1d970f1SPoul-Henning Kamp 		if (time_adjtime > 1000000)
609e1d970f1SPoul-Henning Kamp 			tickrate = 5000;
610e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -1000000)
611e1d970f1SPoul-Henning Kamp 			tickrate = -5000;
612e1d970f1SPoul-Henning Kamp 		else if (time_adjtime > 500)
613e1d970f1SPoul-Henning Kamp 			tickrate = 500;
614e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -500)
615e1d970f1SPoul-Henning Kamp 			tickrate = -500;
616e1d970f1SPoul-Henning Kamp 		else
617bcfe6d8bSPoul-Henning Kamp 			tickrate = time_adjtime;
618e1d970f1SPoul-Henning Kamp 		time_adjtime -= tickrate;
619e1d970f1SPoul-Henning Kamp 		L_LINT(ftemp, tickrate * 1000);
620e1d970f1SPoul-Henning Kamp 		L_ADD(time_adj, ftemp);
621e1d970f1SPoul-Henning Kamp 	}
622b4a1d0deSPoul-Henning Kamp 	*adjustment = time_adj;
623e1d970f1SPoul-Henning Kamp 
624c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
625c68996e2SPoul-Henning Kamp 	if (pps_valid > 0)
626c68996e2SPoul-Henning Kamp 		pps_valid--;
627c68996e2SPoul-Henning Kamp 	else
62824dbea46SJohn Hay 		time_status &= ~STA_PPSSIGNAL;
629c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
6304493f659SKonstantin Belousov 
6314493f659SKonstantin Belousov 	NTP_UNLOCK();
632c68996e2SPoul-Henning Kamp }
633c68996e2SPoul-Henning Kamp 
634c68996e2SPoul-Henning Kamp /*
6356f70df15SPoul-Henning Kamp  * hardupdate() - local clock update
6366f70df15SPoul-Henning Kamp  *
6376f70df15SPoul-Henning Kamp  * This routine is called by ntp_adjtime() to update the local clock
6386f70df15SPoul-Henning Kamp  * phase and frequency. The implementation is of an adaptive-parameter,
6396f70df15SPoul-Henning Kamp  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
6406f70df15SPoul-Henning Kamp  * time and frequency offset estimates for each call. If the kernel PPS
6416f70df15SPoul-Henning Kamp  * discipline code is configured (PPS_SYNC), the PPS signal itself
6426f70df15SPoul-Henning Kamp  * determines the new time offset, instead of the calling argument.
6436f70df15SPoul-Henning Kamp  * Presumably, calls to ntp_adjtime() occur only when the caller
6446f70df15SPoul-Henning Kamp  * believes the local clock is valid within some bound (+-128 ms with
6456f70df15SPoul-Henning Kamp  * NTP). If the caller's time is far different than the PPS time, an
6466f70df15SPoul-Henning Kamp  * argument will ensue, and it's not clear who will lose.
6476f70df15SPoul-Henning Kamp  *
648c68996e2SPoul-Henning Kamp  * For uncompensated quartz crystal oscillators and nominal update
649c68996e2SPoul-Henning Kamp  * intervals less than 256 s, operation should be in phase-lock mode,
650c68996e2SPoul-Henning Kamp  * where the loop is disciplined to phase. For update intervals greater
651c68996e2SPoul-Henning Kamp  * than 1024 s, operation should be in frequency-lock mode, where the
652c68996e2SPoul-Henning Kamp  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
653c68996e2SPoul-Henning Kamp  * is selected by the STA_MODE status bit.
6546f70df15SPoul-Henning Kamp  */
6556f70df15SPoul-Henning Kamp static void
656c68996e2SPoul-Henning Kamp hardupdate(offset)
657c68996e2SPoul-Henning Kamp 	long offset;		/* clock offset (ns) */
6586f70df15SPoul-Henning Kamp {
65997804a5cSPoul-Henning Kamp 	long mtemp;
660c68996e2SPoul-Henning Kamp 	l_fp ftemp;
6616f70df15SPoul-Henning Kamp 
6624493f659SKonstantin Belousov 	NTP_ASSERT_LOCKED();
663364c516cSKonstantin Belousov 
664c68996e2SPoul-Henning Kamp 	/*
665c68996e2SPoul-Henning Kamp 	 * Select how the phase is to be controlled and from which
666c68996e2SPoul-Henning Kamp 	 * source. If the PPS signal is present and enabled to
667c68996e2SPoul-Henning Kamp 	 * discipline the time, the PPS offset is used; otherwise, the
668c68996e2SPoul-Henning Kamp 	 * argument offset is used.
669c68996e2SPoul-Henning Kamp 	 */
67082e84c5bSPoul-Henning Kamp 	if (!(time_status & STA_PLL))
67182e84c5bSPoul-Henning Kamp 		return;
67297804a5cSPoul-Henning Kamp 	if (!(time_status & STA_PPSTIME && time_status &
67397804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)) {
67497804a5cSPoul-Henning Kamp 		if (offset > MAXPHASE)
67597804a5cSPoul-Henning Kamp 			time_monitor = MAXPHASE;
67697804a5cSPoul-Henning Kamp 		else if (offset < -MAXPHASE)
67797804a5cSPoul-Henning Kamp 			time_monitor = -MAXPHASE;
67897804a5cSPoul-Henning Kamp 		else
67997804a5cSPoul-Henning Kamp 			time_monitor = offset;
68097804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
68197804a5cSPoul-Henning Kamp 	}
6826f70df15SPoul-Henning Kamp 
6836f70df15SPoul-Henning Kamp 	/*
684c68996e2SPoul-Henning Kamp 	 * Select how the frequency is to be controlled and in which
685c68996e2SPoul-Henning Kamp 	 * mode (PLL or FLL). If the PPS signal is present and enabled
686c68996e2SPoul-Henning Kamp 	 * to discipline the frequency, the PPS frequency is used;
687c68996e2SPoul-Henning Kamp 	 * otherwise, the argument offset is used to compute it.
6886f70df15SPoul-Henning Kamp 	 */
689c68996e2SPoul-Henning Kamp 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
690969fc29eSIan Lepore 		time_reftime = time_uptime;
691c68996e2SPoul-Henning Kamp 		return;
692c68996e2SPoul-Henning Kamp 	}
6936f70df15SPoul-Henning Kamp 	if (time_status & STA_FREQHOLD || time_reftime == 0)
694969fc29eSIan Lepore 		time_reftime = time_uptime;
695969fc29eSIan Lepore 	mtemp = time_uptime - time_reftime;
69697804a5cSPoul-Henning Kamp 	L_LINT(ftemp, time_monitor);
697c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
698c68996e2SPoul-Henning Kamp 	L_MPY(ftemp, mtemp);
699c68996e2SPoul-Henning Kamp 	L_ADD(time_freq, ftemp);
700c68996e2SPoul-Henning Kamp 	time_status &= ~STA_MODE;
70197804a5cSPoul-Henning Kamp 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
70297804a5cSPoul-Henning Kamp 	    MAXSEC)) {
70397804a5cSPoul-Henning Kamp 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
70482e84c5bSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
70582e84c5bSPoul-Henning Kamp 		L_ADD(time_freq, ftemp);
70682e84c5bSPoul-Henning Kamp 		time_status |= STA_MODE;
707c68996e2SPoul-Henning Kamp 	}
708969fc29eSIan Lepore 	time_reftime = time_uptime;
709c68996e2SPoul-Henning Kamp 	if (L_GINT(time_freq) > MAXFREQ)
710c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, MAXFREQ);
711c68996e2SPoul-Henning Kamp 	else if (L_GINT(time_freq) < -MAXFREQ)
712c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, -MAXFREQ);
7133f31c649SGarrett Wollman }
7143f31c649SGarrett Wollman 
7156f70df15SPoul-Henning Kamp #ifdef PPS_SYNC
7166f70df15SPoul-Henning Kamp /*
7176f70df15SPoul-Henning Kamp  * hardpps() - discipline CPU clock oscillator to external PPS signal
7186f70df15SPoul-Henning Kamp  *
7196f70df15SPoul-Henning Kamp  * This routine is called at each PPS interrupt in order to discipline
72097804a5cSPoul-Henning Kamp  * the CPU clock oscillator to the PPS signal. There are two independent
72197804a5cSPoul-Henning Kamp  * first-order feedback loops, one for the phase, the other for the
72297804a5cSPoul-Henning Kamp  * frequency. The phase loop measures and grooms the PPS phase offset
72397804a5cSPoul-Henning Kamp  * and leaves it in a handy spot for the seconds overflow routine. The
72497804a5cSPoul-Henning Kamp  * frequency loop averages successive PPS phase differences and
72597804a5cSPoul-Henning Kamp  * calculates the PPS frequency offset, which is also processed by the
72697804a5cSPoul-Henning Kamp  * seconds overflow routine. The code requires the caller to capture the
72797804a5cSPoul-Henning Kamp  * time and architecture-dependent hardware counter values in
72897804a5cSPoul-Henning Kamp  * nanoseconds at the on-time PPS signal transition.
7296f70df15SPoul-Henning Kamp  *
730c68996e2SPoul-Henning Kamp  * Note that, on some Unix systems this routine runs at an interrupt
7316f70df15SPoul-Henning Kamp  * priority level higher than the timer interrupt routine hardclock().
7326f70df15SPoul-Henning Kamp  * Therefore, the variables used are distinct from the hardclock()
733c68996e2SPoul-Henning Kamp  * variables, except for the actual time and frequency variables, which
734c68996e2SPoul-Henning Kamp  * are determined by this routine and updated atomically.
735f27ac8e2SEd Maste  *
736*c7c53e3cSSebastian Huber  * tsp  - time at current PPS event
737*c7c53e3cSSebastian Huber  * delta_nsec - time elapsed between the previous and current PPS event
7386f70df15SPoul-Henning Kamp  */
7396f70df15SPoul-Henning Kamp void
740*c7c53e3cSSebastian Huber hardpps(struct timespec *tsp, long delta_nsec)
7416f70df15SPoul-Henning Kamp {
74297804a5cSPoul-Henning Kamp 	long u_sec, u_nsec, v_nsec; /* temps */
743c68996e2SPoul-Henning Kamp 	l_fp ftemp;
7446f70df15SPoul-Henning Kamp 
7454493f659SKonstantin Belousov 	NTP_LOCK();
746364c516cSKonstantin Belousov 
7476f70df15SPoul-Henning Kamp 	/*
74897804a5cSPoul-Henning Kamp 	 * The signal is first processed by a range gate and frequency
74997804a5cSPoul-Henning Kamp 	 * discriminator. The range gate rejects noise spikes outside
75097804a5cSPoul-Henning Kamp 	 * the range +-500 us. The frequency discriminator rejects input
75197804a5cSPoul-Henning Kamp 	 * signals with apparent frequency outside the range 1 +-500
75297804a5cSPoul-Henning Kamp 	 * PPM. If two hits occur in the same second, we ignore the
75397804a5cSPoul-Henning Kamp 	 * later hit; if not and a hit occurs outside the range gate,
75497804a5cSPoul-Henning Kamp 	 * keep the later hit for later comparison, but do not process
75597804a5cSPoul-Henning Kamp 	 * it.
7566f70df15SPoul-Henning Kamp 	 */
757c68996e2SPoul-Henning Kamp 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
758c68996e2SPoul-Henning Kamp 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
759c68996e2SPoul-Henning Kamp 	pps_valid = PPS_VALID;
760c68996e2SPoul-Henning Kamp 	u_sec = tsp->tv_sec;
761c68996e2SPoul-Henning Kamp 	u_nsec = tsp->tv_nsec;
762c68996e2SPoul-Henning Kamp 	if (u_nsec >= (NANOSECOND >> 1)) {
763c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
764c68996e2SPoul-Henning Kamp 		u_sec++;
7656f70df15SPoul-Henning Kamp 	}
76682e84c5bSPoul-Henning Kamp 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
767364c516cSKonstantin Belousov 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND - MAXFREQ)
768364c516cSKonstantin Belousov 		goto out;
769c68996e2SPoul-Henning Kamp 	pps_tf[2] = pps_tf[1];
770c68996e2SPoul-Henning Kamp 	pps_tf[1] = pps_tf[0];
77182e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = u_sec;
77282e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_nsec = u_nsec;
7736f70df15SPoul-Henning Kamp 
7746f70df15SPoul-Henning Kamp 	/*
775c68996e2SPoul-Henning Kamp 	 * Compute the difference between the current and previous
776c68996e2SPoul-Henning Kamp 	 * counter values. If the difference exceeds 0.5 s, assume it
777*c7c53e3cSSebastian Huber 	 * has wrapped around, so correct 1.0 s.
778c68996e2SPoul-Henning Kamp 	 */
779*c7c53e3cSSebastian Huber 	u_nsec = delta_nsec;
780c68996e2SPoul-Henning Kamp 	if (u_nsec > (NANOSECOND >> 1))
781c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
782c68996e2SPoul-Henning Kamp 	else if (u_nsec < -(NANOSECOND >> 1))
783c68996e2SPoul-Henning Kamp 		u_nsec += NANOSECOND;
784884ab557SPoul-Henning Kamp 	pps_fcount += u_nsec;
78524dbea46SJohn Hay 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
786364c516cSKonstantin Belousov 		goto out;
787c68996e2SPoul-Henning Kamp 	time_status &= ~STA_PPSJITTER;
788c68996e2SPoul-Henning Kamp 
789c68996e2SPoul-Henning Kamp 	/*
790c68996e2SPoul-Henning Kamp 	 * A three-stage median filter is used to help denoise the PPS
7916f70df15SPoul-Henning Kamp 	 * time. The median sample becomes the time offset estimate; the
7926f70df15SPoul-Henning Kamp 	 * difference between the other two samples becomes the time
7936f70df15SPoul-Henning Kamp 	 * dispersion (jitter) estimate.
7946f70df15SPoul-Henning Kamp 	 */
79582e84c5bSPoul-Henning Kamp 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
79682e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
79782e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
79882e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
79982e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
80082e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
80182e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
8026f70df15SPoul-Henning Kamp 		} else {
80382e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
80482e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
805c68996e2SPoul-Henning Kamp 		}
806c68996e2SPoul-Henning Kamp 	} else {
80782e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
80882e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
80982e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
81082e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
81182e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
81282e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
813c68996e2SPoul-Henning Kamp 		} else {
81482e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
81582e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
8166f70df15SPoul-Henning Kamp 		}
8176f70df15SPoul-Henning Kamp 	}
8186f70df15SPoul-Henning Kamp 
8196f70df15SPoul-Henning Kamp 	/*
820c68996e2SPoul-Henning Kamp 	 * Nominal jitter is due to PPS signal noise and interrupt
82197804a5cSPoul-Henning Kamp 	 * latency. If it exceeds the popcorn threshold, the sample is
82297804a5cSPoul-Henning Kamp 	 * discarded. otherwise, if so enabled, the time offset is
82397804a5cSPoul-Henning Kamp 	 * updated. We can tolerate a modest loss of data here without
82497804a5cSPoul-Henning Kamp 	 * much degrading time accuracy.
82579f1fdb8SWarner Losh 	 *
82679f1fdb8SWarner Losh 	 * The measurements being checked here were made with the system
82779f1fdb8SWarner Losh 	 * timecounter, so the popcorn threshold is not allowed to fall below
82879f1fdb8SWarner Losh 	 * the number of nanoseconds in two ticks of the timecounter.  For a
82979f1fdb8SWarner Losh 	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
83079f1fdb8SWarner Losh 	 * to avoid a nonsensical threshold of zero.
8316f70df15SPoul-Henning Kamp 	*/
83279f1fdb8SWarner Losh 	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
83379f1fdb8SWarner Losh 	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
834c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSJITTER;
835c68996e2SPoul-Henning Kamp 		pps_jitcnt++;
836c68996e2SPoul-Henning Kamp 	} else if (time_status & STA_PPSTIME) {
83797804a5cSPoul-Henning Kamp 		time_monitor = -v_nsec;
83897804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
839c68996e2SPoul-Henning Kamp 	}
840c68996e2SPoul-Henning Kamp 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
84182e84c5bSPoul-Henning Kamp 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
842c68996e2SPoul-Henning Kamp 	if (u_sec < (1 << pps_shift))
843364c516cSKonstantin Belousov 		goto out;
844c68996e2SPoul-Henning Kamp 
845c68996e2SPoul-Henning Kamp 	/*
846c68996e2SPoul-Henning Kamp 	 * At the end of the calibration interval the difference between
847c68996e2SPoul-Henning Kamp 	 * the first and last counter values becomes the scaled
848c68996e2SPoul-Henning Kamp 	 * frequency. It will later be divided by the length of the
849c68996e2SPoul-Henning Kamp 	 * interval to determine the frequency update. If the frequency
850c68996e2SPoul-Henning Kamp 	 * exceeds a sanity threshold, or if the actual calibration
851c68996e2SPoul-Henning Kamp 	 * interval is not equal to the expected length, the data are
852c68996e2SPoul-Henning Kamp 	 * discarded. We can tolerate a modest loss of data here without
85397804a5cSPoul-Henning Kamp 	 * much degrading frequency accuracy.
854c68996e2SPoul-Henning Kamp 	 */
855c68996e2SPoul-Henning Kamp 	pps_calcnt++;
856884ab557SPoul-Henning Kamp 	v_nsec = -pps_fcount;
85782e84c5bSPoul-Henning Kamp 	pps_lastsec = pps_tf[0].tv_sec;
858884ab557SPoul-Henning Kamp 	pps_fcount = 0;
859c68996e2SPoul-Henning Kamp 	u_nsec = MAXFREQ << pps_shift;
860364c516cSKonstantin Belousov 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 << pps_shift)) {
861c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSERROR;
862c68996e2SPoul-Henning Kamp 		pps_errcnt++;
863364c516cSKonstantin Belousov 		goto out;
864c68996e2SPoul-Henning Kamp 	}
865c68996e2SPoul-Henning Kamp 
866c68996e2SPoul-Henning Kamp 	/*
86782e84c5bSPoul-Henning Kamp 	 * Here the raw frequency offset and wander (stability) is
86882e84c5bSPoul-Henning Kamp 	 * calculated. If the wander is less than the wander threshold
86982e84c5bSPoul-Henning Kamp 	 * for four consecutive averaging intervals, the interval is
87082e84c5bSPoul-Henning Kamp 	 * doubled; if it is greater than the threshold for four
87182e84c5bSPoul-Henning Kamp 	 * consecutive intervals, the interval is halved. The scaled
87282e84c5bSPoul-Henning Kamp 	 * frequency offset is converted to frequency offset. The
87382e84c5bSPoul-Henning Kamp 	 * stability metric is calculated as the average of recent
87482e84c5bSPoul-Henning Kamp 	 * frequency changes, but is used only for performance
875c68996e2SPoul-Henning Kamp 	 * monitoring.
876c68996e2SPoul-Henning Kamp 	 */
877c68996e2SPoul-Henning Kamp 	L_LINT(ftemp, v_nsec);
878c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, pps_shift);
879c68996e2SPoul-Henning Kamp 	L_SUB(ftemp, pps_freq);
880c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(ftemp);
88182e84c5bSPoul-Henning Kamp 	if (u_nsec > PPS_MAXWANDER) {
88282e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, PPS_MAXWANDER);
883c68996e2SPoul-Henning Kamp 		pps_intcnt--;
884c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
885c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
88682e84c5bSPoul-Henning Kamp 	} else if (u_nsec < -PPS_MAXWANDER) {
88782e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, -PPS_MAXWANDER);
888c68996e2SPoul-Henning Kamp 		pps_intcnt--;
889c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
890c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
891c68996e2SPoul-Henning Kamp 	} else {
8926f70df15SPoul-Henning Kamp 		pps_intcnt++;
8936f70df15SPoul-Henning Kamp 	}
89497804a5cSPoul-Henning Kamp 	if (pps_intcnt >= 4) {
895c68996e2SPoul-Henning Kamp 		pps_intcnt = 4;
89682e84c5bSPoul-Henning Kamp 		if (pps_shift < pps_shiftmax) {
897c68996e2SPoul-Henning Kamp 			pps_shift++;
898c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
899c68996e2SPoul-Henning Kamp 		}
90097804a5cSPoul-Henning Kamp 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
901c68996e2SPoul-Henning Kamp 		pps_intcnt = -4;
902c68996e2SPoul-Henning Kamp 		if (pps_shift > PPS_FAVG) {
903c68996e2SPoul-Henning Kamp 			pps_shift--;
904c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
905c68996e2SPoul-Henning Kamp 		}
906c68996e2SPoul-Henning Kamp 	}
907c68996e2SPoul-Henning Kamp 	if (u_nsec < 0)
908c68996e2SPoul-Henning Kamp 		u_nsec = -u_nsec;
909c68996e2SPoul-Henning Kamp 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
9109ada5a50SPoul-Henning Kamp 
911c68996e2SPoul-Henning Kamp 	/*
91282e84c5bSPoul-Henning Kamp 	 * The PPS frequency is recalculated and clamped to the maximum
91382e84c5bSPoul-Henning Kamp 	 * MAXFREQ. If enabled, the system clock frequency is updated as
91482e84c5bSPoul-Henning Kamp 	 * well.
915c68996e2SPoul-Henning Kamp 	 */
916c68996e2SPoul-Henning Kamp 	L_ADD(pps_freq, ftemp);
917c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(pps_freq);
918c68996e2SPoul-Henning Kamp 	if (u_nsec > MAXFREQ)
919c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, MAXFREQ);
920c68996e2SPoul-Henning Kamp 	else if (u_nsec < -MAXFREQ)
921c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, -MAXFREQ);
92297804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSFREQ)
923c68996e2SPoul-Henning Kamp 		time_freq = pps_freq;
924364c516cSKonstantin Belousov 
925364c516cSKonstantin Belousov out:
9264493f659SKonstantin Belousov 	NTP_UNLOCK();
927c68996e2SPoul-Henning Kamp }
9286f70df15SPoul-Henning Kamp #endif /* PPS_SYNC */
929e1d970f1SPoul-Henning Kamp 
930e1d970f1SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
931e1d970f1SPoul-Henning Kamp struct adjtime_args {
932e1d970f1SPoul-Henning Kamp 	struct timeval *delta;
933e1d970f1SPoul-Henning Kamp 	struct timeval *olddelta;
934e1d970f1SPoul-Henning Kamp };
935e1d970f1SPoul-Henning Kamp #endif
936e1d970f1SPoul-Henning Kamp /* ARGSUSED */
937e1d970f1SPoul-Henning Kamp int
9388451d0ddSKip Macy sys_adjtime(struct thread *td, struct adjtime_args *uap)
939e1d970f1SPoul-Henning Kamp {
940b88ec951SJohn Baldwin 	struct timeval delta, olddelta, *deltap;
941b88ec951SJohn Baldwin 	int error;
942b88ec951SJohn Baldwin 
943b88ec951SJohn Baldwin 	if (uap->delta) {
944b88ec951SJohn Baldwin 		error = copyin(uap->delta, &delta, sizeof(delta));
945b88ec951SJohn Baldwin 		if (error)
946b88ec951SJohn Baldwin 			return (error);
947b88ec951SJohn Baldwin 		deltap = &delta;
948b88ec951SJohn Baldwin 	} else
949b88ec951SJohn Baldwin 		deltap = NULL;
950b88ec951SJohn Baldwin 	error = kern_adjtime(td, deltap, &olddelta);
951b88ec951SJohn Baldwin 	if (uap->olddelta && error == 0)
952b88ec951SJohn Baldwin 		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
953b88ec951SJohn Baldwin 	return (error);
954b88ec951SJohn Baldwin }
955b88ec951SJohn Baldwin 
956b88ec951SJohn Baldwin int
957b88ec951SJohn Baldwin kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
958b88ec951SJohn Baldwin {
959e1d970f1SPoul-Henning Kamp 	struct timeval atv;
960364c516cSKonstantin Belousov 	int64_t ltr, ltw;
961e1d970f1SPoul-Henning Kamp 	int error;
962e1d970f1SPoul-Henning Kamp 
963364c516cSKonstantin Belousov 	if (delta != NULL) {
964364c516cSKonstantin Belousov 		error = priv_check(td, PRIV_ADJTIME);
965364c516cSKonstantin Belousov 		if (error != 0)
966364c516cSKonstantin Belousov 			return (error);
967364c516cSKonstantin Belousov 		ltw = (int64_t)delta->tv_sec * 1000000 + delta->tv_usec;
968364c516cSKonstantin Belousov 	}
9694493f659SKonstantin Belousov 	NTP_LOCK();
970364c516cSKonstantin Belousov 	ltr = time_adjtime;
971364c516cSKonstantin Belousov 	if (delta != NULL)
972364c516cSKonstantin Belousov 		time_adjtime = ltw;
9734493f659SKonstantin Belousov 	NTP_UNLOCK();
974364c516cSKonstantin Belousov 	if (olddelta != NULL) {
975364c516cSKonstantin Belousov 		atv.tv_sec = ltr / 1000000;
976364c516cSKonstantin Belousov 		atv.tv_usec = ltr % 1000000;
977e1d970f1SPoul-Henning Kamp 		if (atv.tv_usec < 0) {
978e1d970f1SPoul-Henning Kamp 			atv.tv_usec += 1000000;
979e1d970f1SPoul-Henning Kamp 			atv.tv_sec--;
980e1d970f1SPoul-Henning Kamp 		}
981b88ec951SJohn Baldwin 		*olddelta = atv;
982e1d970f1SPoul-Henning Kamp 	}
983b4be6ef2SRobert Watson 	return (0);
984b4be6ef2SRobert Watson }
985e1d970f1SPoul-Henning Kamp 
9865c7e270fSAndriy Gapon static struct callout resettodr_callout;
9875c7e270fSAndriy Gapon static int resettodr_period = 1800;
9885c7e270fSAndriy Gapon 
9895c7e270fSAndriy Gapon static void
9905c7e270fSAndriy Gapon periodic_resettodr(void *arg __unused)
9915c7e270fSAndriy Gapon {
9925c7e270fSAndriy Gapon 
993364c516cSKonstantin Belousov 	/*
994364c516cSKonstantin Belousov 	 * Read of time_status is lock-less, which is fine since
995364c516cSKonstantin Belousov 	 * ntp_is_time_error() operates on the consistent read value.
996364c516cSKonstantin Belousov 	 */
997364c516cSKonstantin Belousov 	if (!ntp_is_time_error(time_status))
9985c7e270fSAndriy Gapon 		resettodr();
9995c7e270fSAndriy Gapon 	if (resettodr_period > 0)
10005c7e270fSAndriy Gapon 		callout_schedule(&resettodr_callout, resettodr_period * hz);
10015c7e270fSAndriy Gapon }
10025c7e270fSAndriy Gapon 
10035c7e270fSAndriy Gapon static void
10045c7e270fSAndriy Gapon shutdown_resettodr(void *arg __unused, int howto __unused)
10055c7e270fSAndriy Gapon {
10065c7e270fSAndriy Gapon 
10075c7e270fSAndriy Gapon 	callout_drain(&resettodr_callout);
1008364c516cSKonstantin Belousov 	/* Another unlocked read of time_status */
1009364c516cSKonstantin Belousov 	if (resettodr_period > 0 && !ntp_is_time_error(time_status))
10105c7e270fSAndriy Gapon 		resettodr();
10115c7e270fSAndriy Gapon }
10125c7e270fSAndriy Gapon 
10135c7e270fSAndriy Gapon static int
10145c7e270fSAndriy Gapon sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
10155c7e270fSAndriy Gapon {
10165c7e270fSAndriy Gapon 	int error;
10175c7e270fSAndriy Gapon 
10185c7e270fSAndriy Gapon 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
10195c7e270fSAndriy Gapon 	if (error || !req->newptr)
10205c7e270fSAndriy Gapon 		return (error);
1021af3b2549SHans Petter Selasky 	if (cold)
1022af3b2549SHans Petter Selasky 		goto done;
10235c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10245c7e270fSAndriy Gapon 		callout_stop(&resettodr_callout);
10255c7e270fSAndriy Gapon 	else
10265c7e270fSAndriy Gapon 		callout_reset(&resettodr_callout, resettodr_period * hz,
10275c7e270fSAndriy Gapon 		    periodic_resettodr, NULL);
1028af3b2549SHans Petter Selasky done:
10295c7e270fSAndriy Gapon 	return (0);
10305c7e270fSAndriy Gapon }
10315c7e270fSAndriy Gapon 
1032364c516cSKonstantin Belousov SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT | CTLFLAG_RWTUN |
1033364c516cSKonstantin Belousov     CTLFLAG_MPSAFE, &resettodr_period, 1800, sysctl_resettodr_period, "I",
10345c7e270fSAndriy Gapon     "Save system time to RTC with this period (in seconds)");
10355c7e270fSAndriy Gapon 
10365c7e270fSAndriy Gapon static void
10375c7e270fSAndriy Gapon start_periodic_resettodr(void *arg __unused)
10385c7e270fSAndriy Gapon {
10395c7e270fSAndriy Gapon 
10405c7e270fSAndriy Gapon 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
10415c7e270fSAndriy Gapon 	    SHUTDOWN_PRI_FIRST);
10425c7e270fSAndriy Gapon 	callout_init(&resettodr_callout, 1);
10435c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10445c7e270fSAndriy Gapon 		return;
10455c7e270fSAndriy Gapon 	callout_reset(&resettodr_callout, resettodr_period * hz,
10465c7e270fSAndriy Gapon 	    periodic_resettodr, NULL);
10475c7e270fSAndriy Gapon }
10485c7e270fSAndriy Gapon 
1049785797c3SAndriy Gapon SYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
10505c7e270fSAndriy Gapon 	start_periodic_resettodr, NULL);
1051