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