xref: /netbsd-src/sys/kern/kern_ntptime.c (revision 2718af68c3efc72c9769069b5c7f9ed36f6b9def)
1 /*	$NetBSD: kern_ntptime.c,v 1.63 2022/03/13 12:57:33 riastradh Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*-
30  ***********************************************************************
31  *								       *
32  * Copyright (c) David L. Mills 1993-2001			       *
33  *								       *
34  * Permission to use, copy, modify, and distribute this software and   *
35  * its documentation for any purpose and without fee is hereby	       *
36  * granted, provided that the above copyright notice appears in all    *
37  * copies and that both the copyright notice and this permission       *
38  * notice appear in supporting documentation, and that the name	       *
39  * University of Delaware not be used in advertising or publicity      *
40  * pertaining to distribution of the software without specific,	       *
41  * written prior permission. The University of Delaware makes no       *
42  * representations about the suitability this software for any	       *
43  * purpose. It is provided "as is" without express or implied	       *
44  * warranty.							       *
45  *								       *
46  **********************************************************************/
47 
48 /*
49  * Adapted from the original sources for FreeBSD and timecounters by:
50  * Poul-Henning Kamp <phk@FreeBSD.org>.
51  *
52  * The 32bit version of the "LP" macros seems a bit past its "sell by"
53  * date so I have retained only the 64bit version and included it directly
54  * in this file.
55  *
56  * Only minor changes done to interface with the timecounters over in
57  * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
58  * confusing and/or plain wrong in that context.
59  */
60 
61 #include <sys/cdefs.h>
62 /* __FBSDID("$FreeBSD: src/sys/kern/kern_ntptime.c,v 1.59 2005/05/28 14:34:41 rwatson Exp $"); */
63 __KERNEL_RCSID(0, "$NetBSD: kern_ntptime.c,v 1.63 2022/03/13 12:57:33 riastradh Exp $");
64 
65 #ifdef _KERNEL_OPT
66 #include "opt_ntp.h"
67 #endif
68 
69 #include <sys/param.h>
70 #include <sys/resourcevar.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/proc.h>
74 #include <sys/sysctl.h>
75 #include <sys/timex.h>
76 #include <sys/vnode.h>
77 #include <sys/kauth.h>
78 #include <sys/mount.h>
79 #include <sys/syscallargs.h>
80 #include <sys/cpu.h>
81 
82 #include <compat/sys/timex.h>
83 
84 /*
85  * Single-precision macros for 64-bit machines
86  */
87 typedef int64_t l_fp;
88 #define L_ADD(v, u)	((v) += (u))
89 #define L_SUB(v, u)	((v) -= (u))
90 #define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
91 #define L_NEG(v)	((v) = -(v))
92 #define L_RSHIFT(v, n) \
93 	do { \
94 		if ((v) < 0) \
95 			(v) = -(-(v) >> (n)); \
96 		else \
97 			(v) = (v) >> (n); \
98 	} while (0)
99 #define L_MPY(v, a)	((v) *= (a))
100 #define L_CLR(v)	((v) = 0)
101 #define L_ISNEG(v)	((v) < 0)
102 #define L_LINT(v, a)	((v) = (int64_t)((uint64_t)(a) << 32))
103 #define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
104 
105 #ifdef NTP
106 /*
107  * Generic NTP kernel interface
108  *
109  * These routines constitute the Network Time Protocol (NTP) interfaces
110  * for user and daemon application programs. The ntp_gettime() routine
111  * provides the time, maximum error (synch distance) and estimated error
112  * (dispersion) to client user application programs. The ntp_adjtime()
113  * routine is used by the NTP daemon to adjust the system clock to an
114  * externally derived time. The time offset and related variables set by
115  * this routine are used by other routines in this module to adjust the
116  * phase and frequency of the clock discipline loop which controls the
117  * system clock.
118  *
119  * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
120  * defined), the time at each tick interrupt is derived directly from
121  * the kernel time variable. When the kernel time is reckoned in
122  * microseconds, (NTP_NANO undefined), the time is derived from the
123  * kernel time variable together with a variable representing the
124  * leftover nanoseconds at the last tick interrupt. In either case, the
125  * current nanosecond time is reckoned from these values plus an
126  * interpolated value derived by the clock routines in another
127  * architecture-specific module. The interpolation can use either a
128  * dedicated counter or a processor cycle counter (PCC) implemented in
129  * some architectures.
130  *
131  * Note that all routines must run at priority splclock or higher.
132  */
133 /*
134  * Phase/frequency-lock loop (PLL/FLL) definitions
135  *
136  * The nanosecond clock discipline uses two variable types, time
137  * variables and frequency variables. Both types are represented as 64-
138  * bit fixed-point quantities with the decimal point between two 32-bit
139  * halves. On a 32-bit machine, each half is represented as a single
140  * word and mathematical operations are done using multiple-precision
141  * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
142  * used.
143  *
144  * A time variable is a signed 64-bit fixed-point number in ns and
145  * fraction. It represents the remaining time offset to be amortized
146  * over succeeding tick interrupts. The maximum time offset is about
147  * 0.5 s and the resolution is about 2.3e-10 ns.
148  *
149  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
150  *  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
151  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
152  * |s s s|			 ns				   |
153  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
154  * |			    fraction				   |
155  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
156  *
157  * A frequency variable is a signed 64-bit fixed-point number in ns/s
158  * and fraction. It represents the ns and fraction to be added to the
159  * kernel time variable at each second. The maximum frequency offset is
160  * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
161  *
162  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
163  *  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
164  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
165  * |s s s s s s s s s s s s s|	          ns/s			   |
166  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
167  * |			    fraction				   |
168  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
169  */
170 /*
171  * The following variables establish the state of the PLL/FLL and the
172  * residual time and frequency offset of the local clock.
173  */
174 #define SHIFT_PLL	4		/* PLL loop gain (shift) */
175 #define SHIFT_FLL	2		/* FLL loop gain (shift) */
176 
177 static int time_state = TIME_OK;	/* clock state */
178 static int time_status = STA_UNSYNC;	/* clock status bits */
179 static long time_tai;			/* TAI offset (s) */
180 static long time_monitor;		/* last time offset scaled (ns) */
181 static long time_constant;		/* poll interval (shift) (s) */
182 static long time_precision = 1;		/* clock precision (ns) */
183 static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
184 static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
185 static time_t time_reftime;		/* time at last adjustment (s) */
186 static l_fp time_offset;		/* time offset (ns) */
187 static l_fp time_freq;			/* frequency offset (ns/s) */
188 #endif /* NTP */
189 
190 static l_fp time_adj;			/* tick adjust (ns/s) */
191 int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
192 
193 extern int time_adjusted;	/* ntp might have changed the system time */
194 
195 #ifdef NTP
196 #ifdef PPS_SYNC
197 /*
198  * The following variables are used when a pulse-per-second (PPS) signal
199  * is available and connected via a modem control lead. They establish
200  * the engineering parameters of the clock discipline loop when
201  * controlled by the PPS signal.
202  */
203 #define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
204 #define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
205 #define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
206 #define PPS_PAVG	4		/* phase avg interval (s) (shift) */
207 #define PPS_VALID	120		/* PPS signal watchdog max (s) */
208 #define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
209 #define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
210 
211 static struct timespec pps_tf[3];	/* phase median filter */
212 static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
213 static long pps_fcount;			/* frequency accumulator */
214 static long pps_jitter;			/* nominal jitter (ns) */
215 static long pps_stabil;			/* nominal stability (scaled ns/s) */
216 static long pps_lastsec;		/* time at last calibration (s) */
217 static int pps_valid;			/* signal watchdog counter */
218 static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
219 static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
220 static int pps_intcnt;			/* wander counter */
221 
222 /*
223  * PPS signal quality monitors
224  */
225 static long pps_calcnt;			/* calibration intervals */
226 static long pps_jitcnt;			/* jitter limit exceeded */
227 static long pps_stbcnt;			/* stability limit exceeded */
228 static long pps_errcnt;			/* calibration errors */
229 #endif /* PPS_SYNC */
230 /*
231  * End of phase/frequency-lock loop (PLL/FLL) definitions
232  */
233 
234 static void hardupdate(long offset);
235 
236 /*
237  * ntp_gettime() - NTP user application interface
238  */
239 void
240 ntp_gettime(struct ntptimeval *ntv)
241 {
242 	memset(ntv, 0, sizeof(*ntv));
243 
244 	mutex_spin_enter(&timecounter_lock);
245 	nanotime(&ntv->time);
246 	ntv->maxerror = time_maxerror;
247 	ntv->esterror = time_esterror;
248 	ntv->tai = time_tai;
249 	ntv->time_state = time_state;
250 	mutex_spin_exit(&timecounter_lock);
251 }
252 
253 /* ARGSUSED */
254 /*
255  * ntp_adjtime() - NTP daemon application interface
256  */
257 int
258 sys_ntp_adjtime(struct lwp *l, const struct sys_ntp_adjtime_args *uap, register_t *retval)
259 {
260 	/* {
261 		syscallarg(struct timex *) tp;
262 	} */
263 	struct timex ntv;
264 	int error;
265 
266 	error = copyin((void *)SCARG(uap, tp), (void *)&ntv, sizeof(ntv));
267 	if (error != 0)
268 		return (error);
269 
270 	if (ntv.modes != 0 && (error = kauth_authorize_system(l->l_cred,
271 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_NTPADJTIME, NULL,
272 	    NULL, NULL)) != 0)
273 		return (error);
274 
275 	ntp_adjtime1(&ntv);
276 
277 	error = copyout((void *)&ntv, (void *)SCARG(uap, tp), sizeof(ntv));
278 	if (!error)
279 		*retval = ntp_timestatus();
280 
281 	return error;
282 }
283 
284 void
285 ntp_adjtime1(struct timex *ntv)
286 {
287 	long freq;
288 	int modes;
289 
290 	/*
291 	 * Update selected clock variables - only the superuser can
292 	 * change anything. Note that there is no error checking here on
293 	 * the assumption the superuser should know what it is doing.
294 	 * Note that either the time constant or TAI offset are loaded
295 	 * from the ntv.constant member, depending on the mode bits. If
296 	 * the STA_PLL bit in the status word is cleared, the state and
297 	 * status words are reset to the initial values at boot.
298 	 */
299 	mutex_spin_enter(&timecounter_lock);
300 	modes = ntv->modes;
301 	if (modes != 0)
302 		/* We need to save the system time during shutdown */
303 		time_adjusted |= 2;
304 	if (modes & MOD_MAXERROR)
305 		time_maxerror = ntv->maxerror;
306 	if (modes & MOD_ESTERROR)
307 		time_esterror = ntv->esterror;
308 	if (modes & MOD_STATUS) {
309 		if (time_status & STA_PLL && !(ntv->status & STA_PLL)) {
310 			time_state = TIME_OK;
311 			time_status = STA_UNSYNC;
312 #ifdef PPS_SYNC
313 			pps_shift = PPS_FAVG;
314 #endif /* PPS_SYNC */
315 		}
316 		time_status &= STA_RONLY;
317 		time_status |= ntv->status & ~STA_RONLY;
318 	}
319 	if (modes & MOD_TIMECONST) {
320 		if (ntv->constant < 0)
321 			time_constant = 0;
322 		else if (ntv->constant > MAXTC)
323 			time_constant = MAXTC;
324 		else
325 			time_constant = ntv->constant;
326 	}
327 	if (modes & MOD_TAI) {
328 		if (ntv->constant > 0)	/* XXX zero & negative numbers ? */
329 			time_tai = ntv->constant;
330 	}
331 #ifdef PPS_SYNC
332 	if (modes & MOD_PPSMAX) {
333 		if (ntv->shift < PPS_FAVG)
334 			pps_shiftmax = PPS_FAVG;
335 		else if (ntv->shift > PPS_FAVGMAX)
336 			pps_shiftmax = PPS_FAVGMAX;
337 		else
338 			pps_shiftmax = ntv->shift;
339 	}
340 #endif /* PPS_SYNC */
341 	if (modes & MOD_NANO)
342 		time_status |= STA_NANO;
343 	if (modes & MOD_MICRO)
344 		time_status &= ~STA_NANO;
345 	if (modes & MOD_CLKB)
346 		time_status |= STA_CLK;
347 	if (modes & MOD_CLKA)
348 		time_status &= ~STA_CLK;
349 	if (modes & MOD_FREQUENCY) {
350 		freq = MIN(INT32_MAX, MAX(INT32_MIN, ntv->freq));
351 		freq = (freq * (int64_t)1000) >> 16;
352 		if (freq > MAXFREQ)
353 			L_LINT(time_freq, MAXFREQ);
354 		else if (freq < -MAXFREQ)
355 			L_LINT(time_freq, -MAXFREQ);
356 		else {
357 			/*
358 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
359 			 * time_freq is [ns/s * 2^32]
360 			 */
361 			time_freq = ntv->freq * 1000LL * 65536LL;
362 		}
363 #ifdef PPS_SYNC
364 		pps_freq = time_freq;
365 #endif /* PPS_SYNC */
366 	}
367 	if (modes & MOD_OFFSET) {
368 		if (time_status & STA_NANO) {
369 			hardupdate(ntv->offset);
370 		} else {
371 			long offset = ntv->offset;
372 			offset = MIN(offset, MAXPHASE/1000);
373 			offset = MAX(offset, -MAXPHASE/1000);
374 			hardupdate(offset * 1000);
375 		}
376 	}
377 
378 	/*
379 	 * Retrieve all clock variables. Note that the TAI offset is
380 	 * returned only by ntp_gettime();
381 	 */
382 	if (time_status & STA_NANO)
383 		ntv->offset = L_GINT(time_offset);
384 	else
385 		ntv->offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
386 	if (time_freq < 0)
387 		ntv->freq = L_GINT(-((-time_freq / 1000LL) << 16));
388 	else
389 		ntv->freq = L_GINT((time_freq / 1000LL) << 16);
390 	ntv->maxerror = time_maxerror;
391 	ntv->esterror = time_esterror;
392 	ntv->status = time_status;
393 	ntv->constant = time_constant;
394 	if (time_status & STA_NANO)
395 		ntv->precision = time_precision;
396 	else
397 		ntv->precision = time_precision / 1000;
398 	ntv->tolerance = MAXFREQ * SCALE_PPM;
399 #ifdef PPS_SYNC
400 	ntv->shift = pps_shift;
401 	ntv->ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
402 	if (time_status & STA_NANO)
403 		ntv->jitter = pps_jitter;
404 	else
405 		ntv->jitter = pps_jitter / 1000;
406 	ntv->stabil = pps_stabil;
407 	ntv->calcnt = pps_calcnt;
408 	ntv->errcnt = pps_errcnt;
409 	ntv->jitcnt = pps_jitcnt;
410 	ntv->stbcnt = pps_stbcnt;
411 #endif /* PPS_SYNC */
412 	mutex_spin_exit(&timecounter_lock);
413 }
414 #endif /* NTP */
415 
416 /*
417  * second_overflow() - called after ntp_tick_adjust()
418  *
419  * This routine is ordinarily called immediately following the above
420  * routine ntp_tick_adjust(). While these two routines are normally
421  * combined, they are separated here only for the purposes of
422  * simulation.
423  */
424 void
425 ntp_update_second(int64_t *adjustment, time_t *newsec)
426 {
427 	int tickrate;
428 	l_fp ftemp;		/* 32/64-bit temporary */
429 
430 	KASSERT(mutex_owned(&timecounter_lock));
431 
432 #ifdef NTP
433 
434 	/*
435 	 * On rollover of the second both the nanosecond and microsecond
436 	 * clocks are updated and the state machine cranked as
437 	 * necessary. The phase adjustment to be used for the next
438 	 * second is calculated and the maximum error is increased by
439 	 * the tolerance.
440 	 */
441 	time_maxerror += MAXFREQ / 1000;
442 
443 	/*
444 	 * Leap second processing. If in leap-insert state at
445 	 * the end of the day, the system clock is set back one
446 	 * second; if in leap-delete state, the system clock is
447 	 * set ahead one second. The nano_time() routine or
448 	 * external clock driver will insure that reported time
449 	 * is always monotonic.
450 	 */
451 	switch (time_state) {
452 
453 		/*
454 		 * No warning.
455 		 */
456 		case TIME_OK:
457 		if (time_status & STA_INS)
458 			time_state = TIME_INS;
459 		else if (time_status & STA_DEL)
460 			time_state = TIME_DEL;
461 		break;
462 
463 		/*
464 		 * Insert second 23:59:60 following second
465 		 * 23:59:59.
466 		 */
467 		case TIME_INS:
468 		if (!(time_status & STA_INS))
469 			time_state = TIME_OK;
470 		else if ((*newsec) % 86400 == 0) {
471 			(*newsec)--;
472 			time_state = TIME_OOP;
473 			time_tai++;
474 		}
475 		break;
476 
477 		/*
478 		 * Delete second 23:59:59.
479 		 */
480 		case TIME_DEL:
481 		if (!(time_status & STA_DEL))
482 			time_state = TIME_OK;
483 		else if (((*newsec) + 1) % 86400 == 0) {
484 			(*newsec)++;
485 			time_tai--;
486 			time_state = TIME_WAIT;
487 		}
488 		break;
489 
490 		/*
491 		 * Insert second in progress.
492 		 */
493 		case TIME_OOP:
494 			time_state = TIME_WAIT;
495 		break;
496 
497 		/*
498 		 * Wait for status bits to clear.
499 		 */
500 		case TIME_WAIT:
501 		if (!(time_status & (STA_INS | STA_DEL)))
502 			time_state = TIME_OK;
503 	}
504 
505 	/*
506 	 * Compute the total time adjustment for the next second
507 	 * in ns. The offset is reduced by a factor depending on
508 	 * whether the PPS signal is operating. Note that the
509 	 * value is in effect scaled by the clock frequency,
510 	 * since the adjustment is added at each tick interrupt.
511 	 */
512 	ftemp = time_offset;
513 #ifdef PPS_SYNC
514 	/* XXX even if PPS signal dies we should finish adjustment ? */
515 	if (time_status & STA_PPSTIME && time_status &
516 	    STA_PPSSIGNAL)
517 		L_RSHIFT(ftemp, pps_shift);
518 	else
519 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
520 #else
521 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
522 #endif /* PPS_SYNC */
523 	time_adj = ftemp;
524 	L_SUB(time_offset, ftemp);
525 	L_ADD(time_adj, time_freq);
526 
527 #ifdef PPS_SYNC
528 	if (pps_valid > 0)
529 		pps_valid--;
530 	else
531 		time_status &= ~STA_PPSSIGNAL;
532 #endif /* PPS_SYNC */
533 #else  /* !NTP */
534 	L_CLR(time_adj);
535 #endif /* !NTP */
536 
537 	/*
538 	 * Apply any correction from adjtime(2).  If more than one second
539 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
540 	 * until the last second is slewed the final < 500 usecs.
541 	 */
542 	if (time_adjtime != 0) {
543 		if (time_adjtime > 1000000)
544 			tickrate = 5000;
545 		else if (time_adjtime < -1000000)
546 			tickrate = -5000;
547 		else if (time_adjtime > 500)
548 			tickrate = 500;
549 		else if (time_adjtime < -500)
550 			tickrate = -500;
551 		else
552 			tickrate = time_adjtime;
553 		time_adjtime -= tickrate;
554 		L_LINT(ftemp, tickrate * 1000);
555 		L_ADD(time_adj, ftemp);
556 	}
557 	*adjustment = time_adj;
558 }
559 
560 /*
561  * ntp_init() - initialize variables and structures
562  *
563  * This routine must be called after the kernel variables hz and tick
564  * are set or changed and before the next tick interrupt. In this
565  * particular implementation, these values are assumed set elsewhere in
566  * the kernel. The design allows the clock frequency and tick interval
567  * to be changed while the system is running. So, this routine should
568  * probably be integrated with the code that does that.
569  */
570 void
571 ntp_init(void)
572 {
573 
574 	/*
575 	 * The following variables are initialized only at startup. Only
576 	 * those structures not cleared by the compiler need to be
577 	 * initialized, and these only in the simulator. In the actual
578 	 * kernel, any nonzero values here will quickly evaporate.
579 	 */
580 	L_CLR(time_adj);
581 #ifdef NTP
582 	L_CLR(time_offset);
583 	L_CLR(time_freq);
584 #ifdef PPS_SYNC
585 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
586 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
587 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
588 	pps_fcount = 0;
589 	L_CLR(pps_freq);
590 #endif /* PPS_SYNC */
591 #endif
592 }
593 
594 #ifdef NTP
595 /*
596  * hardupdate() - local clock update
597  *
598  * This routine is called by ntp_adjtime() to update the local clock
599  * phase and frequency. The implementation is of an adaptive-parameter,
600  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
601  * time and frequency offset estimates for each call. If the kernel PPS
602  * discipline code is configured (PPS_SYNC), the PPS signal itself
603  * determines the new time offset, instead of the calling argument.
604  * Presumably, calls to ntp_adjtime() occur only when the caller
605  * believes the local clock is valid within some bound (+-128 ms with
606  * NTP). If the caller's time is far different than the PPS time, an
607  * argument will ensue, and it's not clear who will lose.
608  *
609  * For uncompensated quartz crystal oscillators and nominal update
610  * intervals less than 256 s, operation should be in phase-lock mode,
611  * where the loop is disciplined to phase. For update intervals greater
612  * than 1024 s, operation should be in frequency-lock mode, where the
613  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
614  * is selected by the STA_MODE status bit.
615  *
616  * Note: splclock() is in effect.
617  */
618 void
619 hardupdate(long offset)
620 {
621 	long mtemp;
622 	l_fp ftemp;
623 
624 	KASSERT(mutex_owned(&timecounter_lock));
625 
626 	/*
627 	 * Select how the phase is to be controlled and from which
628 	 * source. If the PPS signal is present and enabled to
629 	 * discipline the time, the PPS offset is used; otherwise, the
630 	 * argument offset is used.
631 	 */
632 	if (!(time_status & STA_PLL))
633 		return;
634 	if (!(time_status & STA_PPSTIME && time_status &
635 	    STA_PPSSIGNAL)) {
636 		if (offset > MAXPHASE)
637 			time_monitor = MAXPHASE;
638 		else if (offset < -MAXPHASE)
639 			time_monitor = -MAXPHASE;
640 		else
641 			time_monitor = offset;
642 		L_LINT(time_offset, time_monitor);
643 	}
644 
645 	/*
646 	 * Select how the frequency is to be controlled and in which
647 	 * mode (PLL or FLL). If the PPS signal is present and enabled
648 	 * to discipline the frequency, the PPS frequency is used;
649 	 * otherwise, the argument offset is used to compute it.
650 	 */
651 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
652 		time_reftime = time_second;
653 		return;
654 	}
655 	if (time_status & STA_FREQHOLD || time_reftime == 0)
656 		time_reftime = time_second;
657 	mtemp = time_second - time_reftime;
658 	L_LINT(ftemp, time_monitor);
659 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
660 	L_MPY(ftemp, mtemp);
661 	L_ADD(time_freq, ftemp);
662 	time_status &= ~STA_MODE;
663 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
664 	    MAXSEC)) {
665 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
666 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
667 		L_ADD(time_freq, ftemp);
668 		time_status |= STA_MODE;
669 	}
670 	time_reftime = time_second;
671 	if (L_GINT(time_freq) > MAXFREQ)
672 		L_LINT(time_freq, MAXFREQ);
673 	else if (L_GINT(time_freq) < -MAXFREQ)
674 		L_LINT(time_freq, -MAXFREQ);
675 }
676 
677 #ifdef PPS_SYNC
678 /*
679  * hardpps() - discipline CPU clock oscillator to external PPS signal
680  *
681  * This routine is called at each PPS interrupt in order to discipline
682  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
683  * and leaves it in a handy spot for the hardclock() routine. It
684  * integrates successive PPS phase differences and calculates the
685  * frequency offset. This is used in hardclock() to discipline the CPU
686  * clock oscillator so that intrinsic frequency error is cancelled out.
687  * The code requires the caller to capture the time and hardware counter
688  * value at the on-time PPS signal transition.
689  *
690  * Note that, on some Unix systems, this routine runs at an interrupt
691  * priority level higher than the timer interrupt routine hardclock().
692  * Therefore, the variables used are distinct from the hardclock()
693  * variables, except for certain exceptions: The PPS frequency pps_freq
694  * and phase pps_offset variables are determined by this routine and
695  * updated atomically. The time_tolerance variable can be considered a
696  * constant, since it is infrequently changed, and then only when the
697  * PPS signal is disabled. The watchdog counter pps_valid is updated
698  * once per second by hardclock() and is atomically cleared in this
699  * routine.
700  */
701 void
702 hardpps(struct timespec *tsp,		/* time at PPS */
703 	long nsec			/* hardware counter at PPS */)
704 {
705 	long u_sec, u_nsec, v_nsec; /* temps */
706 	l_fp ftemp;
707 
708 	KASSERT(mutex_owned(&timecounter_lock));
709 
710 	/*
711 	 * The signal is first processed by a range gate and frequency
712 	 * discriminator. The range gate rejects noise spikes outside
713 	 * the range +-500 us. The frequency discriminator rejects input
714 	 * signals with apparent frequency outside the range 1 +-500
715 	 * PPM. If two hits occur in the same second, we ignore the
716 	 * later hit; if not and a hit occurs outside the range gate,
717 	 * keep the later hit for later comparison, but do not process
718 	 * it.
719 	 */
720 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
721 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
722 	pps_valid = PPS_VALID;
723 	u_sec = tsp->tv_sec;
724 	u_nsec = tsp->tv_nsec;
725 	if (u_nsec >= (NANOSECOND >> 1)) {
726 		u_nsec -= NANOSECOND;
727 		u_sec++;
728 	}
729 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
730 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
731 	    MAXFREQ)
732 		return;
733 	pps_tf[2] = pps_tf[1];
734 	pps_tf[1] = pps_tf[0];
735 	pps_tf[0].tv_sec = u_sec;
736 	pps_tf[0].tv_nsec = u_nsec;
737 
738 	/*
739 	 * Compute the difference between the current and previous
740 	 * counter values. If the difference exceeds 0.5 s, assume it
741 	 * has wrapped around, so correct 1.0 s. If the result exceeds
742 	 * the tick interval, the sample point has crossed a tick
743 	 * boundary during the last second, so correct the tick. Very
744 	 * intricate.
745 	 */
746 	u_nsec = nsec;
747 	if (u_nsec > (NANOSECOND >> 1))
748 		u_nsec -= NANOSECOND;
749 	else if (u_nsec < -(NANOSECOND >> 1))
750 		u_nsec += NANOSECOND;
751 	pps_fcount += u_nsec;
752 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
753 		return;
754 	time_status &= ~STA_PPSJITTER;
755 
756 	/*
757 	 * A three-stage median filter is used to help denoise the PPS
758 	 * time. The median sample becomes the time offset estimate; the
759 	 * difference between the other two samples becomes the time
760 	 * dispersion (jitter) estimate.
761 	 */
762 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
763 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
764 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
765 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
766 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
767 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
768 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
769 		} else {
770 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
771 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
772 		}
773 	} else {
774 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
775 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
776 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
777 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
778 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
779 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
780 		} else {
781 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
782 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
783 		}
784 	}
785 
786 	/*
787 	 * Nominal jitter is due to PPS signal noise and interrupt
788 	 * latency. If it exceeds the popcorn threshold, the sample is
789 	 * discarded. otherwise, if so enabled, the time offset is
790 	 * updated. We can tolerate a modest loss of data here without
791 	 * much degrading time accuracy.
792 	 */
793 	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
794 		time_status |= STA_PPSJITTER;
795 		pps_jitcnt++;
796 	} else if (time_status & STA_PPSTIME) {
797 		time_monitor = -v_nsec;
798 		L_LINT(time_offset, time_monitor);
799 	}
800 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
801 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
802 	if (u_sec < (1 << pps_shift))
803 		return;
804 
805 	/*
806 	 * At the end of the calibration interval the difference between
807 	 * the first and last counter values becomes the scaled
808 	 * frequency. It will later be divided by the length of the
809 	 * interval to determine the frequency update. If the frequency
810 	 * exceeds a sanity threshold, or if the actual calibration
811 	 * interval is not equal to the expected length, the data are
812 	 * discarded. We can tolerate a modest loss of data here without
813 	 * much degrading frequency accuracy.
814 	 */
815 	pps_calcnt++;
816 	v_nsec = -pps_fcount;
817 	pps_lastsec = pps_tf[0].tv_sec;
818 	pps_fcount = 0;
819 	u_nsec = MAXFREQ << pps_shift;
820 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
821 	    pps_shift)) {
822 		time_status |= STA_PPSERROR;
823 		pps_errcnt++;
824 		return;
825 	}
826 
827 	/*
828 	 * Here the raw frequency offset and wander (stability) is
829 	 * calculated. If the wander is less than the wander threshold
830 	 * for four consecutive averaging intervals, the interval is
831 	 * doubled; if it is greater than the threshold for four
832 	 * consecutive intervals, the interval is halved. The scaled
833 	 * frequency offset is converted to frequency offset. The
834 	 * stability metric is calculated as the average of recent
835 	 * frequency changes, but is used only for performance
836 	 * monitoring.
837 	 */
838 	L_LINT(ftemp, v_nsec);
839 	L_RSHIFT(ftemp, pps_shift);
840 	L_SUB(ftemp, pps_freq);
841 	u_nsec = L_GINT(ftemp);
842 	if (u_nsec > PPS_MAXWANDER) {
843 		L_LINT(ftemp, PPS_MAXWANDER);
844 		pps_intcnt--;
845 		time_status |= STA_PPSWANDER;
846 		pps_stbcnt++;
847 	} else if (u_nsec < -PPS_MAXWANDER) {
848 		L_LINT(ftemp, -PPS_MAXWANDER);
849 		pps_intcnt--;
850 		time_status |= STA_PPSWANDER;
851 		pps_stbcnt++;
852 	} else {
853 		pps_intcnt++;
854 	}
855 	if (pps_intcnt >= 4) {
856 		pps_intcnt = 4;
857 		if (pps_shift < pps_shiftmax) {
858 			pps_shift++;
859 			pps_intcnt = 0;
860 		}
861 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
862 		pps_intcnt = -4;
863 		if (pps_shift > PPS_FAVG) {
864 			pps_shift--;
865 			pps_intcnt = 0;
866 		}
867 	}
868 	if (u_nsec < 0)
869 		u_nsec = -u_nsec;
870 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
871 
872 	/*
873 	 * The PPS frequency is recalculated and clamped to the maximum
874 	 * MAXFREQ. If enabled, the system clock frequency is updated as
875 	 * well.
876 	 */
877 	L_ADD(pps_freq, ftemp);
878 	u_nsec = L_GINT(pps_freq);
879 	if (u_nsec > MAXFREQ)
880 		L_LINT(pps_freq, MAXFREQ);
881 	else if (u_nsec < -MAXFREQ)
882 		L_LINT(pps_freq, -MAXFREQ);
883 	if (time_status & STA_PPSFREQ)
884 		time_freq = pps_freq;
885 }
886 #endif /* PPS_SYNC */
887 #endif /* NTP */
888 
889 #ifdef NTP
890 int
891 ntp_timestatus(void)
892 {
893 	int rv;
894 
895 	/*
896 	 * Status word error decode. If any of these conditions
897 	 * occur, an error is returned, instead of the status
898 	 * word. Most applications will care only about the fact
899 	 * the system clock may not be trusted, not about the
900 	 * details.
901 	 *
902 	 * Hardware or software error
903 	 */
904 	mutex_spin_enter(&timecounter_lock);
905 	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
906 
907 	/*
908 	 * PPS signal lost when either time or frequency
909 	 * synchronization requested
910 	 */
911 	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
912 	     !(time_status & STA_PPSSIGNAL)) ||
913 
914 	/*
915 	 * PPS jitter exceeded when time synchronization
916 	 * requested
917 	 */
918 	    (time_status & STA_PPSTIME &&
919 	     time_status & STA_PPSJITTER) ||
920 
921 	/*
922 	 * PPS wander exceeded or calibration error when
923 	 * frequency synchronization requested
924 	 */
925 	    (time_status & STA_PPSFREQ &&
926 	     time_status & (STA_PPSWANDER | STA_PPSERROR)))
927 		rv = TIME_ERROR;
928 	else
929 		rv = time_state;
930 	mutex_spin_exit(&timecounter_lock);
931 
932 	return rv;
933 }
934 
935 /*ARGSUSED*/
936 /*
937  * ntp_gettime() - NTP user application interface
938  */
939 int
940 sys___ntp_gettime50(struct lwp *l, const struct sys___ntp_gettime50_args *uap, register_t *retval)
941 {
942 	/* {
943 		syscallarg(struct ntptimeval *) ntvp;
944 	} */
945 	struct ntptimeval ntv;
946 	int error = 0;
947 
948 	if (SCARG(uap, ntvp)) {
949 		ntp_gettime(&ntv);
950 
951 		error = copyout((void *)&ntv, (void *)SCARG(uap, ntvp),
952 				sizeof(ntv));
953 	}
954 	if (!error) {
955 		*retval = ntp_timestatus();
956 	}
957 	return(error);
958 }
959 
960 /*
961  * return information about kernel precision timekeeping
962  */
963 static int
964 sysctl_kern_ntptime(SYSCTLFN_ARGS)
965 {
966 	struct sysctlnode node;
967 	struct ntptimeval ntv;
968 
969 	ntp_gettime(&ntv);
970 
971 	node = *rnode;
972 	node.sysctl_data = &ntv;
973 	node.sysctl_size = sizeof(ntv);
974 	return (sysctl_lookup(SYSCTLFN_CALL(&node)));
975 }
976 
977 SYSCTL_SETUP(sysctl_kern_ntptime_setup, "sysctl kern.ntptime node setup")
978 {
979 
980 	sysctl_createv(clog, 0, NULL, NULL,
981 		       CTLFLAG_PERMANENT,
982 		       CTLTYPE_STRUCT, "ntptime",
983 		       SYSCTL_DESCR("Kernel clock values for NTP"),
984 		       sysctl_kern_ntptime, 0, NULL,
985 		       sizeof(struct ntptimeval),
986 		       CTL_KERN, KERN_NTPTIME, CTL_EOL);
987 }
988 #endif /* !NTP */
989