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