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