kern_ntptime.c revision 45302
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 * 1000LL) >> 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 / 1000LL) << 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 / 1000LL) << 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		p->p_retval[0] = TIME_ERROR;
382	else
383		p->p_retval[0] = time_state;
384	return (error);
385}
386
387/*
388 * second_overflow() - called after ntp_tick_adjust()
389 *
390 * This routine is ordinarily called immediately following the above
391 * routine ntp_tick_adjust(). While these two routines are normally
392 * combined, they are separated here only for the purposes of
393 * simulation.
394 */
395void
396ntp_update_second(struct timecounter *tcp)
397{
398	u_int32_t *newsec;
399	l_fp ftemp, time_adj;		/* 32/64-bit temporaries */
400
401	newsec = &tcp->tc_offset_sec;
402	time_maxerror += MAXFREQ / 1000;
403
404	/*
405	 * Leap second processing. If in leap-insert state at
406	 * the end of the day, the system clock is set back one
407	 * second; if in leap-delete state, the system clock is
408	 * set ahead one second. The nano_time() routine or
409	 * external clock driver will insure that reported time
410	 * is always monotonic.
411	 */
412	switch (time_state) {
413
414		/*
415		 * No warning.
416		 */
417		case TIME_OK:
418		if (time_status & STA_INS)
419			time_state = TIME_INS;
420		else if (time_status & STA_DEL)
421			time_state = TIME_DEL;
422		break;
423
424		/*
425		 * Insert second 23:59:60 following second
426		 * 23:59:59.
427		 */
428		case TIME_INS:
429		if (!(time_status & STA_INS))
430			time_state = TIME_OK;
431		else if ((*newsec) % 86400 == 0) {
432			(*newsec)--;
433			time_state = TIME_OOP;
434		}
435		break;
436
437		/*
438		 * Delete second 23:59:59.
439		 */
440		case TIME_DEL:
441		if (!(time_status & STA_DEL))
442			time_state = TIME_OK;
443		else if (((*newsec) + 1) % 86400 == 0) {
444			(*newsec)++;
445			time_state = TIME_WAIT;
446		}
447		break;
448
449		/*
450		 * Insert second in progress.
451		 */
452		case TIME_OOP:
453		time_state = TIME_WAIT;
454		break;
455
456		/*
457		 * Wait for status bits to clear.
458		 */
459		case TIME_WAIT:
460		if (!(time_status & (STA_INS | STA_DEL)))
461			time_state = TIME_OK;
462	}
463
464	/*
465	 * Compute the total time adjustment for the next
466	 * second in ns. The offset is reduced by a factor
467	 * depending on FLL or PLL mode and whether the PPS
468	 * signal is operating. Note that the value is in effect
469	 * scaled by the clock frequency, since the adjustment
470	 * is added at each tick interrupt.
471	 */
472	ftemp = time_offset;
473#ifdef PPS_SYNC
474	if (time_status & STA_PPSTIME && time_status &
475	    STA_PPSSIGNAL)
476		L_RSHIFT(ftemp, PPS_FAVG);
477	else if (time_status & STA_MODE)
478#else
479	if (time_status & STA_MODE)
480#endif /* PPS_SYNC */
481		L_RSHIFT(ftemp, SHIFT_FLL);
482	else
483		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
484	time_adj = ftemp;
485	L_SUB(time_offset, ftemp);
486	L_ADD(time_adj, time_freq);
487	tcp->tc_adjustment = time_adj;
488#ifdef PPS_SYNC
489	if (pps_valid > 0)
490		pps_valid--;
491	else
492		time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
493		    STA_PPSWANDER | STA_PPSERROR);
494#endif /* PPS_SYNC */
495}
496
497/*
498 * ntp_init() - initialize variables and structures
499 *
500 * This routine must be called after the kernel variables hz and tick
501 * are set or changed and before the next tick interrupt. In this
502 * particular implementation, these values are assumed set elsewhere in
503 * the kernel. The design allows the clock frequency and tick interval
504 * to be changed while the system is running. So, this routine should
505 * probably be integrated with the code that does that.
506 */
507static void
508ntp_init()
509{
510
511	/*
512	 * The following variable must be initialized any time the
513	 * kernel variable hz is changed.
514	 */
515	time_tick = NANOSECOND / hz;
516
517	/*
518	 * The following variables are initialized only at startup. Only
519	 * those structures not cleared by the compiler need to be
520	 * initialized, and these only in the simulator. In the actual
521	 * kernel, any nonzero values here will quickly evaporate.
522	 */
523	L_CLR(time_offset);
524	L_CLR(time_freq);
525#ifdef PPS_SYNC
526	pps_filt.sec = pps_filt.nsec = 0;
527	pps_tf[0] = pps_tf[1] = pps_tf[2] = pps_filt;
528	pps_fcount = 0;
529	L_CLR(pps_freq);
530#endif /* PPS_SYNC */
531}
532
533SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
534
535/*
536 * hardupdate() - local clock update
537 *
538 * This routine is called by ntp_adjtime() to update the local clock
539 * phase and frequency. The implementation is of an adaptive-parameter,
540 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
541 * time and frequency offset estimates for each call. If the kernel PPS
542 * discipline code is configured (PPS_SYNC), the PPS signal itself
543 * determines the new time offset, instead of the calling argument.
544 * Presumably, calls to ntp_adjtime() occur only when the caller
545 * believes the local clock is valid within some bound (+-128 ms with
546 * NTP). If the caller's time is far different than the PPS time, an
547 * argument will ensue, and it's not clear who will lose.
548 *
549 * For uncompensated quartz crystal oscillators and nominal update
550 * intervals less than 256 s, operation should be in phase-lock mode,
551 * where the loop is disciplined to phase. For update intervals greater
552 * than 1024 s, operation should be in frequency-lock mode, where the
553 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
554 * is selected by the STA_MODE status bit.
555 */
556static void
557hardupdate(offset)
558	long offset;		/* clock offset (ns) */
559{
560	long ltemp, mtemp;
561	l_fp ftemp;
562
563	/*
564	 * Select how the phase is to be controlled and from which
565	 * source. If the PPS signal is present and enabled to
566	 * discipline the time, the PPS offset is used; otherwise, the
567	 * argument offset is used.
568	 */
569	ltemp = offset;
570	if (ltemp > MAXPHASE)
571		ltemp = MAXPHASE;
572	else if (ltemp < -MAXPHASE)
573		ltemp = -MAXPHASE;
574	if (!(time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL))
575		L_LINT(time_offset, ltemp);
576
577	/*
578	 * Select how the frequency is to be controlled and in which
579	 * mode (PLL or FLL). If the PPS signal is present and enabled
580	 * to discipline the frequency, the PPS frequency is used;
581	 * otherwise, the argument offset is used to compute it.
582	 */
583	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
584		time_reftime = time_second;
585		return;
586	}
587	if (time_status & STA_FREQHOLD || time_reftime == 0)
588		time_reftime = time_second;
589	mtemp = time_second - time_reftime;
590	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)
591	    ) {
592		L_LINT(ftemp, (ltemp << 4) / mtemp);
593		L_RSHIFT(ftemp, SHIFT_FLL + 4);
594		L_ADD(time_freq, ftemp);
595		time_status |= STA_MODE;
596	} else {
597		L_LINT(ftemp, ltemp);
598		L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
599		L_MPY(ftemp, mtemp);
600		L_ADD(time_freq, ftemp);
601		time_status &= ~STA_MODE;
602	}
603	time_reftime = time_second;
604	if (L_GINT(time_freq) > MAXFREQ)
605		L_LINT(time_freq, MAXFREQ);
606	else if (L_GINT(time_freq) < -MAXFREQ)
607		L_LINT(time_freq, -MAXFREQ);
608}
609
610#ifdef PPS_SYNC
611/*
612 * hardpps() - discipline CPU clock oscillator to external PPS signal
613 *
614 * This routine is called at each PPS interrupt in order to discipline
615 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
616 * and leaves it in a handy spot for the hardclock() routine. It
617 * integrates successive PPS phase differences and calculates the
618 * frequency offset. This is used in hardclock() to discipline the CPU
619 * clock oscillator so that the intrinsic frequency error is cancelled
620 * out. The code requires the caller to capture the time and
621 * architecture-dependent hardware counter values in nanoseconds at the
622 * on-time PPS signal transition.
623 *
624 * Note that, on some Unix systems this routine runs at an interrupt
625 * priority level higher than the timer interrupt routine hardclock().
626 * Therefore, the variables used are distinct from the hardclock()
627 * variables, except for the actual time and frequency variables, which
628 * are determined by this routine and updated atomically.
629 */
630void
631hardpps(tsp, nsec)
632	struct timespec *tsp;	/* time at PPS */
633	long nsec;		/* hardware counter at PPS */
634{
635	long u_sec, u_nsec, v_nsec; /* temps */
636	l_fp ftemp;
637
638	/*
639	 * The signal is first processed by a frequency discriminator
640	 * which rejects noise and input signals with frequencies
641	 * outside the range 1 +-MAXFREQ PPS. If two hits occur in the
642	 * same second, we ignore the later hit; if not and a hit occurs
643	 * outside the range gate, keep the later hit but do not
644	 * process it.
645	 */
646	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
647	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
648	pps_valid = PPS_VALID;
649	u_sec = tsp->tv_sec;
650	u_nsec = tsp->tv_nsec;
651	if (u_nsec >= (NANOSECOND >> 1)) {
652		u_nsec -= NANOSECOND;
653		u_sec++;
654	}
655	v_nsec = u_nsec - pps_tf[0].nsec;
656	if (u_sec == pps_tf[0].sec && v_nsec < -MAXFREQ) {
657		return;
658	}
659	pps_tf[2] = pps_tf[1];
660	pps_tf[1] = pps_tf[0];
661	pps_tf[0].sec = u_sec;
662	pps_tf[0].nsec = u_nsec;
663
664	/*
665	 * Compute the difference between the current and previous
666	 * counter values. If the difference exceeds 0.5 s, assume it
667	 * has wrapped around, so correct 1.0 s. If the result exceeds
668	 * the tick interval, the sample point has crossed a tick
669	 * boundary during the last second, so correct the tick. Very
670	 * intricate.
671	 */
672	u_nsec = nsec;
673	if (u_nsec > (NANOSECOND >> 1))
674		u_nsec -= NANOSECOND;
675	else if (u_nsec < -(NANOSECOND >> 1))
676		u_nsec += NANOSECOND;
677	pps_fcount += u_nsec;
678	if (v_nsec > MAXFREQ) {
679		return;
680	}
681	time_status &= ~STA_PPSJITTER;
682
683	/*
684	 * A three-stage median filter is used to help denoise the PPS
685	 * time. The median sample becomes the time offset estimate; the
686	 * difference between the other two samples becomes the time
687	 * dispersion (jitter) estimate.
688	 */
689	if (pps_tf[0].nsec > pps_tf[1].nsec) {
690		if (pps_tf[1].nsec > pps_tf[2].nsec) {
691			pps_filt = pps_tf[1];	/* 0 1 2 */
692			u_nsec = pps_tf[0].nsec - pps_tf[2].nsec;
693		} else if (pps_tf[2].nsec > pps_tf[0].nsec) {
694			pps_filt = pps_tf[0];	/* 2 0 1 */
695			u_nsec = pps_tf[2].nsec - pps_tf[1].nsec;
696		} else {
697			pps_filt = pps_tf[2];	/* 0 2 1 */
698			u_nsec = pps_tf[0].nsec - pps_tf[1].nsec;
699		}
700	} else {
701		if (pps_tf[1].nsec < pps_tf[2].nsec) {
702			pps_filt = pps_tf[1];	/* 2 1 0 */
703			u_nsec = pps_tf[2].nsec - pps_tf[0].nsec;
704		} else  if (pps_tf[2].nsec < pps_tf[0].nsec) {
705			pps_filt = pps_tf[0];	/* 1 0 2 */
706			u_nsec = pps_tf[1].nsec - pps_tf[2].nsec;
707		} else {
708			pps_filt = pps_tf[2];	/* 1 2 0 */
709			u_nsec = pps_tf[1].nsec - pps_tf[0].nsec;
710		}
711	}
712
713	/*
714	 * Nominal jitter is due to PPS signal noise and  interrupt
715	 * latency. If it exceeds the jitter limit, the sample is
716	 * discarded. otherwise, if so enabled, the time offset is
717	 * updated. The offsets are accumulated over the phase averaging
718	 * interval to improve accuracy. The jitter is averaged only for
719	 * performance monitoring. We can tolerate a modest loss of data
720	 * here without degrading time accuracy.
721	 */
722	if (u_nsec > MAXTIME) {
723		time_status |= STA_PPSJITTER;
724		pps_jitcnt++;
725	} else if (time_status & STA_PPSTIME) {
726		pps_offacc -= pps_filt.nsec;
727		pps_offcnt++;
728	}
729	if (pps_offcnt >= (1 << PPS_PAVG)) {
730		if (time_status & STA_PPSTIME) {
731			L_LINT(time_offset, pps_offacc);
732			L_RSHIFT(time_offset, PPS_PAVG);
733		}
734		pps_offacc = 0;
735		pps_offcnt = 0;
736	}
737	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
738	u_sec = pps_tf[0].sec - pps_lastsec;
739	if (ntp_div && ntp_mult) {
740		L_LINT(ftemp, (pps_filt.nsec));
741		L_RSHIFT(ftemp, ntp_div);
742		L_MPY(ftemp, ntp_mult);
743		L_ADD(pps_freq, ftemp);
744		if (time_status & STA_PPSFREQ)
745			time_freq = pps_freq;
746		return;
747	}
748	if (u_sec < (1 << pps_shift))
749		return;
750
751	/*
752	 * At the end of the calibration interval the difference between
753	 * the first and last counter values becomes the scaled
754	 * frequency. It will later be divided by the length of the
755	 * interval to determine the frequency update. If the frequency
756	 * exceeds a sanity threshold, or if the actual calibration
757	 * interval is not equal to the expected length, the data are
758	 * discarded. We can tolerate a modest loss of data here without
759	 * degrading frequency ccuracy.
760	 */
761	pps_calcnt++;
762	v_nsec = -pps_fcount;
763	pps_lastsec = pps_tf[0].sec;
764	pps_fcount = 0;
765	u_nsec = MAXFREQ << pps_shift;
766	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
767	    pps_shift)) {
768		time_status |= STA_PPSERROR;
769		pps_errcnt++;
770		return;
771	}
772
773	/*
774	 * If the actual calibration interval is not equal to the
775	 * expected length, the data are discarded. If the wander is
776	 * less than the wander threshold for four consecutive
777	 * intervals, the interval is doubled; if it is greater than the
778	 * threshold for four consecutive intervals, the interval is
779	 * halved. The scaled frequency offset is converted to frequency
780	 * offset. The stability metric is calculated as the average of
781	 * recent frequency changes, but is used only for performance
782	 * monitoring.
783	 */
784	L_LINT(ftemp, v_nsec);
785	L_RSHIFT(ftemp, pps_shift);
786	L_SUB(ftemp, pps_freq);
787	u_nsec = L_GINT(ftemp);
788	if (u_nsec > MAXWANDER) {
789		L_LINT(ftemp, MAXWANDER);
790		pps_intcnt--;
791		time_status |= STA_PPSWANDER;
792		pps_stbcnt++;
793	} else if (u_nsec < -MAXWANDER) {
794		L_LINT(ftemp, -MAXWANDER);
795		pps_intcnt--;
796		time_status |= STA_PPSWANDER;
797		pps_stbcnt++;
798	} else {
799		pps_intcnt++;
800	}
801	if (pps_intcnt >= 4) {
802		pps_intcnt = 4;
803		if (pps_shift < PPS_FAVGMAX) {
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 frequency offset is averaged into the PPS frequency. If
820	 * enabled, the system clock frequency is updated as well.
821	 */
822	L_RSHIFT(ftemp, PPS_FAVG);
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