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