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