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