kern_ntptime.c revision 44574
1/***********************************************************************
2 *								       *
3 * Copyright (c) David L. Mills 1993-1998			       *
4 *								       *
5 * Permission to use, copy, modify, and distribute this software and   *
6 * its documentation for any purpose and without fee is hereby	       *
7 * granted, provided that the above copyright notice appears in all    *
8 * copies and that both the copyright notice and this permission       *
9 * notice appear in supporting documentation, and that the name	       *
10 * University of Delaware not be used in advertising or publicity      *
11 * pertaining to distribution of the software without specific,	       *
12 * written prior permission. The University of Delaware makes no       *
13 * representations about the suitability this software for any	       *
14 * purpose. It is provided "as is" without express or implied	       *
15 * warranty.							       *
16 *								       *
17 **********************************************************************/
18
19/*
20 * Adapted from the original sources for FreeBSD and timecounters by:
21 * Poul-Henning Kamp <phk@FreeBSD.org>
22 *
23 * The 32bit version of the "LP" macros seems a bit past its "sell by"
24 * date so I have retained only the 64bit version and included it directly
25 * in this file.
26 *
27 * Only minor changes done to interface with the timecounters over in
28 * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
29 * confusing and/or plain wrong in that context.
30 *
31 * The PPS_SYNC/hardpps() is currently not supported.
32 *
33 */
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/sysproto.h>
38#include <sys/kernel.h>
39#include <sys/proc.h>
40#include <sys/time.h>
41#include <sys/timex.h>
42#include <sys/timepps.h>
43#include <sys/sysctl.h>
44
45/*
46 * Single-precision macros for 64-bit machines
47 */
48typedef long long l_fp;
49#define L_ADD(v, u)	((v) += (u))
50#define L_SUB(v, u)	((v) -= (u))
51#define L_ADDHI(v, a)	((v) += (long long)(a) << 32)
52#define L_NEG(v)	((v) = -(v))
53#define L_RSHIFT(v, n) \
54	do { \
55		if ((v) < 0) \
56			(v) = -(-(v) >> (n)); \
57		else \
58			(v) = (v) >> (n); \
59	} while (0)
60#define L_MPY(v, a)	((v) *= (a))
61#define L_CLR(v)	((v) = 0)
62#define L_ISNEG(v)	((v) < 0)
63#define L_LINT(v, a)	((v) = (long long)(a) << 32)
64#define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
65
66/*
67 * Generic NTP kernel interface
68 *
69 * These routines constitute the Network Time Protocol (NTP) interfaces
70 * for user and daemon application programs. The ntp_gettime() routine
71 * provides the time, maximum error (synch distance) and estimated error
72 * (dispersion) to client user application programs. The ntp_adjtime()
73 * routine is used by the NTP daemon to adjust the system clock to an
74 * externally derived time. The time offset and related variables set by
75 * this routine are used by other routines in this module to adjust the
76 * phase and frequency of the clock discipline loop which controls the
77 * system clock.
78 *
79 * When the kernel time is reckoned directly in nanoseconds (NANO
80 * defined), the time at each tick interrupt is derived directly from
81 * the kernel time variable. When the kernel time is reckoned in
82 * microseconds, (NANO undefined), the time is derived from the kernel
83 * time variable together with a variable representing the leftover
84 * nanoseconds at the last tick interrupt. In either case, the current
85 * nanosecond time is reckoned from these values plus an interpolated
86 * value derived by the clock routines in another architecture-specific
87 * module. The interpolation can use either a dedicated counter or a
88 * processor cycle counter (PCC) implemented in some architectures.
89 *
90 * Note that all routines must run at priority splclock or higher.
91 */
92
93/*
94 * Phase/frequency-lock loop (PLL/FLL) definitions
95 *
96 * The nanosecond clock discipline uses two variable types, time
97 * variables and frequency variables. Both types are represented as 64-
98 * bit fixed-point quantities with the decimal point between two 32-bit
99 * halves. On a 32-bit machine, each half is represented as a single
100 * word and mathematical operations are done using multiple-precision
101 * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
102 * used.
103 *
104 * A time variable is a signed 64-bit fixed-point number in ns and
105 * fraction. It represents the remaining time offset to be amortized
106 * over succeeding tick interrupts. The maximum time offset is about
107 * 0.512 s and the resolution is about 2.3e-10 ns.
108 *
109 *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
110 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
111 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112 * |s s s|			 ns				   |
113 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114 * |			    fraction				   |
115 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116 *
117 * A frequency variable is a signed 64-bit fixed-point number in ns/s
118 * and fraction. It represents the ns and fraction to be added to the
119 * kernel time variable at each second. The maximum frequency offset is
120 * about +-512000 ns/s and the resolution is about 2.3e-10 ns/s.
121 *
122 *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
123 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
124 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
125 * |s s s s s s s s s s s s s|	          ns/s			   |
126 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
127 * |			    fraction				   |
128 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129 */
130/*
131 * The following variables establish the state of the PLL/FLL and the
132 * residual time and frequency offset of the local clock.
133 */
134#define SHIFT_PLL	4		/* PLL loop gain (shift) */
135#define SHIFT_FLL	2		/* FLL loop gain (shift) */
136
137static int time_state = TIME_OK;	/* clock state */
138static int time_status = STA_UNSYNC;	/* clock status bits */
139static long time_constant;		/* poll interval (shift) (s) */
140static long time_precision = 1;		/* clock precision (ns) */
141static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
142static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
143static long time_reftime;		/* time at last adjustment (s) */
144static long time_tick;			/* nanoseconds per tick (ns) */
145static l_fp time_offset;		/* time offset (ns) */
146static l_fp time_freq;			/* frequency offset (ns/s) */
147
148#ifdef PPS_SYNC
149/*
150 * The following variables are used when a pulse-per-second (PPS) signal
151 * is available and connected via a modem control lead. They establish
152 * the engineering parameters of the clock discipline loop when
153 * controlled by the PPS signal.
154 */
155#define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
156#define PPS_FAVGMAX	8		/* max freq avg interval (s) (shift) */
157#define PPS_PAVG	4		/* phase avg interval (s) (shift) */
158#define PPS_VALID	120		/* PPS signal watchdog max (s) */
159#define MAXTIME		500000		/* max PPS error (jitter) (ns) */
160#define MAXWANDER	500000		/* max PPS wander (ns/s/s) */
161
162struct ppstime {
163	long sec;			/* PPS seconds */
164	long nsec;			/* PPS nanoseconds */
165	long count;			/* PPS nanosecond counter */
166};
167static struct ppstime pps_tf[3];	/* phase median filter */
168static struct ppstime pps_filt;		/* phase offset */
169static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
170static long pps_lastfreq;		/* last scaled freq offset (ns/s) */
171static long pps_offacc;			/* offset accumulator */
172static long pps_jitter;			/* scaled time dispersion (ns) */
173static long pps_stabil;			/* scaled frequency dispersion (ns/s) */
174static long pps_lastcount;		/* last counter offset */
175static long pps_lastsec;		/* time at last calibration (s) */
176static int pps_valid;			/* signal watchdog counter */
177static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
178static int pps_intcnt;			/* wander counter */
179static int pps_offcnt;			/* offset accumulator counter */
180
181/*
182 * PPS signal quality monitors
183 */
184static long pps_calcnt;			/* calibration intervals */
185static long pps_jitcnt;			/* jitter limit exceeded */
186static long pps_stbcnt;			/* stability limit exceeded */
187static long pps_errcnt;			/* calibration errors */
188#endif /* PPS_SYNC */
189/*
190 * End of phase/frequency-lock loop (PLL/FLL) definitions
191 */
192
193static void ntp_init(void);
194static void hardupdate(long offset);
195
196/*
197 * ntp_gettime() - NTP user application interface
198 *
199 * See the timex.h header file for synopsis and API description.
200 */
201static int
202ntp_sysctl SYSCTL_HANDLER_ARGS
203{
204	struct ntptimeval ntv;	/* temporary structure */
205	struct timespec atv;	/* nanosecond time */
206
207	nanotime(&atv);
208	ntv.time.tv_sec = atv.tv_sec;
209	ntv.time.tv_nsec = atv.tv_nsec;
210	ntv.maxerror = time_maxerror;
211	ntv.esterror = time_esterror;
212	ntv.time_state = time_state;
213
214	/*
215	 * Status word error decode. If any of these conditions occur,
216	 * an error is returned, instead of the status word. Most
217	 * applications will care only about the fact the system clock
218	 * may not be trusted, not about the details.
219	 *
220	 * Hardware or software error
221	 */
222	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
223
224	/*
225	 * PPS signal lost when either time or frequency synchronization
226	 * requested
227	 */
228	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
229	    !(time_status & STA_PPSSIGNAL)) ||
230
231	/*
232	 * PPS jitter exceeded when time synchronization requested
233	 */
234	    (time_status & STA_PPSTIME &&
235	    time_status & STA_PPSJITTER) ||
236
237	/*
238	 * PPS wander exceeded or calibration error when frequency
239	 * synchronization requested
240	 */
241	    (time_status & STA_PPSFREQ &&
242	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
243		ntv.time_state = TIME_ERROR;
244	return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
245}
246
247SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
248SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
249	0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
250
251
252/*
253 * ntp_adjtime() - NTP daemon application interface
254 *
255 * See the timex.h header file for synopsis and API description.
256 */
257#ifndef _SYS_SYSPROTO_H_
258struct ntp_adjtime_args {
259	struct timex *tp;
260};
261#endif
262
263int
264ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
265{
266	struct timex ntv;	/* temporary structure */
267	int modes;		/* mode bits from structure */
268	int s;			/* caller priority */
269	int error;
270
271	error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
272	if (error)
273		return(error);
274
275	/*
276	 * Update selected clock variables - only the superuser can
277	 * change anything. Note that there is no error checking here on
278	 * the assumption the superuser should know what it is doing.
279	 */
280	modes = ntv.modes;
281	error = suser(p->p_cred->pc_ucred, &p->p_acflag);
282	if (error)
283		return (error);
284	s = splclock();
285	if (modes & MOD_FREQUENCY) {
286		L_LINT(time_freq, ntv.freq / SCALE_PPM);
287#ifdef PPS_SYNC
288		pps_freq = time_freq;
289#endif /* PPS_SYNC */
290	}
291	if (modes & MOD_MAXERROR)
292		time_maxerror = ntv.maxerror;
293	if (modes & MOD_ESTERROR)
294		time_esterror = ntv.esterror;
295	if (modes & MOD_STATUS) {
296		time_status &= STA_RONLY;
297		time_status |= ntv.status & ~STA_RONLY;
298	}
299	if (modes & MOD_TIMECONST)
300		time_constant = ntv.constant;
301	if (modes & MOD_NANO)
302		time_status |= STA_NANO;
303	if (modes & MOD_MICRO)
304		time_status &= ~STA_NANO;
305	if (modes & MOD_CLKB)
306		time_status |= STA_CLK;
307	if (modes & MOD_CLKA)
308		time_status &= ~STA_CLK;
309	if (modes & MOD_OFFSET) {
310		if (time_status & STA_NANO)
311			hardupdate(ntv.offset);
312		else
313			hardupdate(ntv.offset * 1000);
314	}
315
316	/*
317	 * Retrieve all clock variables
318	 */
319	if (time_status & STA_NANO)
320		ntv.offset = L_GINT(time_offset);
321	else
322		ntv.offset = L_GINT(time_offset) / 1000;
323	ntv.freq = L_GINT(time_freq) * SCALE_PPM;
324	ntv.maxerror = time_maxerror;
325	ntv.esterror = time_esterror;
326	ntv.status = time_status;
327	if (ntv.constant < 0)
328		time_constant = 0;
329	else if (ntv.constant > MAXTC)
330		time_constant = MAXTC;
331	else
332		time_constant = ntv.constant;
333	if (time_status & STA_NANO)
334		ntv.precision = time_precision;
335	else
336		ntv.precision = time_precision / 1000;
337	ntv.tolerance = MAXFREQ * SCALE_PPM;
338#ifdef PPS_SYNC
339	ntv.shift = pps_shift;
340	ntv.ppsfreq = L_GINT(pps_freq) * SCALE_PPM;
341	ntv.jitter = pps_jitter;
342	if (time_status & STA_NANO)
343		ntv.jitter = pps_jitter;
344	else
345		ntv.jitter = pps_jitter / 1000;
346	ntv.stabil = pps_stabil;
347	ntv.calcnt = pps_calcnt;
348	ntv.errcnt = pps_errcnt;
349	ntv.jitcnt = pps_jitcnt;
350	ntv.stbcnt = pps_stbcnt;
351#endif /* PPS_SYNC */
352	splx(s);
353
354	error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
355	if (error)
356		return (error);
357
358	/*
359	 * Status word error decode. See comments in
360	 * ntp_gettime() routine.
361	 */
362	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
363	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
364	    !(time_status & STA_PPSSIGNAL)) ||
365	    (time_status & STA_PPSTIME &&
366	    time_status & STA_PPSJITTER) ||
367	    (time_status & STA_PPSFREQ &&
368	    time_status & (STA_PPSWANDER | STA_PPSERROR)))
369		return (TIME_ERROR);
370	return (time_state);
371}
372
373/*
374 * second_overflow() - called after ntp_tick_adjust()
375 *
376 * This routine is ordinarily called immediately following the above
377 * routine ntp_tick_adjust(). While these two routines are normally
378 * combined, they are separated here only for the purposes of
379 * simulation.
380 */
381void
382ntp_update_second(struct timecounter *tcp)
383{
384	u_int32_t *newsec;
385	l_fp ftemp, time_adj;		/* 32/64-bit temporary */
386
387	newsec = &tcp->tc_offset_sec;
388	time_maxerror += MAXFREQ / 1000;
389
390	/*
391	 * Leap second processing. If in leap-insert state at
392	 * the end of the day, the system clock is set back one
393	 * second; if in leap-delete state, the system clock is
394	 * set ahead one second. The nano_time() routine or
395	 * external clock driver will insure that reported time
396	 * is always monotonic.
397	 */
398	switch (time_state) {
399
400		/*
401		 * No warning.
402		 */
403		case TIME_OK:
404		if (time_status & STA_INS)
405			time_state = TIME_INS;
406		else if (time_status & STA_DEL)
407			time_state = TIME_DEL;
408		break;
409
410		/*
411		 * Insert second 23:59:60 following second
412		 * 23:59:59.
413		 */
414		case TIME_INS:
415		if (!(time_status & STA_INS))
416			time_state = TIME_OK;
417		else if ((*newsec) % 86400 == 0) {
418			(*newsec)--;
419			time_state = TIME_OOP;
420		}
421		break;
422
423		/*
424		 * Delete second 23:59:59.
425		 */
426		case TIME_DEL:
427		if (!(time_status & STA_DEL))
428			time_state = TIME_OK;
429		else if (((*newsec) + 1) % 86400 == 0) {
430			(*newsec)++;
431			time_state = TIME_WAIT;
432		}
433		break;
434
435		/*
436		 * Insert second in progress.
437		 */
438		case TIME_OOP:
439		time_state = TIME_WAIT;
440		break;
441
442		/*
443		 * Wait for status bits to clear.
444		 */
445		case TIME_WAIT:
446		if (!(time_status & (STA_INS | STA_DEL)))
447			time_state = TIME_OK;
448	}
449
450	/*
451	 * Compute the total time adjustment for the next
452	 * second in ns. The offset is reduced by a factor
453	 * depending on FLL or PLL mode and whether the PPS
454	 * signal is operating. Note that the value is in effect
455	 * scaled by the clock frequency, since the adjustment
456	 * is added at each tick interrupt.
457	 */
458	ftemp = time_offset;
459#ifdef PPS_SYNC
460	if (time_status & STA_PPSTIME && time_status &
461	    STA_PPSSIGNAL)
462		L_RSHIFT(ftemp, PPS_FAVG);
463	else if (time_status & STA_MODE)
464#else
465	if (time_status & STA_MODE)
466#endif /* PPS_SYNC */
467		L_RSHIFT(ftemp, SHIFT_FLL);
468	else
469		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
470	time_adj = ftemp;
471	L_SUB(time_offset, ftemp);
472	L_ADD(time_adj, time_freq);
473	tcp->tc_adjustment = time_adj;
474#ifdef PPS_SYNC
475	if (pps_valid > 0)
476		pps_valid--;
477	else
478		time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
479		    STA_PPSWANDER | STA_PPSERROR);
480#endif /* PPS_SYNC */
481}
482
483/*
484 * ntp_init() - initialize variables and structures
485 *
486 * This routine must be called after the kernel variables hz and tick
487 * are set or changed and before the next tick interrupt. In this
488 * particular implementation, these values are assumed set elsewhere in
489 * the kernel. The design allows the clock frequency and tick interval
490 * to be changed while the system is running. So, this routine should
491 * probably be integrated with the code that does that.
492 */
493static void
494ntp_init()
495{
496
497	/*
498	 * The following variable must be initialized any time the
499	 * kernel variable hz is changed.
500	 */
501	time_tick = NANOSECOND / hz;
502
503	/*
504	 * The following variables are initialized only at startup. Only
505	 * those structures not cleared by the compiler need to be
506	 * initialized, and these only in the simulator. In the actual
507	 * kernel, any nonzero values here will quickly evaporate.
508	 */
509	L_CLR(time_offset);
510	L_CLR(time_freq);
511#ifdef PPS_SYNC
512	pps_filt.sec = pps_filt.nsec = pps_filt.count = 0;
513	pps_tf[0] = pps_tf[1] = pps_tf[2] = pps_filt;
514	L_CLR(pps_freq);
515#endif /* PPS_SYNC */
516}
517
518SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
519
520/*
521 * hardupdate() - local clock update
522 *
523 * This routine is called by ntp_adjtime() to update the local clock
524 * phase and frequency. The implementation is of an adaptive-parameter,
525 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
526 * time and frequency offset estimates for each call. If the kernel PPS
527 * discipline code is configured (PPS_SYNC), the PPS signal itself
528 * determines the new time offset, instead of the calling argument.
529 * Presumably, calls to ntp_adjtime() occur only when the caller
530 * believes the local clock is valid within some bound (+-128 ms with
531 * NTP). If the caller's time is far different than the PPS time, an
532 * argument will ensue, and it's not clear who will lose.
533 *
534 * For uncompensated quartz crystal oscillators and nominal update
535 * intervals less than 256 s, operation should be in phase-lock mode,
536 * where the loop is disciplined to phase. For update intervals greater
537 * than 1024 s, operation should be in frequency-lock mode, where the
538 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
539 * is selected by the STA_MODE status bit.
540 */
541static void
542hardupdate(offset)
543	long offset;		/* clock offset (ns) */
544{
545	long ltemp, mtemp;
546	l_fp ftemp;
547
548	/*
549	 * Select how the phase is to be controlled and from which
550	 * source. If the PPS signal is present and enabled to
551	 * discipline the time, the PPS offset is used; otherwise, the
552	 * argument offset is used.
553	 */
554	ltemp = offset;
555	if (ltemp > MAXPHASE)
556		ltemp = MAXPHASE;
557	else if (ltemp < -MAXPHASE)
558		ltemp = -MAXPHASE;
559	if (!(time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL))
560		L_LINT(time_offset, ltemp);
561
562	/*
563	 * Select how the frequency is to be controlled and in which
564	 * mode (PLL or FLL). If the PPS signal is present and enabled
565	 * to discipline the frequency, the PPS frequency is used;
566	 * otherwise, the argument offset is used to compute it.
567	 */
568	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
569		time_reftime = time_second;
570		return;
571	}
572	if (time_status & STA_FREQHOLD || time_reftime == 0)
573		time_reftime = time_second;
574	mtemp = time_second - time_reftime;
575	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)
576	    ) {
577		L_LINT(ftemp, (ltemp << 4) / mtemp);
578		L_RSHIFT(ftemp, SHIFT_FLL + 4);
579		L_ADD(time_freq, ftemp);
580		time_status |= STA_MODE;
581	} else {
582		L_LINT(ftemp, ltemp);
583		L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
584		L_MPY(ftemp, mtemp);
585		L_ADD(time_freq, ftemp);
586		time_status &= ~STA_MODE;
587	}
588	time_reftime = time_second;
589	if (L_GINT(time_freq) > MAXFREQ)
590		L_LINT(time_freq, MAXFREQ);
591	else if (L_GINT(time_freq) < -MAXFREQ)
592		L_LINT(time_freq, -MAXFREQ);
593}
594
595#ifdef PPS_SYNC
596/*
597 * hardpps() - discipline CPU clock oscillator to external PPS signal
598 *
599 * This routine is called at each PPS interrupt in order to discipline
600 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
601 * and leaves it in a handy spot for the hardclock() routine. It
602 * integrates successive PPS phase differences and calculates the
603 * frequency offset. This is used in hardclock() to discipline the CPU
604 * clock oscillator so that the intrinsic frequency error is cancelled
605 * out. The code requires the caller to capture the time and
606 * architecture-dependent hardware counter values in nanoseconds at the
607 * on-time PPS signal transition.
608 *
609 * Note that, on some Unix systems this routine runs at an interrupt
610 * priority level higher than the timer interrupt routine hardclock().
611 * Therefore, the variables used are distinct from the hardclock()
612 * variables, except for the actual time and frequency variables, which
613 * are determined by this routine and updated atomically.
614 */
615void
616hardpps(tsp, nsec)
617	struct timespec *tsp;	/* time at PPS */
618	long nsec;		/* hardware counter at PPS */
619{
620	long u_sec, u_nsec, v_nsec; /* temps */
621	l_fp ftemp;
622
623	/*
624	 * The signal is first processed by a frequency discriminator
625	 * which rejects noise and input signals with frequencies
626	 * outside the range 1 +-MAXFREQ PPS. If two hits occur in the
627	 * same second, we ignore the later hit; if not and a hit occurs
628	 * outside the range gate, keep the later hit but do not
629	 * process it.
630	 */
631	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
632	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
633	pps_valid = PPS_VALID;
634	u_sec = tsp->tv_sec;
635	u_nsec = tsp->tv_nsec;
636	if (u_nsec >= (NANOSECOND >> 1)) {
637		u_nsec -= NANOSECOND;
638		u_sec++;
639	}
640	v_nsec = u_nsec - pps_tf[0].nsec;
641	if (u_sec == pps_tf[0].sec && v_nsec < -MAXFREQ) {
642		return;
643	}
644	pps_tf[2] = pps_tf[1];
645	pps_tf[1] = pps_tf[0];
646	pps_tf[0].sec = u_sec;
647	pps_tf[0].nsec = u_nsec;
648
649	/*
650	 * Compute the difference between the current and previous
651	 * counter values. If the difference exceeds 0.5 s, assume it
652	 * has wrapped around, so correct 1.0 s. If the result exceeds
653	 * the tick interval, the sample point has crossed a tick
654	 * boundary during the last second, so correct the tick. Very
655	 * intricate.
656	 */
657	u_nsec = nsec - pps_lastcount;
658	pps_lastcount = nsec;
659	if (u_nsec > (NANOSECOND >> 1))
660		u_nsec -= NANOSECOND;
661	else if (u_nsec < -(NANOSECOND >> 1))
662		u_nsec += NANOSECOND;
663	if (u_nsec > (time_tick >> 1))
664		u_nsec -= time_tick;
665	else if (u_nsec < -(time_tick >> 1))
666		u_nsec += time_tick;
667	pps_tf[0].count = pps_tf[1].count + u_nsec;
668	if (v_nsec > MAXFREQ) {
669		return;
670	}
671	time_status &= ~STA_PPSJITTER;
672
673	/*
674	 * A three-stage median filter is used to help denoise the PPS
675	 * time. The median sample becomes the time offset estimate; the
676	 * difference between the other two samples becomes the time
677	 * dispersion (jitter) estimate.
678	 */
679	if (pps_tf[0].nsec > pps_tf[1].nsec) {
680		if (pps_tf[1].nsec > pps_tf[2].nsec) {
681			pps_filt = pps_tf[1];	/* 0 1 2 */
682			u_nsec = pps_tf[0].nsec - pps_tf[2].nsec;
683		} else if (pps_tf[2].nsec > pps_tf[0].nsec) {
684			pps_filt = pps_tf[0];	/* 2 0 1 */
685			u_nsec = pps_tf[2].nsec - pps_tf[1].nsec;
686		} else {
687			pps_filt = pps_tf[2];	/* 0 2 1 */
688			u_nsec = pps_tf[0].nsec - pps_tf[1].nsec;
689		}
690	} else {
691		if (pps_tf[1].nsec < pps_tf[2].nsec) {
692			pps_filt = pps_tf[1];	/* 2 1 0 */
693			u_nsec = pps_tf[2].nsec - pps_tf[0].nsec;
694		} else  if (pps_tf[2].nsec < pps_tf[0].nsec) {
695			pps_filt = pps_tf[0];	/* 1 0 2 */
696			u_nsec = pps_tf[1].nsec - pps_tf[2].nsec;
697		} else {
698			pps_filt = pps_tf[2];	/* 1 2 0 */
699			u_nsec = pps_tf[1].nsec - pps_tf[0].nsec;
700		}
701	}
702
703	/*
704	 * Nominal jitter is due to PPS signal noise and  interrupt
705	 * latency. If it exceeds the jitter limit, the sample is
706	 * discarded. otherwise, if so enabled, the time offset is
707	 * updated. The offsets are accumulated over the phase averaging
708	 * interval to improve accuracy. The jitter is averaged only for
709	 * performance monitoring. We can tolerate a modest loss of data
710	 * here without degrading time accuracy.
711	 */
712	if (u_nsec > MAXTIME) {
713		time_status |= STA_PPSJITTER;
714		pps_jitcnt++;
715	} else if (time_status & STA_PPSTIME) {
716		pps_offacc -= pps_filt.nsec;
717		pps_offcnt++;
718	}
719	if (pps_offcnt >= (1 << PPS_PAVG)) {
720		if (time_status & STA_PPSTIME) {
721			L_LINT(time_offset, pps_offacc);
722			L_RSHIFT(time_offset, PPS_PAVG);
723		}
724		pps_offacc = 0;
725		pps_offcnt = 0;
726
727	}
728	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
729	u_sec = pps_tf[0].sec - pps_lastsec;
730	if (u_sec < (1 << pps_shift))
731		return;
732
733	/*
734	 * At the end of the calibration interval the difference between
735	 * the first and last counter values becomes the scaled
736	 * frequency. It will later be divided by the length of the
737	 * interval to determine the frequency update. If the frequency
738	 * exceeds a sanity threshold, or if the actual calibration
739	 * interval is not equal to the expected length, the data are
740	 * discarded. We can tolerate a modest loss of data here without
741	 * degrading frequency ccuracy.
742	 */
743	pps_calcnt++;
744	v_nsec = -pps_filt.count;
745	pps_lastsec = pps_tf[0].sec;
746	pps_tf[0].count = 0;
747	u_nsec = MAXFREQ << pps_shift;
748	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
749	    pps_shift)) {
750		time_status |= STA_PPSERROR;
751		pps_errcnt++;
752		return;
753	}
754
755	/*
756	 * If the actual calibration interval is not equal to the
757	 * expected length, the data are discarded. If the wander is
758	 * less than the wander threshold for four consecutive
759	 * intervals, the interval is doubled; if it is greater than the
760	 * threshold for four consecutive intervals, the interval is
761	 * halved. The scaled frequency offset is converted to frequency
762	 * offset. The stability metric is calculated as the average of
763	 * recent frequency changes, but is used only for performance
764	 * monitoring.
765	 */
766	L_LINT(ftemp, v_nsec);
767	L_RSHIFT(ftemp, pps_shift);
768	L_SUB(ftemp, pps_freq);
769	u_nsec = L_GINT(ftemp);
770	if (u_nsec > MAXWANDER) {
771		L_LINT(ftemp, MAXWANDER);
772		pps_intcnt--;
773		time_status |= STA_PPSWANDER;
774		pps_stbcnt++;
775	} else if (u_nsec < -MAXWANDER) {
776		L_LINT(ftemp, -MAXWANDER);
777		pps_intcnt--;
778		time_status |= STA_PPSWANDER;
779		pps_stbcnt++;
780	} else {
781		pps_intcnt++;
782	}
783	if (pps_intcnt >= 4) {
784		pps_intcnt = 4;
785		if (pps_shift < PPS_FAVGMAX) {
786			pps_shift++;
787			pps_intcnt = 0;
788		}
789	} else if (pps_intcnt <= -4) {
790		pps_intcnt = -4;
791		if (pps_shift > PPS_FAVG) {
792			pps_shift--;
793			pps_intcnt = 0;
794		}
795	}
796	if (u_nsec < 0)
797		u_nsec = -u_nsec;
798	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
799
800	/*
801	 * The frequency offset is averaged into the PPS frequency. If
802	 * enabled, the system clock frequency is updated as well.
803	 */
804	L_RSHIFT(ftemp, PPS_FAVG);
805	L_ADD(pps_freq, ftemp);
806	u_nsec = L_GINT(pps_freq);
807	if (u_nsec > MAXFREQ)
808		L_LINT(pps_freq, MAXFREQ);
809	else if (u_nsec < -MAXFREQ)
810		L_LINT(pps_freq, -MAXFREQ);
811	if (time_status & STA_PPSFREQ)
812		time_freq = pps_freq;
813}
814#endif /* PPS_SYNC */
815
816int
817std_pps_ioctl(u_long cmd, caddr_t data, pps_params_t *pp, pps_info_t *pi, int ppscap)
818{
819        pps_params_t *app;
820        pps_info_t *api;
821
822        switch (cmd) {
823        case PPS_IOC_CREATE:
824                return (0);
825        case PPS_IOC_DESTROY:
826                return (0);
827        case PPS_IOC_SETPARAMS:
828                app = (pps_params_t *)data;
829                if (app->mode & ~ppscap)
830                        return (EINVAL);
831                *pp = *app;
832                return (0);
833        case PPS_IOC_GETPARAMS:
834                app = (pps_params_t *)data;
835                *app = *pp;
836                return (0);
837        case PPS_IOC_GETCAP:
838                *(int*)data = ppscap;
839                return (0);
840        case PPS_IOC_FETCH:
841                api = (pps_info_t *)data;
842                *api = *pi;
843                pi->current_mode = pp->mode;
844                return (0);
845        case PPS_IOC_WAIT:
846                return (EOPNOTSUPP);
847        default:
848                return (ENODEV);
849        }
850}
851