kern_ntptime.c revision 228449
1254721Semaste/*-
2254721Semaste ***********************************************************************
3254721Semaste *								       *
4254721Semaste * Copyright (c) David L. Mills 1993-2001			       *
5254721Semaste *								       *
6254721Semaste * Permission to use, copy, modify, and distribute this software and   *
7254721Semaste * its documentation for any purpose and without fee is hereby	       *
8254721Semaste * granted, provided that the above copyright notice appears in all    *
9254721Semaste * copies and that both the copyright notice and this permission       *
10254721Semaste * notice appear in supporting documentation, and that the name	       *
11254721Semaste * University of Delaware not be used in advertising or publicity      *
12254721Semaste * pertaining to distribution of the software without specific,	       *
13254721Semaste * written prior permission. The University of Delaware makes no       *
14254721Semaste * representations about the suitability this software for any	       *
15254721Semaste * purpose. It is provided "as is" without express or implied	       *
16269024Semaste * warranty.							       *
17254721Semaste *								       *
18254721Semaste **********************************************************************/
19254721Semaste
20254721Semaste/*
21254721Semaste * Adapted from the original sources for FreeBSD and timecounters by:
22254721Semaste * Poul-Henning Kamp <phk@FreeBSD.org>.
23254721Semaste *
24254721Semaste * The 32bit version of the "LP" macros seems a bit past its "sell by"
25254721Semaste * date so I have retained only the 64bit version and included it directly
26254721Semaste * in this file.
27254721Semaste *
28254721Semaste * Only minor changes done to interface with the timecounters over in
29254721Semaste * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
30254721Semaste * confusing and/or plain wrong in that context.
31254721Semaste */
32254721Semaste
33254721Semaste#include <sys/cdefs.h>
34254721Semaste__FBSDID("$FreeBSD: head/sys/kern/kern_ntptime.c 228449 2011-12-13 00:38:50Z eadler $");
35254721Semaste
36254721Semaste#include "opt_ntp.h"
37254721Semaste
38254721Semaste#include <sys/param.h>
39254721Semaste#include <sys/systm.h>
40254721Semaste#include <sys/sysproto.h>
41254721Semaste#include <sys/eventhandler.h>
42254721Semaste#include <sys/kernel.h>
43254721Semaste#include <sys/priv.h>
44254721Semaste#include <sys/proc.h>
45263363Semaste#include <sys/lock.h>
46254721Semaste#include <sys/mutex.h>
47254721Semaste#include <sys/time.h>
48254721Semaste#include <sys/timex.h>
49254721Semaste#include <sys/timetc.h>
50254721Semaste#include <sys/timepps.h>
51254721Semaste#include <sys/syscallsubr.h>
52254721Semaste#include <sys/sysctl.h>
53254721Semaste
54254721Semaste#ifdef PPS_SYNC
55254721SemasteFEATURE(pps_sync, "Support usage of external PPS signal by kernel PLL");
56254721Semaste#endif
57254721Semaste
58263363Semaste/*
59254721Semaste * Single-precision macros for 64-bit machines
60254721Semaste */
61254721Semastetypedef int64_t l_fp;
62254721Semaste#define L_ADD(v, u)	((v) += (u))
63254721Semaste#define L_SUB(v, u)	((v) -= (u))
64254721Semaste#define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
65254721Semaste#define L_NEG(v)	((v) = -(v))
66263363Semaste#define L_RSHIFT(v, n) \
67263363Semaste	do { \
68254721Semaste		if ((v) < 0) \
69254721Semaste			(v) = -(-(v) >> (n)); \
70254721Semaste		else \
71254721Semaste			(v) = (v) >> (n); \
72254721Semaste	} while (0)
73254721Semaste#define L_MPY(v, a)	((v) *= (a))
74254721Semaste#define L_CLR(v)	((v) = 0)
75254721Semaste#define L_ISNEG(v)	((v) < 0)
76254721Semaste#define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
77254721Semaste#define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
78254721Semaste
79254721Semaste/*
80254721Semaste * Generic NTP kernel interface
81254721Semaste *
82254721Semaste * These routines constitute the Network Time Protocol (NTP) interfaces
83254721Semaste * for user and daemon application programs. The ntp_gettime() routine
84254721Semaste * provides the time, maximum error (synch distance) and estimated error
85254721Semaste * (dispersion) to client user application programs. The ntp_adjtime()
86254721Semaste * routine is used by the NTP daemon to adjust the system clock to an
87254721Semaste * externally derived time. The time offset and related variables set by
88254721Semaste * this routine are used by other routines in this module to adjust the
89254721Semaste * phase and frequency of the clock discipline loop which controls the
90254721Semaste * system clock.
91254721Semaste *
92254721Semaste * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
93254721Semaste * defined), the time at each tick interrupt is derived directly from
94269024Semaste * the kernel time variable. When the kernel time is reckoned in
95269024Semaste * microseconds, (NTP_NANO undefined), the time is derived from the
96269024Semaste * kernel time variable together with a variable representing the
97269024Semaste * leftover nanoseconds at the last tick interrupt. In either case, the
98269024Semaste * current nanosecond time is reckoned from these values plus an
99254721Semaste * interpolated value derived by the clock routines in another
100254721Semaste * architecture-specific module. The interpolation can use either a
101254721Semaste * dedicated counter or a processor cycle counter (PCC) implemented in
102254721Semaste * some architectures.
103254721Semaste *
104254721Semaste * Note that all routines must run at priority splclock or higher.
105254721Semaste */
106254721Semaste/*
107254721Semaste * Phase/frequency-lock loop (PLL/FLL) definitions
108254721Semaste *
109254721Semaste * The nanosecond clock discipline uses two variable types, time
110269024Semaste * variables and frequency variables. Both types are represented as 64-
111254721Semaste * bit fixed-point quantities with the decimal point between two 32-bit
112254721Semaste * halves. On a 32-bit machine, each half is represented as a single
113254721Semaste * word and mathematical operations are done using multiple-precision
114254721Semaste * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
115254721Semaste * used.
116254721Semaste *
117254721Semaste * A time variable is a signed 64-bit fixed-point number in ns and
118254721Semaste * fraction. It represents the remaining time offset to be amortized
119254721Semaste * over succeeding tick interrupts. The maximum time offset is about
120254721Semaste * 0.5 s and the resolution is about 2.3e-10 ns.
121254721Semaste *
122254721Semaste *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
123254721Semaste *  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
124254721Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
125269024Semaste * |s s s|			 ns				   |
126269024Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
127269024Semaste * |			    fraction				   |
128269024Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129254721Semaste *
130254721Semaste * A frequency variable is a signed 64-bit fixed-point number in ns/s
131254721Semaste * and fraction. It represents the ns and fraction to be added to the
132254721Semaste * kernel time variable at each second. The maximum frequency offset is
133254721Semaste * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
134254721Semaste *
135254721Semaste *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
136254721Semaste *  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
137254721Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
138254721Semaste * |s s s s s s s s s s s s s|	          ns/s			   |
139254721Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
140254721Semaste * |			    fraction				   |
141254721Semaste * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
142254721Semaste */
143254721Semaste/*
144254721Semaste * The following variables establish the state of the PLL/FLL and the
145254721Semaste * residual time and frequency offset of the local clock.
146254721Semaste */
147254721Semaste#define SHIFT_PLL	4		/* PLL loop gain (shift) */
148254721Semaste#define SHIFT_FLL	2		/* FLL loop gain (shift) */
149254721Semaste
150254721Semastestatic int time_state = TIME_OK;	/* clock state */
151254721Semastestatic int time_status = STA_UNSYNC;	/* clock status bits */
152254721Semastestatic long time_tai;			/* TAI offset (s) */
153254721Semastestatic long time_monitor;		/* last time offset scaled (ns) */
154254721Semastestatic long time_constant;		/* poll interval (shift) (s) */
155254721Semastestatic long time_precision = 1;		/* clock precision (ns) */
156254721Semastestatic long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
157254721Semastestatic long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
158254721Semastestatic long time_reftime;		/* time at last adjustment (s) */
159254721Semastestatic l_fp time_offset;		/* time offset (ns) */
160254721Semastestatic l_fp time_freq;			/* frequency offset (ns/s) */
161254721Semastestatic l_fp time_adj;			/* tick adjust (ns/s) */
162254721Semaste
163254721Semastestatic int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
164254721Semaste
165254721Semaste#ifdef PPS_SYNC
166254721Semaste/*
167254721Semaste * The following variables are used when a pulse-per-second (PPS) signal
168254721Semaste * is available and connected via a modem control lead. They establish
169254721Semaste * the engineering parameters of the clock discipline loop when
170254721Semaste * controlled by the PPS signal.
171254721Semaste */
172254721Semaste#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
173254721Semaste#define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
174254721Semaste#define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
175254721Semaste#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
176254721Semaste#define PPS_VALID	120		/* PPS signal watchdog max (s) */
177254721Semaste#define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
178254721Semaste#define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
179254721Semaste
180254721Semastestatic struct timespec pps_tf[3];	/* phase median filter */
181254721Semastestatic l_fp pps_freq;			/* scaled frequency offset (ns/s) */
182254721Semastestatic long pps_fcount;			/* frequency accumulator */
183254721Semastestatic long pps_jitter;			/* nominal jitter (ns) */
184254721Semastestatic long pps_stabil;			/* nominal stability (scaled ns/s) */
185254721Semastestatic long pps_lastsec;		/* time at last calibration (s) */
186254721Semastestatic int pps_valid;			/* signal watchdog counter */
187254721Semastestatic int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
188254721Semastestatic int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
189254721Semastestatic int pps_intcnt;			/* wander counter */
190254721Semaste
191254721Semaste/*
192254721Semaste * PPS signal quality monitors
193254721Semaste */
194254721Semastestatic long pps_calcnt;			/* calibration intervals */
195254721Semastestatic long pps_jitcnt;			/* jitter limit exceeded */
196254721Semastestatic long pps_stbcnt;			/* stability limit exceeded */
197254721Semastestatic long pps_errcnt;			/* calibration errors */
198254721Semaste#endif /* PPS_SYNC */
199254721Semaste/*
200254721Semaste * End of phase/frequency-lock loop (PLL/FLL) definitions
201254721Semaste */
202254721Semaste
203254721Semastestatic void ntp_init(void);
204254721Semastestatic void hardupdate(long offset);
205254721Semastestatic void ntp_gettime1(struct ntptimeval *ntvp);
206254721Semastestatic int ntp_is_time_error(void);
207254721Semaste
208254721Semastestatic int
209254721Semastentp_is_time_error(void)
210254721Semaste{
211254721Semaste	/*
212254721Semaste	 * Status word error decode. If any of these conditions occur,
213254721Semaste	 * an error is returned, instead of the status word. Most
214254721Semaste	 * applications will care only about the fact the system clock
215254721Semaste	 * may not be trusted, not about the details.
216269024Semaste	 *
217269024Semaste	 * Hardware or software error
218269024Semaste	 */
219269024Semaste	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
220269024Semaste
221269024Semaste	/*
222269024Semaste	 * PPS signal lost when either time or frequency synchronization
223269024Semaste	 * requested
224269024Semaste	 */
225269024Semaste	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
226269024Semaste	    !(time_status & STA_PPSSIGNAL)) ||
227269024Semaste
228269024Semaste	/*
229269024Semaste	 * PPS jitter exceeded when time synchronization requested
230269024Semaste	 */
231269024Semaste	    (time_status & STA_PPSTIME &&
232269024Semaste	    time_status & STA_PPSJITTER) ||
233269024Semaste
234269024Semaste	/*
235269024Semaste	 * PPS wander exceeded or calibration error when frequency
236269024Semaste	 * synchronization requested
237254721Semaste	 */
238254721Semaste	    (time_status & STA_PPSFREQ &&
239254721Semaste	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
240254721Semaste		return (1);
241254721Semaste
242254721Semaste	return (0);
243254721Semaste}
244254721Semaste
245254721Semastestatic void
246254721Semastentp_gettime1(struct ntptimeval *ntvp)
247254721Semaste{
248254721Semaste	struct timespec atv;	/* nanosecond time */
249254721Semaste
250254721Semaste	GIANT_REQUIRED;
251254721Semaste
252254721Semaste	nanotime(&atv);
253254721Semaste	ntvp->time.tv_sec = atv.tv_sec;
254254721Semaste	ntvp->time.tv_nsec = atv.tv_nsec;
255254721Semaste	ntvp->maxerror = time_maxerror;
256254721Semaste	ntvp->esterror = time_esterror;
257254721Semaste	ntvp->tai = time_tai;
258254721Semaste	ntvp->time_state = time_state;
259254721Semaste
260254721Semaste	if (ntp_is_time_error())
261254721Semaste		ntvp->time_state = TIME_ERROR;
262254721Semaste}
263254721Semaste
264254721Semaste/*
265254721Semaste * ntp_gettime() - NTP user application interface
266254721Semaste *
267254721Semaste * See the timex.h header file for synopsis and API description.  Note that
268254721Semaste * the TAI offset is returned in the ntvtimeval.tai structure member.
269254721Semaste */
270254721Semaste#ifndef _SYS_SYSPROTO_H_
271254721Semastestruct ntp_gettime_args {
272254721Semaste	struct ntptimeval *ntvp;
273254721Semaste};
274254721Semaste#endif
275254721Semaste/* ARGSUSED */
276254721Semasteint
277254721Semastesys_ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
278254721Semaste{
279254721Semaste	struct ntptimeval ntv;
280254721Semaste
281254721Semaste	mtx_lock(&Giant);
282254721Semaste	ntp_gettime1(&ntv);
283254721Semaste	mtx_unlock(&Giant);
284254721Semaste
285254721Semaste	td->td_retval[0] = ntv.time_state;
286254721Semaste	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
287254721Semaste}
288254721Semaste
289254721Semastestatic int
290254721Semastentp_sysctl(SYSCTL_HANDLER_ARGS)
291254721Semaste{
292254721Semaste	struct ntptimeval ntv;	/* temporary structure */
293254721Semaste
294254721Semaste	ntp_gettime1(&ntv);
295254721Semaste
296254721Semaste	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
297254721Semaste}
298254721Semaste
299254721SemasteSYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
300254721SemasteSYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
301254721Semaste	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
302254721Semaste
303254721Semaste#ifdef PPS_SYNC
304254721SemasteSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW,
305254721Semaste    &pps_shiftmax, 0, "Max interval duration (sec) (shift)");
306254721SemasteSYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW,
307254721Semaste    &pps_shift, 0, "Interval duration (sec) (shift)");
308254721SemasteSYSCTL_LONG(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD,
309254721Semaste    &time_monitor, 0, "Last time offset scaled (ns)");
310254721Semaste
311254721SemasteSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD,
312254721Semaste    &pps_freq, sizeof(pps_freq), "I", "Scaled frequency offset (ns/sec)");
313254721SemasteSYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD,
314254721Semaste    &time_freq, sizeof(time_freq), "I", "Frequency offset (ns/sec)");
315254721Semaste#endif
316254721Semaste
317254721Semaste/*
318254721Semaste * ntp_adjtime() - NTP daemon application interface
319254721Semaste *
320254721Semaste * See the timex.h header file for synopsis and API description.  Note that
321254721Semaste * the timex.constant structure member has a dual purpose to set the time
322254721Semaste * constant and to set the TAI offset.
323254721Semaste */
324254721Semaste#ifndef _SYS_SYSPROTO_H_
325254721Semastestruct ntp_adjtime_args {
326254721Semaste	struct timex *tp;
327254721Semaste};
328254721Semaste#endif
329254721Semaste
330254721Semasteint
331254721Semastesys_ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
332254721Semaste{
333254721Semaste	struct timex ntv;	/* temporary structure */
334254721Semaste	long freq;		/* frequency ns/s) */
335254721Semaste	int modes;		/* mode bits from structure */
336254721Semaste	int s;			/* caller priority */
337254721Semaste	int error;
338254721Semaste
339254721Semaste	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
340254721Semaste	if (error)
341254721Semaste		return(error);
342254721Semaste
343254721Semaste	/*
344254721Semaste	 * Update selected clock variables - only the superuser can
345254721Semaste	 * change anything. Note that there is no error checking here on
346254721Semaste	 * the assumption the superuser should know what it is doing.
347254721Semaste	 * Note that either the time constant or TAI offset are loaded
348254721Semaste	 * from the ntv.constant member, depending on the mode bits. If
349254721Semaste	 * the STA_PLL bit in the status word is cleared, the state and
350254721Semaste	 * status words are reset to the initial values at boot.
351254721Semaste	 */
352254721Semaste	mtx_lock(&Giant);
353254721Semaste	modes = ntv.modes;
354254721Semaste	if (modes)
355254721Semaste		error = priv_check(td, PRIV_NTP_ADJTIME);
356254721Semaste	if (error)
357254721Semaste		goto done2;
358254721Semaste	s = splclock();
359254721Semaste	if (modes & MOD_MAXERROR)
360254721Semaste		time_maxerror = ntv.maxerror;
361254721Semaste	if (modes & MOD_ESTERROR)
362254721Semaste		time_esterror = ntv.esterror;
363254721Semaste	if (modes & MOD_STATUS) {
364254721Semaste		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
365254721Semaste			time_state = TIME_OK;
366254721Semaste			time_status = STA_UNSYNC;
367254721Semaste#ifdef PPS_SYNC
368254721Semaste			pps_shift = PPS_FAVG;
369254721Semaste#endif /* PPS_SYNC */
370254721Semaste		}
371254721Semaste		time_status &= STA_RONLY;
372254721Semaste		time_status |= ntv.status & ~STA_RONLY;
373254721Semaste	}
374254721Semaste	if (modes & MOD_TIMECONST) {
375254721Semaste		if (ntv.constant < 0)
376254721Semaste			time_constant = 0;
377254721Semaste		else if (ntv.constant > MAXTC)
378254721Semaste			time_constant = MAXTC;
379254721Semaste		else
380254721Semaste			time_constant = ntv.constant;
381254721Semaste	}
382254721Semaste	if (modes & MOD_TAI) {
383254721Semaste		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
384254721Semaste			time_tai = ntv.constant;
385254721Semaste	}
386254721Semaste#ifdef PPS_SYNC
387254721Semaste	if (modes & MOD_PPSMAX) {
388254721Semaste		if (ntv.shift < PPS_FAVG)
389254721Semaste			pps_shiftmax = PPS_FAVG;
390254721Semaste		else if (ntv.shift > PPS_FAVGMAX)
391254721Semaste			pps_shiftmax = PPS_FAVGMAX;
392254721Semaste		else
393254721Semaste			pps_shiftmax = ntv.shift;
394254721Semaste	}
395254721Semaste#endif /* PPS_SYNC */
396254721Semaste	if (modes & MOD_NANO)
397254721Semaste		time_status |= STA_NANO;
398254721Semaste	if (modes & MOD_MICRO)
399254721Semaste		time_status &= ~STA_NANO;
400254721Semaste	if (modes & MOD_CLKB)
401254721Semaste		time_status |= STA_CLK;
402254721Semaste	if (modes & MOD_CLKA)
403254721Semaste		time_status &= ~STA_CLK;
404254721Semaste	if (modes & MOD_FREQUENCY) {
405254721Semaste		freq = (ntv.freq * 1000LL) >> 16;
406254721Semaste		if (freq > MAXFREQ)
407254721Semaste			L_LINT(time_freq, MAXFREQ);
408254721Semaste		else if (freq < -MAXFREQ)
409254721Semaste			L_LINT(time_freq, -MAXFREQ);
410254721Semaste		else {
411254721Semaste			/*
412254721Semaste			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
413254721Semaste			 * time_freq is [ns/s * 2^32]
414254721Semaste			 */
415254721Semaste			time_freq = ntv.freq * 1000LL * 65536LL;
416254721Semaste		}
417254721Semaste#ifdef PPS_SYNC
418254721Semaste		pps_freq = time_freq;
419254721Semaste#endif /* PPS_SYNC */
420254721Semaste	}
421254721Semaste	if (modes & MOD_OFFSET) {
422254721Semaste		if (time_status & STA_NANO)
423254721Semaste			hardupdate(ntv.offset);
424254721Semaste		else
425254721Semaste			hardupdate(ntv.offset * 1000);
426254721Semaste	}
427254721Semaste
428254721Semaste	/*
429254721Semaste	 * Retrieve all clock variables. Note that the TAI offset is
430254721Semaste	 * returned only by ntp_gettime();
431254721Semaste	 */
432254721Semaste	if (time_status & STA_NANO)
433254721Semaste		ntv.offset = L_GINT(time_offset);
434269024Semaste	else
435269024Semaste		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
436254721Semaste	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
437254721Semaste	ntv.maxerror = time_maxerror;
438254721Semaste	ntv.esterror = time_esterror;
439254721Semaste	ntv.status = time_status;
440254721Semaste	ntv.constant = time_constant;
441254721Semaste	if (time_status & STA_NANO)
442254721Semaste		ntv.precision = time_precision;
443254721Semaste	else
444254721Semaste		ntv.precision = time_precision / 1000;
445254721Semaste	ntv.tolerance = MAXFREQ * SCALE_PPM;
446254721Semaste#ifdef PPS_SYNC
447254721Semaste	ntv.shift = pps_shift;
448254721Semaste	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
449254721Semaste	if (time_status & STA_NANO)
450254721Semaste		ntv.jitter = pps_jitter;
451254721Semaste	else
452254721Semaste		ntv.jitter = pps_jitter / 1000;
453254721Semaste	ntv.stabil = pps_stabil;
454254721Semaste	ntv.calcnt = pps_calcnt;
455254721Semaste	ntv.errcnt = pps_errcnt;
456254721Semaste	ntv.jitcnt = pps_jitcnt;
457254721Semaste	ntv.stbcnt = pps_stbcnt;
458254721Semaste#endif /* PPS_SYNC */
459254721Semaste	splx(s);
460
461	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
462	if (error)
463		goto done2;
464
465	if (ntp_is_time_error())
466		td->td_retval[0] = TIME_ERROR;
467	else
468		td->td_retval[0] = time_state;
469
470done2:
471	mtx_unlock(&Giant);
472	return (error);
473}
474
475/*
476 * second_overflow() - called after ntp_tick_adjust()
477 *
478 * This routine is ordinarily called immediately following the above
479 * routine ntp_tick_adjust(). While these two routines are normally
480 * combined, they are separated here only for the purposes of
481 * simulation.
482 */
483void
484ntp_update_second(int64_t *adjustment, time_t *newsec)
485{
486	int tickrate;
487	l_fp ftemp;		/* 32/64-bit temporary */
488
489	/*
490	 * On rollover of the second both the nanosecond and microsecond
491	 * clocks are updated and the state machine cranked as
492	 * necessary. The phase adjustment to be used for the next
493	 * second is calculated and the maximum error is increased by
494	 * the tolerance.
495	 */
496	time_maxerror += MAXFREQ / 1000;
497
498	/*
499	 * Leap second processing. If in leap-insert state at
500	 * the end of the day, the system clock is set back one
501	 * second; if in leap-delete state, the system clock is
502	 * set ahead one second. The nano_time() routine or
503	 * external clock driver will insure that reported time
504	 * is always monotonic.
505	 */
506	switch (time_state) {
507
508		/*
509		 * No warning.
510		 */
511		case TIME_OK:
512		if (time_status & STA_INS)
513			time_state = TIME_INS;
514		else if (time_status & STA_DEL)
515			time_state = TIME_DEL;
516		break;
517
518		/*
519		 * Insert second 23:59:60 following second
520		 * 23:59:59.
521		 */
522		case TIME_INS:
523		if (!(time_status & STA_INS))
524			time_state = TIME_OK;
525		else if ((*newsec) % 86400 == 0) {
526			(*newsec)--;
527			time_state = TIME_OOP;
528			time_tai++;
529		}
530		break;
531
532		/*
533		 * Delete second 23:59:59.
534		 */
535		case TIME_DEL:
536		if (!(time_status & STA_DEL))
537			time_state = TIME_OK;
538		else if (((*newsec) + 1) % 86400 == 0) {
539			(*newsec)++;
540			time_tai--;
541			time_state = TIME_WAIT;
542		}
543		break;
544
545		/*
546		 * Insert second in progress.
547		 */
548		case TIME_OOP:
549			time_state = TIME_WAIT;
550		break;
551
552		/*
553		 * Wait for status bits to clear.
554		 */
555		case TIME_WAIT:
556		if (!(time_status & (STA_INS | STA_DEL)))
557			time_state = TIME_OK;
558	}
559
560	/*
561	 * Compute the total time adjustment for the next second
562	 * in ns. The offset is reduced by a factor depending on
563	 * whether the PPS signal is operating. Note that the
564	 * value is in effect scaled by the clock frequency,
565	 * since the adjustment is added at each tick interrupt.
566	 */
567	ftemp = time_offset;
568#ifdef PPS_SYNC
569	/* XXX even if PPS signal dies we should finish adjustment ? */
570	if (time_status & STA_PPSTIME && time_status &
571	    STA_PPSSIGNAL)
572		L_RSHIFT(ftemp, pps_shift);
573	else
574		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
575#else
576		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
577#endif /* PPS_SYNC */
578	time_adj = ftemp;
579	L_SUB(time_offset, ftemp);
580	L_ADD(time_adj, time_freq);
581
582	/*
583	 * Apply any correction from adjtime(2).  If more than one second
584	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
585	 * until the last second is slewed the final < 500 usecs.
586	 */
587	if (time_adjtime != 0) {
588		if (time_adjtime > 1000000)
589			tickrate = 5000;
590		else if (time_adjtime < -1000000)
591			tickrate = -5000;
592		else if (time_adjtime > 500)
593			tickrate = 500;
594		else if (time_adjtime < -500)
595			tickrate = -500;
596		else
597			tickrate = time_adjtime;
598		time_adjtime -= tickrate;
599		L_LINT(ftemp, tickrate * 1000);
600		L_ADD(time_adj, ftemp);
601	}
602	*adjustment = time_adj;
603
604#ifdef PPS_SYNC
605	if (pps_valid > 0)
606		pps_valid--;
607	else
608		time_status &= ~STA_PPSSIGNAL;
609#endif /* PPS_SYNC */
610}
611
612/*
613 * ntp_init() - initialize variables and structures
614 *
615 * This routine must be called after the kernel variables hz and tick
616 * are set or changed and before the next tick interrupt. In this
617 * particular implementation, these values are assumed set elsewhere in
618 * the kernel. The design allows the clock frequency and tick interval
619 * to be changed while the system is running. So, this routine should
620 * probably be integrated with the code that does that.
621 */
622static void
623ntp_init()
624{
625
626	/*
627	 * The following variables are initialized only at startup. Only
628	 * those structures not cleared by the compiler need to be
629	 * initialized, and these only in the simulator. In the actual
630	 * kernel, any nonzero values here will quickly evaporate.
631	 */
632	L_CLR(time_offset);
633	L_CLR(time_freq);
634#ifdef PPS_SYNC
635	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
636	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
637	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
638	pps_fcount = 0;
639	L_CLR(pps_freq);
640#endif /* PPS_SYNC */
641}
642
643SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
644
645/*
646 * hardupdate() - local clock update
647 *
648 * This routine is called by ntp_adjtime() to update the local clock
649 * phase and frequency. The implementation is of an adaptive-parameter,
650 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
651 * time and frequency offset estimates for each call. If the kernel PPS
652 * discipline code is configured (PPS_SYNC), the PPS signal itself
653 * determines the new time offset, instead of the calling argument.
654 * Presumably, calls to ntp_adjtime() occur only when the caller
655 * believes the local clock is valid within some bound (+-128 ms with
656 * NTP). If the caller's time is far different than the PPS time, an
657 * argument will ensue, and it's not clear who will lose.
658 *
659 * For uncompensated quartz crystal oscillators and nominal update
660 * intervals less than 256 s, operation should be in phase-lock mode,
661 * where the loop is disciplined to phase. For update intervals greater
662 * than 1024 s, operation should be in frequency-lock mode, where the
663 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
664 * is selected by the STA_MODE status bit.
665 */
666static void
667hardupdate(offset)
668	long offset;		/* clock offset (ns) */
669{
670	long mtemp;
671	l_fp ftemp;
672
673	/*
674	 * Select how the phase is to be controlled and from which
675	 * source. If the PPS signal is present and enabled to
676	 * discipline the time, the PPS offset is used; otherwise, the
677	 * argument offset is used.
678	 */
679	if (!(time_status & STA_PLL))
680		return;
681	if (!(time_status & STA_PPSTIME && time_status &
682	    STA_PPSSIGNAL)) {
683		if (offset > MAXPHASE)
684			time_monitor = MAXPHASE;
685		else if (offset < -MAXPHASE)
686			time_monitor = -MAXPHASE;
687		else
688			time_monitor = offset;
689		L_LINT(time_offset, time_monitor);
690	}
691
692	/*
693	 * Select how the frequency is to be controlled and in which
694	 * mode (PLL or FLL). If the PPS signal is present and enabled
695	 * to discipline the frequency, the PPS frequency is used;
696	 * otherwise, the argument offset is used to compute it.
697	 */
698	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
699		time_reftime = time_second;
700		return;
701	}
702	if (time_status & STA_FREQHOLD || time_reftime == 0)
703		time_reftime = time_second;
704	mtemp = time_second - time_reftime;
705	L_LINT(ftemp, time_monitor);
706	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
707	L_MPY(ftemp, mtemp);
708	L_ADD(time_freq, ftemp);
709	time_status &= ~STA_MODE;
710	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
711	    MAXSEC)) {
712		L_LINT(ftemp, (time_monitor << 4) / mtemp);
713		L_RSHIFT(ftemp, SHIFT_FLL + 4);
714		L_ADD(time_freq, ftemp);
715		time_status |= STA_MODE;
716	}
717	time_reftime = time_second;
718	if (L_GINT(time_freq) > MAXFREQ)
719		L_LINT(time_freq, MAXFREQ);
720	else if (L_GINT(time_freq) < -MAXFREQ)
721		L_LINT(time_freq, -MAXFREQ);
722}
723
724#ifdef PPS_SYNC
725/*
726 * hardpps() - discipline CPU clock oscillator to external PPS signal
727 *
728 * This routine is called at each PPS interrupt in order to discipline
729 * the CPU clock oscillator to the PPS signal. There are two independent
730 * first-order feedback loops, one for the phase, the other for the
731 * frequency. The phase loop measures and grooms the PPS phase offset
732 * and leaves it in a handy spot for the seconds overflow routine. The
733 * frequency loop averages successive PPS phase differences and
734 * calculates the PPS frequency offset, which is also processed by the
735 * seconds overflow routine. The code requires the caller to capture the
736 * time and architecture-dependent hardware counter values in
737 * nanoseconds at the on-time PPS signal transition.
738 *
739 * Note that, on some Unix systems this routine runs at an interrupt
740 * priority level higher than the timer interrupt routine hardclock().
741 * Therefore, the variables used are distinct from the hardclock()
742 * variables, except for the actual time and frequency variables, which
743 * are determined by this routine and updated atomically.
744 */
745void
746hardpps(tsp, nsec)
747	struct timespec *tsp;	/* time at PPS */
748	long nsec;		/* hardware counter at PPS */
749{
750	long u_sec, u_nsec, v_nsec; /* temps */
751	l_fp ftemp;
752
753	/*
754	 * The signal is first processed by a range gate and frequency
755	 * discriminator. The range gate rejects noise spikes outside
756	 * the range +-500 us. The frequency discriminator rejects input
757	 * signals with apparent frequency outside the range 1 +-500
758	 * PPM. If two hits occur in the same second, we ignore the
759	 * later hit; if not and a hit occurs outside the range gate,
760	 * keep the later hit for later comparison, but do not process
761	 * it.
762	 */
763	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
764	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
765	pps_valid = PPS_VALID;
766	u_sec = tsp->tv_sec;
767	u_nsec = tsp->tv_nsec;
768	if (u_nsec >= (NANOSECOND >> 1)) {
769		u_nsec -= NANOSECOND;
770		u_sec++;
771	}
772	v_nsec = u_nsec - pps_tf[0].tv_nsec;
773	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
774	    MAXFREQ)
775		return;
776	pps_tf[2] = pps_tf[1];
777	pps_tf[1] = pps_tf[0];
778	pps_tf[0].tv_sec = u_sec;
779	pps_tf[0].tv_nsec = u_nsec;
780
781	/*
782	 * Compute the difference between the current and previous
783	 * counter values. If the difference exceeds 0.5 s, assume it
784	 * has wrapped around, so correct 1.0 s. If the result exceeds
785	 * the tick interval, the sample point has crossed a tick
786	 * boundary during the last second, so correct the tick. Very
787	 * intricate.
788	 */
789	u_nsec = nsec;
790	if (u_nsec > (NANOSECOND >> 1))
791		u_nsec -= NANOSECOND;
792	else if (u_nsec < -(NANOSECOND >> 1))
793		u_nsec += NANOSECOND;
794	pps_fcount += u_nsec;
795	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
796		return;
797	time_status &= ~STA_PPSJITTER;
798
799	/*
800	 * A three-stage median filter is used to help denoise the PPS
801	 * time. The median sample becomes the time offset estimate; the
802	 * difference between the other two samples becomes the time
803	 * dispersion (jitter) estimate.
804	 */
805	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
806		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
807			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
808			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
809		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
810			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
811			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
812		} else {
813			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
814			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
815		}
816	} else {
817		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
818			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
819			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
820		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
821			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
822			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
823		} else {
824			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
825			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
826		}
827	}
828
829	/*
830	 * Nominal jitter is due to PPS signal noise and interrupt
831	 * latency. If it exceeds the popcorn threshold, the sample is
832	 * discarded. otherwise, if so enabled, the time offset is
833	 * updated. We can tolerate a modest loss of data here without
834	 * much degrading time accuracy.
835	 */
836	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
837		time_status |= STA_PPSJITTER;
838		pps_jitcnt++;
839	} else if (time_status & STA_PPSTIME) {
840		time_monitor = -v_nsec;
841		L_LINT(time_offset, time_monitor);
842	}
843	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
844	u_sec = pps_tf[0].tv_sec - pps_lastsec;
845	if (u_sec < (1 << pps_shift))
846		return;
847
848	/*
849	 * At the end of the calibration interval the difference between
850	 * the first and last counter values becomes the scaled
851	 * frequency. It will later be divided by the length of the
852	 * interval to determine the frequency update. If the frequency
853	 * exceeds a sanity threshold, or if the actual calibration
854	 * interval is not equal to the expected length, the data are
855	 * discarded. We can tolerate a modest loss of data here without
856	 * much degrading frequency accuracy.
857	 */
858	pps_calcnt++;
859	v_nsec = -pps_fcount;
860	pps_lastsec = pps_tf[0].tv_sec;
861	pps_fcount = 0;
862	u_nsec = MAXFREQ << pps_shift;
863	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
864	    pps_shift)) {
865		time_status |= STA_PPSERROR;
866		pps_errcnt++;
867		return;
868	}
869
870	/*
871	 * Here the raw frequency offset and wander (stability) is
872	 * calculated. If the wander is less than the wander threshold
873	 * for four consecutive averaging intervals, the interval is
874	 * doubled; if it is greater than the threshold for four
875	 * consecutive intervals, the interval is halved. The scaled
876	 * frequency offset is converted to frequency offset. The
877	 * stability metric is calculated as the average of recent
878	 * frequency changes, but is used only for performance
879	 * monitoring.
880	 */
881	L_LINT(ftemp, v_nsec);
882	L_RSHIFT(ftemp, pps_shift);
883	L_SUB(ftemp, pps_freq);
884	u_nsec = L_GINT(ftemp);
885	if (u_nsec > PPS_MAXWANDER) {
886		L_LINT(ftemp, PPS_MAXWANDER);
887		pps_intcnt--;
888		time_status |= STA_PPSWANDER;
889		pps_stbcnt++;
890	} else if (u_nsec < -PPS_MAXWANDER) {
891		L_LINT(ftemp, -PPS_MAXWANDER);
892		pps_intcnt--;
893		time_status |= STA_PPSWANDER;
894		pps_stbcnt++;
895	} else {
896		pps_intcnt++;
897	}
898	if (pps_intcnt >= 4) {
899		pps_intcnt = 4;
900		if (pps_shift < pps_shiftmax) {
901			pps_shift++;
902			pps_intcnt = 0;
903		}
904	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
905		pps_intcnt = -4;
906		if (pps_shift > PPS_FAVG) {
907			pps_shift--;
908			pps_intcnt = 0;
909		}
910	}
911	if (u_nsec < 0)
912		u_nsec = -u_nsec;
913	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
914
915	/*
916	 * The PPS frequency is recalculated and clamped to the maximum
917	 * MAXFREQ. If enabled, the system clock frequency is updated as
918	 * well.
919	 */
920	L_ADD(pps_freq, ftemp);
921	u_nsec = L_GINT(pps_freq);
922	if (u_nsec > MAXFREQ)
923		L_LINT(pps_freq, MAXFREQ);
924	else if (u_nsec < -MAXFREQ)
925		L_LINT(pps_freq, -MAXFREQ);
926	if (time_status & STA_PPSFREQ)
927		time_freq = pps_freq;
928}
929#endif /* PPS_SYNC */
930
931#ifndef _SYS_SYSPROTO_H_
932struct adjtime_args {
933	struct timeval *delta;
934	struct timeval *olddelta;
935};
936#endif
937/* ARGSUSED */
938int
939sys_adjtime(struct thread *td, struct adjtime_args *uap)
940{
941	struct timeval delta, olddelta, *deltap;
942	int error;
943
944	if (uap->delta) {
945		error = copyin(uap->delta, &delta, sizeof(delta));
946		if (error)
947			return (error);
948		deltap = &delta;
949	} else
950		deltap = NULL;
951	error = kern_adjtime(td, deltap, &olddelta);
952	if (uap->olddelta && error == 0)
953		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
954	return (error);
955}
956
957int
958kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
959{
960	struct timeval atv;
961	int error;
962
963	mtx_lock(&Giant);
964	if (olddelta) {
965		atv.tv_sec = time_adjtime / 1000000;
966		atv.tv_usec = time_adjtime % 1000000;
967		if (atv.tv_usec < 0) {
968			atv.tv_usec += 1000000;
969			atv.tv_sec--;
970		}
971		*olddelta = atv;
972	}
973	if (delta) {
974		if ((error = priv_check(td, PRIV_ADJTIME))) {
975			mtx_unlock(&Giant);
976			return (error);
977		}
978		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
979		    delta->tv_usec;
980	}
981	mtx_unlock(&Giant);
982	return (0);
983}
984
985static struct callout resettodr_callout;
986static int resettodr_period = 1800;
987
988static void
989periodic_resettodr(void *arg __unused)
990{
991
992	if (!ntp_is_time_error()) {
993		mtx_lock(&Giant);
994		resettodr();
995		mtx_unlock(&Giant);
996	}
997	if (resettodr_period > 0)
998		callout_schedule(&resettodr_callout, resettodr_period * hz);
999}
1000
1001static void
1002shutdown_resettodr(void *arg __unused, int howto __unused)
1003{
1004
1005	callout_drain(&resettodr_callout);
1006	if (resettodr_period > 0 && !ntp_is_time_error()) {
1007		mtx_lock(&Giant);
1008		resettodr();
1009		mtx_unlock(&Giant);
1010	}
1011}
1012
1013static int
1014sysctl_resettodr_period(SYSCTL_HANDLER_ARGS)
1015{
1016	int error;
1017
1018	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1019	if (error || !req->newptr)
1020		return (error);
1021	if (resettodr_period == 0)
1022		callout_stop(&resettodr_callout);
1023	else
1024		callout_reset(&resettodr_callout, resettodr_period * hz,
1025		    periodic_resettodr, NULL);
1026	return (0);
1027}
1028
1029SYSCTL_PROC(_machdep, OID_AUTO, rtc_save_period, CTLTYPE_INT|CTLFLAG_RW,
1030	&resettodr_period, 1800, sysctl_resettodr_period, "I",
1031	"Save system time to RTC with this period (in seconds)");
1032TUNABLE_INT("machdep.rtc_save_period", &resettodr_period);
1033
1034static void
1035start_periodic_resettodr(void *arg __unused)
1036{
1037
1038	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_resettodr, NULL,
1039	    SHUTDOWN_PRI_FIRST);
1040	callout_init(&resettodr_callout, 1);
1041	if (resettodr_period == 0)
1042		return;
1043	callout_reset(&resettodr_callout, resettodr_period * hz,
1044	    periodic_resettodr, NULL);
1045}
1046
1047SYSINIT(periodic_resettodr, SI_SUB_RUN_SCHEDULER, SI_ORDER_MIDDLE,
1048	start_periodic_resettodr, NULL);
1049