kern_ntptime.c revision 207359
1/*-
2 ***********************************************************************
3 *								       *
4 * Copyright (c) David L. Mills 1993-2001			       *
5 *								       *
6 * Permission to use, copy, modify, and distribute this software and   *
7 * its documentation for any purpose and without fee is hereby	       *
8 * granted, provided that the above copyright notice appears in all    *
9 * copies and that both the copyright notice and this permission       *
10 * notice appear in supporting documentation, and that the name	       *
11 * University of Delaware not be used in advertising or publicity      *
12 * pertaining to distribution of the software without specific,	       *
13 * written prior permission. The University of Delaware makes no       *
14 * representations about the suitability this software for any	       *
15 * purpose. It is provided "as is" without express or implied	       *
16 * warranty.							       *
17 *								       *
18 **********************************************************************/
19
20/*
21 * Adapted from the original sources for FreeBSD and timecounters by:
22 * Poul-Henning Kamp <phk@FreeBSD.org>.
23 *
24 * The 32bit version of the "LP" macros seems a bit past its "sell by"
25 * date so I have retained only the 64bit version and included it directly
26 * in this file.
27 *
28 * Only minor changes done to interface with the timecounters over in
29 * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
30 * confusing and/or plain wrong in that context.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/kern/kern_ntptime.c 207359 2010-04-29 09:02:21Z avg $");
35
36#include "opt_ntp.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/sysproto.h>
41#include <sys/kernel.h>
42#include <sys/priv.h>
43#include <sys/proc.h>
44#include <sys/lock.h>
45#include <sys/mutex.h>
46#include <sys/time.h>
47#include <sys/timex.h>
48#include <sys/timetc.h>
49#include <sys/timepps.h>
50#include <sys/syscallsubr.h>
51#include <sys/sysctl.h>
52
53/*
54 * Single-precision macros for 64-bit machines
55 */
56typedef int64_t l_fp;
57#define L_ADD(v, u)	((v) += (u))
58#define L_SUB(v, u)	((v) -= (u))
59#define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
60#define L_NEG(v)	((v) = -(v))
61#define L_RSHIFT(v, n) \
62	do { \
63		if ((v) < 0) \
64			(v) = -(-(v) >> (n)); \
65		else \
66			(v) = (v) >> (n); \
67	} while (0)
68#define L_MPY(v, a)	((v) *= (a))
69#define L_CLR(v)	((v) = 0)
70#define L_ISNEG(v)	((v) < 0)
71#define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
72#define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
73
74/*
75 * Generic NTP kernel interface
76 *
77 * These routines constitute the Network Time Protocol (NTP) interfaces
78 * for user and daemon application programs. The ntp_gettime() routine
79 * provides the time, maximum error (synch distance) and estimated error
80 * (dispersion) to client user application programs. The ntp_adjtime()
81 * routine is used by the NTP daemon to adjust the system clock to an
82 * externally derived time. The time offset and related variables set by
83 * this routine are used by other routines in this module to adjust the
84 * phase and frequency of the clock discipline loop which controls the
85 * system clock.
86 *
87 * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
88 * defined), the time at each tick interrupt is derived directly from
89 * the kernel time variable. When the kernel time is reckoned in
90 * microseconds, (NTP_NANO undefined), the time is derived from the
91 * kernel time variable together with a variable representing the
92 * leftover nanoseconds at the last tick interrupt. In either case, the
93 * current nanosecond time is reckoned from these values plus an
94 * interpolated value derived by the clock routines in another
95 * architecture-specific module. The interpolation can use either a
96 * dedicated counter or a processor cycle counter (PCC) implemented in
97 * some architectures.
98 *
99 * Note that all routines must run at priority splclock or higher.
100 */
101/*
102 * Phase/frequency-lock loop (PLL/FLL) definitions
103 *
104 * The nanosecond clock discipline uses two variable types, time
105 * variables and frequency variables. Both types are represented as 64-
106 * bit fixed-point quantities with the decimal point between two 32-bit
107 * halves. On a 32-bit machine, each half is represented as a single
108 * word and mathematical operations are done using multiple-precision
109 * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
110 * used.
111 *
112 * A time variable is a signed 64-bit fixed-point number in ns and
113 * fraction. It represents the remaining time offset to be amortized
114 * over succeeding tick interrupts. The maximum time offset is about
115 * 0.5 s and the resolution is about 2.3e-10 ns.
116 *
117 *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
118 *  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
119 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120 * |s s s|			 ns				   |
121 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122 * |			    fraction				   |
123 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124 *
125 * A frequency variable is a signed 64-bit fixed-point number in ns/s
126 * and fraction. It represents the ns and fraction to be added to the
127 * kernel time variable at each second. The maximum frequency offset is
128 * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
129 *
130 *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
131 *  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
132 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
133 * |s s s s s s s s s s s s s|	          ns/s			   |
134 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
135 * |			    fraction				   |
136 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
137 */
138/*
139 * The following variables establish the state of the PLL/FLL and the
140 * residual time and frequency offset of the local clock.
141 */
142#define SHIFT_PLL	4		/* PLL loop gain (shift) */
143#define SHIFT_FLL	2		/* FLL loop gain (shift) */
144
145static int time_state = TIME_OK;	/* clock state */
146static int time_status = STA_UNSYNC;	/* clock status bits */
147static long time_tai;			/* TAI offset (s) */
148static long time_monitor;		/* last time offset scaled (ns) */
149static long time_constant;		/* poll interval (shift) (s) */
150static long time_precision = 1;		/* clock precision (ns) */
151static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
152static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
153static long time_reftime;		/* time at last adjustment (s) */
154static l_fp time_offset;		/* time offset (ns) */
155static l_fp time_freq;			/* frequency offset (ns/s) */
156static l_fp time_adj;			/* tick adjust (ns/s) */
157
158static int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
159
160#ifdef PPS_SYNC
161/*
162 * The following variables are used when a pulse-per-second (PPS) signal
163 * is available and connected via a modem control lead. They establish
164 * the engineering parameters of the clock discipline loop when
165 * controlled by the PPS signal.
166 */
167#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
168#define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
169#define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
170#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
171#define PPS_VALID	120		/* PPS signal watchdog max (s) */
172#define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
173#define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
174
175static struct timespec pps_tf[3];	/* phase median filter */
176static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
177static long pps_fcount;			/* frequency accumulator */
178static long pps_jitter;			/* nominal jitter (ns) */
179static long pps_stabil;			/* nominal stability (scaled ns/s) */
180static long pps_lastsec;		/* time at last calibration (s) */
181static int pps_valid;			/* signal watchdog counter */
182static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
183static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
184static int pps_intcnt;			/* wander counter */
185
186/*
187 * PPS signal quality monitors
188 */
189static long pps_calcnt;			/* calibration intervals */
190static long pps_jitcnt;			/* jitter limit exceeded */
191static long pps_stbcnt;			/* stability limit exceeded */
192static long pps_errcnt;			/* calibration errors */
193#endif /* PPS_SYNC */
194/*
195 * End of phase/frequency-lock loop (PLL/FLL) definitions
196 */
197
198static void ntp_init(void);
199static void hardupdate(long offset);
200static void ntp_gettime1(struct ntptimeval *ntvp);
201static int ntp_is_time_error(void);
202
203static int
204ntp_is_time_error(void)
205{
206	/*
207	 * Status word error decode. If any of these conditions occur,
208	 * an error is returned, instead of the status word. Most
209	 * applications will care only about the fact the system clock
210	 * may not be trusted, not about the details.
211	 *
212	 * Hardware or software error
213	 */
214	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
215
216	/*
217	 * PPS signal lost when either time or frequency synchronization
218	 * requested
219	 */
220	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
221	    !(time_status & STA_PPSSIGNAL)) ||
222
223	/*
224	 * PPS jitter exceeded when time synchronization requested
225	 */
226	    (time_status & STA_PPSTIME &&
227	    time_status & STA_PPSJITTER) ||
228
229	/*
230	 * PPS wander exceeded or calibration error when frequency
231	 * synchronization requested
232	 */
233	    (time_status & STA_PPSFREQ &&
234	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
235		return (1);
236
237	return (0);
238}
239
240static void
241ntp_gettime1(struct ntptimeval *ntvp)
242{
243	struct timespec atv;	/* nanosecond time */
244
245	GIANT_REQUIRED;
246
247	nanotime(&atv);
248	ntvp->time.tv_sec = atv.tv_sec;
249	ntvp->time.tv_nsec = atv.tv_nsec;
250	ntvp->maxerror = time_maxerror;
251	ntvp->esterror = time_esterror;
252	ntvp->tai = time_tai;
253	ntvp->time_state = time_state;
254
255	if (ntp_is_time_error())
256		ntvp->time_state = TIME_ERROR;
257}
258
259/*
260 * ntp_gettime() - NTP user application interface
261 *
262 * See the timex.h header file for synopsis and API description.  Note that
263 * the TAI offset is returned in the ntvtimeval.tai structure member.
264 */
265#ifndef _SYS_SYSPROTO_H_
266struct ntp_gettime_args {
267	struct ntptimeval *ntvp;
268};
269#endif
270/* ARGSUSED */
271int
272ntp_gettime(struct thread *td, struct ntp_gettime_args *uap)
273{
274	struct ntptimeval ntv;
275
276	mtx_lock(&Giant);
277	ntp_gettime1(&ntv);
278	mtx_unlock(&Giant);
279
280	td->td_retval[0] = ntv.time_state;
281	return (copyout(&ntv, uap->ntvp, sizeof(ntv)));
282}
283
284static int
285ntp_sysctl(SYSCTL_HANDLER_ARGS)
286{
287	struct ntptimeval ntv;	/* temporary structure */
288
289	ntp_gettime1(&ntv);
290
291	return (sysctl_handle_opaque(oidp, &ntv, sizeof(ntv), req));
292}
293
294SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
295SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
296	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
297
298#ifdef PPS_SYNC
299SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
300SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
301SYSCTL_INT(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD, &time_monitor, 0, "");
302
303SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", "");
304SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD, &time_freq, sizeof(time_freq), "I", "");
305#endif
306
307/*
308 * ntp_adjtime() - NTP daemon application interface
309 *
310 * See the timex.h header file for synopsis and API description.  Note that
311 * the timex.constant structure member has a dual purpose to set the time
312 * constant and to set the TAI offset.
313 */
314#ifndef _SYS_SYSPROTO_H_
315struct ntp_adjtime_args {
316	struct timex *tp;
317};
318#endif
319
320int
321ntp_adjtime(struct thread *td, struct ntp_adjtime_args *uap)
322{
323	struct timex ntv;	/* temporary structure */
324	long freq;		/* frequency ns/s) */
325	int modes;		/* mode bits from structure */
326	int s;			/* caller priority */
327	int error;
328
329	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
330	if (error)
331		return(error);
332
333	/*
334	 * Update selected clock variables - only the superuser can
335	 * change anything. Note that there is no error checking here on
336	 * the assumption the superuser should know what it is doing.
337	 * Note that either the time constant or TAI offset are loaded
338	 * from the ntv.constant member, depending on the mode bits. If
339	 * the STA_PLL bit in the status word is cleared, the state and
340	 * status words are reset to the initial values at boot.
341	 */
342	mtx_lock(&Giant);
343	modes = ntv.modes;
344	if (modes)
345		error = priv_check(td, PRIV_NTP_ADJTIME);
346	if (error)
347		goto done2;
348	s = splclock();
349	if (modes & MOD_MAXERROR)
350		time_maxerror = ntv.maxerror;
351	if (modes & MOD_ESTERROR)
352		time_esterror = ntv.esterror;
353	if (modes & MOD_STATUS) {
354		if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
355			time_state = TIME_OK;
356			time_status = STA_UNSYNC;
357#ifdef PPS_SYNC
358			pps_shift = PPS_FAVG;
359#endif /* PPS_SYNC */
360		}
361		time_status &= STA_RONLY;
362		time_status |= ntv.status & ~STA_RONLY;
363	}
364	if (modes & MOD_TIMECONST) {
365		if (ntv.constant < 0)
366			time_constant = 0;
367		else if (ntv.constant > MAXTC)
368			time_constant = MAXTC;
369		else
370			time_constant = ntv.constant;
371	}
372	if (modes & MOD_TAI) {
373		if (ntv.constant > 0) /* XXX zero & negative numbers ? */
374			time_tai = ntv.constant;
375	}
376#ifdef PPS_SYNC
377	if (modes & MOD_PPSMAX) {
378		if (ntv.shift < PPS_FAVG)
379			pps_shiftmax = PPS_FAVG;
380		else if (ntv.shift > PPS_FAVGMAX)
381			pps_shiftmax = PPS_FAVGMAX;
382		else
383			pps_shiftmax = ntv.shift;
384	}
385#endif /* PPS_SYNC */
386	if (modes & MOD_NANO)
387		time_status |= STA_NANO;
388	if (modes & MOD_MICRO)
389		time_status &= ~STA_NANO;
390	if (modes & MOD_CLKB)
391		time_status |= STA_CLK;
392	if (modes & MOD_CLKA)
393		time_status &= ~STA_CLK;
394	if (modes & MOD_FREQUENCY) {
395		freq = (ntv.freq * 1000LL) >> 16;
396		if (freq > MAXFREQ)
397			L_LINT(time_freq, MAXFREQ);
398		else if (freq < -MAXFREQ)
399			L_LINT(time_freq, -MAXFREQ);
400		else {
401			/*
402			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
403			 * time_freq is [ns/s * 2^32]
404			 */
405			time_freq = ntv.freq * 1000LL * 65536LL;
406		}
407#ifdef PPS_SYNC
408		pps_freq = time_freq;
409#endif /* PPS_SYNC */
410	}
411	if (modes & MOD_OFFSET) {
412		if (time_status & STA_NANO)
413			hardupdate(ntv.offset);
414		else
415			hardupdate(ntv.offset * 1000);
416	}
417
418	/*
419	 * Retrieve all clock variables. Note that the TAI offset is
420	 * returned only by ntp_gettime();
421	 */
422	if (time_status & STA_NANO)
423		ntv.offset = L_GINT(time_offset);
424	else
425		ntv.offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
426	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
427	ntv.maxerror = time_maxerror;
428	ntv.esterror = time_esterror;
429	ntv.status = time_status;
430	ntv.constant = time_constant;
431	if (time_status & STA_NANO)
432		ntv.precision = time_precision;
433	else
434		ntv.precision = time_precision / 1000;
435	ntv.tolerance = MAXFREQ * SCALE_PPM;
436#ifdef PPS_SYNC
437	ntv.shift = pps_shift;
438	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
439	if (time_status & STA_NANO)
440		ntv.jitter = pps_jitter;
441	else
442		ntv.jitter = pps_jitter / 1000;
443	ntv.stabil = pps_stabil;
444	ntv.calcnt = pps_calcnt;
445	ntv.errcnt = pps_errcnt;
446	ntv.jitcnt = pps_jitcnt;
447	ntv.stbcnt = pps_stbcnt;
448#endif /* PPS_SYNC */
449	splx(s);
450
451	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
452	if (error)
453		goto done2;
454
455	/*
456	 * Status word error decode. See comments in
457	 * ntp_gettime() routine.
458	 */
459	if (ntp_is_time_error())
460		td->td_retval[0] = TIME_ERROR;
461	else
462		td->td_retval[0] = time_state;
463
464done2:
465	mtx_unlock(&Giant);
466	return (error);
467}
468
469/*
470 * second_overflow() - called after ntp_tick_adjust()
471 *
472 * This routine is ordinarily called immediately following the above
473 * routine ntp_tick_adjust(). While these two routines are normally
474 * combined, they are separated here only for the purposes of
475 * simulation.
476 */
477void
478ntp_update_second(int64_t *adjustment, time_t *newsec)
479{
480	int tickrate;
481	l_fp ftemp;		/* 32/64-bit temporary */
482
483	/*
484	 * On rollover of the second both the nanosecond and microsecond
485	 * clocks are updated and the state machine cranked as
486	 * necessary. The phase adjustment to be used for the next
487	 * second is calculated and the maximum error is increased by
488	 * the tolerance.
489	 */
490	time_maxerror += MAXFREQ / 1000;
491
492	/*
493	 * Leap second processing. If in leap-insert state at
494	 * the end of the day, the system clock is set back one
495	 * second; if in leap-delete state, the system clock is
496	 * set ahead one second. The nano_time() routine or
497	 * external clock driver will insure that reported time
498	 * is always monotonic.
499	 */
500	switch (time_state) {
501
502		/*
503		 * No warning.
504		 */
505		case TIME_OK:
506		if (time_status & STA_INS)
507			time_state = TIME_INS;
508		else if (time_status & STA_DEL)
509			time_state = TIME_DEL;
510		break;
511
512		/*
513		 * Insert second 23:59:60 following second
514		 * 23:59:59.
515		 */
516		case TIME_INS:
517		if (!(time_status & STA_INS))
518			time_state = TIME_OK;
519		else if ((*newsec) % 86400 == 0) {
520			(*newsec)--;
521			time_state = TIME_OOP;
522			time_tai++;
523		}
524		break;
525
526		/*
527		 * Delete second 23:59:59.
528		 */
529		case TIME_DEL:
530		if (!(time_status & STA_DEL))
531			time_state = TIME_OK;
532		else if (((*newsec) + 1) % 86400 == 0) {
533			(*newsec)++;
534			time_tai--;
535			time_state = TIME_WAIT;
536		}
537		break;
538
539		/*
540		 * Insert second in progress.
541		 */
542		case TIME_OOP:
543			time_state = TIME_WAIT;
544		break;
545
546		/*
547		 * Wait for status bits to clear.
548		 */
549		case TIME_WAIT:
550		if (!(time_status & (STA_INS | STA_DEL)))
551			time_state = TIME_OK;
552	}
553
554	/*
555	 * Compute the total time adjustment for the next second
556	 * in ns. The offset is reduced by a factor depending on
557	 * whether the PPS signal is operating. Note that the
558	 * value is in effect scaled by the clock frequency,
559	 * since the adjustment is added at each tick interrupt.
560	 */
561	ftemp = time_offset;
562#ifdef PPS_SYNC
563	/* XXX even if PPS signal dies we should finish adjustment ? */
564	if (time_status & STA_PPSTIME && time_status &
565	    STA_PPSSIGNAL)
566		L_RSHIFT(ftemp, pps_shift);
567	else
568		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
569#else
570		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
571#endif /* PPS_SYNC */
572	time_adj = ftemp;
573	L_SUB(time_offset, ftemp);
574	L_ADD(time_adj, time_freq);
575
576	/*
577	 * Apply any correction from adjtime(2).  If more than one second
578	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
579	 * until the last second is slewed the final < 500 usecs.
580	 */
581	if (time_adjtime != 0) {
582		if (time_adjtime > 1000000)
583			tickrate = 5000;
584		else if (time_adjtime < -1000000)
585			tickrate = -5000;
586		else if (time_adjtime > 500)
587			tickrate = 500;
588		else if (time_adjtime < -500)
589			tickrate = -500;
590		else
591			tickrate = time_adjtime;
592		time_adjtime -= tickrate;
593		L_LINT(ftemp, tickrate * 1000);
594		L_ADD(time_adj, ftemp);
595	}
596	*adjustment = time_adj;
597
598#ifdef PPS_SYNC
599	if (pps_valid > 0)
600		pps_valid--;
601	else
602		time_status &= ~STA_PPSSIGNAL;
603#endif /* PPS_SYNC */
604}
605
606/*
607 * ntp_init() - initialize variables and structures
608 *
609 * This routine must be called after the kernel variables hz and tick
610 * are set or changed and before the next tick interrupt. In this
611 * particular implementation, these values are assumed set elsewhere in
612 * the kernel. The design allows the clock frequency and tick interval
613 * to be changed while the system is running. So, this routine should
614 * probably be integrated with the code that does that.
615 */
616static void
617ntp_init()
618{
619
620	/*
621	 * The following variables are initialized only at startup. Only
622	 * those structures not cleared by the compiler need to be
623	 * initialized, and these only in the simulator. In the actual
624	 * kernel, any nonzero values here will quickly evaporate.
625	 */
626	L_CLR(time_offset);
627	L_CLR(time_freq);
628#ifdef PPS_SYNC
629	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
630	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
631	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
632	pps_fcount = 0;
633	L_CLR(pps_freq);
634#endif /* PPS_SYNC */
635}
636
637SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, ntp_init, NULL);
638
639/*
640 * hardupdate() - local clock update
641 *
642 * This routine is called by ntp_adjtime() to update the local clock
643 * phase and frequency. The implementation is of an adaptive-parameter,
644 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
645 * time and frequency offset estimates for each call. If the kernel PPS
646 * discipline code is configured (PPS_SYNC), the PPS signal itself
647 * determines the new time offset, instead of the calling argument.
648 * Presumably, calls to ntp_adjtime() occur only when the caller
649 * believes the local clock is valid within some bound (+-128 ms with
650 * NTP). If the caller's time is far different than the PPS time, an
651 * argument will ensue, and it's not clear who will lose.
652 *
653 * For uncompensated quartz crystal oscillators and nominal update
654 * intervals less than 256 s, operation should be in phase-lock mode,
655 * where the loop is disciplined to phase. For update intervals greater
656 * than 1024 s, operation should be in frequency-lock mode, where the
657 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
658 * is selected by the STA_MODE status bit.
659 */
660static void
661hardupdate(offset)
662	long offset;		/* clock offset (ns) */
663{
664	long mtemp;
665	l_fp ftemp;
666
667	/*
668	 * Select how the phase is to be controlled and from which
669	 * source. If the PPS signal is present and enabled to
670	 * discipline the time, the PPS offset is used; otherwise, the
671	 * argument offset is used.
672	 */
673	if (!(time_status & STA_PLL))
674		return;
675	if (!(time_status & STA_PPSTIME && time_status &
676	    STA_PPSSIGNAL)) {
677		if (offset > MAXPHASE)
678			time_monitor = MAXPHASE;
679		else if (offset < -MAXPHASE)
680			time_monitor = -MAXPHASE;
681		else
682			time_monitor = offset;
683		L_LINT(time_offset, time_monitor);
684	}
685
686	/*
687	 * Select how the frequency is to be controlled and in which
688	 * mode (PLL or FLL). If the PPS signal is present and enabled
689	 * to discipline the frequency, the PPS frequency is used;
690	 * otherwise, the argument offset is used to compute it.
691	 */
692	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
693		time_reftime = time_second;
694		return;
695	}
696	if (time_status & STA_FREQHOLD || time_reftime == 0)
697		time_reftime = time_second;
698	mtemp = time_second - time_reftime;
699	L_LINT(ftemp, time_monitor);
700	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
701	L_MPY(ftemp, mtemp);
702	L_ADD(time_freq, ftemp);
703	time_status &= ~STA_MODE;
704	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
705	    MAXSEC)) {
706		L_LINT(ftemp, (time_monitor << 4) / mtemp);
707		L_RSHIFT(ftemp, SHIFT_FLL + 4);
708		L_ADD(time_freq, ftemp);
709		time_status |= STA_MODE;
710	}
711	time_reftime = time_second;
712	if (L_GINT(time_freq) > MAXFREQ)
713		L_LINT(time_freq, MAXFREQ);
714	else if (L_GINT(time_freq) < -MAXFREQ)
715		L_LINT(time_freq, -MAXFREQ);
716}
717
718#ifdef PPS_SYNC
719/*
720 * hardpps() - discipline CPU clock oscillator to external PPS signal
721 *
722 * This routine is called at each PPS interrupt in order to discipline
723 * the CPU clock oscillator to the PPS signal. There are two independent
724 * first-order feedback loops, one for the phase, the other for the
725 * frequency. The phase loop measures and grooms the PPS phase offset
726 * and leaves it in a handy spot for the seconds overflow routine. The
727 * frequency loop averages successive PPS phase differences and
728 * calculates the PPS frequency offset, which is also processed by the
729 * seconds overflow routine. The code requires the caller to capture the
730 * time and architecture-dependent hardware counter values in
731 * nanoseconds at the on-time PPS signal transition.
732 *
733 * Note that, on some Unix systems this routine runs at an interrupt
734 * priority level higher than the timer interrupt routine hardclock().
735 * Therefore, the variables used are distinct from the hardclock()
736 * variables, except for the actual time and frequency variables, which
737 * are determined by this routine and updated atomically.
738 */
739void
740hardpps(tsp, nsec)
741	struct timespec *tsp;	/* time at PPS */
742	long nsec;		/* hardware counter at PPS */
743{
744	long u_sec, u_nsec, v_nsec; /* temps */
745	l_fp ftemp;
746
747	/*
748	 * The signal is first processed by a range gate and frequency
749	 * discriminator. The range gate rejects noise spikes outside
750	 * the range +-500 us. The frequency discriminator rejects input
751	 * signals with apparent frequency outside the range 1 +-500
752	 * PPM. If two hits occur in the same second, we ignore the
753	 * later hit; if not and a hit occurs outside the range gate,
754	 * keep the later hit for later comparison, but do not process
755	 * it.
756	 */
757	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
758	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
759	pps_valid = PPS_VALID;
760	u_sec = tsp->tv_sec;
761	u_nsec = tsp->tv_nsec;
762	if (u_nsec >= (NANOSECOND >> 1)) {
763		u_nsec -= NANOSECOND;
764		u_sec++;
765	}
766	v_nsec = u_nsec - pps_tf[0].tv_nsec;
767	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
768	    MAXFREQ)
769		return;
770	pps_tf[2] = pps_tf[1];
771	pps_tf[1] = pps_tf[0];
772	pps_tf[0].tv_sec = u_sec;
773	pps_tf[0].tv_nsec = u_nsec;
774
775	/*
776	 * Compute the difference between the current and previous
777	 * counter values. If the difference exceeds 0.5 s, assume it
778	 * has wrapped around, so correct 1.0 s. If the result exceeds
779	 * the tick interval, the sample point has crossed a tick
780	 * boundary during the last second, so correct the tick. Very
781	 * intricate.
782	 */
783	u_nsec = nsec;
784	if (u_nsec > (NANOSECOND >> 1))
785		u_nsec -= NANOSECOND;
786	else if (u_nsec < -(NANOSECOND >> 1))
787		u_nsec += NANOSECOND;
788	pps_fcount += u_nsec;
789	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
790		return;
791	time_status &= ~STA_PPSJITTER;
792
793	/*
794	 * A three-stage median filter is used to help denoise the PPS
795	 * time. The median sample becomes the time offset estimate; the
796	 * difference between the other two samples becomes the time
797	 * dispersion (jitter) estimate.
798	 */
799	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
800		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
801			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
802			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
803		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
804			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
805			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
806		} else {
807			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
808			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
809		}
810	} else {
811		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
812			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
813			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
814		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
815			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
816			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
817		} else {
818			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
819			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
820		}
821	}
822
823	/*
824	 * Nominal jitter is due to PPS signal noise and interrupt
825	 * latency. If it exceeds the popcorn threshold, the sample is
826	 * discarded. otherwise, if so enabled, the time offset is
827	 * updated. We can tolerate a modest loss of data here without
828	 * much degrading time accuracy.
829	 */
830	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
831		time_status |= STA_PPSJITTER;
832		pps_jitcnt++;
833	} else if (time_status & STA_PPSTIME) {
834		time_monitor = -v_nsec;
835		L_LINT(time_offset, time_monitor);
836	}
837	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
838	u_sec = pps_tf[0].tv_sec - pps_lastsec;
839	if (u_sec < (1 << pps_shift))
840		return;
841
842	/*
843	 * At the end of the calibration interval the difference between
844	 * the first and last counter values becomes the scaled
845	 * frequency. It will later be divided by the length of the
846	 * interval to determine the frequency update. If the frequency
847	 * exceeds a sanity threshold, or if the actual calibration
848	 * interval is not equal to the expected length, the data are
849	 * discarded. We can tolerate a modest loss of data here without
850	 * much degrading frequency accuracy.
851	 */
852	pps_calcnt++;
853	v_nsec = -pps_fcount;
854	pps_lastsec = pps_tf[0].tv_sec;
855	pps_fcount = 0;
856	u_nsec = MAXFREQ << pps_shift;
857	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
858	    pps_shift)) {
859		time_status |= STA_PPSERROR;
860		pps_errcnt++;
861		return;
862	}
863
864	/*
865	 * Here the raw frequency offset and wander (stability) is
866	 * calculated. If the wander is less than the wander threshold
867	 * for four consecutive averaging intervals, the interval is
868	 * doubled; if it is greater than the threshold for four
869	 * consecutive intervals, the interval is halved. The scaled
870	 * frequency offset is converted to frequency offset. The
871	 * stability metric is calculated as the average of recent
872	 * frequency changes, but is used only for performance
873	 * monitoring.
874	 */
875	L_LINT(ftemp, v_nsec);
876	L_RSHIFT(ftemp, pps_shift);
877	L_SUB(ftemp, pps_freq);
878	u_nsec = L_GINT(ftemp);
879	if (u_nsec > PPS_MAXWANDER) {
880		L_LINT(ftemp, PPS_MAXWANDER);
881		pps_intcnt--;
882		time_status |= STA_PPSWANDER;
883		pps_stbcnt++;
884	} else if (u_nsec < -PPS_MAXWANDER) {
885		L_LINT(ftemp, -PPS_MAXWANDER);
886		pps_intcnt--;
887		time_status |= STA_PPSWANDER;
888		pps_stbcnt++;
889	} else {
890		pps_intcnt++;
891	}
892	if (pps_intcnt >= 4) {
893		pps_intcnt = 4;
894		if (pps_shift < pps_shiftmax) {
895			pps_shift++;
896			pps_intcnt = 0;
897		}
898	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
899		pps_intcnt = -4;
900		if (pps_shift > PPS_FAVG) {
901			pps_shift--;
902			pps_intcnt = 0;
903		}
904	}
905	if (u_nsec < 0)
906		u_nsec = -u_nsec;
907	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
908
909	/*
910	 * The PPS frequency is recalculated and clamped to the maximum
911	 * MAXFREQ. If enabled, the system clock frequency is updated as
912	 * well.
913	 */
914	L_ADD(pps_freq, ftemp);
915	u_nsec = L_GINT(pps_freq);
916	if (u_nsec > MAXFREQ)
917		L_LINT(pps_freq, MAXFREQ);
918	else if (u_nsec < -MAXFREQ)
919		L_LINT(pps_freq, -MAXFREQ);
920	if (time_status & STA_PPSFREQ)
921		time_freq = pps_freq;
922}
923#endif /* PPS_SYNC */
924
925#ifndef _SYS_SYSPROTO_H_
926struct adjtime_args {
927	struct timeval *delta;
928	struct timeval *olddelta;
929};
930#endif
931/* ARGSUSED */
932int
933adjtime(struct thread *td, struct adjtime_args *uap)
934{
935	struct timeval delta, olddelta, *deltap;
936	int error;
937
938	if (uap->delta) {
939		error = copyin(uap->delta, &delta, sizeof(delta));
940		if (error)
941			return (error);
942		deltap = &delta;
943	} else
944		deltap = NULL;
945	error = kern_adjtime(td, deltap, &olddelta);
946	if (uap->olddelta && error == 0)
947		error = copyout(&olddelta, uap->olddelta, sizeof(olddelta));
948	return (error);
949}
950
951int
952kern_adjtime(struct thread *td, struct timeval *delta, struct timeval *olddelta)
953{
954	struct timeval atv;
955	int error;
956
957	mtx_lock(&Giant);
958	if (olddelta) {
959		atv.tv_sec = time_adjtime / 1000000;
960		atv.tv_usec = time_adjtime % 1000000;
961		if (atv.tv_usec < 0) {
962			atv.tv_usec += 1000000;
963			atv.tv_sec--;
964		}
965		*olddelta = atv;
966	}
967	if (delta) {
968		if ((error = priv_check(td, PRIV_ADJTIME))) {
969			mtx_unlock(&Giant);
970			return (error);
971		}
972		time_adjtime = (int64_t)delta->tv_sec * 1000000 +
973		    delta->tv_usec;
974	}
975	mtx_unlock(&Giant);
976	return (0);
977}
978
979