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