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