xref: /freebsd/sys/kern/kern_ntptime.c (revision de5b19526b7350b9c608ae4bf0bd80b91e51a5df)
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 
54*de5b1952SAlexander Leidinger #ifdef PPS_SYNC
55*de5b1952SAlexander Leidinger FEATURE(pps_sync, "Support usage of external PPS signal by kernel PLL");
56*de5b1952SAlexander Leidinger #endif
57*de5b1952SAlexander 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 */
151c68996e2SPoul-Henning Kamp static 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) */
157c68996e2SPoul-Henning Kamp static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
158c68996e2SPoul-Henning Kamp static long time_reftime;		/* time 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
277932cfd41SMark Santcroos 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
30482e84c5bSPoul-Henning Kamp SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
3056a77f60dSPoul-Henning Kamp SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
306240577c2SMatthew D Fleming SYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
307240577c2SMatthew D Fleming     &time_monitor, 0, "");
3087fd299cbSPoul-Henning Kamp 
3097fd299cbSPoul-Henning Kamp SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", "");
3107fd299cbSPoul-Henning Kamp SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD, &time_freq, sizeof(time_freq), "I", "");
3115968e18bSPoul-Henning Kamp #endif
312873fbcd7SRobert Watson 
313c68996e2SPoul-Henning Kamp /*
314c68996e2SPoul-Henning Kamp  * ntp_adjtime() - NTP daemon application interface
315c68996e2SPoul-Henning Kamp  *
316873fbcd7SRobert Watson  * See the timex.h header file for synopsis and API description.  Note that
317873fbcd7SRobert Watson  * the timex.constant structure member has a dual purpose to set the time
318873fbcd7SRobert Watson  * constant and to set the TAI offset.
319c68996e2SPoul-Henning Kamp  */
320c68996e2SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
321c68996e2SPoul-Henning Kamp struct ntp_adjtime_args {
322c68996e2SPoul-Henning Kamp 	struct timex *tp;
323c68996e2SPoul-Henning Kamp };
324c68996e2SPoul-Henning Kamp #endif
325c68996e2SPoul-Henning Kamp 
326c68996e2SPoul-Henning Kamp int
327b40ce416SJulian Elischer ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
328c68996e2SPoul-Henning Kamp {
329c68996e2SPoul-Henning Kamp 	struct timex ntv;	/* temporary structure */
330f425c1f6SPoul-Henning Kamp 	long freq;		/* frequency ns/s) */
331c68996e2SPoul-Henning Kamp 	int modes;		/* mode bits from structure */
332c68996e2SPoul-Henning Kamp 	int s;			/* caller priority */
333c68996e2SPoul-Henning Kamp 	int error;
334c68996e2SPoul-Henning Kamp 
335c68996e2SPoul-Henning Kamp 	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
336c68996e2SPoul-Henning Kamp 	if (error)
337c68996e2SPoul-Henning Kamp 		return(error);
338c68996e2SPoul-Henning Kamp 
339c68996e2SPoul-Henning Kamp 	/*
340c68996e2SPoul-Henning Kamp 	 * Update selected clock variables - only the superuser can
341c68996e2SPoul-Henning Kamp 	 * change anything. Note that there is no error checking here on
342c68996e2SPoul-Henning Kamp 	 * the assumption the superuser should know what it is doing.
34397804a5cSPoul-Henning Kamp 	 * Note that either the time constant or TAI offset are loaded
34424dbea46SJohn Hay 	 * from the ntv.constant member, depending on the mode bits. If
34524dbea46SJohn Hay 	 * the STA_PLL bit in the status word is cleared, the state and
34624dbea46SJohn Hay 	 * status words are reset to the initial values at boot.
347c68996e2SPoul-Henning Kamp 	 */
3486f1e8c18SMatthew Dillon 	mtx_lock(&Giant);
349c68996e2SPoul-Henning Kamp 	modes = ntv.modes;
350fafbe352SPoul-Henning Kamp 	if (modes)
351acd3428bSRobert Watson 		error = priv_check(td, PRIV_NTP_ADJTIME);
352c68996e2SPoul-Henning Kamp 	if (error)
3536f1e8c18SMatthew Dillon 		goto done2;
354c68996e2SPoul-Henning Kamp 	s = splclock();
355c68996e2SPoul-Henning Kamp 	if (modes & MOD_MAXERROR)
356c68996e2SPoul-Henning Kamp 		time_maxerror = ntv.maxerror;
357c68996e2SPoul-Henning Kamp 	if (modes & MOD_ESTERROR)
358c68996e2SPoul-Henning Kamp 		time_esterror = ntv.esterror;
359c68996e2SPoul-Henning Kamp 	if (modes & MOD_STATUS) {
36024dbea46SJohn Hay 		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
36124dbea46SJohn Hay 			time_state = TIME_OK;
36224dbea46SJohn Hay 			time_status = STA_UNSYNC;
36324dbea46SJohn Hay #ifdef PPS_SYNC
36424dbea46SJohn Hay 			pps_shift = PPS_FAVG;
36524dbea46SJohn Hay #endif /* PPS_SYNC */
36624dbea46SJohn Hay 		}
367c68996e2SPoul-Henning Kamp 		time_status &= STA_RONLY;
368c68996e2SPoul-Henning Kamp 		time_status |= ntv.status & ~STA_RONLY;
369c68996e2SPoul-Henning Kamp 	}
370f425c1f6SPoul-Henning Kamp 	if (modes & MOD_TIMECONST) {
371f425c1f6SPoul-Henning Kamp 		if (ntv.constant < 0)
372f425c1f6SPoul-Henning Kamp 			time_constant = 0;
373f425c1f6SPoul-Henning Kamp 		else if (ntv.constant > MAXTC)
374f425c1f6SPoul-Henning Kamp 			time_constant = MAXTC;
375f425c1f6SPoul-Henning Kamp 		else
376c68996e2SPoul-Henning Kamp 			time_constant = ntv.constant;
377f425c1f6SPoul-Henning Kamp 	}
37897804a5cSPoul-Henning Kamp 	if (modes & MOD_TAI) {
37997804a5cSPoul-Henning Kamp 		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
38097804a5cSPoul-Henning Kamp 			time_tai = ntv.constant;
38197804a5cSPoul-Henning Kamp 	}
38282e84c5bSPoul-Henning Kamp #ifdef PPS_SYNC
38382e84c5bSPoul-Henning Kamp 	if (modes & MOD_PPSMAX) {
38482e84c5bSPoul-Henning Kamp 		if (ntv.shift < PPS_FAVG)
38582e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVG;
38682e84c5bSPoul-Henning Kamp 		else if (ntv.shift > PPS_FAVGMAX)
38782e84c5bSPoul-Henning Kamp 			pps_shiftmax = PPS_FAVGMAX;
38882e84c5bSPoul-Henning Kamp 		else
38982e84c5bSPoul-Henning Kamp 			pps_shiftmax = ntv.shift;
39082e84c5bSPoul-Henning Kamp 	}
39182e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
392c68996e2SPoul-Henning Kamp 	if (modes & MOD_NANO)
393c68996e2SPoul-Henning Kamp 		time_status |= STA_NANO;
394c68996e2SPoul-Henning Kamp 	if (modes & MOD_MICRO)
395c68996e2SPoul-Henning Kamp 		time_status &= ~STA_NANO;
396c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKB)
397c68996e2SPoul-Henning Kamp 		time_status |= STA_CLK;
398c68996e2SPoul-Henning Kamp 	if (modes & MOD_CLKA)
399c68996e2SPoul-Henning Kamp 		time_status &= ~STA_CLK;
40024dbea46SJohn Hay 	if (modes & MOD_FREQUENCY) {
40124dbea46SJohn Hay 		freq = (ntv.freq * 1000LL) >> 16;
40224dbea46SJohn Hay 		if (freq > MAXFREQ)
40324dbea46SJohn Hay 			L_LINT(time_freq, MAXFREQ);
40424dbea46SJohn Hay 		else if (freq < -MAXFREQ)
40524dbea46SJohn Hay 			L_LINT(time_freq, -MAXFREQ);
406bcfe6d8bSPoul-Henning Kamp 		else {
407bcfe6d8bSPoul-Henning Kamp 			/*
408bcfe6d8bSPoul-Henning Kamp 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
409bcfe6d8bSPoul-Henning Kamp 			 * time_freq is [ns/s * 2^32]
410bcfe6d8bSPoul-Henning Kamp 			 */
411bcfe6d8bSPoul-Henning Kamp 			time_freq = ntv.freq * 1000LL * 65536LL;
412bcfe6d8bSPoul-Henning Kamp 		}
41324dbea46SJohn Hay #ifdef PPS_SYNC
41424dbea46SJohn Hay 		pps_freq = time_freq;
41524dbea46SJohn Hay #endif /* PPS_SYNC */
41624dbea46SJohn Hay 	}
417551260fcSPoul-Henning Kamp 	if (modes & MOD_OFFSET) {
418551260fcSPoul-Henning Kamp 		if (time_status & STA_NANO)
419551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset);
420551260fcSPoul-Henning Kamp 		else
421551260fcSPoul-Henning Kamp 			hardupdate(ntv.offset * 1000);
422551260fcSPoul-Henning Kamp 	}
423c68996e2SPoul-Henning Kamp 
424c68996e2SPoul-Henning Kamp 	/*
42597804a5cSPoul-Henning Kamp 	 * Retrieve all clock variables. Note that the TAI offset is
42697804a5cSPoul-Henning Kamp 	 * returned only by ntp_gettime();
427c68996e2SPoul-Henning Kamp 	 */
428c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
429b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset);
430c68996e2SPoul-Henning Kamp 	else
431b9c6e8bdSPoul-Henning Kamp 		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
43234cffbe3SPoul-Henning Kamp 	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
433c68996e2SPoul-Henning Kamp 	ntv.maxerror = time_maxerror;
434c68996e2SPoul-Henning Kamp 	ntv.esterror = time_esterror;
435c68996e2SPoul-Henning Kamp 	ntv.status = time_status;
436f425c1f6SPoul-Henning Kamp 	ntv.constant = time_constant;
437c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
438c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision;
439c68996e2SPoul-Henning Kamp 	else
440c68996e2SPoul-Henning Kamp 		ntv.precision = time_precision / 1000;
441c68996e2SPoul-Henning Kamp 	ntv.tolerance = MAXFREQ * SCALE_PPM;
442c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
443c68996e2SPoul-Henning Kamp 	ntv.shift = pps_shift;
44434cffbe3SPoul-Henning Kamp 	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
445c68996e2SPoul-Henning Kamp 	if (time_status & STA_NANO)
446c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter;
447c68996e2SPoul-Henning Kamp 	else
448c68996e2SPoul-Henning Kamp 		ntv.jitter = pps_jitter / 1000;
449c68996e2SPoul-Henning Kamp 	ntv.stabil = pps_stabil;
450c68996e2SPoul-Henning Kamp 	ntv.calcnt = pps_calcnt;
451c68996e2SPoul-Henning Kamp 	ntv.errcnt = pps_errcnt;
452c68996e2SPoul-Henning Kamp 	ntv.jitcnt = pps_jitcnt;
453c68996e2SPoul-Henning Kamp 	ntv.stbcnt = pps_stbcnt;
454c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
455c68996e2SPoul-Henning Kamp 	splx(s);
456c68996e2SPoul-Henning Kamp 
457c68996e2SPoul-Henning Kamp 	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
458c68996e2SPoul-Henning Kamp 	if (error)
4596f1e8c18SMatthew Dillon 		goto done2;
460c68996e2SPoul-Henning Kamp 
4619a9ae42aSAndriy Gapon 	if (ntp_is_time_error())
462b40ce416SJulian Elischer 		td->td_retval[0] = TIME_ERROR;
4639a9ae42aSAndriy Gapon 	else
464b40ce416SJulian Elischer 		td->td_retval[0] = time_state;
4659a9ae42aSAndriy Gapon 
4666f1e8c18SMatthew Dillon done2:
4676f1e8c18SMatthew Dillon 	mtx_unlock(&Giant);
468a5088017SPoul-Henning Kamp 	return (error);
469c68996e2SPoul-Henning Kamp }
470c68996e2SPoul-Henning Kamp 
471c68996e2SPoul-Henning Kamp /*
472c68996e2SPoul-Henning Kamp  * second_overflow() - called after ntp_tick_adjust()
473c68996e2SPoul-Henning Kamp  *
474c68996e2SPoul-Henning Kamp  * This routine is ordinarily called immediately following the above
475c68996e2SPoul-Henning Kamp  * routine ntp_tick_adjust(). While these two routines are normally
476c68996e2SPoul-Henning Kamp  * combined, they are separated here only for the purposes of
477c68996e2SPoul-Henning Kamp  * simulation.
478c68996e2SPoul-Henning Kamp  */
479c68996e2SPoul-Henning Kamp void
480b4a1d0deSPoul-Henning Kamp ntp_update_second(int64_t *adjustment, time_t *newsec)
481c68996e2SPoul-Henning Kamp {
482e1d970f1SPoul-Henning Kamp 	int tickrate;
48397804a5cSPoul-Henning Kamp 	l_fp ftemp;		/* 32/64-bit temporary */
484c68996e2SPoul-Henning Kamp 
48582e84c5bSPoul-Henning Kamp 	/*
48682e84c5bSPoul-Henning Kamp 	 * On rollover of the second both the nanosecond and microsecond
48782e84c5bSPoul-Henning Kamp 	 * clocks are updated and the state machine cranked as
48882e84c5bSPoul-Henning Kamp 	 * necessary. The phase adjustment to be used for the next
48982e84c5bSPoul-Henning Kamp 	 * second is calculated and the maximum error is increased by
49082e84c5bSPoul-Henning Kamp 	 * the tolerance.
49182e84c5bSPoul-Henning Kamp 	 */
492c68996e2SPoul-Henning Kamp 	time_maxerror += MAXFREQ / 1000;
493c68996e2SPoul-Henning Kamp 
494c68996e2SPoul-Henning Kamp 	/*
495c68996e2SPoul-Henning Kamp 	 * Leap second processing. If in leap-insert state at
496c68996e2SPoul-Henning Kamp 	 * the end of the day, the system clock is set back one
497c68996e2SPoul-Henning Kamp 	 * second; if in leap-delete state, the system clock is
498c68996e2SPoul-Henning Kamp 	 * set ahead one second. The nano_time() routine or
499c68996e2SPoul-Henning Kamp 	 * external clock driver will insure that reported time
500c68996e2SPoul-Henning Kamp 	 * is always monotonic.
501c68996e2SPoul-Henning Kamp 	 */
502c68996e2SPoul-Henning Kamp 	switch (time_state) {
503c68996e2SPoul-Henning Kamp 
504c68996e2SPoul-Henning Kamp 		/*
505c68996e2SPoul-Henning Kamp 		 * No warning.
506c68996e2SPoul-Henning Kamp 		 */
507c68996e2SPoul-Henning Kamp 		case TIME_OK:
508c68996e2SPoul-Henning Kamp 		if (time_status & STA_INS)
509c68996e2SPoul-Henning Kamp 			time_state = TIME_INS;
510c68996e2SPoul-Henning Kamp 		else if (time_status & STA_DEL)
511c68996e2SPoul-Henning Kamp 			time_state = TIME_DEL;
512c68996e2SPoul-Henning Kamp 		break;
513c68996e2SPoul-Henning Kamp 
514c68996e2SPoul-Henning Kamp 		/*
515c68996e2SPoul-Henning Kamp 		 * Insert second 23:59:60 following second
516c68996e2SPoul-Henning Kamp 		 * 23:59:59.
517c68996e2SPoul-Henning Kamp 		 */
518c68996e2SPoul-Henning Kamp 		case TIME_INS:
519c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_INS))
520c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
521c68996e2SPoul-Henning Kamp 		else if ((*newsec) % 86400 == 0) {
522c68996e2SPoul-Henning Kamp 			(*newsec)--;
523c68996e2SPoul-Henning Kamp 			time_state = TIME_OOP;
524eac3c62bSWarner Losh 			time_tai++;
525c68996e2SPoul-Henning Kamp 		}
526c68996e2SPoul-Henning Kamp 		break;
527c68996e2SPoul-Henning Kamp 
528c68996e2SPoul-Henning Kamp 		/*
529c68996e2SPoul-Henning Kamp 		 * Delete second 23:59:59.
530c68996e2SPoul-Henning Kamp 		 */
531c68996e2SPoul-Henning Kamp 		case TIME_DEL:
532c68996e2SPoul-Henning Kamp 		if (!(time_status & STA_DEL))
533c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
534c68996e2SPoul-Henning Kamp 		else if (((*newsec) + 1) % 86400 == 0) {
535c68996e2SPoul-Henning Kamp 			(*newsec)++;
53697804a5cSPoul-Henning Kamp 			time_tai--;
537c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
538c68996e2SPoul-Henning Kamp 		}
539c68996e2SPoul-Henning Kamp 		break;
540c68996e2SPoul-Henning Kamp 
541c68996e2SPoul-Henning Kamp 		/*
542c68996e2SPoul-Henning Kamp 		 * Insert second in progress.
543c68996e2SPoul-Henning Kamp 		 */
544c68996e2SPoul-Henning Kamp 		case TIME_OOP:
545c68996e2SPoul-Henning Kamp 			time_state = TIME_WAIT;
546c68996e2SPoul-Henning Kamp 		break;
547c68996e2SPoul-Henning Kamp 
548c68996e2SPoul-Henning Kamp 		/*
549c68996e2SPoul-Henning Kamp 		 * Wait for status bits to clear.
550c68996e2SPoul-Henning Kamp 		 */
551c68996e2SPoul-Henning Kamp 		case TIME_WAIT:
552c68996e2SPoul-Henning Kamp 		if (!(time_status & (STA_INS | STA_DEL)))
553c68996e2SPoul-Henning Kamp 			time_state = TIME_OK;
554c68996e2SPoul-Henning Kamp 	}
555c68996e2SPoul-Henning Kamp 
556c68996e2SPoul-Henning Kamp 	/*
55782e84c5bSPoul-Henning Kamp 	 * Compute the total time adjustment for the next second
55882e84c5bSPoul-Henning Kamp 	 * in ns. The offset is reduced by a factor depending on
55982e84c5bSPoul-Henning Kamp 	 * whether the PPS signal is operating. Note that the
56082e84c5bSPoul-Henning Kamp 	 * value is in effect scaled by the clock frequency,
56182e84c5bSPoul-Henning Kamp 	 * since the adjustment is added at each tick interrupt.
562c68996e2SPoul-Henning Kamp 	 */
56397804a5cSPoul-Henning Kamp 	ftemp = time_offset;
564c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
56597804a5cSPoul-Henning Kamp 	/* XXX even if PPS signal dies we should finish adjustment ? */
56697804a5cSPoul-Henning Kamp 	if (time_status & STA_PPSTIME && time_status &
56797804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)
56897804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, pps_shift);
56997804a5cSPoul-Henning Kamp 	else
57097804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57182e84c5bSPoul-Henning Kamp #else
57297804a5cSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
57382e84c5bSPoul-Henning Kamp #endif /* PPS_SYNC */
57497804a5cSPoul-Henning Kamp 	time_adj = ftemp;
57597804a5cSPoul-Henning Kamp 	L_SUB(time_offset, ftemp);
576c68996e2SPoul-Henning Kamp 	L_ADD(time_adj, time_freq);
577e1d970f1SPoul-Henning Kamp 
578e1d970f1SPoul-Henning Kamp 	/*
579e1d970f1SPoul-Henning Kamp 	 * Apply any correction from adjtime(2).  If more than one second
580e1d970f1SPoul-Henning Kamp 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
581e1d970f1SPoul-Henning Kamp 	 * until the last second is slewed the final < 500 usecs.
582e1d970f1SPoul-Henning Kamp 	 */
583e1d970f1SPoul-Henning Kamp 	if (time_adjtime != 0) {
584e1d970f1SPoul-Henning Kamp 		if (time_adjtime > 1000000)
585e1d970f1SPoul-Henning Kamp 			tickrate = 5000;
586e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -1000000)
587e1d970f1SPoul-Henning Kamp 			tickrate = -5000;
588e1d970f1SPoul-Henning Kamp 		else if (time_adjtime > 500)
589e1d970f1SPoul-Henning Kamp 			tickrate = 500;
590e1d970f1SPoul-Henning Kamp 		else if (time_adjtime < -500)
591e1d970f1SPoul-Henning Kamp 			tickrate = -500;
592e1d970f1SPoul-Henning Kamp 		else
593bcfe6d8bSPoul-Henning Kamp 			tickrate = time_adjtime;
594e1d970f1SPoul-Henning Kamp 		time_adjtime -= tickrate;
595e1d970f1SPoul-Henning Kamp 		L_LINT(ftemp, tickrate * 1000);
596e1d970f1SPoul-Henning Kamp 		L_ADD(time_adj, ftemp);
597e1d970f1SPoul-Henning Kamp 	}
598b4a1d0deSPoul-Henning Kamp 	*adjustment = time_adj;
599e1d970f1SPoul-Henning Kamp 
600c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
601c68996e2SPoul-Henning Kamp 	if (pps_valid > 0)
602c68996e2SPoul-Henning Kamp 		pps_valid--;
603c68996e2SPoul-Henning Kamp 	else
60424dbea46SJohn Hay 		time_status &= ~STA_PPSSIGNAL;
605c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
606c68996e2SPoul-Henning Kamp }
607c68996e2SPoul-Henning Kamp 
608c68996e2SPoul-Henning Kamp /*
609c68996e2SPoul-Henning Kamp  * ntp_init() - initialize variables and structures
610c68996e2SPoul-Henning Kamp  *
611c68996e2SPoul-Henning Kamp  * This routine must be called after the kernel variables hz and tick
612c68996e2SPoul-Henning Kamp  * are set or changed and before the next tick interrupt. In this
613c68996e2SPoul-Henning Kamp  * particular implementation, these values are assumed set elsewhere in
614c68996e2SPoul-Henning Kamp  * the kernel. The design allows the clock frequency and tick interval
615c68996e2SPoul-Henning Kamp  * to be changed while the system is running. So, this routine should
616c68996e2SPoul-Henning Kamp  * probably be integrated with the code that does that.
617c68996e2SPoul-Henning Kamp  */
618c68996e2SPoul-Henning Kamp static void
619c68996e2SPoul-Henning Kamp ntp_init()
620c68996e2SPoul-Henning Kamp {
621c68996e2SPoul-Henning Kamp 
622c68996e2SPoul-Henning Kamp 	/*
623c68996e2SPoul-Henning Kamp 	 * The following variables are initialized only at startup. Only
624c68996e2SPoul-Henning Kamp 	 * those structures not cleared by the compiler need to be
625c68996e2SPoul-Henning Kamp 	 * initialized, and these only in the simulator. In the actual
626c68996e2SPoul-Henning Kamp 	 * kernel, any nonzero values here will quickly evaporate.
627c68996e2SPoul-Henning Kamp 	 */
628c68996e2SPoul-Henning Kamp 	L_CLR(time_offset);
629c68996e2SPoul-Henning Kamp 	L_CLR(time_freq);
630c68996e2SPoul-Henning Kamp #ifdef PPS_SYNC
63182e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
63282e84c5bSPoul-Henning Kamp 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
63382e84c5bSPoul-Henning Kamp 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
634f425c1f6SPoul-Henning Kamp 	pps_fcount = 0;
635c68996e2SPoul-Henning Kamp 	L_CLR(pps_freq);
636c68996e2SPoul-Henning Kamp #endif /* PPS_SYNC */
637c68996e2SPoul-Henning Kamp }
638c68996e2SPoul-Henning Kamp 
639237fdd78SRobert Watson SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
6406f70df15SPoul-Henning Kamp 
6416f70df15SPoul-Henning Kamp /*
6426f70df15SPoul-Henning Kamp  * hardupdate() - local clock update
6436f70df15SPoul-Henning Kamp  *
6446f70df15SPoul-Henning Kamp  * This routine is called by ntp_adjtime() to update the local clock
6456f70df15SPoul-Henning Kamp  * phase and frequency. The implementation is of an adaptive-parameter,
6466f70df15SPoul-Henning Kamp  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
6476f70df15SPoul-Henning Kamp  * time and frequency offset estimates for each call. If the kernel PPS
6486f70df15SPoul-Henning Kamp  * discipline code is configured (PPS_SYNC), the PPS signal itself
6496f70df15SPoul-Henning Kamp  * determines the new time offset, instead of the calling argument.
6506f70df15SPoul-Henning Kamp  * Presumably, calls to ntp_adjtime() occur only when the caller
6516f70df15SPoul-Henning Kamp  * believes the local clock is valid within some bound (+-128 ms with
6526f70df15SPoul-Henning Kamp  * NTP). If the caller's time is far different than the PPS time, an
6536f70df15SPoul-Henning Kamp  * argument will ensue, and it's not clear who will lose.
6546f70df15SPoul-Henning Kamp  *
655c68996e2SPoul-Henning Kamp  * For uncompensated quartz crystal oscillators and nominal update
656c68996e2SPoul-Henning Kamp  * intervals less than 256 s, operation should be in phase-lock mode,
657c68996e2SPoul-Henning Kamp  * where the loop is disciplined to phase. For update intervals greater
658c68996e2SPoul-Henning Kamp  * than 1024 s, operation should be in frequency-lock mode, where the
659c68996e2SPoul-Henning Kamp  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
660c68996e2SPoul-Henning Kamp  * is selected by the STA_MODE status bit.
6616f70df15SPoul-Henning Kamp  */
6626f70df15SPoul-Henning Kamp static void
663c68996e2SPoul-Henning Kamp hardupdate(offset)
664c68996e2SPoul-Henning Kamp 	long offset;		/* clock offset (ns) */
6656f70df15SPoul-Henning Kamp {
66697804a5cSPoul-Henning Kamp 	long mtemp;
667c68996e2SPoul-Henning Kamp 	l_fp ftemp;
6686f70df15SPoul-Henning Kamp 
669c68996e2SPoul-Henning Kamp 	/*
670c68996e2SPoul-Henning Kamp 	 * Select how the phase is to be controlled and from which
671c68996e2SPoul-Henning Kamp 	 * source. If the PPS signal is present and enabled to
672c68996e2SPoul-Henning Kamp 	 * discipline the time, the PPS offset is used; otherwise, the
673c68996e2SPoul-Henning Kamp 	 * argument offset is used.
674c68996e2SPoul-Henning Kamp 	 */
67582e84c5bSPoul-Henning Kamp 	if (!(time_status & STA_PLL))
67682e84c5bSPoul-Henning Kamp 		return;
67797804a5cSPoul-Henning Kamp 	if (!(time_status & STA_PPSTIME && time_status &
67897804a5cSPoul-Henning Kamp 	    STA_PPSSIGNAL)) {
67997804a5cSPoul-Henning Kamp 		if (offset > MAXPHASE)
68097804a5cSPoul-Henning Kamp 			time_monitor = MAXPHASE;
68197804a5cSPoul-Henning Kamp 		else if (offset < -MAXPHASE)
68297804a5cSPoul-Henning Kamp 			time_monitor = -MAXPHASE;
68397804a5cSPoul-Henning Kamp 		else
68497804a5cSPoul-Henning Kamp 			time_monitor = offset;
68597804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
68697804a5cSPoul-Henning Kamp 	}
6876f70df15SPoul-Henning Kamp 
6886f70df15SPoul-Henning Kamp 	/*
689c68996e2SPoul-Henning Kamp 	 * Select how the frequency is to be controlled and in which
690c68996e2SPoul-Henning Kamp 	 * mode (PLL or FLL). If the PPS signal is present and enabled
691c68996e2SPoul-Henning Kamp 	 * to discipline the frequency, the PPS frequency is used;
692c68996e2SPoul-Henning Kamp 	 * otherwise, the argument offset is used to compute it.
6936f70df15SPoul-Henning Kamp 	 */
694c68996e2SPoul-Henning Kamp 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
695c68996e2SPoul-Henning Kamp 		time_reftime = time_second;
696c68996e2SPoul-Henning Kamp 		return;
697c68996e2SPoul-Henning Kamp 	}
6986f70df15SPoul-Henning Kamp 	if (time_status & STA_FREQHOLD || time_reftime == 0)
699227ee8a1SPoul-Henning Kamp 		time_reftime = time_second;
700227ee8a1SPoul-Henning Kamp 	mtemp = time_second - time_reftime;
70197804a5cSPoul-Henning Kamp 	L_LINT(ftemp, time_monitor);
702c68996e2SPoul-Henning Kamp 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
703c68996e2SPoul-Henning Kamp 	L_MPY(ftemp, mtemp);
704c68996e2SPoul-Henning Kamp 	L_ADD(time_freq, ftemp);
705c68996e2SPoul-Henning Kamp 	time_status &= ~STA_MODE;
70697804a5cSPoul-Henning Kamp 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
70797804a5cSPoul-Henning Kamp 	    MAXSEC)) {
70897804a5cSPoul-Henning Kamp 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
70982e84c5bSPoul-Henning Kamp 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
71082e84c5bSPoul-Henning Kamp 		L_ADD(time_freq, ftemp);
71182e84c5bSPoul-Henning Kamp 		time_status |= STA_MODE;
712c68996e2SPoul-Henning Kamp 	}
713227ee8a1SPoul-Henning Kamp 	time_reftime = time_second;
714c68996e2SPoul-Henning Kamp 	if (L_GINT(time_freq) > MAXFREQ)
715c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, MAXFREQ);
716c68996e2SPoul-Henning Kamp 	else if (L_GINT(time_freq) < -MAXFREQ)
717c68996e2SPoul-Henning Kamp 		L_LINT(time_freq, -MAXFREQ);
7183f31c649SGarrett Wollman }
7193f31c649SGarrett Wollman 
7206f70df15SPoul-Henning Kamp #ifdef PPS_SYNC
7216f70df15SPoul-Henning Kamp /*
7226f70df15SPoul-Henning Kamp  * hardpps() - discipline CPU clock oscillator to external PPS signal
7236f70df15SPoul-Henning Kamp  *
7246f70df15SPoul-Henning Kamp  * This routine is called at each PPS interrupt in order to discipline
72597804a5cSPoul-Henning Kamp  * the CPU clock oscillator to the PPS signal. There are two independent
72697804a5cSPoul-Henning Kamp  * first-order feedback loops, one for the phase, the other for the
72797804a5cSPoul-Henning Kamp  * frequency. The phase loop measures and grooms the PPS phase offset
72897804a5cSPoul-Henning Kamp  * and leaves it in a handy spot for the seconds overflow routine. The
72997804a5cSPoul-Henning Kamp  * frequency loop averages successive PPS phase differences and
73097804a5cSPoul-Henning Kamp  * calculates the PPS frequency offset, which is also processed by the
73197804a5cSPoul-Henning Kamp  * seconds overflow routine. The code requires the caller to capture the
73297804a5cSPoul-Henning Kamp  * time and architecture-dependent hardware counter values in
73397804a5cSPoul-Henning Kamp  * nanoseconds at the on-time PPS signal transition.
7346f70df15SPoul-Henning Kamp  *
735c68996e2SPoul-Henning Kamp  * Note that, on some Unix systems this routine runs at an interrupt
7366f70df15SPoul-Henning Kamp  * priority level higher than the timer interrupt routine hardclock().
7376f70df15SPoul-Henning Kamp  * Therefore, the variables used are distinct from the hardclock()
738c68996e2SPoul-Henning Kamp  * variables, except for the actual time and frequency variables, which
739c68996e2SPoul-Henning Kamp  * are determined by this routine and updated atomically.
7406f70df15SPoul-Henning Kamp  */
7416f70df15SPoul-Henning Kamp void
742c68996e2SPoul-Henning Kamp hardpps(tsp, nsec)
743c68996e2SPoul-Henning Kamp 	struct timespec *tsp;	/* time at PPS */
744c68996e2SPoul-Henning Kamp 	long nsec;		/* hardware counter at PPS */
7456f70df15SPoul-Henning Kamp {
74697804a5cSPoul-Henning Kamp 	long u_sec, u_nsec, v_nsec; /* temps */
747c68996e2SPoul-Henning Kamp 	l_fp ftemp;
7486f70df15SPoul-Henning Kamp 
7496f70df15SPoul-Henning Kamp 	/*
75097804a5cSPoul-Henning Kamp 	 * The signal is first processed by a range gate and frequency
75197804a5cSPoul-Henning Kamp 	 * discriminator. The range gate rejects noise spikes outside
75297804a5cSPoul-Henning Kamp 	 * the range +-500 us. The frequency discriminator rejects input
75397804a5cSPoul-Henning Kamp 	 * signals with apparent frequency outside the range 1 +-500
75497804a5cSPoul-Henning Kamp 	 * PPM. If two hits occur in the same second, we ignore the
75597804a5cSPoul-Henning Kamp 	 * later hit; if not and a hit occurs outside the range gate,
75697804a5cSPoul-Henning Kamp 	 * keep the later hit for later comparison, but do not process
75797804a5cSPoul-Henning Kamp 	 * it.
7586f70df15SPoul-Henning Kamp 	 */
759c68996e2SPoul-Henning Kamp 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
760c68996e2SPoul-Henning Kamp 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
761c68996e2SPoul-Henning Kamp 	pps_valid = PPS_VALID;
762c68996e2SPoul-Henning Kamp 	u_sec = tsp->tv_sec;
763c68996e2SPoul-Henning Kamp 	u_nsec = tsp->tv_nsec;
764c68996e2SPoul-Henning Kamp 	if (u_nsec >= (NANOSECOND >> 1)) {
765c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
766c68996e2SPoul-Henning Kamp 		u_sec++;
7676f70df15SPoul-Henning Kamp 	}
76882e84c5bSPoul-Henning Kamp 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
76924dbea46SJohn Hay 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
77024dbea46SJohn Hay 	    MAXFREQ)
771c68996e2SPoul-Henning Kamp 		return;
772c68996e2SPoul-Henning Kamp 	pps_tf[2] = pps_tf[1];
773c68996e2SPoul-Henning Kamp 	pps_tf[1] = pps_tf[0];
77482e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_sec = u_sec;
77582e84c5bSPoul-Henning Kamp 	pps_tf[0].tv_nsec = u_nsec;
7766f70df15SPoul-Henning Kamp 
7776f70df15SPoul-Henning Kamp 	/*
778c68996e2SPoul-Henning Kamp 	 * Compute the difference between the current and previous
779c68996e2SPoul-Henning Kamp 	 * counter values. If the difference exceeds 0.5 s, assume it
780c68996e2SPoul-Henning Kamp 	 * has wrapped around, so correct 1.0 s. If the result exceeds
781c68996e2SPoul-Henning Kamp 	 * the tick interval, the sample point has crossed a tick
782c68996e2SPoul-Henning Kamp 	 * boundary during the last second, so correct the tick. Very
783c68996e2SPoul-Henning Kamp 	 * intricate.
784c68996e2SPoul-Henning Kamp 	 */
78532c20357SPoul-Henning Kamp 	u_nsec = nsec;
786c68996e2SPoul-Henning Kamp 	if (u_nsec > (NANOSECOND >> 1))
787c68996e2SPoul-Henning Kamp 		u_nsec -= NANOSECOND;
788c68996e2SPoul-Henning Kamp 	else if (u_nsec < -(NANOSECOND >> 1))
789c68996e2SPoul-Henning Kamp 		u_nsec += NANOSECOND;
790884ab557SPoul-Henning Kamp 	pps_fcount += u_nsec;
79124dbea46SJohn Hay 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
792c68996e2SPoul-Henning Kamp 		return;
793c68996e2SPoul-Henning Kamp 	time_status &= ~STA_PPSJITTER;
794c68996e2SPoul-Henning Kamp 
795c68996e2SPoul-Henning Kamp 	/*
796c68996e2SPoul-Henning Kamp 	 * A three-stage median filter is used to help denoise the PPS
7976f70df15SPoul-Henning Kamp 	 * time. The median sample becomes the time offset estimate; the
7986f70df15SPoul-Henning Kamp 	 * difference between the other two samples becomes the time
7996f70df15SPoul-Henning Kamp 	 * dispersion (jitter) estimate.
8006f70df15SPoul-Henning Kamp 	 */
80182e84c5bSPoul-Henning Kamp 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
80282e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
80382e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
80482e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
80582e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
80682e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
80782e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
8086f70df15SPoul-Henning Kamp 		} else {
80982e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
81082e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
811c68996e2SPoul-Henning Kamp 		}
812c68996e2SPoul-Henning Kamp 	} else {
81382e84c5bSPoul-Henning Kamp 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
81482e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
81582e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
81682e84c5bSPoul-Henning Kamp 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
81782e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
81882e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
819c68996e2SPoul-Henning Kamp 		} else {
82082e84c5bSPoul-Henning Kamp 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
82182e84c5bSPoul-Henning Kamp 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
8226f70df15SPoul-Henning Kamp 		}
8236f70df15SPoul-Henning Kamp 	}
8246f70df15SPoul-Henning Kamp 
8256f70df15SPoul-Henning Kamp 	/*
826c68996e2SPoul-Henning Kamp 	 * Nominal jitter is due to PPS signal noise and interrupt
82797804a5cSPoul-Henning Kamp 	 * latency. If it exceeds the popcorn threshold, the sample is
82897804a5cSPoul-Henning Kamp 	 * discarded. otherwise, if so enabled, the time offset is
82997804a5cSPoul-Henning Kamp 	 * updated. We can tolerate a modest loss of data here without
83097804a5cSPoul-Henning Kamp 	 * much degrading time accuracy.
8316f70df15SPoul-Henning Kamp 	 */
83282e84c5bSPoul-Henning Kamp 	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
833c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSJITTER;
834c68996e2SPoul-Henning Kamp 		pps_jitcnt++;
835c68996e2SPoul-Henning Kamp 	} else if (time_status & STA_PPSTIME) {
83697804a5cSPoul-Henning Kamp 		time_monitor = -v_nsec;
83797804a5cSPoul-Henning Kamp 		L_LINT(time_offset, time_monitor);
838c68996e2SPoul-Henning Kamp 	}
839c68996e2SPoul-Henning Kamp 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
84082e84c5bSPoul-Henning Kamp 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
841c68996e2SPoul-Henning Kamp 	if (u_sec < (1 << pps_shift))
842c68996e2SPoul-Henning Kamp 		return;
843c68996e2SPoul-Henning Kamp 
844c68996e2SPoul-Henning Kamp 	/*
845c68996e2SPoul-Henning Kamp 	 * At the end of the calibration interval the difference between
846c68996e2SPoul-Henning Kamp 	 * the first and last counter values becomes the scaled
847c68996e2SPoul-Henning Kamp 	 * frequency. It will later be divided by the length of the
848c68996e2SPoul-Henning Kamp 	 * interval to determine the frequency update. If the frequency
849c68996e2SPoul-Henning Kamp 	 * exceeds a sanity threshold, or if the actual calibration
850c68996e2SPoul-Henning Kamp 	 * interval is not equal to the expected length, the data are
851c68996e2SPoul-Henning Kamp 	 * discarded. We can tolerate a modest loss of data here without
85297804a5cSPoul-Henning Kamp 	 * much degrading frequency accuracy.
853c68996e2SPoul-Henning Kamp 	 */
854c68996e2SPoul-Henning Kamp 	pps_calcnt++;
855884ab557SPoul-Henning Kamp 	v_nsec = -pps_fcount;
85682e84c5bSPoul-Henning Kamp 	pps_lastsec = pps_tf[0].tv_sec;
857884ab557SPoul-Henning Kamp 	pps_fcount = 0;
858c68996e2SPoul-Henning Kamp 	u_nsec = MAXFREQ << pps_shift;
859c68996e2SPoul-Henning Kamp 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
860c68996e2SPoul-Henning Kamp 	    pps_shift)) {
861c68996e2SPoul-Henning Kamp 		time_status |= STA_PPSERROR;
862c68996e2SPoul-Henning Kamp 		pps_errcnt++;
863c68996e2SPoul-Henning Kamp 		return;
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;
924c68996e2SPoul-Henning Kamp }
9256f70df15SPoul-Henning Kamp #endif /* PPS_SYNC */
926e1d970f1SPoul-Henning Kamp 
927e1d970f1SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
928e1d970f1SPoul-Henning Kamp struct adjtime_args {
929e1d970f1SPoul-Henning Kamp 	struct timeval *delta;
930e1d970f1SPoul-Henning Kamp 	struct timeval *olddelta;
931e1d970f1SPoul-Henning Kamp };
932e1d970f1SPoul-Henning Kamp #endif
933e1d970f1SPoul-Henning Kamp /* ARGSUSED */
934e1d970f1SPoul-Henning Kamp int
935e1d970f1SPoul-Henning Kamp adjtime(struct thread *td, struct adjtime_args *uap)
936e1d970f1SPoul-Henning Kamp {
937b88ec951SJohn Baldwin 	struct timeval delta, olddelta, *deltap;
938b88ec951SJohn Baldwin 	int error;
939b88ec951SJohn Baldwin 
940b88ec951SJohn Baldwin 	if (uap->delta) {
941b88ec951SJohn Baldwin 		error = copyin(uap->delta, &delta, sizeof(delta));
942b88ec951SJohn Baldwin 		if (error)
943b88ec951SJohn Baldwin 			return (error);
944b88ec951SJohn Baldwin 		deltap = &delta;
945b88ec951SJohn Baldwin 	} else
946b88ec951SJohn Baldwin 		deltap = NULL;
947b88ec951SJohn Baldwin 	error = kern_adjtime(td, deltap, &olddelta);
948b88ec951SJohn Baldwin 	if (uap->olddelta && error == 0)
949b88ec951SJohn Baldwin 		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
950b88ec951SJohn Baldwin 	return (error);
951b88ec951SJohn Baldwin }
952b88ec951SJohn Baldwin 
953b88ec951SJohn Baldwin int
954b88ec951SJohn Baldwin kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
955b88ec951SJohn Baldwin {
956e1d970f1SPoul-Henning Kamp 	struct timeval atv;
957e1d970f1SPoul-Henning Kamp 	int error;
958e1d970f1SPoul-Henning Kamp 
9593bdd2d06SPoul-Henning Kamp 	mtx_lock(&Giant);
960b88ec951SJohn Baldwin 	if (olddelta) {
961e1d970f1SPoul-Henning Kamp 		atv.tv_sec = time_adjtime / 1000000;
962e1d970f1SPoul-Henning Kamp 		atv.tv_usec = time_adjtime % 1000000;
963e1d970f1SPoul-Henning Kamp 		if (atv.tv_usec < 0) {
964e1d970f1SPoul-Henning Kamp 			atv.tv_usec += 1000000;
965e1d970f1SPoul-Henning Kamp 			atv.tv_sec--;
966e1d970f1SPoul-Henning Kamp 		}
967b88ec951SJohn Baldwin 		*olddelta = atv;
968e1d970f1SPoul-Henning Kamp 	}
969b4be6ef2SRobert Watson 	if (delta) {
970b4be6ef2SRobert Watson 		if ((error = priv_check(td, PRIV_ADJTIME))) {
971e1d970f1SPoul-Henning Kamp 			mtx_unlock(&Giant);
972e1d970f1SPoul-Henning Kamp 			return (error);
973e1d970f1SPoul-Henning Kamp 		}
974b4be6ef2SRobert Watson 		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
975b4be6ef2SRobert Watson 		    delta->tv_usec;
976b4be6ef2SRobert Watson 	}
977b4be6ef2SRobert Watson 	mtx_unlock(&Giant);
978b4be6ef2SRobert Watson 	return (0);
979b4be6ef2SRobert Watson }
980e1d970f1SPoul-Henning Kamp 
9815c7e270fSAndriy Gapon static struct callout resettodr_callout;
9825c7e270fSAndriy Gapon static int resettodr_period = 1800;
9835c7e270fSAndriy Gapon 
9845c7e270fSAndriy Gapon static void
9855c7e270fSAndriy Gapon periodic_resettodr(void *arg __unused)
9865c7e270fSAndriy Gapon {
9875c7e270fSAndriy Gapon 
9885c7e270fSAndriy Gapon 	if (!ntp_is_time_error()) {
9895c7e270fSAndriy Gapon 		mtx_lock(&Giant);
9905c7e270fSAndriy Gapon 		resettodr();
9915c7e270fSAndriy Gapon 		mtx_unlock(&Giant);
9925c7e270fSAndriy Gapon 	}
9935c7e270fSAndriy Gapon 	if (resettodr_period > 0)
9945c7e270fSAndriy Gapon 		callout_schedule(&resettodr_callout, resettodr_period * hz);
9955c7e270fSAndriy Gapon }
9965c7e270fSAndriy Gapon 
9975c7e270fSAndriy Gapon static void
9985c7e270fSAndriy Gapon shutdown_resettodr(void *arg __unused, int howto __unused)
9995c7e270fSAndriy Gapon {
10005c7e270fSAndriy Gapon 
10015c7e270fSAndriy Gapon 	callout_drain(&resettodr_callout);
10025c7e270fSAndriy Gapon 	if (resettodr_period > 0 && !ntp_is_time_error()) {
10035c7e270fSAndriy Gapon 		mtx_lock(&Giant);
10045c7e270fSAndriy Gapon 		resettodr();
10055c7e270fSAndriy Gapon 		mtx_unlock(&Giant);
10065c7e270fSAndriy Gapon 	}
10075c7e270fSAndriy Gapon }
10085c7e270fSAndriy Gapon 
10095c7e270fSAndriy Gapon static int
10105c7e270fSAndriy Gapon sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
10115c7e270fSAndriy Gapon {
10125c7e270fSAndriy Gapon 	int error;
10135c7e270fSAndriy Gapon 
10145c7e270fSAndriy Gapon 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
10155c7e270fSAndriy Gapon 	if (error || !req->newptr)
10165c7e270fSAndriy Gapon 		return (error);
10175c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10185c7e270fSAndriy Gapon 		callout_stop(&resettodr_callout);
10195c7e270fSAndriy Gapon 	else
10205c7e270fSAndriy Gapon 		callout_reset(&resettodr_callout, resettodr_period * hz,
10215c7e270fSAndriy Gapon 		    periodic_resettodr, NULL);
10225c7e270fSAndriy Gapon 	return (0);
10235c7e270fSAndriy Gapon }
10245c7e270fSAndriy Gapon 
10255c7e270fSAndriy Gapon SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT|CTLFLAG_RW,
10265c7e270fSAndriy Gapon 	&resettodr_period, 1800, sysctl_resettodr_period, "I",
10275c7e270fSAndriy Gapon 	"Save system time to RTC with this period (in seconds)");
10285c7e270fSAndriy Gapon TUNABLE_INT("machdep.rtc_save_period", &resettodr_period);
10295c7e270fSAndriy Gapon 
10305c7e270fSAndriy Gapon static void
10315c7e270fSAndriy Gapon start_periodic_resettodr(void *arg __unused)
10325c7e270fSAndriy Gapon {
10335c7e270fSAndriy Gapon 
10345c7e270fSAndriy Gapon 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
10355c7e270fSAndriy Gapon 	    SHUTDOWN_PRI_FIRST);
10365c7e270fSAndriy Gapon 	callout_init(&resettodr_callout, 1);
10375c7e270fSAndriy Gapon 	if (resettodr_period == 0)
10385c7e270fSAndriy Gapon 		return;
10395c7e270fSAndriy Gapon 	callout_reset(&resettodr_callout, resettodr_period * hz,
10405c7e270fSAndriy Gapon 	    periodic_resettodr, NULL);
10415c7e270fSAndriy Gapon }
10425c7e270fSAndriy Gapon 
10437b9df13bSAndriy Gapon SYSINIT(periodic_resettodr, SI_SUB_RUN_SCHEDULER, SI_ORDER_MIDDLE,
10445c7e270fSAndriy Gapon 	start_periodic_resettodr, NULL);
1045