xref: /freebsd/sys/kern/kern_ntptime.c (revision 969fc29e0b811bf33c39d86e11eb2bb7b53a093d)
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) */
158*969fc29eSIan 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 
1653f31c649SGarrett Wollman #ifdef PPS_SYNC
1663f31c649SGarrett Wollman /*
167c68996e2SPoul-Henning Kamp  * The following variables are used when a pulse-per-second (PPS) signal
168c68996e2SPoul-Henning Kamp  * is available and connected via a modem control lead. They establish
169c68996e2SPoul-Henning Kamp  * the engineering parameters of the clock discipline loop when
170c68996e2SPoul-Henning Kamp  * controlled by the PPS signal.
1713f31c649SGarrett Wollman  */
172c68996e2SPoul-Henning Kamp #define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
17324dbea46SJohn Hay #define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
17482e84c5bSPoul-Henning Kamp #define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
175c68996e2SPoul-Henning Kamp #define PPS_PAVG	4		/* phase avg interval (s) (shift) */
176c68996e2SPoul-Henning Kamp #define PPS_VALID	120		/* PPS signal watchdog max (s) */
17782e84c5bSPoul-Henning Kamp #define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
17882e84c5bSPoul-Henning Kamp #define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
179c68996e2SPoul-Henning Kamp 
18082e84c5bSPoul-Henning Kamp static struct timespec pps_tf[3];	/* phase median filter */
181c68996e2SPoul-Henning Kamp static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
182f425c1f6SPoul-Henning Kamp static long pps_fcount;			/* frequency accumulator */
18382e84c5bSPoul-Henning Kamp static long pps_jitter;			/* nominal jitter (ns) */
18482e84c5bSPoul-Henning Kamp static long pps_stabil;			/* nominal stability (scaled ns/s) */
185c68996e2SPoul-Henning Kamp static long pps_lastsec;		/* time at last calibration (s) */
186c68996e2SPoul-Henning Kamp static int pps_valid;			/* signal watchdog counter */
187c68996e2SPoul-Henning Kamp static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
18882e84c5bSPoul-Henning Kamp static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
189c68996e2SPoul-Henning Kamp static int pps_intcnt;			/* wander counter */
1906f70df15SPoul-Henning Kamp 
1916f70df15SPoul-Henning Kamp /*
1926f70df15SPoul-Henning Kamp  * PPS signal quality monitors
1936f70df15SPoul-Henning Kamp  */
194c68996e2SPoul-Henning Kamp static long pps_calcnt;			/* calibration intervals */
195c68996e2SPoul-Henning Kamp static long pps_jitcnt;			/* jitter limit exceeded */
196c68996e2SPoul-Henning Kamp static long pps_stbcnt;			/* stability limit exceeded */
197c68996e2SPoul-Henning Kamp static long pps_errcnt;			/* calibration errors */
1983f31c649SGarrett Wollman #endif /* PPS_SYNC */
199c68996e2SPoul-Henning Kamp /*
200c68996e2SPoul-Henning Kamp  * End of phase/frequency-lock loop (PLL/FLL) definitions
201c68996e2SPoul-Henning Kamp  */
2023f31c649SGarrett Wollman 
203c68996e2SPoul-Henning Kamp static void ntp_init(void);
204c68996e2SPoul-Henning Kamp static void hardupdate(long offset);
205932cfd41SMark Santcroos static void ntp_gettime1(struct ntptimeval *ntvp);
2069a9ae42aSAndriy Gapon static int ntp_is_time_error(void);
207c68996e2SPoul-Henning Kamp 
2089a9ae42aSAndriy Gapon static int
2099a9ae42aSAndriy Gapon ntp_is_time_error(void)
210c68996e2SPoul-Henning Kamp {
211c68996e2SPoul-Henning Kamp 	/*
212c68996e2SPoul-Henning Kamp 	 * Status word error decode. If any of these conditions occur,
213c68996e2SPoul-Henning Kamp 	 * an error is returned, instead of the status word. Most
214c68996e2SPoul-Henning Kamp 	 * applications will care only about the fact the system clock
215c68996e2SPoul-Henning Kamp 	 * may not be trusted, not about the details.
216c68996e2SPoul-Henning Kamp 	 *
217c68996e2SPoul-Henning Kamp 	 * Hardware or software error
218c68996e2SPoul-Henning Kamp 	 */
219c68996e2SPoul-Henning Kamp 	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
220c68996e2SPoul-Henning Kamp 
221c68996e2SPoul-Henning Kamp 	/*
222c68996e2SPoul-Henning Kamp 	 * PPS signal lost when either time or frequency synchronization
223c68996e2SPoul-Henning Kamp 	 * requested
224c68996e2SPoul-Henning Kamp 	 */
225c68996e2SPoul-Henning Kamp 	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
226c68996e2SPoul-Henning Kamp 	    !(time_status & STA_PPSSIGNAL)) ||
227c68996e2SPoul-Henning Kamp 
228c68996e2SPoul-Henning Kamp 	/*
229c68996e2SPoul-Henning Kamp 	 * PPS jitter exceeded when time synchronization requested
230c68996e2SPoul-Henning Kamp 	 */
231c68996e2SPoul-Henning Kamp 	    (time_status & STA_PPSTIME &&
232c68996e2SPoul-Henning Kamp 	    time_status & STA_PPSJITTER) ||
233c68996e2SPoul-Henning Kamp 
234c68996e2SPoul-Henning Kamp 	/*
235c68996e2SPoul-Henning Kamp 	 * PPS wander exceeded or calibration error when frequency
236c68996e2SPoul-Henning Kamp 	 * synchronization requested
237c68996e2SPoul-Henning Kamp 	 */
238c68996e2SPoul-Henning Kamp 	    (time_status & STA_PPSFREQ &&
239c68996e2SPoul-Henning Kamp 	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
2409a9ae42aSAndriy Gapon 		return (1);
2419a9ae42aSAndriy Gapon 
2429a9ae42aSAndriy Gapon 	return (0);
2439a9ae42aSAndriy Gapon }
2449a9ae42aSAndriy Gapon 
2459a9ae42aSAndriy Gapon static void
2469a9ae42aSAndriy Gapon ntp_gettime1(struct ntptimeval *ntvp)
2479a9ae42aSAndriy Gapon {
2489a9ae42aSAndriy Gapon 	struct timespec atv;	/* nanosecond time */
2499a9ae42aSAndriy Gapon 
2509a9ae42aSAndriy Gapon 	GIANT_REQUIRED;
2519a9ae42aSAndriy Gapon 
2529a9ae42aSAndriy Gapon 	nanotime(&atv);
2539a9ae42aSAndriy Gapon 	ntvp->time.tv_sec = atv.tv_sec;
2549a9ae42aSAndriy Gapon 	ntvp->time.tv_nsec = atv.tv_nsec;
2559a9ae42aSAndriy Gapon 	ntvp->maxerror = time_maxerror;
2569a9ae42aSAndriy Gapon 	ntvp->esterror = time_esterror;
2579a9ae42aSAndriy Gapon 	ntvp->tai = time_tai;
2589a9ae42aSAndriy Gapon 	ntvp->time_state = time_state;
2599a9ae42aSAndriy Gapon 
2609a9ae42aSAndriy Gapon 	if (ntp_is_time_error())
261932cfd41SMark Santcroos 		ntvp->time_state = TIME_ERROR;
262932cfd41SMark Santcroos }
263932cfd41SMark Santcroos 
2649b7fe7e4SMark Santcroos /*
2659b7fe7e4SMark Santcroos  * ntp_gettime() - NTP user application interface
2669b7fe7e4SMark Santcroos  *
267873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
268873fbcd7SRobert Watson  * the TAI offset is returned in the ntvtimeval.tai structure member.
2699b7fe7e4SMark Santcroos  */
270932cfd41SMark Santcroos #ifndef _SYS_SYSPROTO_H_
271932cfd41SMark Santcroos struct ntp_gettime_args {
272932cfd41SMark Santcroos 	struct ntptimeval *ntvp;
273932cfd41SMark Santcroos };
274932cfd41SMark Santcroos #endif
275932cfd41SMark Santcroos /* ARGSUSED */
276932cfd41SMark Santcroos int
2778451d0ddSKip Macy sys_ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
278932cfd41SMark Santcroos {
279932cfd41SMark Santcroos 	struct ntptimeval ntv;
280932cfd41SMark Santcroos 
28175b82238SRobert Watson 	mtx_lock(&Giant);
282932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
28375b82238SRobert Watson 	mtx_unlock(&Giant);
284932cfd41SMark Santcroos 
285fe18f385SWarner Losh 	td->td_retval[0] = ntv.time_state;
286932cfd41SMark Santcroos 	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
287932cfd41SMark Santcroos }
288932cfd41SMark Santcroos 
289932cfd41SMark Santcroos static int
290932cfd41SMark Santcroos ntp_sysctl(SYSCTL_HANDLER_ARGS)
291932cfd41SMark Santcroos {
292932cfd41SMark Santcroos 	struct ntptimeval ntv;	/* temporary structure */
293932cfd41SMark Santcroos 
294932cfd41SMark Santcroos 	ntp_gettime1(&ntv);
295932cfd41SMark Santcroos 
296932cfd41SMark Santcroos 	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
297c68996e2SPoul-Henning Kamp }
298c68996e2SPoul-Henning Kamp 
299c68996e2SPoul-Henning Kamp SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
300c68996e2SPoul-Henning Kamp SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
301c68996e2SPoul-Henning Kamp 	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
302c68996e2SPoul-Henning Kamp 
3035968e18bSPoul-Henning Kamp #ifdef PPS_SYNC
3043eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
3053eb9ab52SEitan Adler     &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
3063eb9ab52SEitan Adler SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
3073eb9ab52SEitan Adler     &pps_shift, 0, "Interval duration (sec) (shift)");
308240577c2SMatthew D Fleming SYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
3093eb9ab52SEitan Adler     &time_monitor, 0, "Last time offset scaled (ns)");
3107fd299cbSPoul-Henning Kamp 
3113eb9ab52SEitan Adler SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD,
3123eb9ab52SEitan Adler     &pps_freq, sizeof(pps_freq), "I", "Scaled frequency offset (ns/sec)");
3133eb9ab52SEitan Adler SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD,
3143eb9ab52SEitan Adler     &time_freq, sizeof(time_freq), "I", "Frequency offset (ns/sec)");
3155968e18bSPoul-Henning Kamp #endif
316873fbcd7SRobert Watson 
317c68996e2SPoul-Henning Kamp /*
318c68996e2SPoul-Henning Kamp  * ntp_adjtime() - NTP daemon application interface
319c68996e2SPoul-Henning Kamp  *
320873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
321873fbcd7SRobert Watson  * the timex.constant structure member has a dual purpose to set the time
322873fbcd7SRobert Watson  * constant and to set the TAI offset.
323c68996e2SPoul-Henning Kamp  */
324c68996e2SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
325c68996e2SPoul-Henning Kamp struct ntp_adjtime_args {
326c68996e2SPoul-Henning Kamp 	struct timex *tp;
327c68996e2SPoul-Henning Kamp };
328c68996e2SPoul-Henning Kamp #endif
329c68996e2SPoul-Henning Kamp 
330c68996e2SPoul-Henning Kamp int
3318451d0ddSKip Macy sys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
332c68996e2SPoul-Henning Kamp {
333c68996e2SPoul-Henning Kamp 	struct timex ntv;	/* temporary structure */
334f425c1f6SPoul-Henning Kamp 	long freq;		/* frequency ns/s) */
335c68996e2SPoul-Henning Kamp 	int modes;		/* mode bits from structure */
336c68996e2SPoul-Henning Kamp 	int s;			/* caller priority */
337c68996e2SPoul-Henning Kamp 	int error;
338c68996e2SPoul-Henning Kamp 
339c68996e2SPoul-Henning Kamp 	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
340c68996e2SPoul-Henning Kamp 	if (error)
341c68996e2SPoul-Henning Kamp 		return(error);
342c68996e2SPoul-Henning Kamp 
343c68996e2SPoul-Henning Kamp 	/*
344c68996e2SPoul-Henning Kamp 	 * Update selected clock variables - only the superuser can
345c68996e2SPoul-Henning Kamp 	 * change anything. Note that there is no error checking here on
346c68996e2SPoul-Henning Kamp 	 * the assumption the superuser should know what it is doing.
34797804a5cSPoul-Henning Kamp 	 * Note that either the time constant or TAI offset are loaded
34824dbea46SJohn Hay 	 * from the ntv.constant member, depending on the mode bits. If
34924dbea46SJohn Hay 	 * the STA_PLL bit in the status word is cleared, the state and
35024dbea46SJohn Hay 	 * status words are reset to the initial values at boot.
351c68996e2SPoul-Henning Kamp 	 */
3526f1e8c18SMatthew Dillon 	mtx_lock(&Giant);
353c68996e2SPoul-Henning Kamp 	modes = ntv.modes;
354fafbe352SPoul-Henning Kamp 	if (modes)
355acd3428bSRobert Watson 		error = priv_check(td, PRIV_NTP_ADJTIME);
356c68996e2SPoul-Henning Kamp 	if (error)
3576f1e8c18SMatthew Dillon 		goto done2;
358c68996e2SPoul-Henning Kamp 	s = splclock();
359c68996e2SPoul-Henning Kamp 	if (modes & MOD_MAXERROR)
360c68996e2SPoul-Henning Kamp 		time_maxerror = ntv.maxerror;
361c68996e2SPoul-Henning Kamp 	if (modes & MOD_ESTERROR)
362c68996e2SPoul-Henning Kamp 		time_esterror = ntv.esterror;
363c68996e2SPoul-Henning Kamp 	if (modes & MOD_STATUS) {
36424dbea46SJohn Hay 		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
36524dbea46SJohn Hay 			time_state = TIME_OK;
36624dbea46SJohn Hay 			time_status = STA_UNSYNC;
36724dbea46SJohn Hay #ifdef PPS_SYNC
36824dbea46SJohn Hay 			pps_shift = PPS_FAVG;
36924dbea46SJohn Hay #endif /* PPS_SYNC */
37024dbea46SJohn Hay 		}
371c68996e2SPoul-Henning Kamp 		time_status &= STA_RONLY;
372c68996e2SPoul-Henning Kamp 		time_status |= ntv.status & ~STA_RONLY;
373c68996e2SPoul-Henning Kamp 	}
374f425c1f6SPoul-Henning Kamp 	if (modes & MOD_TIMECONST) {
375f425c1f6SPoul-Henning Kamp 		if (ntv.constant < 0)
376f425c1f6SPoul-Henning Kamp 			time_constant = 0;
377f425c1f6SPoul-Henning Kamp 		else if (ntv.constant > MAXTC)
378f425c1f6SPoul-Henning Kamp 			time_constant = MAXTC;
379f425c1f6SPoul-Henning Kamp 		else
380c68996e2SPoul-Henning Kamp 			time_constant = ntv.constant;
381f425c1f6SPoul-Henning Kamp 	}
38297804a5cSPoul-Henning Kamp 	if (modes & MOD_TAI) {
38397804a5cSPoul-Henning Kamp 		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
38497804a5cSPoul-Henning Kamp 			time_tai = ntv.constant;
38597804a5cSPoul-Henning Kamp 	}
38682e84c5bSPoul-Henning Kamp #ifdef PPS_SYNC
38782e84c5bSPoul-Henning Kamp 	if (modes & MOD_PPSMAX) {
38882e84c5bSPoul-Henning Kamp 		if (ntv.shift < PPS_FAVG)
38982e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVG;
39082e84c5bSPoul-Henning Kamp 		else if (ntv.shift > PPS_FAVGMAX)
39182e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVGMAX;
39282e84c5bSPoul-Henning Kamp 		else
39382e84c5bSPoul-Henning Kamp 			pps_shiftmax = ntv.shift;
39482e84c5bSPoul-Henning Kamp 	}
39582e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
396c68996e2SPoul-Henning Kamp 	if (modes & MOD_NANO)
397c68996e2SPoul-Henning Kamp 		time_status |= STA_NANO;
398c68996e2SPoul-Henning Kamp 	if (modes & MOD_MICRO)
399c68996e2SPoul-Henning Kamp 		time_status &= ~STA_NANO;
400c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKB)
401c68996e2SPoul-Henning Kamp 		time_status |= STA_CLK;
402c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKA)
403c68996e2SPoul-Henning Kamp 		time_status &= ~STA_CLK;
40424dbea46SJohn Hay 	if (modes & MOD_FREQUENCY) {
40524dbea46SJohn Hay 		freq = (ntv.freq * 1000LL) >> 16;
40624dbea46SJohn Hay 		if (freq > MAXFREQ)
40724dbea46SJohn Hay 			L_LINT(time_freq, MAXFREQ);
40824dbea46SJohn Hay 		else if (freq < -MAXFREQ)
40924dbea46SJohn Hay 			L_LINT(time_freq, -MAXFREQ);
410bcfe6d8bSPoul-Henning Kamp 		else {
411bcfe6d8bSPoul-Henning Kamp 			/*
412bcfe6d8bSPoul-Henning Kamp 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
413bcfe6d8bSPoul-Henning Kamp 			 * time_freq is [ns/s * 2^32]
414bcfe6d8bSPoul-Henning Kamp 			 */
415bcfe6d8bSPoul-Henning Kamp 			time_freq = ntv.freq * 1000LL * 65536LL;
416bcfe6d8bSPoul-Henning Kamp 		}
41724dbea46SJohn Hay #ifdef PPS_SYNC
41824dbea46SJohn Hay 		pps_freq = time_freq;
41924dbea46SJohn Hay #endif /* PPS_SYNC */
42024dbea46SJohn Hay 	}
421551260fcSPoul-Henning Kamp 	if (modes & MOD_OFFSET) {
422551260fcSPoul-Henning Kamp 		if (time_status & STA_NANO)
423551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset);
424551260fcSPoul-Henning Kamp 		else
425551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset * 1000);
426551260fcSPoul-Henning Kamp 	}
427c68996e2SPoul-Henning Kamp 
428c68996e2SPoul-Henning Kamp 	/*
42997804a5cSPoul-Henning Kamp 	 * Retrieve all clock variables. Note that the TAI offset is
43097804a5cSPoul-Henning Kamp 	 * returned only by ntp_gettime();
431c68996e2SPoul-Henning Kamp 	 */
432c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
433b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset);
434c68996e2SPoul-Henning Kamp 	else
435b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
43634cffbe3SPoul-Henning Kamp 	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
437c68996e2SPoul-Henning Kamp 	ntv.maxerror = time_maxerror;
438c68996e2SPoul-Henning Kamp 	ntv.esterror = time_esterror;
439c68996e2SPoul-Henning Kamp 	ntv.status = time_status;
440f425c1f6SPoul-Henning Kamp 	ntv.constant = time_constant;
441c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
442c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision;
443c68996e2SPoul-Henning Kamp 	else
444c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision / 1000;
445c68996e2SPoul-Henning Kamp 	ntv.tolerance = MAXFREQ * SCALE_PPM;
446c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
447c68996e2SPoul-Henning Kamp 	ntv.shift = pps_shift;
44834cffbe3SPoul-Henning Kamp 	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
449c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
450c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter;
451c68996e2SPoul-Henning Kamp 	else
452c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter / 1000;
453c68996e2SPoul-Henning Kamp 	ntv.stabil = pps_stabil;
454c68996e2SPoul-Henning Kamp 	ntv.calcnt = pps_calcnt;
455c68996e2SPoul-Henning Kamp 	ntv.errcnt = pps_errcnt;
456c68996e2SPoul-Henning Kamp 	ntv.jitcnt = pps_jitcnt;
457c68996e2SPoul-Henning Kamp 	ntv.stbcnt = pps_stbcnt;
458c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
459c68996e2SPoul-Henning Kamp 	splx(s);
460c68996e2SPoul-Henning Kamp 
461c68996e2SPoul-Henning Kamp 	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
462c68996e2SPoul-Henning Kamp 	if (error)
4636f1e8c18SMatthew Dillon 		goto done2;
464c68996e2SPoul-Henning Kamp 
4659a9ae42aSAndriy Gapon 	if (ntp_is_time_error())
466b40ce416SJulian Elischer 		td->td_retval[0] = TIME_ERROR;
4679a9ae42aSAndriy Gapon 	else
468b40ce416SJulian Elischer 		td->td_retval[0] = time_state;
4699a9ae42aSAndriy Gapon 
4706f1e8c18SMatthew Dillon done2:
4716f1e8c18SMatthew Dillon 	mtx_unlock(&Giant);
472a5088017SPoul-Henning Kamp 	return (error);
473c68996e2SPoul-Henning Kamp }
474c68996e2SPoul-Henning Kamp 
475c68996e2SPoul-Henning Kamp /*
476c68996e2SPoul-Henning Kamp  * second_overflow() - called after ntp_tick_adjust()
477c68996e2SPoul-Henning Kamp  *
478c68996e2SPoul-Henning Kamp  * This routine is ordinarily called immediately following the above
479c68996e2SPoul-Henning Kamp  * routine ntp_tick_adjust(). While these two routines are normally
480c68996e2SPoul-Henning Kamp  * combined, they are separated here only for the purposes of
481c68996e2SPoul-Henning Kamp  * simulation.
482c68996e2SPoul-Henning Kamp  */
483c68996e2SPoul-Henning Kamp void
484b4a1d0deSPoul-Henning Kamp ntp_update_second(int64_t *adjustment, time_t *newsec)
485c68996e2SPoul-Henning Kamp {
486e1d970f1SPoul-Henning Kamp 	int tickrate;
48797804a5cSPoul-Henning Kamp 	l_fp ftemp;		/* 32/64-bit temporary */
488c68996e2SPoul-Henning Kamp 
48982e84c5bSPoul-Henning Kamp 	/*
49082e84c5bSPoul-Henning Kamp 	 * On rollover of the second both the nanosecond and microsecond
49182e84c5bSPoul-Henning Kamp 	 * clocks are updated and the state machine cranked as
49282e84c5bSPoul-Henning Kamp 	 * necessary. The phase adjustment to be used for the next
49382e84c5bSPoul-Henning Kamp 	 * second is calculated and the maximum error is increased by
49482e84c5bSPoul-Henning Kamp 	 * the tolerance.
49582e84c5bSPoul-Henning Kamp 	 */
496c68996e2SPoul-Henning Kamp 	time_maxerror += MAXFREQ / 1000;
497c68996e2SPoul-Henning Kamp 
498c68996e2SPoul-Henning Kamp 	/*
499c68996e2SPoul-Henning Kamp 	 * Leap second processing. If in leap-insert state at
500c68996e2SPoul-Henning Kamp 	 * the end of the day, the system clock is set back one
501c68996e2SPoul-Henning Kamp 	 * second; if in leap-delete state, the system clock is
502c68996e2SPoul-Henning Kamp 	 * set ahead one second. The nano_time() routine or
503c68996e2SPoul-Henning Kamp 	 * external clock driver will insure that reported time
504c68996e2SPoul-Henning Kamp 	 * is always monotonic.
505c68996e2SPoul-Henning Kamp 	 */
506c68996e2SPoul-Henning Kamp 	switch (time_state) {
507c68996e2SPoul-Henning Kamp 
508c68996e2SPoul-Henning Kamp 		/*
509c68996e2SPoul-Henning Kamp 		 * No warning.
510c68996e2SPoul-Henning Kamp 		 */
511c68996e2SPoul-Henning Kamp 		case TIME_OK:
512c68996e2SPoul-Henning Kamp 		if (time_status & STA_INS)
513c68996e2SPoul-Henning Kamp 			time_state = TIME_INS;
514c68996e2SPoul-Henning Kamp 		else if (time_status & STA_DEL)
515c68996e2SPoul-Henning Kamp 			time_state = TIME_DEL;
516c68996e2SPoul-Henning Kamp 		break;
517c68996e2SPoul-Henning Kamp 
518c68996e2SPoul-Henning Kamp 		/*
519c68996e2SPoul-Henning Kamp 		 * Insert second 23:59:60 following second
520c68996e2SPoul-Henning Kamp 		 * 23:59:59.
521c68996e2SPoul-Henning Kamp 		 */
522c68996e2SPoul-Henning Kamp 		case TIME_INS:
523c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_INS))
524c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
525c68996e2SPoul-Henning Kamp 		else if ((*newsec) % 86400 == 0) {
526c68996e2SPoul-Henning Kamp 			(*newsec)--;
527c68996e2SPoul-Henning Kamp 			time_state = TIME_OOP;
528eac3c62bSWarner Losh 			time_tai++;
529c68996e2SPoul-Henning Kamp 		}
530c68996e2SPoul-Henning Kamp 		break;
531c68996e2SPoul-Henning Kamp 
532c68996e2SPoul-Henning Kamp 		/*
533c68996e2SPoul-Henning Kamp 		 * Delete second 23:59:59.
534c68996e2SPoul-Henning Kamp 		 */
535c68996e2SPoul-Henning Kamp 		case TIME_DEL:
536c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_DEL))
537c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
538c68996e2SPoul-Henning Kamp 		else if (((*newsec) + 1) % 86400 == 0) {
539c68996e2SPoul-Henning Kamp 			(*newsec)++;
54097804a5cSPoul-Henning Kamp 			time_tai--;
541c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
542c68996e2SPoul-Henning Kamp 		}
543c68996e2SPoul-Henning Kamp 		break;
544c68996e2SPoul-Henning Kamp 
545c68996e2SPoul-Henning Kamp 		/*
546c68996e2SPoul-Henning Kamp 		 * Insert second in progress.
547c68996e2SPoul-Henning Kamp 		 */
548c68996e2SPoul-Henning Kamp 		case TIME_OOP:
549c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
550c68996e2SPoul-Henning Kamp 		break;
551c68996e2SPoul-Henning Kamp 
552c68996e2SPoul-Henning Kamp 		/*
553c68996e2SPoul-Henning Kamp 		 * Wait for status bits to clear.
554c68996e2SPoul-Henning Kamp 		 */
555c68996e2SPoul-Henning Kamp 		case TIME_WAIT:
556c68996e2SPoul-Henning Kamp 		if (!(time_status & (STA_INS | STA_DEL)))
557c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
558c68996e2SPoul-Henning Kamp 	}
559c68996e2SPoul-Henning Kamp 
560c68996e2SPoul-Henning Kamp 	/*
56182e84c5bSPoul-Henning Kamp 	 * Compute the total time adjustment for the next second
56282e84c5bSPoul-Henning Kamp 	 * in ns. The offset is reduced by a factor depending on
56382e84c5bSPoul-Henning Kamp 	 * whether the PPS signal is operating. Note that the
56482e84c5bSPoul-Henning Kamp 	 * value is in effect scaled by the clock frequency,
56582e84c5bSPoul-Henning Kamp 	 * since the adjustment is added at each tick interrupt.
566c68996e2SPoul-Henning Kamp 	 */
56797804a5cSPoul-Henning Kamp 	ftemp = time_offset;
568c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
56997804a5cSPoul-Henning Kamp 	/* XXX even if PPS signal dies we should finish adjustment ? */
57097804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSTIME && time_status &
57197804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)
57297804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, pps_shift);
57397804a5cSPoul-Henning Kamp 	else
57497804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57582e84c5bSPoul-Henning Kamp #else
57697804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57782e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
57897804a5cSPoul-Henning Kamp 	time_adj = ftemp;
57997804a5cSPoul-Henning Kamp 	L_SUB(time_offset, ftemp);
580c68996e2SPoul-Henning Kamp 	L_ADD(time_adj, time_freq);
581e1d970f1SPoul-Henning Kamp 
582e1d970f1SPoul-Henning Kamp 	/*
583e1d970f1SPoul-Henning Kamp 	 * Apply any correction from adjtime(2).  If more than one second
584e1d970f1SPoul-Henning Kamp 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
585e1d970f1SPoul-Henning Kamp 	 * until the last second is slewed the final < 500 usecs.
586e1d970f1SPoul-Henning Kamp 	 */
587e1d970f1SPoul-Henning Kamp 	if (time_adjtime != 0) {
588e1d970f1SPoul-Henning Kamp 		if (time_adjtime > 1000000)
589e1d970f1SPoul-Henning Kamp 			tickrate = 5000;
590e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -1000000)
591e1d970f1SPoul-Henning Kamp 			tickrate = -5000;
592e1d970f1SPoul-Henning Kamp 		else if (time_adjtime > 500)
593e1d970f1SPoul-Henning Kamp 			tickrate = 500;
594e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -500)
595e1d970f1SPoul-Henning Kamp 			tickrate = -500;
596e1d970f1SPoul-Henning Kamp 		else
597bcfe6d8bSPoul-Henning Kamp 			tickrate = time_adjtime;
598e1d970f1SPoul-Henning Kamp 		time_adjtime -= tickrate;
599e1d970f1SPoul-Henning Kamp 		L_LINT(ftemp, tickrate * 1000);
600e1d970f1SPoul-Henning Kamp 		L_ADD(time_adj, ftemp);
601e1d970f1SPoul-Henning Kamp 	}
602b4a1d0deSPoul-Henning Kamp 	*adjustment = time_adj;
603e1d970f1SPoul-Henning Kamp 
604c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
605c68996e2SPoul-Henning Kamp 	if (pps_valid > 0)
606c68996e2SPoul-Henning Kamp 		pps_valid--;
607c68996e2SPoul-Henning Kamp 	else
60824dbea46SJohn Hay 		time_status &= ~STA_PPSSIGNAL;
609c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
610c68996e2SPoul-Henning Kamp }
611c68996e2SPoul-Henning Kamp 
612c68996e2SPoul-Henning Kamp /*
613c68996e2SPoul-Henning Kamp  * ntp_init() - initialize variables and structures
614c68996e2SPoul-Henning Kamp  *
615c68996e2SPoul-Henning Kamp  * This routine must be called after the kernel variables hz and tick
616c68996e2SPoul-Henning Kamp  * are set or changed and before the next tick interrupt. In this
617c68996e2SPoul-Henning Kamp  * particular implementation, these values are assumed set elsewhere in
618c68996e2SPoul-Henning Kamp  * the kernel. The design allows the clock frequency and tick interval
619c68996e2SPoul-Henning Kamp  * to be changed while the system is running. So, this routine should
620c68996e2SPoul-Henning Kamp  * probably be integrated with the code that does that.
621c68996e2SPoul-Henning Kamp  */
622c68996e2SPoul-Henning Kamp static void
623c68996e2SPoul-Henning Kamp ntp_init()
624c68996e2SPoul-Henning Kamp {
625c68996e2SPoul-Henning Kamp 
626c68996e2SPoul-Henning Kamp 	/*
627c68996e2SPoul-Henning Kamp 	 * The following variables are initialized only at startup. Only
628c68996e2SPoul-Henning Kamp 	 * those structures not cleared by the compiler need to be
629c68996e2SPoul-Henning Kamp 	 * initialized, and these only in the simulator. In the actual
630c68996e2SPoul-Henning Kamp 	 * kernel, any nonzero values here will quickly evaporate.
631c68996e2SPoul-Henning Kamp 	 */
632c68996e2SPoul-Henning Kamp 	L_CLR(time_offset);
633c68996e2SPoul-Henning Kamp 	L_CLR(time_freq);
634c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
63582e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
63682e84c5bSPoul-Henning Kamp 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
63782e84c5bSPoul-Henning Kamp 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
638f425c1f6SPoul-Henning Kamp 	pps_fcount = 0;
639c68996e2SPoul-Henning Kamp 	L_CLR(pps_freq);
640c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
641c68996e2SPoul-Henning Kamp }
642c68996e2SPoul-Henning Kamp 
643237fdd78SRobert Watson SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
6446f70df15SPoul-Henning Kamp 
6456f70df15SPoul-Henning Kamp /*
6466f70df15SPoul-Henning Kamp  * hardupdate() - local clock update
6476f70df15SPoul-Henning Kamp  *
6486f70df15SPoul-Henning Kamp  * This routine is called by ntp_adjtime() to update the local clock
6496f70df15SPoul-Henning Kamp  * phase and frequency. The implementation is of an adaptive-parameter,
6506f70df15SPoul-Henning Kamp  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
6516f70df15SPoul-Henning Kamp  * time and frequency offset estimates for each call. If the kernel PPS
6526f70df15SPoul-Henning Kamp  * discipline code is configured (PPS_SYNC), the PPS signal itself
6536f70df15SPoul-Henning Kamp  * determines the new time offset, instead of the calling argument.
6546f70df15SPoul-Henning Kamp  * Presumably, calls to ntp_adjtime() occur only when the caller
6556f70df15SPoul-Henning Kamp  * believes the local clock is valid within some bound (+-128 ms with
6566f70df15SPoul-Henning Kamp  * NTP). If the caller's time is far different than the PPS time, an
6576f70df15SPoul-Henning Kamp  * argument will ensue, and it's not clear who will lose.
6586f70df15SPoul-Henning Kamp  *
659c68996e2SPoul-Henning Kamp  * For uncompensated quartz crystal oscillators and nominal update
660c68996e2SPoul-Henning Kamp  * intervals less than 256 s, operation should be in phase-lock mode,
661c68996e2SPoul-Henning Kamp  * where the loop is disciplined to phase. For update intervals greater
662c68996e2SPoul-Henning Kamp  * than 1024 s, operation should be in frequency-lock mode, where the
663c68996e2SPoul-Henning Kamp  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
664c68996e2SPoul-Henning Kamp  * is selected by the STA_MODE status bit.
6656f70df15SPoul-Henning Kamp  */
6666f70df15SPoul-Henning Kamp static void
667c68996e2SPoul-Henning Kamp hardupdate(offset)
668c68996e2SPoul-Henning Kamp 	long offset;		/* clock offset (ns) */
6696f70df15SPoul-Henning Kamp {
67097804a5cSPoul-Henning Kamp 	long mtemp;
671c68996e2SPoul-Henning Kamp 	l_fp ftemp;
6726f70df15SPoul-Henning Kamp 
673c68996e2SPoul-Henning Kamp 	/*
674c68996e2SPoul-Henning Kamp 	 * Select how the phase is to be controlled and from which
675c68996e2SPoul-Henning Kamp 	 * source. If the PPS signal is present and enabled to
676c68996e2SPoul-Henning Kamp 	 * discipline the time, the PPS offset is used; otherwise, the
677c68996e2SPoul-Henning Kamp 	 * argument offset is used.
678c68996e2SPoul-Henning Kamp 	 */
67982e84c5bSPoul-Henning Kamp 	if (!(time_status & STA_PLL))
68082e84c5bSPoul-Henning Kamp 		return;
68197804a5cSPoul-Henning Kamp 	if (!(time_status & STA_PPSTIME && time_status &
68297804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)) {
68397804a5cSPoul-Henning Kamp 		if (offset > MAXPHASE)
68497804a5cSPoul-Henning Kamp 			time_monitor = MAXPHASE;
68597804a5cSPoul-Henning Kamp 		else if (offset < -MAXPHASE)
68697804a5cSPoul-Henning Kamp 			time_monitor = -MAXPHASE;
68797804a5cSPoul-Henning Kamp 		else
68897804a5cSPoul-Henning Kamp 			time_monitor = offset;
68997804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
69097804a5cSPoul-Henning Kamp 	}
6916f70df15SPoul-Henning Kamp 
6926f70df15SPoul-Henning Kamp 	/*
693c68996e2SPoul-Henning Kamp 	 * Select how the frequency is to be controlled and in which
694c68996e2SPoul-Henning Kamp 	 * mode (PLL or FLL). If the PPS signal is present and enabled
695c68996e2SPoul-Henning Kamp 	 * to discipline the frequency, the PPS frequency is used;
696c68996e2SPoul-Henning Kamp 	 * otherwise, the argument offset is used to compute it.
6976f70df15SPoul-Henning Kamp 	 */
698c68996e2SPoul-Henning Kamp 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
699*969fc29eSIan Lepore 		time_reftime = time_uptime;
700c68996e2SPoul-Henning Kamp 		return;
701c68996e2SPoul-Henning Kamp 	}
7026f70df15SPoul-Henning Kamp 	if (time_status & STA_FREQHOLD || time_reftime == 0)
703*969fc29eSIan Lepore 		time_reftime = time_uptime;
704*969fc29eSIan Lepore 	mtemp = time_uptime - time_reftime;
70597804a5cSPoul-Henning Kamp 	L_LINT(ftemp, time_monitor);
706c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
707c68996e2SPoul-Henning Kamp 	L_MPY(ftemp, mtemp);
708c68996e2SPoul-Henning Kamp 	L_ADD(time_freq, ftemp);
709c68996e2SPoul-Henning Kamp 	time_status &= ~STA_MODE;
71097804a5cSPoul-Henning Kamp 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
71197804a5cSPoul-Henning Kamp 	    MAXSEC)) {
71297804a5cSPoul-Henning Kamp 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
71382e84c5bSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
71482e84c5bSPoul-Henning Kamp 		L_ADD(time_freq, ftemp);
71582e84c5bSPoul-Henning Kamp 		time_status |= STA_MODE;
716c68996e2SPoul-Henning Kamp 	}
717*969fc29eSIan Lepore 	time_reftime = time_uptime;
718c68996e2SPoul-Henning Kamp 	if (L_GINT(time_freq) > MAXFREQ)
719c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, MAXFREQ);
720c68996e2SPoul-Henning Kamp 	else if (L_GINT(time_freq) < -MAXFREQ)
721c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, -MAXFREQ);
7223f31c649SGarrett Wollman }
7233f31c649SGarrett Wollman 
7246f70df15SPoul-Henning Kamp #ifdef PPS_SYNC
7256f70df15SPoul-Henning Kamp /*
7266f70df15SPoul-Henning Kamp  * hardpps() - discipline CPU clock oscillator to external PPS signal
7276f70df15SPoul-Henning Kamp  *
7286f70df15SPoul-Henning Kamp  * This routine is called at each PPS interrupt in order to discipline
72997804a5cSPoul-Henning Kamp  * the CPU clock oscillator to the PPS signal. There are two independent
73097804a5cSPoul-Henning Kamp  * first-order feedback loops, one for the phase, the other for the
73197804a5cSPoul-Henning Kamp  * frequency. The phase loop measures and grooms the PPS phase offset
73297804a5cSPoul-Henning Kamp  * and leaves it in a handy spot for the seconds overflow routine. The
73397804a5cSPoul-Henning Kamp  * frequency loop averages successive PPS phase differences and
73497804a5cSPoul-Henning Kamp  * calculates the PPS frequency offset, which is also processed by the
73597804a5cSPoul-Henning Kamp  * seconds overflow routine. The code requires the caller to capture the
73697804a5cSPoul-Henning Kamp  * time and architecture-dependent hardware counter values in
73797804a5cSPoul-Henning Kamp  * nanoseconds at the on-time PPS signal transition.
7386f70df15SPoul-Henning Kamp  *
739c68996e2SPoul-Henning Kamp  * Note that, on some Unix systems this routine runs at an interrupt
7406f70df15SPoul-Henning Kamp  * priority level higher than the timer interrupt routine hardclock().
7416f70df15SPoul-Henning Kamp  * Therefore, the variables used are distinct from the hardclock()
742c68996e2SPoul-Henning Kamp  * variables, except for the actual time and frequency variables, which
743c68996e2SPoul-Henning Kamp  * are determined by this routine and updated atomically.
7446f70df15SPoul-Henning Kamp  */
7456f70df15SPoul-Henning Kamp void
746c68996e2SPoul-Henning Kamp hardpps(tsp, nsec)
747c68996e2SPoul-Henning Kamp 	struct timespec *tsp;	/* time at PPS */
748c68996e2SPoul-Henning Kamp 	long nsec;		/* hardware counter at PPS */
7496f70df15SPoul-Henning Kamp {
75097804a5cSPoul-Henning Kamp 	long u_sec, u_nsec, v_nsec; /* temps */
751c68996e2SPoul-Henning Kamp 	l_fp ftemp;
7526f70df15SPoul-Henning Kamp 
7536f70df15SPoul-Henning Kamp 	/*
75497804a5cSPoul-Henning Kamp 	 * The signal is first processed by a range gate and frequency
75597804a5cSPoul-Henning Kamp 	 * discriminator. The range gate rejects noise spikes outside
75697804a5cSPoul-Henning Kamp 	 * the range +-500 us. The frequency discriminator rejects input
75797804a5cSPoul-Henning Kamp 	 * signals with apparent frequency outside the range 1 +-500
75897804a5cSPoul-Henning Kamp 	 * PPM. If two hits occur in the same second, we ignore the
75997804a5cSPoul-Henning Kamp 	 * later hit; if not and a hit occurs outside the range gate,
76097804a5cSPoul-Henning Kamp 	 * keep the later hit for later comparison, but do not process
76197804a5cSPoul-Henning Kamp 	 * it.
7626f70df15SPoul-Henning Kamp 	 */
763c68996e2SPoul-Henning Kamp 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
764c68996e2SPoul-Henning Kamp 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
765c68996e2SPoul-Henning Kamp 	pps_valid = PPS_VALID;
766c68996e2SPoul-Henning Kamp 	u_sec = tsp->tv_sec;
767c68996e2SPoul-Henning Kamp 	u_nsec = tsp->tv_nsec;
768c68996e2SPoul-Henning Kamp 	if (u_nsec >= (NANOSECOND >> 1)) {
769c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
770c68996e2SPoul-Henning Kamp 		u_sec++;
7716f70df15SPoul-Henning Kamp 	}
77282e84c5bSPoul-Henning Kamp 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
77324dbea46SJohn Hay 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
77424dbea46SJohn Hay 	    MAXFREQ)
775c68996e2SPoul-Henning Kamp 		return;
776c68996e2SPoul-Henning Kamp 	pps_tf[2] = pps_tf[1];
777c68996e2SPoul-Henning Kamp 	pps_tf[1] = pps_tf[0];
77882e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = u_sec;
77982e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_nsec = u_nsec;
7806f70df15SPoul-Henning Kamp 
7816f70df15SPoul-Henning Kamp 	/*
782c68996e2SPoul-Henning Kamp 	 * Compute the difference between the current and previous
783c68996e2SPoul-Henning Kamp 	 * counter values. If the difference exceeds 0.5 s, assume it
784c68996e2SPoul-Henning Kamp 	 * has wrapped around, so correct 1.0 s. If the result exceeds
785c68996e2SPoul-Henning Kamp 	 * the tick interval, the sample point has crossed a tick
786c68996e2SPoul-Henning Kamp 	 * boundary during the last second, so correct the tick. Very
787c68996e2SPoul-Henning Kamp 	 * intricate.
788c68996e2SPoul-Henning Kamp 	 */
78932c20357SPoul-Henning Kamp 	u_nsec = nsec;
790c68996e2SPoul-Henning Kamp 	if (u_nsec > (NANOSECOND >> 1))
791c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
792c68996e2SPoul-Henning Kamp 	else if (u_nsec < -(NANOSECOND >> 1))
793c68996e2SPoul-Henning Kamp 		u_nsec += NANOSECOND;
794884ab557SPoul-Henning Kamp 	pps_fcount += u_nsec;
79524dbea46SJohn Hay 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
796c68996e2SPoul-Henning Kamp 		return;
797c68996e2SPoul-Henning Kamp 	time_status &= ~STA_PPSJITTER;
798c68996e2SPoul-Henning Kamp 
799c68996e2SPoul-Henning Kamp 	/*
800c68996e2SPoul-Henning Kamp 	 * A three-stage median filter is used to help denoise the PPS
8016f70df15SPoul-Henning Kamp 	 * time. The median sample becomes the time offset estimate; the
8026f70df15SPoul-Henning Kamp 	 * difference between the other two samples becomes the time
8036f70df15SPoul-Henning Kamp 	 * dispersion (jitter) estimate.
8046f70df15SPoul-Henning Kamp 	 */
80582e84c5bSPoul-Henning Kamp 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
80682e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
80782e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
80882e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
80982e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
81082e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
81182e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
8126f70df15SPoul-Henning Kamp 		} else {
81382e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
81482e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
815c68996e2SPoul-Henning Kamp 		}
816c68996e2SPoul-Henning Kamp 	} else {
81782e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
81882e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
81982e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
82082e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
82182e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
82282e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
823c68996e2SPoul-Henning Kamp 		} else {
82482e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
82582e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
8266f70df15SPoul-Henning Kamp 		}
8276f70df15SPoul-Henning Kamp 	}
8286f70df15SPoul-Henning Kamp 
8296f70df15SPoul-Henning Kamp 	/*
830c68996e2SPoul-Henning Kamp 	 * Nominal jitter is due to PPS signal noise and interrupt
83197804a5cSPoul-Henning Kamp 	 * latency. If it exceeds the popcorn threshold, the sample is
83297804a5cSPoul-Henning Kamp 	 * discarded. otherwise, if so enabled, the time offset is
83397804a5cSPoul-Henning Kamp 	 * updated. We can tolerate a modest loss of data here without
83497804a5cSPoul-Henning Kamp 	 * much degrading time accuracy.
83579f1fdb8SWarner Losh 	 *
83679f1fdb8SWarner Losh 	 * The measurements being checked here were made with the system
83779f1fdb8SWarner Losh 	 * timecounter, so the popcorn threshold is not allowed to fall below
83879f1fdb8SWarner Losh 	 * the number of nanoseconds in two ticks of the timecounter.  For a
83979f1fdb8SWarner Losh 	 * timecounter running faster than 1 GHz the lower bound is 2ns, just
84079f1fdb8SWarner Losh 	 * to avoid a nonsensical threshold of zero.
8416f70df15SPoul-Henning Kamp 	*/
84279f1fdb8SWarner Losh 	if (u_nsec > lmax(pps_jitter << PPS_POPCORN,
84379f1fdb8SWarner Losh 	    2 * (NANOSECOND / (long)qmin(NANOSECOND, tc_getfrequency())))) {
844c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSJITTER;
845c68996e2SPoul-Henning Kamp 		pps_jitcnt++;
846c68996e2SPoul-Henning Kamp 	} else if (time_status & STA_PPSTIME) {
84797804a5cSPoul-Henning Kamp 		time_monitor = -v_nsec;
84897804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
849c68996e2SPoul-Henning Kamp 	}
850c68996e2SPoul-Henning Kamp 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
85182e84c5bSPoul-Henning Kamp 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
852c68996e2SPoul-Henning Kamp 	if (u_sec < (1 << pps_shift))
853c68996e2SPoul-Henning Kamp 		return;
854c68996e2SPoul-Henning Kamp 
855c68996e2SPoul-Henning Kamp 	/*
856c68996e2SPoul-Henning Kamp 	 * At the end of the calibration interval the difference between
857c68996e2SPoul-Henning Kamp 	 * the first and last counter values becomes the scaled
858c68996e2SPoul-Henning Kamp 	 * frequency. It will later be divided by the length of the
859c68996e2SPoul-Henning Kamp 	 * interval to determine the frequency update. If the frequency
860c68996e2SPoul-Henning Kamp 	 * exceeds a sanity threshold, or if the actual calibration
861c68996e2SPoul-Henning Kamp 	 * interval is not equal to the expected length, the data are
862c68996e2SPoul-Henning Kamp 	 * discarded. We can tolerate a modest loss of data here without
86397804a5cSPoul-Henning Kamp 	 * much degrading frequency accuracy.
864c68996e2SPoul-Henning Kamp 	 */
865c68996e2SPoul-Henning Kamp 	pps_calcnt++;
866884ab557SPoul-Henning Kamp 	v_nsec = -pps_fcount;
86782e84c5bSPoul-Henning Kamp 	pps_lastsec = pps_tf[0].tv_sec;
868884ab557SPoul-Henning Kamp 	pps_fcount = 0;
869c68996e2SPoul-Henning Kamp 	u_nsec = MAXFREQ << pps_shift;
870c68996e2SPoul-Henning Kamp 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
871c68996e2SPoul-Henning Kamp 	    pps_shift)) {
872c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSERROR;
873c68996e2SPoul-Henning Kamp 		pps_errcnt++;
874c68996e2SPoul-Henning Kamp 		return;
875c68996e2SPoul-Henning Kamp 	}
876c68996e2SPoul-Henning Kamp 
877c68996e2SPoul-Henning Kamp 	/*
87882e84c5bSPoul-Henning Kamp 	 * Here the raw frequency offset and wander (stability) is
87982e84c5bSPoul-Henning Kamp 	 * calculated. If the wander is less than the wander threshold
88082e84c5bSPoul-Henning Kamp 	 * for four consecutive averaging intervals, the interval is
88182e84c5bSPoul-Henning Kamp 	 * doubled; if it is greater than the threshold for four
88282e84c5bSPoul-Henning Kamp 	 * consecutive intervals, the interval is halved. The scaled
88382e84c5bSPoul-Henning Kamp 	 * frequency offset is converted to frequency offset. The
88482e84c5bSPoul-Henning Kamp 	 * stability metric is calculated as the average of recent
88582e84c5bSPoul-Henning Kamp 	 * frequency changes, but is used only for performance
886c68996e2SPoul-Henning Kamp 	 * monitoring.
887c68996e2SPoul-Henning Kamp 	 */
888c68996e2SPoul-Henning Kamp 	L_LINT(ftemp, v_nsec);
889c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, pps_shift);
890c68996e2SPoul-Henning Kamp 	L_SUB(ftemp, pps_freq);
891c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(ftemp);
89282e84c5bSPoul-Henning Kamp 	if (u_nsec > PPS_MAXWANDER) {
89382e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, PPS_MAXWANDER);
894c68996e2SPoul-Henning Kamp 		pps_intcnt--;
895c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
896c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
89782e84c5bSPoul-Henning Kamp 	} else if (u_nsec < -PPS_MAXWANDER) {
89882e84c5bSPoul-Henning Kamp 		L_LINT(ftemp, -PPS_MAXWANDER);
899c68996e2SPoul-Henning Kamp 		pps_intcnt--;
900c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSWANDER;
901c68996e2SPoul-Henning Kamp 		pps_stbcnt++;
902c68996e2SPoul-Henning Kamp 	} else {
9036f70df15SPoul-Henning Kamp 		pps_intcnt++;
9046f70df15SPoul-Henning Kamp 	}
90597804a5cSPoul-Henning Kamp 	if (pps_intcnt >= 4) {
906c68996e2SPoul-Henning Kamp 		pps_intcnt = 4;
90782e84c5bSPoul-Henning Kamp 		if (pps_shift < pps_shiftmax) {
908c68996e2SPoul-Henning Kamp 			pps_shift++;
909c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
910c68996e2SPoul-Henning Kamp 		}
91197804a5cSPoul-Henning Kamp 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
912c68996e2SPoul-Henning Kamp 		pps_intcnt = -4;
913c68996e2SPoul-Henning Kamp 		if (pps_shift > PPS_FAVG) {
914c68996e2SPoul-Henning Kamp 			pps_shift--;
915c68996e2SPoul-Henning Kamp 			pps_intcnt = 0;
916c68996e2SPoul-Henning Kamp 		}
917c68996e2SPoul-Henning Kamp 	}
918c68996e2SPoul-Henning Kamp 	if (u_nsec < 0)
919c68996e2SPoul-Henning Kamp 		u_nsec = -u_nsec;
920c68996e2SPoul-Henning Kamp 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
9219ada5a50SPoul-Henning Kamp 
922c68996e2SPoul-Henning Kamp 	/*
92382e84c5bSPoul-Henning Kamp 	 * The PPS frequency is recalculated and clamped to the maximum
92482e84c5bSPoul-Henning Kamp 	 * MAXFREQ. If enabled, the system clock frequency is updated as
92582e84c5bSPoul-Henning Kamp 	 * well.
926c68996e2SPoul-Henning Kamp 	 */
927c68996e2SPoul-Henning Kamp 	L_ADD(pps_freq, ftemp);
928c68996e2SPoul-Henning Kamp 	u_nsec = L_GINT(pps_freq);
929c68996e2SPoul-Henning Kamp 	if (u_nsec > MAXFREQ)
930c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, MAXFREQ);
931c68996e2SPoul-Henning Kamp 	else if (u_nsec < -MAXFREQ)
932c68996e2SPoul-Henning Kamp 		L_LINT(pps_freq, -MAXFREQ);
93397804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSFREQ)
934c68996e2SPoul-Henning Kamp 		time_freq = pps_freq;
935c68996e2SPoul-Henning Kamp }
9366f70df15SPoul-Henning Kamp #endif /* PPS_SYNC */
937e1d970f1SPoul-Henning Kamp 
938e1d970f1SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
939e1d970f1SPoul-Henning Kamp struct adjtime_args {
940e1d970f1SPoul-Henning Kamp 	struct timeval *delta;
941e1d970f1SPoul-Henning Kamp 	struct timeval *olddelta;
942e1d970f1SPoul-Henning Kamp };
943e1d970f1SPoul-Henning Kamp #endif
944e1d970f1SPoul-Henning Kamp /* ARGSUSED */
945e1d970f1SPoul-Henning Kamp int
9468451d0ddSKip Macy sys_adjtime(struct thread *td, struct adjtime_args *uap)
947e1d970f1SPoul-Henning Kamp {
948b88ec951SJohn Baldwin 	struct timeval delta, olddelta, *deltap;
949b88ec951SJohn Baldwin 	int error;
950b88ec951SJohn Baldwin 
951b88ec951SJohn Baldwin 	if (uap->delta) {
952b88ec951SJohn Baldwin 		error = copyin(uap->delta, &delta, sizeof(delta));
953b88ec951SJohn Baldwin 		if (error)
954b88ec951SJohn Baldwin 			return (error);
955b88ec951SJohn Baldwin 		deltap = &delta;
956b88ec951SJohn Baldwin 	} else
957b88ec951SJohn Baldwin 		deltap = NULL;
958b88ec951SJohn Baldwin 	error = kern_adjtime(td, deltap, &olddelta);
959b88ec951SJohn Baldwin 	if (uap->olddelta && error == 0)
960b88ec951SJohn Baldwin 		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
961b88ec951SJohn Baldwin 	return (error);
962b88ec951SJohn Baldwin }
963b88ec951SJohn Baldwin 
964b88ec951SJohn Baldwin int
965b88ec951SJohn Baldwin kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
966b88ec951SJohn Baldwin {
967e1d970f1SPoul-Henning Kamp 	struct timeval atv;
968e1d970f1SPoul-Henning Kamp 	int error;
969e1d970f1SPoul-Henning Kamp 
9703bdd2d06SPoul-Henning Kamp 	mtx_lock(&Giant);
971b88ec951SJohn Baldwin 	if (olddelta) {
972e1d970f1SPoul-Henning Kamp 		atv.tv_sec = time_adjtime / 1000000;
973e1d970f1SPoul-Henning Kamp 		atv.tv_usec = time_adjtime % 1000000;
974e1d970f1SPoul-Henning Kamp 		if (atv.tv_usec < 0) {
975e1d970f1SPoul-Henning Kamp 			atv.tv_usec += 1000000;
976e1d970f1SPoul-Henning Kamp 			atv.tv_sec--;
977e1d970f1SPoul-Henning Kamp 		}
978b88ec951SJohn Baldwin 		*olddelta = atv;
979e1d970f1SPoul-Henning Kamp 	}
980b4be6ef2SRobert Watson 	if (delta) {
981b4be6ef2SRobert Watson 		if ((error = priv_check(td, PRIV_ADJTIME))) {
982e1d970f1SPoul-Henning Kamp 			mtx_unlock(&Giant);
983e1d970f1SPoul-Henning Kamp 			return (error);
984e1d970f1SPoul-Henning Kamp 		}
985b4be6ef2SRobert Watson 		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
986b4be6ef2SRobert Watson 		    delta->tv_usec;
987b4be6ef2SRobert Watson 	}
988b4be6ef2SRobert Watson 	mtx_unlock(&Giant);
989b4be6ef2SRobert Watson 	return (0);
990b4be6ef2SRobert Watson }
991e1d970f1SPoul-Henning Kamp 
9925c7e270fSAndriy Gapon static struct callout resettodr_callout;
9935c7e270fSAndriy Gapon static int resettodr_period = 1800;
9945c7e270fSAndriy Gapon 
9955c7e270fSAndriy Gapon static void
9965c7e270fSAndriy Gapon periodic_resettodr(void *arg __unused)
9975c7e270fSAndriy Gapon {
9985c7e270fSAndriy Gapon 
9995c7e270fSAndriy Gapon 	if (!ntp_is_time_error()) {
10005c7e270fSAndriy Gapon 		mtx_lock(&Giant);
10015c7e270fSAndriy Gapon 		resettodr();
10025c7e270fSAndriy Gapon 		mtx_unlock(&Giant);
10035c7e270fSAndriy Gapon 	}
10045c7e270fSAndriy Gapon 	if (resettodr_period > 0)
10055c7e270fSAndriy Gapon 		callout_schedule(&resettodr_callout, resettodr_period * hz);
10065c7e270fSAndriy Gapon }
10075c7e270fSAndriy Gapon 
10085c7e270fSAndriy Gapon static void
10095c7e270fSAndriy Gapon shutdown_resettodr(void *arg __unused, int howto __unused)
10105c7e270fSAndriy Gapon {
10115c7e270fSAndriy Gapon 
10125c7e270fSAndriy Gapon 	callout_drain(&resettodr_callout);
10135c7e270fSAndriy Gapon 	if (resettodr_period > 0 && !ntp_is_time_error()) {
10145c7e270fSAndriy Gapon 		mtx_lock(&Giant);
10155c7e270fSAndriy Gapon 		resettodr();
10165c7e270fSAndriy Gapon 		mtx_unlock(&Giant);
10175c7e270fSAndriy Gapon 	}
10185c7e270fSAndriy Gapon }
10195c7e270fSAndriy Gapon 
10205c7e270fSAndriy Gapon static int
10215c7e270fSAndriy Gapon sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
10225c7e270fSAndriy Gapon {
10235c7e270fSAndriy Gapon 	int error;
10245c7e270fSAndriy Gapon 
10255c7e270fSAndriy Gapon 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
10265c7e270fSAndriy Gapon 	if (error || !req->newptr)
10275c7e270fSAndriy Gapon 		return (error);
1028af3b2549SHans Petter Selasky 	if (cold)
1029af3b2549SHans Petter Selasky 		goto done;
10305c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10315c7e270fSAndriy Gapon 		callout_stop(&resettodr_callout);
10325c7e270fSAndriy Gapon 	else
10335c7e270fSAndriy Gapon 		callout_reset(&resettodr_callout, resettodr_period * hz,
10345c7e270fSAndriy Gapon 		    periodic_resettodr, NULL);
1035af3b2549SHans Petter Selasky done:
10365c7e270fSAndriy Gapon 	return (0);
10375c7e270fSAndriy Gapon }
10385c7e270fSAndriy Gapon 
1039af3b2549SHans Petter Selasky SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT|CTLFLAG_RWTUN,
10405c7e270fSAndriy Gapon 	&resettodr_period, 1800, sysctl_resettodr_period, "I",
10415c7e270fSAndriy Gapon 	"Save system time to RTC with this period (in seconds)");
10425c7e270fSAndriy Gapon 
10435c7e270fSAndriy Gapon static void
10445c7e270fSAndriy Gapon start_periodic_resettodr(void *arg __unused)
10455c7e270fSAndriy Gapon {
10465c7e270fSAndriy Gapon 
10475c7e270fSAndriy Gapon 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
10485c7e270fSAndriy Gapon 	    SHUTDOWN_PRI_FIRST);
10495c7e270fSAndriy Gapon 	callout_init(&resettodr_callout, 1);
10505c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10515c7e270fSAndriy Gapon 		return;
10525c7e270fSAndriy Gapon 	callout_reset(&resettodr_callout, resettodr_period * hz,
10535c7e270fSAndriy Gapon 	    periodic_resettodr, NULL);
10545c7e270fSAndriy Gapon }
10555c7e270fSAndriy Gapon 
1056785797c3SAndriy Gapon SYSINIT(periodic_resettodr, SI_SUB_LAST, SI_ORDER_MIDDLE,
10575c7e270fSAndriy Gapon 	start_periodic_resettodr, NULL);
1058