kern_ntptime.c revision 32925
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}
412static int
413ntp_sysctl SYSCTL_HANDLER_ARGS
414{
415	struct timeval atv;
416	struct ntptimeval ntv;
417	int s;
418
419	s = splclock();
420#ifdef EXT_CLOCK
421	/*
422	 * The microtime() external clock routine returns a
423	 * status code. If less than zero, we declare an error
424	 * in the clock status word and return the kernel
425	 * (software) time variable. While there are other
426	 * places that call microtime(), this is the only place
427	 * that matters from an application point of view.
428	 */
429	if (microtime(&atv) < 0) {
430		time_status |= STA_CLOCKERR;
431		ntv.time = time;
432	} else {
433		time_status &= ~STA_CLOCKERR;
434	}
435#else /* EXT_CLOCK */
436	microtime(&atv);
437#endif /* EXT_CLOCK */
438	ntv.time = atv;
439	ntv.maxerror = time_maxerror;
440	ntv.esterror = time_esterror;
441	splx(s);
442
443	ntv.time_state = time_state;
444
445	/*
446	 * Status word error decode. If any of these conditions
447	 * occur, an error is returned, instead of the status
448	 * word. Most applications will care only about the fact
449	 * the system clock may not be trusted, not about the
450	 * details.
451	 *
452	 * Hardware or software error
453	 */
454	if (time_status & (STA_UNSYNC | STA_CLOCKERR)) {
455		ntv.time_state = TIME_ERROR;
456	}
457
458	/*
459	 * PPS signal lost when either time or frequency
460	 * synchronization requested
461	 */
462	if (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
463	    !(time_status & STA_PPSSIGNAL)) {
464		ntv.time_state = TIME_ERROR;
465	}
466
467	/*
468	 * PPS jitter exceeded when time synchronization
469	 * requested
470	 */
471	if (time_status & STA_PPSTIME &&
472	    time_status & STA_PPSJITTER) {
473		ntv.time_state = TIME_ERROR;
474	}
475
476	/*
477	 * PPS wander exceeded or calibration error when
478	 * frequency synchronization requested
479	 */
480	if (time_status & STA_PPSFREQ &&
481	    time_status & (STA_PPSWANDER | STA_PPSERROR)) {
482		ntv.time_state = TIME_ERROR;
483	}
484	return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
485}
486
487SYSCTL_NODE(_kern, KERN_NTP_PLL, ntp_pll, CTLFLAG_RW, 0,
488	"NTP kernel PLL related stuff");
489SYSCTL_PROC(_kern_ntp_pll, NTP_PLL_GETTIME, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
490	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
491
492/*
493 * ntp_adjtime() - NTP daemon application interface
494 */
495#ifndef _SYS_SYSPROTO_H_
496struct ntp_adjtime_args {
497  struct timex *tp;
498};
499#endif
500
501int
502ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
503{
504	struct timex ntv;
505	int modes;
506	int s;
507	int error;
508
509	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
510	if (error)
511		return error;
512
513	/*
514	 * Update selected clock variables - only the superuser can
515	 * change anything. Note that there is no error checking here on
516	 * the assumption the superuser should know what it is doing.
517	 */
518	modes = ntv.modes;
519	if ((modes != 0)
520	    && (error = suser(p->p_cred->pc_ucred, &p->p_acflag)))
521		return error;
522
523	s = splclock();
524	if (modes & MOD_FREQUENCY)
525#ifdef PPS_SYNC
526		time_freq = ntv.freq - pps_freq;
527#else /* PPS_SYNC */
528		time_freq = ntv.freq;
529#endif /* PPS_SYNC */
530	if (modes & MOD_MAXERROR)
531		time_maxerror = ntv.maxerror;
532	if (modes & MOD_ESTERROR)
533		time_esterror = ntv.esterror;
534	if (modes & MOD_STATUS) {
535		time_status &= STA_RONLY;
536		time_status |= ntv.status & ~STA_RONLY;
537	}
538	if (modes & MOD_TIMECONST)
539		time_constant = ntv.constant;
540	if (modes & MOD_OFFSET)
541		hardupdate(ntv.offset);
542
543	/*
544	 * Retrieve all clock variables
545	 */
546	if (time_offset < 0)
547		ntv.offset = -(-time_offset >> SHIFT_UPDATE);
548	else
549		ntv.offset = time_offset >> SHIFT_UPDATE;
550#ifdef PPS_SYNC
551	ntv.freq = time_freq + pps_freq;
552#else /* PPS_SYNC */
553	ntv.freq = time_freq;
554#endif /* PPS_SYNC */
555	ntv.maxerror = time_maxerror;
556	ntv.esterror = time_esterror;
557	ntv.status = time_status;
558	ntv.constant = time_constant;
559	ntv.precision = time_precision;
560	ntv.tolerance = time_tolerance;
561#ifdef PPS_SYNC
562	ntv.shift = pps_shift;
563	ntv.ppsfreq = pps_freq;
564	ntv.jitter = pps_jitter >> PPS_AVG;
565	ntv.stabil = pps_stabil;
566	ntv.calcnt = pps_calcnt;
567	ntv.errcnt = pps_errcnt;
568	ntv.jitcnt = pps_jitcnt;
569	ntv.stbcnt = pps_stbcnt;
570#endif /* PPS_SYNC */
571	(void)splx(s);
572
573	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
574	if (!error) {
575		/*
576		 * Status word error decode. See comments in
577		 * ntp_gettime() routine.
578		 */
579		p->p_retval[0] = time_state;
580		if (time_status & (STA_UNSYNC | STA_CLOCKERR))
581			p->p_retval[0] = TIME_ERROR;
582		if (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
583		    !(time_status & STA_PPSSIGNAL))
584			p->p_retval[0] = TIME_ERROR;
585		if (time_status & STA_PPSTIME &&
586		    time_status & STA_PPSJITTER)
587			p->p_retval[0] = TIME_ERROR;
588		if (time_status & STA_PPSFREQ &&
589		    time_status & (STA_PPSWANDER | STA_PPSERROR))
590			p->p_retval[0] = TIME_ERROR;
591	}
592	return error;
593}
594
595#ifdef PPS_SYNC
596
597/* We need this ugly monster twice, so lets macroize it... */
598
599#define MEDIAN3X(a, m, s, i1, i2, i3)				\
600	do {							\
601	m = a[i2];						\
602	s = a[i1] - a[i3];					\
603	} while (0)
604
605#define MEDIAN3(a, m, s)					\
606	do {							\
607		if (a[0] > a[1]) {				\
608			if (a[1] > a[2])			\
609				MEDIAN3X(a, m, s, 0, 1, 2);	\
610			else if (a[2] > a[0])			\
611				MEDIAN3X(a, m, s, 2, 0, 1);	\
612			else					\
613				MEDIAN3X(a, m, s, 0, 2, 1);	\
614		} else {					\
615			if (a[2] > a[1])			\
616				MEDIAN3X(a, m, s, 2, 1, 0);	\
617			else  if (a[0] > a[2])			\
618				MEDIAN3X(a, m, s, 1, 0, 2);	\
619			else					\
620				MEDIAN3X(a, m, s, 1, 2, 0);	\
621		}						\
622	} while (0)
623
624/*
625 * hardpps() - discipline CPU clock oscillator to external PPS signal
626 *
627 * This routine is called at each PPS interrupt in order to discipline
628 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
629 * and leaves it in a handy spot for the hardclock() routine. It
630 * integrates successive PPS phase differences and calculates the
631 * frequency offset. This is used in hardclock() to discipline the CPU
632 * clock oscillator so that intrinsic frequency error is cancelled out.
633 * The code requires the caller to capture the time and hardware counter
634 * value at the on-time PPS signal transition.
635 *
636 * Note that, on some Unix systems, this routine runs at an interrupt
637 * priority level higher than the timer interrupt routine hardclock().
638 * Therefore, the variables used are distinct from the hardclock()
639 * variables, except for certain exceptions: The PPS frequency pps_freq
640 * and phase pps_offset variables are determined by this routine and
641 * updated atomically. The time_tolerance variable can be considered a
642 * constant, since it is infrequently changed, and then only when the
643 * PPS signal is disabled. The watchdog counter pps_valid is updated
644 * once per second by hardclock() and is atomically cleared in this
645 * routine.
646 */
647void
648hardpps(tvp, p_usec)
649	struct timeval *tvp;		/* time at PPS */
650	long p_usec;			/* hardware counter at PPS */
651{
652	long u_usec, v_usec, bigtick;
653	long cal_sec, cal_usec;
654
655	/*
656	 * An occasional glitch can be produced when the PPS interrupt
657	 * occurs in the hardclock() routine before the time variable is
658	 * updated. Here the offset is discarded when the difference
659	 * between it and the last one is greater than tick/2, but not
660	 * if the interval since the first discard exceeds 30 s.
661	 */
662	time_status |= STA_PPSSIGNAL;
663	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
664	pps_valid = 0;
665	u_usec = -tvp->tv_usec;
666	if (u_usec < -500000)
667		u_usec += 1000000;
668	v_usec = pps_offset - u_usec;
669	if (v_usec < 0)
670		v_usec = -v_usec;
671	if (v_usec > (tick >> 1)) {
672		if (pps_glitch > MAXGLITCH) {
673			pps_glitch = 0;
674			pps_tf[2] = u_usec;
675			pps_tf[1] = u_usec;
676		} else {
677			pps_glitch++;
678			u_usec = pps_offset;
679		}
680	} else
681		pps_glitch = 0;
682
683	/*
684	 * A three-stage median filter is used to help deglitch 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	pps_tf[2] = pps_tf[1];
690	pps_tf[1] = pps_tf[0];
691	pps_tf[0] = u_usec;
692
693	MEDIAN3(pps_tf, pps_offset, v_usec);
694
695	if (v_usec > MAXTIME)
696		pps_jitcnt++;
697	v_usec = (v_usec << PPS_AVG) - pps_jitter;
698	if (v_usec < 0)
699		pps_jitter -= -v_usec >> PPS_AVG;
700	else
701		pps_jitter += v_usec >> PPS_AVG;
702	if (pps_jitter > (MAXTIME >> 1))
703		time_status |= STA_PPSJITTER;
704
705	/*
706	 * During the calibration interval adjust the starting time when
707	 * the tick overflows. At the end of the interval compute the
708	 * duration of the interval and the difference of the hardware
709	 * counters at the beginning and end of the interval. This code
710	 * is deliciously complicated by the fact valid differences may
711	 * exceed the value of tick when using long calibration
712	 * intervals and small ticks. Note that the counter can be
713	 * greater than tick if caught at just the wrong instant, but
714	 * the values returned and used here are correct.
715	 */
716	bigtick = (long)tick << SHIFT_USEC;
717	pps_usec -= pps_freq;
718	if (pps_usec >= bigtick)
719		pps_usec -= bigtick;
720	if (pps_usec < 0)
721		pps_usec += bigtick;
722	pps_time.tv_sec++;
723	pps_count++;
724	if (pps_count < (1 << pps_shift))
725		return;
726	pps_count = 0;
727	pps_calcnt++;
728	u_usec = p_usec << SHIFT_USEC;
729	v_usec = pps_usec - u_usec;
730	if (v_usec >= bigtick >> 1)
731		v_usec -= bigtick;
732	if (v_usec < -(bigtick >> 1))
733		v_usec += bigtick;
734	if (v_usec < 0)
735		v_usec = -(-v_usec >> pps_shift);
736	else
737		v_usec = v_usec >> pps_shift;
738	pps_usec = u_usec;
739	cal_sec = tvp->tv_sec;
740	cal_usec = tvp->tv_usec;
741	cal_sec -= pps_time.tv_sec;
742	cal_usec -= pps_time.tv_usec;
743	if (cal_usec < 0) {
744		cal_usec += 1000000;
745		cal_sec--;
746	}
747	pps_time = *tvp;
748
749	/*
750	 * Check for lost interrupts, noise, excessive jitter and
751	 * excessive frequency error. The number of timer ticks during
752	 * the interval may vary +-1 tick. Add to this a margin of one
753	 * tick for the PPS signal jitter and maximum frequency
754	 * deviation. If the limits are exceeded, the calibration
755	 * interval is reset to the minimum and we start over.
756	 */
757	u_usec = (long)tick << 1;
758	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
759	    || (cal_sec == 0 && cal_usec < u_usec))
760	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
761		pps_errcnt++;
762		pps_shift = PPS_SHIFT;
763		pps_intcnt = 0;
764		time_status |= STA_PPSERROR;
765		return;
766	}
767
768	/*
769	 * A three-stage median filter is used to help deglitch the pps
770	 * frequency. The median sample becomes the frequency offset
771	 * estimate; the difference between the other two samples
772	 * becomes the frequency dispersion (stability) estimate.
773	 */
774	pps_ff[2] = pps_ff[1];
775	pps_ff[1] = pps_ff[0];
776	pps_ff[0] = v_usec;
777
778	MEDIAN3(pps_ff, u_usec, v_usec);
779
780	/*
781	 * Here the frequency dispersion (stability) is updated. If it
782	 * is less than one-fourth the maximum (MAXFREQ), the frequency
783	 * offset is updated as well, but clamped to the tolerance. It
784	 * will be processed later by the hardclock() routine.
785	 */
786	v_usec = (v_usec >> 1) - pps_stabil;
787	if (v_usec < 0)
788		pps_stabil -= -v_usec >> PPS_AVG;
789	else
790		pps_stabil += v_usec >> PPS_AVG;
791	if (pps_stabil > MAXFREQ >> 2) {
792		pps_stbcnt++;
793		time_status |= STA_PPSWANDER;
794		return;
795	}
796	if (time_status & STA_PPSFREQ) {
797		if (u_usec < 0) {
798			pps_freq -= -u_usec >> PPS_AVG;
799			if (pps_freq < -time_tolerance)
800				pps_freq = -time_tolerance;
801			u_usec = -u_usec;
802		} else {
803			pps_freq += u_usec >> PPS_AVG;
804			if (pps_freq > time_tolerance)
805				pps_freq = time_tolerance;
806		}
807	}
808
809	/*
810	 * Here the calibration interval is adjusted. If the maximum
811	 * time difference is greater than tick / 4, reduce the interval
812	 * by half. If this is not the case for four consecutive
813	 * intervals, double the interval.
814	 */
815	if (u_usec << pps_shift > bigtick >> 2) {
816		pps_intcnt = 0;
817		if (pps_shift > PPS_SHIFT)
818			pps_shift--;
819	} else if (pps_intcnt >= 4) {
820		pps_intcnt = 0;
821		if (pps_shift < PPS_SHIFTMAX)
822			pps_shift++;
823	} else
824		pps_intcnt++;
825}
826#endif /* PPS_SYNC */
827