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