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