kern_ntptime.c revision 33388
1/******************************************************************************
2 *                                                                            *
3 * Copyright (c) David L. Mills 1993, 1994                                    *
4 *                                                                            *
5 * Permission to use, copy, modify, and distribute this software and its      *
6 * documentation for any purpose and without fee is hereby granted, provided  *
7 * that the above copyright notice appears in all copies and that both the    *
8 * copyright notice and this permission notice appear in supporting           *
9 * documentation, and that the name University of Delaware not be used in     *
10 * advertising or publicity pertaining to distribution of the software        *
11 * without specific, written prior permission.  The University of Delaware    *
12 * makes no representations about the suitability this software for any       *
13 * purpose.  It is provided "as is" without express or implied warranty.      *
14 *                                                                            *
15 ******************************************************************************/
16
17/*
18 * Modification history kern_ntptime.c
19 *
20 * 24 Sep 94	David L. Mills
21 *	Tightened code at exits.
22 *
23 * 24 Mar 94	David L. Mills
24 *	Revised syscall interface to include new variables for PPS
25 *	time discipline.
26 *
27 * 14 Feb 94	David L. Mills
28 *	Added code for external clock
29 *
30 * 28 Nov 93	David L. Mills
31 *	Revised frequency scaling to conform with adjusted parameters
32 *
33 * 17 Sep 93	David L. Mills
34 *	Created file
35 */
36/*
37 * ntp_gettime(), ntp_adjtime() - precision time interface for SunOS
38 * V4.1.1 and V4.1.3
39 *
40 * These routines consitute the Network Time Protocol (NTP) interfaces
41 * for user and daemon application programs. The ntp_gettime() routine
42 * provides the time, maximum error (synch distance) and estimated error
43 * (dispersion) to client user application programs. The ntp_adjtime()
44 * routine is used by the NTP daemon to adjust the system clock to an
45 * externally derived time. The time offset and related variables set by
46 * this routine are used by hardclock() to adjust the phase and
47 * frequency of the phase-lock loop which controls the system clock.
48 */
49
50#include "opt_ntp.h"
51
52#include <sys/param.h>
53#include <sys/systm.h>
54#include <sys/sysproto.h>
55#include <sys/kernel.h>
56#include <sys/proc.h>
57#include <sys/timex.h>
58#include <sys/sysctl.h>
59
60/*
61 * Phase/frequency-lock loop (PLL/FLL) definitions
62 *
63 * The following variables are read and set by the ntp_adjtime() system
64 * call.
65 *
66 * time_state shows the state of the system clock, with values defined
67 * in the timex.h header file.
68 *
69 * time_status shows the status of the system clock, with bits defined
70 * in the timex.h header file.
71 *
72 * time_offset is used by the PLL/FLL to adjust the system time in small
73 * increments.
74 *
75 * time_constant determines the bandwidth or "stiffness" of the PLL.
76 *
77 * time_tolerance determines maximum frequency error or tolerance of the
78 * CPU clock oscillator and is a property of the architecture; however,
79 * in principle it could change as result of the presence of external
80 * discipline signals, for instance.
81 *
82 * time_precision is usually equal to the kernel tick variable; however,
83 * in cases where a precision clock counter or external clock is
84 * available, the resolution can be much less than this and depend on
85 * whether the external clock is working or not.
86 *
87 * time_maxerror is initialized by a ntp_adjtime() call and increased by
88 * the kernel once each second to reflect the maximum error
89 * bound growth.
90 *
91 * time_esterror is set and read by the ntp_adjtime() call, but
92 * otherwise not used by the kernel.
93 */
94static int time_status = STA_UNSYNC;	/* clock status bits */
95static int time_state = TIME_OK;	/* clock state */
96static long time_offset = 0;		/* time offset (us) */
97static long time_constant = 0;		/* pll time constant */
98static long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
99static long time_precision = 1;		/* clock precision (us) */
100static long time_maxerror = MAXPHASE;	/* maximum error (us) */
101static long time_esterror = MAXPHASE;	/* estimated error (us) */
102
103/*
104 * The following variables establish the state of the PLL/FLL and the
105 * residual time and frequency offset of the local clock. The scale
106 * factors are defined in the timex.h header file.
107 *
108 * time_phase and time_freq are the phase increment and the frequency
109 * increment, respectively, of the kernel time variable at each tick of
110 * the clock.
111 *
112 * time_freq is set via ntp_adjtime() from a value stored in a file when
113 * the synchronization daemon is first started. Its value is retrieved
114 * via ntp_adjtime() and written to the file about once per hour by the
115 * daemon.
116 *
117 * time_adj is the adjustment added to the value of tick at each timer
118 * interrupt and is recomputed from time_phase and time_freq at each
119 * seconds rollover.
120 *
121 * time_reftime is the second's portion of the system time on the last
122 * call to ntp_adjtime(). It is used to adjust the time_freq variable
123 * and to increase the time_maxerror as the time since last update
124 * increases.
125 */
126long time_phase = 0;			/* phase offset (scaled us) */
127static long time_freq = 0;		/* frequency offset (scaled ppm) */
128long time_adj = 0;			/* tick adjust (scaled 1 / hz) */
129static long time_reftime = 0;		/* time at last adjustment (s) */
130
131#ifdef PPS_SYNC
132/*
133 * The following variables are used only if the kernel PPS discipline
134 * code is configured (PPS_SYNC). The scale factors are defined in the
135 * timex.h header file.
136 *
137 * pps_time contains the time at each calibration interval, as read by
138 * microtime(). pps_count counts the seconds of the calibration
139 * interval, the duration of which is nominally pps_shift in powers of
140 * two.
141 *
142 * pps_offset is the time offset produced by the time median filter
143 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
144 * this filter.
145 *
146 * pps_freq is the frequency offset produced by the frequency median
147 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
148 * by this filter.
149 *
150 * pps_usec is latched from a high resolution counter or external clock
151 * at pps_time. Here we want the hardware counter contents only, not the
152 * contents plus the time_tv.usec as usual.
153 *
154 * pps_valid counts the number of seconds since the last PPS update. It
155 * is used as a watchdog timer to disable the PPS discipline should the
156 * PPS signal be lost.
157 *
158 * pps_glitch counts the number of seconds since the beginning of an
159 * offset burst more than tick/2 from current nominal offset. It is used
160 * mainly to suppress error bursts due to priority conflicts between the
161 * PPS interrupt and timer interrupt.
162 *
163 * pps_intcnt counts the calibration intervals for use in the interval-
164 * adaptation algorithm. It's just too complicated for words.
165 */
166static struct timeval pps_time;	/* kernel time at last interval */
167static long pps_offset = 0;		/* pps time offset (us) */
168static long pps_jitter = MAXTIME;	/* pps time dispersion (jitter) (us) */
169static long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
170static long pps_freq = 0;		/* frequency offset (scaled ppm) */
171static long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
172static long pps_ff[] = {0, 0, 0};	/* frequency offset median filter */
173static long pps_usec = 0;		/* microsec counter at last interval */
174static long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
175static int pps_glitch = 0;		/* pps signal glitch counter */
176static int pps_count = 0;		/* calibration interval counter (s) */
177static int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
178static int pps_intcnt = 0;		/* intervals at current duration */
179
180/*
181 * PPS signal quality monitors
182 *
183 * pps_jitcnt counts the seconds that have been discarded because the
184 * jitter measured by the time median filter exceeds the limit MAXTIME
185 * (100 us).
186 *
187 * pps_calcnt counts the frequency calibration intervals, which are
188 * variable from 4 s to 256 s.
189 *
190 * pps_errcnt counts the calibration intervals which have been discarded
191 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
192 * calibration interval jitter exceeds two ticks.
193 *
194 * pps_stbcnt counts the calibration intervals that have been discarded
195 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
196 */
197static long pps_jitcnt = 0;		/* jitter limit exceeded */
198static long pps_calcnt = 0;		/* calibration intervals */
199static long pps_errcnt = 0;		/* calibration errors */
200static long pps_stbcnt = 0;		/* stability limit exceeded */
201#endif /* PPS_SYNC */
202
203static void hardupdate __P((long offset));
204
205/*
206 * hardupdate() - local clock update
207 *
208 * This routine is called by ntp_adjtime() to update the local clock
209 * phase and frequency. The implementation is of an adaptive-parameter,
210 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
211 * time and frequency offset estimates for each call. If the kernel PPS
212 * discipline code is configured (PPS_SYNC), the PPS signal itself
213 * determines the new time offset, instead of the calling argument.
214 * Presumably, calls to ntp_adjtime() occur only when the caller
215 * believes the local clock is valid within some bound (+-128 ms with
216 * NTP). If the caller's time is far different than the PPS time, an
217 * argument will ensue, and it's not clear who will lose.
218 *
219 * For uncompensated quartz crystal oscillatores and nominal update
220 * intervals less than 1024 s, operation should be in phase-lock mode
221 * (STA_FLL = 0), where the loop is disciplined to phase. For update
222 * intervals greater than thiss, operation should be in frequency-lock
223 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
224 *
225 * Note: splclock() is in effect.
226 */
227static void
228hardupdate(offset)
229	long offset;
230{
231	long ltemp, mtemp;
232
233	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
234		return;
235	ltemp = offset;
236#ifdef PPS_SYNC
237	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
238		ltemp = pps_offset;
239#endif /* PPS_SYNC */
240
241	/*
242	 * Scale the phase adjustment and clamp to the operating range.
243	 */
244	if (ltemp > MAXPHASE)
245		time_offset = MAXPHASE << SHIFT_UPDATE;
246	else if (ltemp < -MAXPHASE)
247		time_offset = -(MAXPHASE << SHIFT_UPDATE);
248	else
249		time_offset = ltemp << SHIFT_UPDATE;
250
251	/*
252	 * Select whether the frequency is to be controlled and in which
253	 * mode (PLL or FLL). Clamp to the operating range. Ugly
254	 * multiply/divide should be replaced someday.
255	 */
256	if (time_status & STA_FREQHOLD || time_reftime == 0)
257		time_reftime = time.tv_sec;
258	mtemp = time.tv_sec - time_reftime;
259	time_reftime = time.tv_sec;
260	if (time_status & STA_FLL) {
261		if (mtemp >= MINSEC) {
262			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
263			    SHIFT_UPDATE));
264			if (ltemp < 0)
265				time_freq -= -ltemp >> SHIFT_KH;
266			else
267				time_freq += ltemp >> SHIFT_KH;
268		}
269	} else {
270		if (mtemp < MAXSEC) {
271			ltemp *= mtemp;
272			if (ltemp < 0)
273				time_freq -= -ltemp >> (time_constant +
274				    time_constant + SHIFT_KF -
275				    SHIFT_USEC);
276			else
277				time_freq += ltemp >> (time_constant +
278				    time_constant + SHIFT_KF -
279				    SHIFT_USEC);
280		}
281	}
282	if (time_freq > time_tolerance)
283		time_freq = time_tolerance;
284	else if (time_freq < -time_tolerance)
285		time_freq = -time_tolerance;
286}
287
288void
289ntp_update_second(long *newsec)
290{
291	long ltemp;
292
293	time_maxerror += time_tolerance >> SHIFT_USEC;
294
295	/*
296	* Compute the phase adjustment for the next second. In
297	* PLL mode, the offset is reduced by a fixed factor
298	* times the time constant. In FLL mode the offset is
299	* used directly. In either mode, the maximum phase
300	* adjustment for each second is clamped so as to spread
301	* the adjustment over not more than the number of
302	* seconds between updates.
303	*/
304	if (time_offset < 0) {
305		ltemp = -time_offset;
306		if (!(time_status & STA_FLL))
307			ltemp >>= SHIFT_KG + time_constant;
308		if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
309			ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
310		time_offset += ltemp;
311		time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
312	} else {
313		ltemp = time_offset;
314		if (!(time_status & STA_FLL))
315			ltemp >>= SHIFT_KG + time_constant;
316		if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
317			ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
318		time_offset -= ltemp;
319		time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
320	}
321
322	/*
323	* Compute the frequency estimate and additional phase
324	* adjustment due to frequency error for the next
325	* second. When the PPS signal is engaged, gnaw on the
326	* watchdog counter and update the frequency computed by
327	* the pll and the PPS signal.
328	*/
329#ifdef PPS_SYNC
330	pps_valid++;
331	if (pps_valid == PPS_VALID) {
332		pps_jitter = MAXTIME;
333		pps_stabil = MAXFREQ;
334		time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
335		    STA_PPSWANDER | STA_PPSERROR);
336	}
337	ltemp = time_freq + pps_freq;
338#else
339	ltemp = time_freq;
340#endif /* PPS_SYNC */
341	if (ltemp < 0)
342		time_adj -= -ltemp >> (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
343	else
344		time_adj += ltemp >> (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
345
346#if SHIFT_HZ == 7
347	/*
348	* When the CPU clock oscillator frequency is not a
349	* power of two in Hz, the SHIFT_HZ is only an
350	* approximate scale factor. In the SunOS kernel, this
351	* results in a PLL gain factor of 1/1.28 = 0.78 what it
352	* should be. In the following code the overall gain is
353	* increased by a factor of 1.25, which results in a
354	* residual error less than 3 percent.
355	*/
356	/* Same thing applies for FreeBSD --GAW */
357	if (hz == 100) {
358		if (time_adj < 0)
359			time_adj -= -time_adj >> 2;
360		else
361			time_adj += time_adj >> 2;
362	}
363#endif /* SHIFT_HZ */
364
365	/* XXX - this is really bogus, but can't be fixed until
366	xntpd's idea of the system clock is fixed to know how
367	the user wants leap seconds handled; in the mean time,
368	we assume that users of NTP are running without proper
369	leap second support (this is now the default anyway) */
370	/*
371	* Leap second processing. If in leap-insert state at
372	* the end of the day, the system clock is set back one
373	* second; if in leap-delete state, the system clock is
374	* set ahead one second. The microtime() routine or
375	* external clock driver will insure that reported time
376	* is always monotonic. The ugly divides should be
377	* replaced.
378	*/
379	switch (time_state) {
380
381		case TIME_OK:
382			if (time_status & STA_INS)
383				time_state = TIME_INS;
384			else if (time_status & STA_DEL)
385				time_state = TIME_DEL;
386			break;
387
388		case TIME_INS:
389			if ((*newsec) % 86400 == 0) {
390				(*newsec)--;
391				time_state = TIME_OOP;
392			}
393			break;
394
395		case TIME_DEL:
396			if (((*newsec) + 1) % 86400 == 0) {
397				(*newsec)++;
398				time_state = TIME_WAIT;
399			}
400			break;
401
402		case TIME_OOP:
403			time_state = TIME_WAIT;
404			break;
405
406		case TIME_WAIT:
407			if (!(time_status & (STA_INS | STA_DEL)))
408				time_state = TIME_OK;
409			break;
410	}
411}
412
413static int
414ntp_sysctl SYSCTL_HANDLER_ARGS
415{
416	struct timeval atv;
417	struct ntptimeval ntv;
418	int s;
419
420	s = splclock();
421	microtime(&atv);
422	ntv.time = atv;
423	ntv.maxerror = time_maxerror;
424	ntv.esterror = time_esterror;
425	splx(s);
426
427	ntv.time_state = time_state;
428
429	/*
430	 * Status word error decode. If any of these conditions
431	 * occur, an error is returned, instead of the status
432	 * word. Most applications will care only about the fact
433	 * the system clock may not be trusted, not about the
434	 * details.
435	 *
436	 * Hardware or software error
437	 */
438	if (time_status & (STA_UNSYNC | STA_CLOCKERR)) {
439		ntv.time_state = TIME_ERROR;
440	}
441
442	/*
443	 * PPS signal lost when either time or frequency
444	 * synchronization requested
445	 */
446	if (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
447	    !(time_status & STA_PPSSIGNAL)) {
448		ntv.time_state = TIME_ERROR;
449	}
450
451	/*
452	 * PPS jitter exceeded when time synchronization
453	 * requested
454	 */
455	if (time_status & STA_PPSTIME &&
456	    time_status & STA_PPSJITTER) {
457		ntv.time_state = TIME_ERROR;
458	}
459
460	/*
461	 * PPS wander exceeded or calibration error when
462	 * frequency synchronization requested
463	 */
464	if (time_status & STA_PPSFREQ &&
465	    time_status & (STA_PPSWANDER | STA_PPSERROR)) {
466		ntv.time_state = TIME_ERROR;
467	}
468	return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
469}
470
471SYSCTL_NODE(_kern, KERN_NTP_PLL, ntp_pll, CTLFLAG_RW, 0,
472	"NTP kernel PLL related stuff");
473SYSCTL_PROC(_kern_ntp_pll, NTP_PLL_GETTIME, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
474	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
475
476/*
477 * ntp_adjtime() - NTP daemon application interface
478 */
479#ifndef _SYS_SYSPROTO_H_
480struct ntp_adjtime_args {
481  struct timex *tp;
482};
483#endif
484
485int
486ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
487{
488	struct timex ntv;
489	int modes;
490	int s;
491	int error;
492
493	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
494	if (error)
495		return error;
496
497	/*
498	 * Update selected clock variables - only the superuser can
499	 * change anything. Note that there is no error checking here on
500	 * the assumption the superuser should know what it is doing.
501	 */
502	modes = ntv.modes;
503	if ((modes != 0)
504	    && (error = suser(p->p_cred->pc_ucred, &p->p_acflag)))
505		return error;
506
507	s = splclock();
508	if (modes & MOD_FREQUENCY)
509#ifdef PPS_SYNC
510		time_freq = ntv.freq - pps_freq;
511#else /* PPS_SYNC */
512		time_freq = ntv.freq;
513#endif /* PPS_SYNC */
514	if (modes & MOD_MAXERROR)
515		time_maxerror = ntv.maxerror;
516	if (modes & MOD_ESTERROR)
517		time_esterror = ntv.esterror;
518	if (modes & MOD_STATUS) {
519		time_status &= STA_RONLY;
520		time_status |= ntv.status & ~STA_RONLY;
521	}
522	if (modes & MOD_TIMECONST)
523		time_constant = ntv.constant;
524	if (modes & MOD_OFFSET)
525		hardupdate(ntv.offset);
526
527	/*
528	 * Retrieve all clock variables
529	 */
530	if (time_offset < 0)
531		ntv.offset = -(-time_offset >> SHIFT_UPDATE);
532	else
533		ntv.offset = time_offset >> SHIFT_UPDATE;
534#ifdef PPS_SYNC
535	ntv.freq = time_freq + pps_freq;
536#else /* PPS_SYNC */
537	ntv.freq = time_freq;
538#endif /* PPS_SYNC */
539	ntv.maxerror = time_maxerror;
540	ntv.esterror = time_esterror;
541	ntv.status = time_status;
542	ntv.constant = time_constant;
543	ntv.precision = time_precision;
544	ntv.tolerance = time_tolerance;
545#ifdef PPS_SYNC
546	ntv.shift = pps_shift;
547	ntv.ppsfreq = pps_freq;
548	ntv.jitter = pps_jitter >> PPS_AVG;
549	ntv.stabil = pps_stabil;
550	ntv.calcnt = pps_calcnt;
551	ntv.errcnt = pps_errcnt;
552	ntv.jitcnt = pps_jitcnt;
553	ntv.stbcnt = pps_stbcnt;
554#endif /* PPS_SYNC */
555	(void)splx(s);
556
557	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
558	if (!error) {
559		/*
560		 * Status word error decode. See comments in
561		 * ntp_gettime() routine.
562		 */
563		p->p_retval[0] = time_state;
564		if (time_status & (STA_UNSYNC | STA_CLOCKERR))
565			p->p_retval[0] = TIME_ERROR;
566		if (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
567		    !(time_status & STA_PPSSIGNAL))
568			p->p_retval[0] = TIME_ERROR;
569		if (time_status & STA_PPSTIME &&
570		    time_status & STA_PPSJITTER)
571			p->p_retval[0] = TIME_ERROR;
572		if (time_status & STA_PPSFREQ &&
573		    time_status & (STA_PPSWANDER | STA_PPSERROR))
574			p->p_retval[0] = TIME_ERROR;
575	}
576	return error;
577}
578
579#ifdef PPS_SYNC
580
581/* We need this ugly monster twice, so let's macroize it. */
582
583#define MEDIAN3X(a, m, s, i1, i2, i3)				\
584	do {							\
585	m = a[i2];						\
586	s = a[i1] - a[i3];					\
587	} while (0)
588
589#define MEDIAN3(a, m, s)					\
590	do {							\
591		if (a[0] > a[1]) {				\
592			if (a[1] > a[2])			\
593				MEDIAN3X(a, m, s, 0, 1, 2);	\
594			else if (a[2] > a[0])			\
595				MEDIAN3X(a, m, s, 2, 0, 1);	\
596			else					\
597				MEDIAN3X(a, m, s, 0, 2, 1);	\
598		} else {					\
599			if (a[2] > a[1])			\
600				MEDIAN3X(a, m, s, 2, 1, 0);	\
601			else  if (a[0] > a[2])			\
602				MEDIAN3X(a, m, s, 1, 0, 2);	\
603			else					\
604				MEDIAN3X(a, m, s, 1, 2, 0);	\
605		}						\
606	} while (0)
607
608/*
609 * hardpps() - discipline CPU clock oscillator to external PPS signal
610 *
611 * This routine is called at each PPS interrupt in order to discipline
612 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
613 * and leaves it in a handy spot for the hardclock() routine. It
614 * integrates successive PPS phase differences and calculates the
615 * frequency offset. This is used in hardclock() to discipline the CPU
616 * clock oscillator so that intrinsic frequency error is cancelled out.
617 * The code requires the caller to capture the time and hardware counter
618 * value at the on-time PPS signal transition.
619 *
620 * Note that, on some Unix systems, this routine runs at an interrupt
621 * priority level higher than the timer interrupt routine hardclock().
622 * Therefore, the variables used are distinct from the hardclock()
623 * variables, except for certain exceptions: The PPS frequency pps_freq
624 * and phase pps_offset variables are determined by this routine and
625 * updated atomically. The time_tolerance variable can be considered a
626 * constant, since it is infrequently changed, and then only when the
627 * PPS signal is disabled. The watchdog counter pps_valid is updated
628 * once per second by hardclock() and is atomically cleared in this
629 * routine.
630 */
631void
632hardpps(tvp, p_usec)
633	struct timeval *tvp;		/* time at PPS */
634	long p_usec;			/* hardware counter at PPS */
635{
636	long u_usec, v_usec, bigtick;
637	long cal_sec, cal_usec;
638
639	/*
640	 * An occasional glitch can be produced when the PPS interrupt
641	 * occurs in the hardclock() routine before the time variable is
642	 * updated. Here the offset is discarded when the difference
643	 * between it and the last one is greater than tick/2, but not
644	 * if the interval since the first discard exceeds 30 s.
645	 */
646	time_status |= STA_PPSSIGNAL;
647	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
648	pps_valid = 0;
649	u_usec = -tvp->tv_usec;
650	if (u_usec < -500000)
651		u_usec += 1000000;
652	v_usec = pps_offset - u_usec;
653	if (v_usec < 0)
654		v_usec = -v_usec;
655	if (v_usec > (tick >> 1)) {
656		if (pps_glitch > MAXGLITCH) {
657			pps_glitch = 0;
658			pps_tf[2] = u_usec;
659			pps_tf[1] = u_usec;
660		} else {
661			pps_glitch++;
662			u_usec = pps_offset;
663		}
664	} else
665		pps_glitch = 0;
666
667	/*
668	 * A three-stage median filter is used to help deglitch the pps
669	 * time. The median sample becomes the time offset estimate; the
670	 * difference between the other two samples becomes the time
671	 * dispersion (jitter) estimate.
672	 */
673	pps_tf[2] = pps_tf[1];
674	pps_tf[1] = pps_tf[0];
675	pps_tf[0] = u_usec;
676	MEDIAN3(pps_tf, pps_offset, v_usec);
677	if (v_usec > MAXTIME)
678		pps_jitcnt++;
679	v_usec = (v_usec << PPS_AVG) - pps_jitter;
680	if (v_usec < 0)
681		pps_jitter -= -v_usec >> PPS_AVG;
682	else
683		pps_jitter += v_usec >> PPS_AVG;
684	if (pps_jitter > (MAXTIME >> 1))
685		time_status |= STA_PPSJITTER;
686
687	/*
688	 * During the calibration interval adjust the starting time when
689	 * the tick overflows. At the end of the interval compute the
690	 * duration of the interval and the difference of the hardware
691	 * counters at the beginning and end of the interval. This code
692	 * is deliciously complicated by the fact valid differences may
693	 * exceed the value of tick when using long calibration
694	 * intervals and small ticks. Note that the counter can be
695	 * greater than tick if caught at just the wrong instant, but
696	 * the values returned and used here are correct.
697	 */
698	bigtick = (long)tick << SHIFT_USEC;
699	pps_usec -= pps_freq;
700	if (pps_usec >= bigtick)
701		pps_usec -= bigtick;
702	if (pps_usec < 0)
703		pps_usec += bigtick;
704	pps_time.tv_sec++;
705	pps_count++;
706	if (pps_count < (1 << pps_shift))
707		return;
708	pps_count = 0;
709	pps_calcnt++;
710	u_usec = p_usec << SHIFT_USEC;
711	v_usec = pps_usec - u_usec;
712	if (v_usec >= bigtick >> 1)
713		v_usec -= bigtick;
714	if (v_usec < -(bigtick >> 1))
715		v_usec += bigtick;
716	if (v_usec < 0)
717		v_usec = -(-v_usec >> pps_shift);
718	else
719		v_usec = v_usec >> pps_shift;
720	pps_usec = u_usec;
721	cal_sec = tvp->tv_sec;
722	cal_usec = tvp->tv_usec;
723	cal_sec -= pps_time.tv_sec;
724	cal_usec -= pps_time.tv_usec;
725	if (cal_usec < 0) {
726		cal_usec += 1000000;
727		cal_sec--;
728	}
729	pps_time = *tvp;
730
731	/*
732	 * Check for lost interrupts, noise, excessive jitter and
733	 * excessive frequency error. The number of timer ticks during
734	 * the interval may vary +-1 tick. Add to this a margin of one
735	 * tick for the PPS signal jitter and maximum frequency
736	 * deviation. If the limits are exceeded, the calibration
737	 * interval is reset to the minimum and we start over.
738	 */
739	u_usec = (long)tick << 1;
740	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
741	    || (cal_sec == 0 && cal_usec < u_usec))
742	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
743		pps_errcnt++;
744		pps_shift = PPS_SHIFT;
745		pps_intcnt = 0;
746		time_status |= STA_PPSERROR;
747		return;
748	}
749
750	/*
751	 * A three-stage median filter is used to help deglitch the pps
752	 * frequency. The median sample becomes the frequency offset
753	 * estimate; the difference between the other two samples
754	 * becomes the frequency dispersion (stability) estimate.
755	 */
756	pps_ff[2] = pps_ff[1];
757	pps_ff[1] = pps_ff[0];
758	pps_ff[0] = v_usec;
759	MEDIAN3(pps_ff, u_usec, v_usec);
760
761	/*
762	 * Here the frequency dispersion (stability) is updated. If it
763	 * is less than one-fourth the maximum (MAXFREQ), the frequency
764	 * offset is updated as well, but clamped to the tolerance. It
765	 * will be processed later by the hardclock() routine.
766	 */
767	v_usec = (v_usec >> 1) - pps_stabil;
768	if (v_usec < 0)
769		pps_stabil -= -v_usec >> PPS_AVG;
770	else
771		pps_stabil += v_usec >> PPS_AVG;
772	if (pps_stabil > MAXFREQ >> 2) {
773		pps_stbcnt++;
774		time_status |= STA_PPSWANDER;
775		return;
776	}
777	if (time_status & STA_PPSFREQ) {
778		if (u_usec < 0) {
779			pps_freq -= -u_usec >> PPS_AVG;
780			if (pps_freq < -time_tolerance)
781				pps_freq = -time_tolerance;
782			u_usec = -u_usec;
783		} else {
784			pps_freq += u_usec >> PPS_AVG;
785			if (pps_freq > time_tolerance)
786				pps_freq = time_tolerance;
787		}
788	}
789
790	/*
791	 * Here the calibration interval is adjusted. If the maximum
792	 * time difference is greater than tick / 4, reduce the interval
793	 * by half. If this is not the case for four consecutive
794	 * intervals, double the interval.
795	 */
796	if (u_usec << pps_shift > bigtick >> 2) {
797		pps_intcnt = 0;
798		if (pps_shift > PPS_SHIFT)
799			pps_shift--;
800	} else if (pps_intcnt >= 4) {
801		pps_intcnt = 0;
802		if (pps_shift < PPS_SHIFTMAX)
803			pps_shift++;
804	} else
805		pps_intcnt++;
806}
807
808#endif /* PPS_SYNC */
809