kern_ntptime.c revision 55413
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 55413 2000-01-04 12:04:39Z 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_offset;		/* time offset (ns) */
167static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
168static long pps_fcount;			/* frequency accumulator */
169static long pps_jitter;			/* nominal jitter (ns) */
170static long pps_stabil;			/* nominal stability (scaled ns/s) */
171static long pps_lastsec;		/* time at last calibration (s) */
172static int pps_valid;			/* signal watchdog counter */
173static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
174static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
175static int pps_intcnt;			/* wander counter */
176
177/*
178 * PPS signal quality monitors
179 */
180static long pps_calcnt;			/* calibration intervals */
181static long pps_jitcnt;			/* jitter limit exceeded */
182static long pps_stbcnt;			/* stability limit exceeded */
183static long pps_errcnt;			/* calibration errors */
184#endif /* PPS_SYNC */
185/*
186 * End of phase/frequency-lock loop (PLL/FLL) definitions
187 */
188
189static void ntp_init(void);
190static void hardupdate(long offset);
191
192/*
193 * ntp_gettime() - NTP user application interface
194 *
195 * See the timex.h header file for synopsis and API description.
196 */
197static int
198ntp_sysctl SYSCTL_HANDLER_ARGS
199{
200	struct ntptimeval ntv;	/* temporary structure */
201	struct timespec atv;	/* nanosecond time */
202
203	nanotime(&atv);
204	ntv.time.tv_sec = atv.tv_sec;
205	ntv.time.tv_nsec = atv.tv_nsec;
206	ntv.maxerror = time_maxerror;
207	ntv.esterror = time_esterror;
208	ntv.time_state = time_state;
209
210	/*
211	 * Status word error decode. If any of these conditions occur,
212	 * an error is returned, instead of the status word. Most
213	 * applications will care only about the fact the system clock
214	 * may not be trusted, not about the details.
215	 *
216	 * Hardware or software error
217	 */
218	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
219
220	/*
221	 * PPS signal lost when either time or frequency synchronization
222	 * requested
223	 */
224	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
225	    !(time_status & STA_PPSSIGNAL)) ||
226
227	/*
228	 * PPS jitter exceeded when time synchronization requested
229	 */
230	    (time_status & STA_PPSTIME &&
231	    time_status & STA_PPSJITTER) ||
232
233	/*
234	 * PPS wander exceeded or calibration error when frequency
235	 * synchronization requested
236	 */
237	    (time_status & STA_PPSFREQ &&
238	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
239		ntv.time_state = TIME_ERROR;
240	return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
241}
242
243SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
244SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
245	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
246
247#ifdef PPS_SYNC
248SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
249SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
250#endif
251/*
252 * ntp_adjtime() - NTP daemon application interface
253 *
254 * See the timex.h header file for synopsis and API description.
255 */
256#ifndef _SYS_SYSPROTO_H_
257struct ntp_adjtime_args {
258	struct timex *tp;
259};
260#endif
261
262int
263ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
264{
265	struct timex ntv;	/* temporary structure */
266	long freq;		/* frequency ns/s) */
267	int modes;		/* mode bits from structure */
268	int s;			/* caller priority */
269	int error;
270
271	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
272	if (error)
273		return(error);
274
275	/*
276	 * Update selected clock variables - only the superuser can
277	 * change anything. Note that there is no error checking here on
278	 * the assumption the superuser should know what it is doing.
279	 */
280	modes = ntv.modes;
281	if (modes)
282		error = suser(p);
283	if (error)
284		return (error);
285	s = splclock();
286	if (modes & MOD_FREQUENCY) {
287		freq = (ntv.freq * 1000LL) >> 16;
288		if (freq > MAXFREQ)
289			L_LINT(time_freq, MAXFREQ);
290		else if (freq < -MAXFREQ)
291			L_LINT(time_freq, -MAXFREQ);
292		else
293			L_LINT(time_freq, freq);
294
295#ifdef PPS_SYNC
296		pps_freq = time_freq;
297#endif /* PPS_SYNC */
298	}
299	if (modes & MOD_MAXERROR)
300		time_maxerror = ntv.maxerror;
301	if (modes & MOD_ESTERROR)
302		time_esterror = ntv.esterror;
303	if (modes & MOD_STATUS) {
304		time_status &= STA_RONLY;
305		time_status |= ntv.status & ~STA_RONLY;
306	}
307	if (modes & MOD_TIMECONST) {
308		if (ntv.constant < 0)
309			time_constant = 0;
310		else if (ntv.constant > MAXTC)
311			time_constant = MAXTC;
312		else
313			time_constant = ntv.constant;
314	}
315#ifdef PPS_SYNC
316	if (modes & MOD_PPSMAX) {
317		if (ntv.shift < PPS_FAVG)
318			pps_shiftmax = PPS_FAVG;
319		else if (ntv.shift > PPS_FAVGMAX)
320			pps_shiftmax = PPS_FAVGMAX;
321		else
322			pps_shiftmax = ntv.shift;
323	}
324#endif /* PPS_SYNC */
325	if (modes & MOD_NANO)
326		time_status |= STA_NANO;
327	if (modes & MOD_MICRO)
328		time_status &= ~STA_NANO;
329	if (modes & MOD_CLKB)
330		time_status |= STA_CLK;
331	if (modes & MOD_CLKA)
332		time_status &= ~STA_CLK;
333	if (modes & MOD_OFFSET) {
334		if (time_status & STA_NANO)
335			hardupdate(ntv.offset);
336		else
337			hardupdate(ntv.offset * 1000);
338	}
339
340	/*
341	 * Retrieve all clock variables
342	 */
343	if (time_status & STA_NANO)
344		ntv.offset = L_GINT(time_offset);
345	else
346		ntv.offset = L_GINT(time_offset) / 1000;
347	ntv.freq = L_GINT((time_freq / 1000LL) << 16);
348	ntv.maxerror = time_maxerror;
349	ntv.esterror = time_esterror;
350	ntv.status = time_status;
351	ntv.constant = time_constant;
352	if (time_status & STA_NANO)
353		ntv.precision = time_precision;
354	else
355		ntv.precision = time_precision / 1000;
356	ntv.tolerance = MAXFREQ * SCALE_PPM;
357#ifdef PPS_SYNC
358	ntv.shift = pps_shift;
359	ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
360	if (time_status & STA_NANO)
361		ntv.jitter = pps_jitter;
362	else
363		ntv.jitter = pps_jitter / 1000;
364	ntv.stabil = pps_stabil;
365	ntv.calcnt = pps_calcnt;
366	ntv.errcnt = pps_errcnt;
367	ntv.jitcnt = pps_jitcnt;
368	ntv.stbcnt = pps_stbcnt;
369#endif /* PPS_SYNC */
370	splx(s);
371
372	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
373	if (error)
374		return (error);
375
376	/*
377	 * Status word error decode. See comments in
378	 * ntp_gettime() routine.
379	 */
380	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
381	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
382	    !(time_status & STA_PPSSIGNAL)) ||
383	    (time_status & STA_PPSTIME &&
384	    time_status & STA_PPSJITTER) ||
385	    (time_status & STA_PPSFREQ &&
386	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
387		p->p_retval[0] = TIME_ERROR;
388	else
389		p->p_retval[0] = time_state;
390	return (error);
391}
392
393/*
394 * second_overflow() - called after ntp_tick_adjust()
395 *
396 * This routine is ordinarily called immediately following the above
397 * routine ntp_tick_adjust(). While these two routines are normally
398 * combined, they are separated here only for the purposes of
399 * simulation.
400 */
401void
402ntp_update_second(struct timecounter *tcp)
403{
404	u_int32_t *newsec;
405	l_fp time_adj;		/* 32/64-bit temporaries */
406
407	newsec = &tcp->tc_offset_sec;
408	/*
409	 * On rollover of the second both the nanosecond and microsecond
410	 * clocks are updated and the state machine cranked as
411	 * necessary. The phase adjustment to be used for the next
412	 * second is calculated and the maximum error is increased by
413	 * the tolerance.
414	 */
415	time_maxerror += MAXFREQ / 1000;
416
417	/*
418	 * Leap second processing. If in leap-insert state at
419	 * the end of the day, the system clock is set back one
420	 * second; if in leap-delete state, the system clock is
421	 * set ahead one second. The nano_time() routine or
422	 * external clock driver will insure that reported time
423	 * is always monotonic.
424	 */
425	switch (time_state) {
426
427		/*
428		 * No warning.
429		 */
430		case TIME_OK:
431		if (time_status & STA_INS)
432			time_state = TIME_INS;
433		else if (time_status & STA_DEL)
434			time_state = TIME_DEL;
435		break;
436
437		/*
438		 * Insert second 23:59:60 following second
439		 * 23:59:59.
440		 */
441		case TIME_INS:
442		if (!(time_status & STA_INS))
443			time_state = TIME_OK;
444		else if ((*newsec) % 86400 == 0) {
445			(*newsec)--;
446			time_state = TIME_OOP;
447		}
448		break;
449
450		/*
451		 * Delete second 23:59:59.
452		 */
453		case TIME_DEL:
454		if (!(time_status & STA_DEL))
455			time_state = TIME_OK;
456		else if (((*newsec) + 1) % 86400 == 0) {
457			(*newsec)++;
458			time_state = TIME_WAIT;
459		}
460		break;
461
462		/*
463		 * Insert second in progress.
464		 */
465		case TIME_OOP:
466		time_state = TIME_WAIT;
467		break;
468
469		/*
470		 * Wait for status bits to clear.
471		 */
472		case TIME_WAIT:
473		if (!(time_status & (STA_INS | STA_DEL)))
474			time_state = TIME_OK;
475	}
476
477	/*
478	 * Compute the total time adjustment for the next second
479	 * in ns. The offset is reduced by a factor depending on
480	 * whether the PPS signal is operating. Note that the
481	 * value is in effect scaled by the clock frequency,
482	 * since the adjustment is added at each tick interrupt.
483	 */
484#ifdef PPS_SYNC
485	/* XXX even if signal dies we should finish adjustment ? */
486	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL) {
487		time_adj = pps_offset;
488		L_RSHIFT(time_adj, pps_shift);
489		L_SUB(pps_offset, time_adj);
490	} else {
491		time_adj = time_offset;
492		L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
493		L_SUB(time_offset, time_adj);
494	}
495#else
496	time_adj = time_offset;
497	L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
498	L_SUB(time_offset, time_adj);
499#endif /* PPS_SYNC */
500	L_ADD(time_adj, time_freq);
501	tcp->tc_adjustment = time_adj;
502#ifdef PPS_SYNC
503	if (pps_valid > 0)
504		pps_valid--;
505	else
506		time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
507		    STA_PPSWANDER | STA_PPSERROR);
508#endif /* PPS_SYNC */
509}
510
511/*
512 * ntp_init() - initialize variables and structures
513 *
514 * This routine must be called after the kernel variables hz and tick
515 * are set or changed and before the next tick interrupt. In this
516 * particular implementation, these values are assumed set elsewhere in
517 * the kernel. The design allows the clock frequency and tick interval
518 * to be changed while the system is running. So, this routine should
519 * probably be integrated with the code that does that.
520 */
521static void
522ntp_init()
523{
524
525	/*
526	 * The following variable must be initialized any time the
527	 * kernel variable hz is changed.
528	 */
529	time_tick = NANOSECOND / hz;
530
531	/*
532	 * The following variables are initialized only at startup. Only
533	 * those structures not cleared by the compiler need to be
534	 * initialized, and these only in the simulator. In the actual
535	 * kernel, any nonzero values here will quickly evaporate.
536	 */
537	L_CLR(time_offset);
538	L_CLR(time_freq);
539#ifdef PPS_SYNC
540	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
541	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
542	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
543	pps_fcount = 0;
544	L_CLR(pps_freq);
545#endif /* PPS_SYNC */
546}
547
548SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
549
550/*
551 * hardupdate() - local clock update
552 *
553 * This routine is called by ntp_adjtime() to update the local clock
554 * phase and frequency. The implementation is of an adaptive-parameter,
555 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
556 * time and frequency offset estimates for each call. If the kernel PPS
557 * discipline code is configured (PPS_SYNC), the PPS signal itself
558 * determines the new time offset, instead of the calling argument.
559 * Presumably, calls to ntp_adjtime() occur only when the caller
560 * believes the local clock is valid within some bound (+-128 ms with
561 * NTP). If the caller's time is far different than the PPS time, an
562 * argument will ensue, and it's not clear who will lose.
563 *
564 * For uncompensated quartz crystal oscillators and nominal update
565 * intervals less than 256 s, operation should be in phase-lock mode,
566 * where the loop is disciplined to phase. For update intervals greater
567 * than 1024 s, operation should be in frequency-lock mode, where the
568 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
569 * is selected by the STA_MODE status bit.
570 */
571static void
572hardupdate(offset)
573	long offset;		/* clock offset (ns) */
574{
575	long ltemp, mtemp;
576	l_fp ftemp;
577
578	/*
579	 * Select how the phase is to be controlled and from which
580	 * source. If the PPS signal is present and enabled to
581	 * discipline the time, the PPS offset is used; otherwise, the
582	 * argument offset is used.
583	 */
584	if (!(time_status & STA_PLL))
585		return;
586	ltemp = offset;
587	if (ltemp > MAXPHASE)
588		ltemp = MAXPHASE;
589	else if (ltemp < -MAXPHASE)
590		ltemp = -MAXPHASE;
591	if (!(time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL))
592		L_LINT(time_offset, ltemp);
593
594	/*
595	 * Select how the frequency is to be controlled and in which
596	 * mode (PLL or FLL). If the PPS signal is present and enabled
597	 * to discipline the frequency, the PPS frequency is used;
598	 * otherwise, the argument offset is used to compute it.
599	 */
600	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
601		time_reftime = time_second;
602		return;
603	}
604	if (time_status & STA_FREQHOLD || time_reftime == 0)
605		time_reftime = time_second;
606	mtemp = time_second - time_reftime;
607	L_LINT(ftemp, ltemp);
608	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
609	L_MPY(ftemp, mtemp);
610	L_ADD(time_freq, ftemp);
611	time_status &= ~STA_MODE;
612	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) {
613		L_LINT(ftemp, (ltemp << 4) / mtemp);
614		L_RSHIFT(ftemp, SHIFT_FLL + 4);
615		L_ADD(time_freq, ftemp);
616		time_status |= STA_MODE;
617	}
618	time_reftime = time_second;
619	if (L_GINT(time_freq) > MAXFREQ)
620		L_LINT(time_freq, MAXFREQ);
621	else if (L_GINT(time_freq) < -MAXFREQ)
622		L_LINT(time_freq, -MAXFREQ);
623}
624
625#ifdef PPS_SYNC
626/*
627 * hardpps() - discipline CPU clock oscillator to external PPS signal
628 *
629 * This routine is called at each PPS interrupt in order to discipline
630 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
631 * and leaves it in a handy spot for the hardclock() routine. It
632 * integrates successive PPS phase differences and calculates the
633 * frequency offset. This is used in hardclock() to discipline the CPU
634 * clock oscillator so that the intrinsic frequency error is cancelled
635 * out. The code requires the caller to capture the time and
636 * architecture-dependent hardware counter values in nanoseconds at the
637 * on-time PPS signal transition.
638 *
639 * Note that, on some Unix systems this routine runs at an interrupt
640 * priority level higher than the timer interrupt routine hardclock().
641 * Therefore, the variables used are distinct from the hardclock()
642 * variables, except for the actual time and frequency variables, which
643 * are determined by this routine and updated atomically.
644 */
645void
646hardpps(tsp, nsec)
647	struct timespec *tsp;	/* time at PPS */
648	long nsec;		/* hardware counter at PPS */
649{
650	long u_sec, u_nsec, v_nsec; /* temps */
651	l_fp ftemp;
652
653	/*
654	 * The signal is first processed by a frequency discriminator
655	 * which rejects noise and input signals with frequencies
656	 * outside the range 1 +-MAXFREQ PPS. If two hits occur in the
657	 * same second, we ignore the later hit; if not and a hit occurs
658	 * outside the range gate, keep the later hit but do not
659	 * process it.
660	 */
661	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
662	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
663	pps_valid = PPS_VALID;
664	u_sec = tsp->tv_sec;
665	u_nsec = tsp->tv_nsec;
666	if (u_nsec >= (NANOSECOND >> 1)) {
667		u_nsec -= NANOSECOND;
668		u_sec++;
669	}
670	v_nsec = u_nsec - pps_tf[0].tv_nsec;
671	if (u_sec == pps_tf[0].tv_sec && v_nsec < -MAXFREQ) {
672		return;
673	}
674	pps_tf[2] = pps_tf[1];
675	pps_tf[1] = pps_tf[0];
676	pps_tf[0].tv_sec = u_sec;
677	pps_tf[0].tv_nsec = u_nsec;
678
679	/*
680	 * Compute the difference between the current and previous
681	 * counter values. If the difference exceeds 0.5 s, assume it
682	 * has wrapped around, so correct 1.0 s. If the result exceeds
683	 * the tick interval, the sample point has crossed a tick
684	 * boundary during the last second, so correct the tick. Very
685	 * intricate.
686	 */
687	u_nsec = nsec;
688	if (u_nsec > (NANOSECOND >> 1))
689		u_nsec -= NANOSECOND;
690	else if (u_nsec < -(NANOSECOND >> 1))
691		u_nsec += NANOSECOND;
692	pps_fcount += u_nsec;
693	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ) {
694		return;
695	}
696	time_status &= ~STA_PPSJITTER;
697
698	/*
699	 * A three-stage median filter is used to help denoise the PPS
700	 * time. The median sample becomes the time offset estimate; the
701	 * difference between the other two samples becomes the time
702	 * dispersion (jitter) estimate.
703	 */
704	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
705		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
706			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
707			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
708		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
709			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
710			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
711		} else {
712			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
713			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
714		}
715	} else {
716		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
717			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
718			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
719		} else  if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
720			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
721			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
722		} else {
723			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
724			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
725		}
726	}
727
728	/*
729	 * Nominal jitter is due to PPS signal noise and  interrupt
730	 * latency. If it exceeds the popcorn threshold,
731	 * the sample is discarded. otherwise, if so enabled, the time
732	 * offset is updated. We can tolerate a modest loss of data here
733	 * without degrading time accuracy.
734	 */
735	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
736		time_status |= STA_PPSJITTER;
737		pps_jitcnt++;
738	} else if (time_status & STA_PPSTIME) {
739		L_LINT(time_offset, -v_nsec);
740		L_LINT(pps_offset, -v_nsec);
741	}
742	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
743	u_sec = pps_tf[0].tv_sec - pps_lastsec;
744	if (u_sec < (1 << pps_shift))
745		return;
746
747	/*
748	 * At the end of the calibration interval the difference between
749	 * the first and last counter values becomes the scaled
750	 * frequency. It will later be divided by the length of the
751	 * interval to determine the frequency update. If the frequency
752	 * exceeds a sanity threshold, or if the actual calibration
753	 * interval is not equal to the expected length, the data are
754	 * discarded. We can tolerate a modest loss of data here without
755	 * degrading frequency ccuracy.
756	 */
757	pps_calcnt++;
758	v_nsec = -pps_fcount;
759	pps_lastsec = pps_tf[0].tv_sec;
760	pps_fcount = 0;
761	u_nsec = MAXFREQ << pps_shift;
762	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
763	    pps_shift)) {
764		time_status |= STA_PPSERROR;
765		pps_errcnt++;
766		return;
767	}
768
769	/*
770	 * Here the raw frequency offset and wander (stability) is
771	 * calculated. If the wander is less than the wander threshold
772	 * for four consecutive averaging intervals, the interval is
773	 * doubled; if it is greater than the threshold for four
774	 * consecutive intervals, the interval is halved. The scaled
775	 * frequency offset is converted to frequency offset. The
776	 * stability metric is calculated as the average of recent
777	 * frequency changes, but is used only for performance
778	 * monitoring.
779	 */
780	L_LINT(ftemp, v_nsec);
781	L_RSHIFT(ftemp, pps_shift);
782	L_SUB(ftemp, pps_freq);
783	u_nsec = L_GINT(ftemp);
784	if (u_nsec > PPS_MAXWANDER) {
785		L_LINT(ftemp, PPS_MAXWANDER);
786		pps_intcnt--;
787		time_status |= STA_PPSWANDER;
788		pps_stbcnt++;
789	} else if (u_nsec < -PPS_MAXWANDER) {
790		L_LINT(ftemp, -PPS_MAXWANDER);
791		pps_intcnt--;
792		time_status |= STA_PPSWANDER;
793		pps_stbcnt++;
794	} else {
795		pps_intcnt++;
796	}
797	if (pps_shift > pps_shiftmax) {
798		/* If we lowered pps_shiftmax */
799		pps_shift = pps_shiftmax;
800		pps_intcnt = 0;
801	} else if (pps_intcnt >= 4) {
802		pps_intcnt = 4;
803		if (pps_shift < pps_shiftmax) {
804			pps_shift++;
805			pps_intcnt = 0;
806		}
807	} else if (pps_intcnt <= -4) {
808		pps_intcnt = -4;
809		if (pps_shift > PPS_FAVG) {
810			pps_shift--;
811			pps_intcnt = 0;
812		}
813	}
814	if (u_nsec < 0)
815		u_nsec = -u_nsec;
816	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
817
818	/*
819	 * The PPS frequency is recalculated and clamped to the maximum
820	 * MAXFREQ. If enabled, the system clock frequency is updated as
821	 * well.
822	 */
823	L_ADD(pps_freq, ftemp);
824	u_nsec = L_GINT(pps_freq);
825	if (u_nsec > MAXFREQ)
826		L_LINT(pps_freq, MAXFREQ);
827	else if (u_nsec < -MAXFREQ)
828		L_LINT(pps_freq, -MAXFREQ);
829	if (time_status & STA_PPSFREQ)
830		time_freq = pps_freq;
831}
832#endif /* PPS_SYNC */
833