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