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