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