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