Deleted Added
full compact
kern_ntptime.c (55219) kern_ntptime.c (55413)
1/***********************************************************************
2 * *
3 * Copyright (c) David L. Mills 1993-1999 *
4 * *
5 * Permission to use, copy, modify, and distribute this software and *
6 * its documentation for any purpose and without fee is hereby *
7 * granted, provided that the above copyright notice appears in all *
8 * copies and that both the copyright notice and this permission *
9 * notice appear in supporting documentation, and that the name *
10 * University of Delaware not be used in advertising or publicity *
11 * pertaining to distribution of the software without specific, *
12 * written prior permission. The University of Delaware makes no *
13 * representations about the suitability this software for any *
14 * purpose. It is provided "as is" without express or implied *
15 * warranty. *
16 * *
17 **********************************************************************/
18
19/*
20 * Adapted from the original sources for FreeBSD and timecounters by:
21 * Poul-Henning Kamp <phk@FreeBSD.org>.
22 *
23 * The 32bit version of the "LP" macros seems a bit past its "sell by"
24 * date so I have retained only the 64bit version and included it directly
25 * in this file.
26 *
27 * Only minor changes done to interface with the timecounters over in
28 * sys/kern/kern_clock.c. Some of the comments below may be (even more)
29 * confusing and/or plain wrong in that context.
30 *
1/***********************************************************************
2 * *
3 * Copyright (c) David L. Mills 1993-1999 *
4 * *
5 * Permission to use, copy, modify, and distribute this software and *
6 * its documentation for any purpose and without fee is hereby *
7 * granted, provided that the above copyright notice appears in all *
8 * copies and that both the copyright notice and this permission *
9 * notice appear in supporting documentation, and that the name *
10 * University of Delaware not be used in advertising or publicity *
11 * pertaining to distribution of the software without specific, *
12 * written prior permission. The University of Delaware makes no *
13 * representations about the suitability this software for any *
14 * purpose. It is provided "as is" without express or implied *
15 * warranty. *
16 * *
17 **********************************************************************/
18
19/*
20 * Adapted from the original sources for FreeBSD and timecounters by:
21 * Poul-Henning Kamp <phk@FreeBSD.org>.
22 *
23 * The 32bit version of the "LP" macros seems a bit past its "sell by"
24 * date so I have retained only the 64bit version and included it directly
25 * in this file.
26 *
27 * Only minor changes done to interface with the timecounters over in
28 * sys/kern/kern_clock.c. Some of the comments below may be (even more)
29 * confusing and/or plain wrong in that context.
30 *
31 * $FreeBSD: head/sys/kern/kern_ntptime.c 55219 1999-12-29 14:39:24Z phk $
31 * $FreeBSD: head/sys/kern/kern_ntptime.c 55413 2000-01-04 12:04:39Z phk $
32 */
33
34#include "opt_ntp.h"
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/sysproto.h>
39#include <sys/kernel.h>
40#include <sys/proc.h>
41#include <sys/time.h>
42#include <sys/timex.h>
43#include <sys/timepps.h>
44#include <sys/sysctl.h>
45
46/*
47 * Single-precision macros for 64-bit machines
48 */
49typedef long long l_fp;
50#define L_ADD(v, u) ((v) += (u))
51#define L_SUB(v, u) ((v) -= (u))
52#define L_ADDHI(v, a) ((v) += (long long)(a) << 32)
53#define L_NEG(v) ((v) = -(v))
54#define L_RSHIFT(v, n) \
55 do { \
56 if ((v) < 0) \
57 (v) = -(-(v) >> (n)); \
58 else \
59 (v) = (v) >> (n); \
60 } while (0)
61#define L_MPY(v, a) ((v) *= (a))
62#define L_CLR(v) ((v) = 0)
63#define L_ISNEG(v) ((v) < 0)
64#define L_LINT(v, a) ((v) = (long long)(a) << 32)
65#define L_GINT(v) ((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
66
67/*
68 * Generic NTP kernel interface
69 *
70 * These routines constitute the Network Time Protocol (NTP) interfaces
71 * for user and daemon application programs. The ntp_gettime() routine
72 * provides the time, maximum error (synch distance) and estimated error
73 * (dispersion) to client user application programs. The ntp_adjtime()
74 * routine is used by the NTP daemon to adjust the system clock to an
75 * externally derived time. The time offset and related variables set by
76 * this routine are used by other routines in this module to adjust the
77 * phase and frequency of the clock discipline loop which controls the
78 * system clock.
79 *
80 * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
81 * defined), the time at each tick interrupt is derived directly from
82 * the kernel time variable. When the kernel time is reckoned in
83 * microseconds, (NTP_NANO undefined), the time is derived from the
84 * kernel time variable together with a variable representing the
85 * leftover nanoseconds at the last tick interrupt. In either case, the
86 * current nanosecond time is reckoned from these values plus an
87 * interpolated value derived by the clock routines in another
88 * architecture-specific module. The interpolation can use either a
89 * dedicated counter or a processor cycle counter (PCC) implemented in
90 * some architectures.
91 *
92 * Note that all routines must run at priority splclock or higher.
93 */
94
95/*
96 * Phase/frequency-lock loop (PLL/FLL) definitions
97 *
98 * The nanosecond clock discipline uses two variable types, time
99 * variables and frequency variables. Both types are represented as 64-
100 * bit fixed-point quantities with the decimal point between two 32-bit
101 * halves. On a 32-bit machine, each half is represented as a single
102 * word and mathematical operations are done using multiple-precision
103 * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
104 * used.
105 *
106 * A time variable is a signed 64-bit fixed-point number in ns and
107 * fraction. It represents the remaining time offset to be amortized
108 * over succeeding tick interrupts. The maximum time offset is about
109 * 0.5 s and the resolution is about 2.3e-10 ns.
110 *
111 * 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
112 * 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
113 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114 * |s s s| ns |
115 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116 * | fraction |
117 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118 *
119 * A frequency variable is a signed 64-bit fixed-point number in ns/s
120 * and fraction. It represents the ns and fraction to be added to the
121 * kernel time variable at each second. The maximum frequency offset is
122 * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
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 s s s s s s s s s s| ns/s |
128 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129 * | fraction |
130 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
131 */
132/*
133 * The following variables establish the state of the PLL/FLL and the
134 * residual time and frequency offset of the local clock.
135 */
136#define SHIFT_PLL 4 /* PLL loop gain (shift) */
137#define SHIFT_FLL 2 /* FLL loop gain (shift) */
138
139static int time_state = TIME_OK; /* clock state */
140static int time_status = STA_UNSYNC; /* clock status bits */
141static long time_constant; /* poll interval (shift) (s) */
142static long time_precision = 1; /* clock precision (ns) */
143static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
144static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
145static long time_reftime; /* time at last adjustment (s) */
146static long time_tick; /* nanoseconds per tick (ns) */
147static l_fp time_offset; /* time offset (ns) */
148static l_fp time_freq; /* frequency offset (ns/s) */
149
150#ifdef PPS_SYNC
151/*
152 * The following variables are used when a pulse-per-second (PPS) signal
153 * is available and connected via a modem control lead. They establish
154 * the engineering parameters of the clock discipline loop when
155 * controlled by the PPS signal.
156 */
157#define PPS_FAVG 2 /* min freq avg interval (s) (shift) */
158#define PPS_FAVGDEF 7 /* default freq avg int (s) (shift) */
159#define PPS_FAVGMAX 15 /* max freq avg interval (s) (shift) */
160#define PPS_PAVG 4 /* phase avg interval (s) (shift) */
161#define PPS_VALID 120 /* PPS signal watchdog max (s) */
162#define PPS_MAXWANDER 100000 /* max PPS wander (ns/s) */
163#define PPS_POPCORN 2 /* popcorn spike threshold (shift) */
164
165static struct timespec pps_tf[3]; /* phase median filter */
32 */
33
34#include "opt_ntp.h"
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/sysproto.h>
39#include <sys/kernel.h>
40#include <sys/proc.h>
41#include <sys/time.h>
42#include <sys/timex.h>
43#include <sys/timepps.h>
44#include <sys/sysctl.h>
45
46/*
47 * Single-precision macros for 64-bit machines
48 */
49typedef long long l_fp;
50#define L_ADD(v, u) ((v) += (u))
51#define L_SUB(v, u) ((v) -= (u))
52#define L_ADDHI(v, a) ((v) += (long long)(a) << 32)
53#define L_NEG(v) ((v) = -(v))
54#define L_RSHIFT(v, n) \
55 do { \
56 if ((v) < 0) \
57 (v) = -(-(v) >> (n)); \
58 else \
59 (v) = (v) >> (n); \
60 } while (0)
61#define L_MPY(v, a) ((v) *= (a))
62#define L_CLR(v) ((v) = 0)
63#define L_ISNEG(v) ((v) < 0)
64#define L_LINT(v, a) ((v) = (long long)(a) << 32)
65#define L_GINT(v) ((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
66
67/*
68 * Generic NTP kernel interface
69 *
70 * These routines constitute the Network Time Protocol (NTP) interfaces
71 * for user and daemon application programs. The ntp_gettime() routine
72 * provides the time, maximum error (synch distance) and estimated error
73 * (dispersion) to client user application programs. The ntp_adjtime()
74 * routine is used by the NTP daemon to adjust the system clock to an
75 * externally derived time. The time offset and related variables set by
76 * this routine are used by other routines in this module to adjust the
77 * phase and frequency of the clock discipline loop which controls the
78 * system clock.
79 *
80 * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
81 * defined), the time at each tick interrupt is derived directly from
82 * the kernel time variable. When the kernel time is reckoned in
83 * microseconds, (NTP_NANO undefined), the time is derived from the
84 * kernel time variable together with a variable representing the
85 * leftover nanoseconds at the last tick interrupt. In either case, the
86 * current nanosecond time is reckoned from these values plus an
87 * interpolated value derived by the clock routines in another
88 * architecture-specific module. The interpolation can use either a
89 * dedicated counter or a processor cycle counter (PCC) implemented in
90 * some architectures.
91 *
92 * Note that all routines must run at priority splclock or higher.
93 */
94
95/*
96 * Phase/frequency-lock loop (PLL/FLL) definitions
97 *
98 * The nanosecond clock discipline uses two variable types, time
99 * variables and frequency variables. Both types are represented as 64-
100 * bit fixed-point quantities with the decimal point between two 32-bit
101 * halves. On a 32-bit machine, each half is represented as a single
102 * word and mathematical operations are done using multiple-precision
103 * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
104 * used.
105 *
106 * A time variable is a signed 64-bit fixed-point number in ns and
107 * fraction. It represents the remaining time offset to be amortized
108 * over succeeding tick interrupts. The maximum time offset is about
109 * 0.5 s and the resolution is about 2.3e-10 ns.
110 *
111 * 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
112 * 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
113 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114 * |s s s| ns |
115 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116 * | fraction |
117 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118 *
119 * A frequency variable is a signed 64-bit fixed-point number in ns/s
120 * and fraction. It represents the ns and fraction to be added to the
121 * kernel time variable at each second. The maximum frequency offset is
122 * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
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 s s s s s s s s s s| ns/s |
128 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129 * | fraction |
130 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
131 */
132/*
133 * The following variables establish the state of the PLL/FLL and the
134 * residual time and frequency offset of the local clock.
135 */
136#define SHIFT_PLL 4 /* PLL loop gain (shift) */
137#define SHIFT_FLL 2 /* FLL loop gain (shift) */
138
139static int time_state = TIME_OK; /* clock state */
140static int time_status = STA_UNSYNC; /* clock status bits */
141static long time_constant; /* poll interval (shift) (s) */
142static long time_precision = 1; /* clock precision (ns) */
143static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
144static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
145static long time_reftime; /* time at last adjustment (s) */
146static long time_tick; /* nanoseconds per tick (ns) */
147static l_fp time_offset; /* time offset (ns) */
148static l_fp time_freq; /* frequency offset (ns/s) */
149
150#ifdef PPS_SYNC
151/*
152 * The following variables are used when a pulse-per-second (PPS) signal
153 * is available and connected via a modem control lead. They establish
154 * the engineering parameters of the clock discipline loop when
155 * controlled by the PPS signal.
156 */
157#define PPS_FAVG 2 /* min freq avg interval (s) (shift) */
158#define PPS_FAVGDEF 7 /* default freq avg int (s) (shift) */
159#define PPS_FAVGMAX 15 /* max freq avg interval (s) (shift) */
160#define PPS_PAVG 4 /* phase avg interval (s) (shift) */
161#define PPS_VALID 120 /* PPS signal watchdog max (s) */
162#define PPS_MAXWANDER 100000 /* max PPS wander (ns/s) */
163#define PPS_POPCORN 2 /* popcorn spike threshold (shift) */
164
165static struct timespec pps_tf[3]; /* phase median filter */
166static l_fp pps_offset; /* time offset (ns) */
166static l_fp pps_freq; /* scaled frequency offset (ns/s) */
167static long pps_fcount; /* frequency accumulator */
168static long pps_jitter; /* nominal jitter (ns) */
169static long pps_stabil; /* nominal stability (scaled ns/s) */
170static long pps_lastsec; /* time at last calibration (s) */
171static int pps_valid; /* signal watchdog counter */
172static int pps_shift = PPS_FAVG; /* interval duration (s) (shift) */
173static int pps_shiftmax = PPS_FAVGDEF; /* max interval duration (s) (shift) */
174static int pps_intcnt; /* wander counter */
175
176/*
177 * PPS signal quality monitors
178 */
179static long pps_calcnt; /* calibration intervals */
180static long pps_jitcnt; /* jitter limit exceeded */
181static long pps_stbcnt; /* stability limit exceeded */
182static long pps_errcnt; /* calibration errors */
183#endif /* PPS_SYNC */
184/*
185 * End of phase/frequency-lock loop (PLL/FLL) definitions
186 */
187
188static void ntp_init(void);
189static void hardupdate(long offset);
190
191/*
192 * ntp_gettime() - NTP user application interface
193 *
194 * See the timex.h header file for synopsis and API description.
195 */
196static int
197ntp_sysctl SYSCTL_HANDLER_ARGS
198{
199 struct ntptimeval ntv; /* temporary structure */
200 struct timespec atv; /* nanosecond time */
201
202 nanotime(&atv);
203 ntv.time.tv_sec = atv.tv_sec;
204 ntv.time.tv_nsec = atv.tv_nsec;
205 ntv.maxerror = time_maxerror;
206 ntv.esterror = time_esterror;
207 ntv.time_state = time_state;
208
209 /*
210 * Status word error decode. If any of these conditions occur,
211 * an error is returned, instead of the status word. Most
212 * applications will care only about the fact the system clock
213 * may not be trusted, not about the details.
214 *
215 * Hardware or software error
216 */
217 if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
218
219 /*
220 * PPS signal lost when either time or frequency synchronization
221 * requested
222 */
223 (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
224 !(time_status & STA_PPSSIGNAL)) ||
225
226 /*
227 * PPS jitter exceeded when time synchronization requested
228 */
229 (time_status & STA_PPSTIME &&
230 time_status & STA_PPSJITTER) ||
231
232 /*
233 * PPS wander exceeded or calibration error when frequency
234 * synchronization requested
235 */
236 (time_status & STA_PPSFREQ &&
237 time_status & (STA_PPSWANDER | STA_PPSERROR)))
238 ntv.time_state = TIME_ERROR;
239 return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
240}
241
242SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
243SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
244 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
245
246#ifdef PPS_SYNC
247SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
167static l_fp pps_freq; /* scaled frequency offset (ns/s) */
168static long pps_fcount; /* frequency accumulator */
169static long pps_jitter; /* nominal jitter (ns) */
170static long pps_stabil; /* nominal stability (scaled ns/s) */
171static long pps_lastsec; /* time at last calibration (s) */
172static int pps_valid; /* signal watchdog counter */
173static int pps_shift = PPS_FAVG; /* interval duration (s) (shift) */
174static int pps_shiftmax = PPS_FAVGDEF; /* max interval duration (s) (shift) */
175static int pps_intcnt; /* wander counter */
176
177/*
178 * PPS signal quality monitors
179 */
180static long pps_calcnt; /* calibration intervals */
181static long pps_jitcnt; /* jitter limit exceeded */
182static long pps_stbcnt; /* stability limit exceeded */
183static long pps_errcnt; /* calibration errors */
184#endif /* PPS_SYNC */
185/*
186 * End of phase/frequency-lock loop (PLL/FLL) definitions
187 */
188
189static void ntp_init(void);
190static void hardupdate(long offset);
191
192/*
193 * ntp_gettime() - NTP user application interface
194 *
195 * See the timex.h header file for synopsis and API description.
196 */
197static int
198ntp_sysctl SYSCTL_HANDLER_ARGS
199{
200 struct ntptimeval ntv; /* temporary structure */
201 struct timespec atv; /* nanosecond time */
202
203 nanotime(&atv);
204 ntv.time.tv_sec = atv.tv_sec;
205 ntv.time.tv_nsec = atv.tv_nsec;
206 ntv.maxerror = time_maxerror;
207 ntv.esterror = time_esterror;
208 ntv.time_state = time_state;
209
210 /*
211 * Status word error decode. If any of these conditions occur,
212 * an error is returned, instead of the status word. Most
213 * applications will care only about the fact the system clock
214 * may not be trusted, not about the details.
215 *
216 * Hardware or software error
217 */
218 if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
219
220 /*
221 * PPS signal lost when either time or frequency synchronization
222 * requested
223 */
224 (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
225 !(time_status & STA_PPSSIGNAL)) ||
226
227 /*
228 * PPS jitter exceeded when time synchronization requested
229 */
230 (time_status & STA_PPSTIME &&
231 time_status & STA_PPSJITTER) ||
232
233 /*
234 * PPS wander exceeded or calibration error when frequency
235 * synchronization requested
236 */
237 (time_status & STA_PPSFREQ &&
238 time_status & (STA_PPSWANDER | STA_PPSERROR)))
239 ntv.time_state = TIME_ERROR;
240 return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
241}
242
243SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
244SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
245 0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
246
247#ifdef PPS_SYNC
248SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
249SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
248#endif
249/*
250 * ntp_adjtime() - NTP daemon application interface
251 *
252 * See the timex.h header file for synopsis and API description.
253 */
254#ifndef _SYS_SYSPROTO_H_
255struct ntp_adjtime_args {
256 struct timex *tp;
257};
258#endif
259
260int
261ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
262{
263 struct timex ntv; /* temporary structure */
264 long freq; /* frequency ns/s) */
265 int modes; /* mode bits from structure */
266 int s; /* caller priority */
267 int error;
268
269 error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
270 if (error)
271 return(error);
272
273 /*
274 * Update selected clock variables - only the superuser can
275 * change anything. Note that there is no error checking here on
276 * the assumption the superuser should know what it is doing.
277 */
278 modes = ntv.modes;
279 if (modes)
280 error = suser(p);
281 if (error)
282 return (error);
283 s = splclock();
284 if (modes & MOD_FREQUENCY) {
285 freq = (ntv.freq * 1000LL) >> 16;
286 if (freq > MAXFREQ)
287 L_LINT(time_freq, MAXFREQ);
288 else if (freq < -MAXFREQ)
289 L_LINT(time_freq, -MAXFREQ);
290 else
291 L_LINT(time_freq, freq);
292
293#ifdef PPS_SYNC
294 pps_freq = time_freq;
295#endif /* PPS_SYNC */
296 }
297 if (modes & MOD_MAXERROR)
298 time_maxerror = ntv.maxerror;
299 if (modes & MOD_ESTERROR)
300 time_esterror = ntv.esterror;
301 if (modes & MOD_STATUS) {
302 time_status &= STA_RONLY;
303 time_status |= ntv.status & ~STA_RONLY;
304 }
305 if (modes & MOD_TIMECONST) {
306 if (ntv.constant < 0)
307 time_constant = 0;
308 else if (ntv.constant > MAXTC)
309 time_constant = MAXTC;
310 else
311 time_constant = 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_OFFSET) {
332 if (time_status & STA_NANO)
333 hardupdate(ntv.offset);
334 else
335 hardupdate(ntv.offset * 1000);
336 }
337
338 /*
339 * Retrieve all clock variables
340 */
341 if (time_status & STA_NANO)
342 ntv.offset = L_GINT(time_offset);
343 else
344 ntv.offset = L_GINT(time_offset) / 1000;
345 ntv.freq = L_GINT((time_freq / 1000LL) << 16);
346 ntv.maxerror = time_maxerror;
347 ntv.esterror = time_esterror;
348 ntv.status = time_status;
349 ntv.constant = time_constant;
350 if (time_status & STA_NANO)
351 ntv.precision = time_precision;
352 else
353 ntv.precision = time_precision / 1000;
354 ntv.tolerance = MAXFREQ * SCALE_PPM;
355#ifdef PPS_SYNC
356 ntv.shift = pps_shift;
357 ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
358 if (time_status & STA_NANO)
359 ntv.jitter = pps_jitter;
360 else
361 ntv.jitter = pps_jitter / 1000;
362 ntv.stabil = pps_stabil;
363 ntv.calcnt = pps_calcnt;
364 ntv.errcnt = pps_errcnt;
365 ntv.jitcnt = pps_jitcnt;
366 ntv.stbcnt = pps_stbcnt;
367#endif /* PPS_SYNC */
368 splx(s);
369
370 error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
371 if (error)
372 return (error);
373
374 /*
375 * Status word error decode. See comments in
376 * ntp_gettime() routine.
377 */
378 if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
379 (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
380 !(time_status & STA_PPSSIGNAL)) ||
381 (time_status & STA_PPSTIME &&
382 time_status & STA_PPSJITTER) ||
383 (time_status & STA_PPSFREQ &&
384 time_status & (STA_PPSWANDER | STA_PPSERROR)))
385 p->p_retval[0] = TIME_ERROR;
386 else
387 p->p_retval[0] = time_state;
388 return (error);
389}
390
391/*
392 * second_overflow() - called after ntp_tick_adjust()
393 *
394 * This routine is ordinarily called immediately following the above
395 * routine ntp_tick_adjust(). While these two routines are normally
396 * combined, they are separated here only for the purposes of
397 * simulation.
398 */
399void
400ntp_update_second(struct timecounter *tcp)
401{
402 u_int32_t *newsec;
403 l_fp time_adj; /* 32/64-bit temporaries */
404
405 newsec = &tcp->tc_offset_sec;
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 }
446 break;
447
448 /*
449 * Delete second 23:59:59.
450 */
451 case TIME_DEL:
452 if (!(time_status & STA_DEL))
453 time_state = TIME_OK;
454 else if (((*newsec) + 1) % 86400 == 0) {
455 (*newsec)++;
456 time_state = TIME_WAIT;
457 }
458 break;
459
460 /*
461 * Insert second in progress.
462 */
463 case TIME_OOP:
464 time_state = TIME_WAIT;
465 break;
466
467 /*
468 * Wait for status bits to clear.
469 */
470 case TIME_WAIT:
471 if (!(time_status & (STA_INS | STA_DEL)))
472 time_state = TIME_OK;
473 }
474
475 /*
476 * Compute the total time adjustment for the next second
477 * in ns. The offset is reduced by a factor depending on
478 * whether the PPS signal is operating. Note that the
479 * value is in effect scaled by the clock frequency,
480 * since the adjustment is added at each tick interrupt.
481 */
250#endif
251/*
252 * ntp_adjtime() - NTP daemon application interface
253 *
254 * See the timex.h header file for synopsis and API description.
255 */
256#ifndef _SYS_SYSPROTO_H_
257struct ntp_adjtime_args {
258 struct timex *tp;
259};
260#endif
261
262int
263ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
264{
265 struct timex ntv; /* temporary structure */
266 long freq; /* frequency ns/s) */
267 int modes; /* mode bits from structure */
268 int s; /* caller priority */
269 int error;
270
271 error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
272 if (error)
273 return(error);
274
275 /*
276 * Update selected clock variables - only the superuser can
277 * change anything. Note that there is no error checking here on
278 * the assumption the superuser should know what it is doing.
279 */
280 modes = ntv.modes;
281 if (modes)
282 error = suser(p);
283 if (error)
284 return (error);
285 s = splclock();
286 if (modes & MOD_FREQUENCY) {
287 freq = (ntv.freq * 1000LL) >> 16;
288 if (freq > MAXFREQ)
289 L_LINT(time_freq, MAXFREQ);
290 else if (freq < -MAXFREQ)
291 L_LINT(time_freq, -MAXFREQ);
292 else
293 L_LINT(time_freq, freq);
294
295#ifdef PPS_SYNC
296 pps_freq = time_freq;
297#endif /* PPS_SYNC */
298 }
299 if (modes & MOD_MAXERROR)
300 time_maxerror = ntv.maxerror;
301 if (modes & MOD_ESTERROR)
302 time_esterror = ntv.esterror;
303 if (modes & MOD_STATUS) {
304 time_status &= STA_RONLY;
305 time_status |= ntv.status & ~STA_RONLY;
306 }
307 if (modes & MOD_TIMECONST) {
308 if (ntv.constant < 0)
309 time_constant = 0;
310 else if (ntv.constant > MAXTC)
311 time_constant = MAXTC;
312 else
313 time_constant = ntv.constant;
314 }
315#ifdef PPS_SYNC
316 if (modes & MOD_PPSMAX) {
317 if (ntv.shift < PPS_FAVG)
318 pps_shiftmax = PPS_FAVG;
319 else if (ntv.shift > PPS_FAVGMAX)
320 pps_shiftmax = PPS_FAVGMAX;
321 else
322 pps_shiftmax = ntv.shift;
323 }
324#endif /* PPS_SYNC */
325 if (modes & MOD_NANO)
326 time_status |= STA_NANO;
327 if (modes & MOD_MICRO)
328 time_status &= ~STA_NANO;
329 if (modes & MOD_CLKB)
330 time_status |= STA_CLK;
331 if (modes & MOD_CLKA)
332 time_status &= ~STA_CLK;
333 if (modes & MOD_OFFSET) {
334 if (time_status & STA_NANO)
335 hardupdate(ntv.offset);
336 else
337 hardupdate(ntv.offset * 1000);
338 }
339
340 /*
341 * Retrieve all clock variables
342 */
343 if (time_status & STA_NANO)
344 ntv.offset = L_GINT(time_offset);
345 else
346 ntv.offset = L_GINT(time_offset) / 1000;
347 ntv.freq = L_GINT((time_freq / 1000LL) << 16);
348 ntv.maxerror = time_maxerror;
349 ntv.esterror = time_esterror;
350 ntv.status = time_status;
351 ntv.constant = time_constant;
352 if (time_status & STA_NANO)
353 ntv.precision = time_precision;
354 else
355 ntv.precision = time_precision / 1000;
356 ntv.tolerance = MAXFREQ * SCALE_PPM;
357#ifdef PPS_SYNC
358 ntv.shift = pps_shift;
359 ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
360 if (time_status & STA_NANO)
361 ntv.jitter = pps_jitter;
362 else
363 ntv.jitter = pps_jitter / 1000;
364 ntv.stabil = pps_stabil;
365 ntv.calcnt = pps_calcnt;
366 ntv.errcnt = pps_errcnt;
367 ntv.jitcnt = pps_jitcnt;
368 ntv.stbcnt = pps_stbcnt;
369#endif /* PPS_SYNC */
370 splx(s);
371
372 error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
373 if (error)
374 return (error);
375
376 /*
377 * Status word error decode. See comments in
378 * ntp_gettime() routine.
379 */
380 if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
381 (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
382 !(time_status & STA_PPSSIGNAL)) ||
383 (time_status & STA_PPSTIME &&
384 time_status & STA_PPSJITTER) ||
385 (time_status & STA_PPSFREQ &&
386 time_status & (STA_PPSWANDER | STA_PPSERROR)))
387 p->p_retval[0] = TIME_ERROR;
388 else
389 p->p_retval[0] = time_state;
390 return (error);
391}
392
393/*
394 * second_overflow() - called after ntp_tick_adjust()
395 *
396 * This routine is ordinarily called immediately following the above
397 * routine ntp_tick_adjust(). While these two routines are normally
398 * combined, they are separated here only for the purposes of
399 * simulation.
400 */
401void
402ntp_update_second(struct timecounter *tcp)
403{
404 u_int32_t *newsec;
405 l_fp time_adj; /* 32/64-bit temporaries */
406
407 newsec = &tcp->tc_offset_sec;
408 /*
409 * On rollover of the second both the nanosecond and microsecond
410 * clocks are updated and the state machine cranked as
411 * necessary. The phase adjustment to be used for the next
412 * second is calculated and the maximum error is increased by
413 * the tolerance.
414 */
415 time_maxerror += MAXFREQ / 1000;
416
417 /*
418 * Leap second processing. If in leap-insert state at
419 * the end of the day, the system clock is set back one
420 * second; if in leap-delete state, the system clock is
421 * set ahead one second. The nano_time() routine or
422 * external clock driver will insure that reported time
423 * is always monotonic.
424 */
425 switch (time_state) {
426
427 /*
428 * No warning.
429 */
430 case TIME_OK:
431 if (time_status & STA_INS)
432 time_state = TIME_INS;
433 else if (time_status & STA_DEL)
434 time_state = TIME_DEL;
435 break;
436
437 /*
438 * Insert second 23:59:60 following second
439 * 23:59:59.
440 */
441 case TIME_INS:
442 if (!(time_status & STA_INS))
443 time_state = TIME_OK;
444 else if ((*newsec) % 86400 == 0) {
445 (*newsec)--;
446 time_state = TIME_OOP;
447 }
448 break;
449
450 /*
451 * Delete second 23:59:59.
452 */
453 case TIME_DEL:
454 if (!(time_status & STA_DEL))
455 time_state = TIME_OK;
456 else if (((*newsec) + 1) % 86400 == 0) {
457 (*newsec)++;
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 */
482 time_adj = time_offset;
483#ifdef PPS_SYNC
484#ifdef PPS_SYNC
485 /* XXX even if signal dies we should finish adjustment ? */
484 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL) {
486 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL) {
487 time_adj = pps_offset;
485 L_RSHIFT(time_adj, pps_shift);
488 L_RSHIFT(time_adj, pps_shift);
489 L_SUB(pps_offset, time_adj);
486 } else {
490 } else {
491 time_adj = time_offset;
487 L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
488 L_SUB(time_offset, time_adj);
489 }
490#else
492 L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
493 L_SUB(time_offset, time_adj);
494 }
495#else
496 time_adj = time_offset;
491 L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
492 L_SUB(time_offset, time_adj);
493#endif /* PPS_SYNC */
494 L_ADD(time_adj, time_freq);
495 tcp->tc_adjustment = time_adj;
496#ifdef PPS_SYNC
497 if (pps_valid > 0)
498 pps_valid--;
499 else
500 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
501 STA_PPSWANDER | STA_PPSERROR);
502#endif /* PPS_SYNC */
503}
504
505/*
506 * ntp_init() - initialize variables and structures
507 *
508 * This routine must be called after the kernel variables hz and tick
509 * are set or changed and before the next tick interrupt. In this
510 * particular implementation, these values are assumed set elsewhere in
511 * the kernel. The design allows the clock frequency and tick interval
512 * to be changed while the system is running. So, this routine should
513 * probably be integrated with the code that does that.
514 */
515static void
516ntp_init()
517{
518
519 /*
520 * The following variable must be initialized any time the
521 * kernel variable hz is changed.
522 */
523 time_tick = NANOSECOND / hz;
524
525 /*
526 * The following variables are initialized only at startup. Only
527 * those structures not cleared by the compiler need to be
528 * initialized, and these only in the simulator. In the actual
529 * kernel, any nonzero values here will quickly evaporate.
530 */
531 L_CLR(time_offset);
532 L_CLR(time_freq);
533#ifdef PPS_SYNC
534 pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
535 pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
536 pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
537 pps_fcount = 0;
538 L_CLR(pps_freq);
539#endif /* PPS_SYNC */
540}
541
542SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
543
544/*
545 * hardupdate() - local clock update
546 *
547 * This routine is called by ntp_adjtime() to update the local clock
548 * phase and frequency. The implementation is of an adaptive-parameter,
549 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
550 * time and frequency offset estimates for each call. If the kernel PPS
551 * discipline code is configured (PPS_SYNC), the PPS signal itself
552 * determines the new time offset, instead of the calling argument.
553 * Presumably, calls to ntp_adjtime() occur only when the caller
554 * believes the local clock is valid within some bound (+-128 ms with
555 * NTP). If the caller's time is far different than the PPS time, an
556 * argument will ensue, and it's not clear who will lose.
557 *
558 * For uncompensated quartz crystal oscillators and nominal update
559 * intervals less than 256 s, operation should be in phase-lock mode,
560 * where the loop is disciplined to phase. For update intervals greater
561 * than 1024 s, operation should be in frequency-lock mode, where the
562 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
563 * is selected by the STA_MODE status bit.
564 */
565static void
566hardupdate(offset)
567 long offset; /* clock offset (ns) */
568{
569 long ltemp, mtemp;
570 l_fp ftemp;
571
572 /*
573 * Select how the phase is to be controlled and from which
574 * source. If the PPS signal is present and enabled to
575 * discipline the time, the PPS offset is used; otherwise, the
576 * argument offset is used.
577 */
578 if (!(time_status & STA_PLL))
579 return;
580 ltemp = offset;
581 if (ltemp > MAXPHASE)
582 ltemp = MAXPHASE;
583 else if (ltemp < -MAXPHASE)
584 ltemp = -MAXPHASE;
585 if (!(time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL))
586 L_LINT(time_offset, ltemp);
587
588 /*
589 * Select how the frequency is to be controlled and in which
590 * mode (PLL or FLL). If the PPS signal is present and enabled
591 * to discipline the frequency, the PPS frequency is used;
592 * otherwise, the argument offset is used to compute it.
593 */
594 if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
595 time_reftime = time_second;
596 return;
597 }
598 if (time_status & STA_FREQHOLD || time_reftime == 0)
599 time_reftime = time_second;
600 mtemp = time_second - time_reftime;
601 L_LINT(ftemp, ltemp);
602 L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
603 L_MPY(ftemp, mtemp);
604 L_ADD(time_freq, ftemp);
605 time_status &= ~STA_MODE;
606 if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) {
607 L_LINT(ftemp, (ltemp << 4) / mtemp);
608 L_RSHIFT(ftemp, SHIFT_FLL + 4);
609 L_ADD(time_freq, ftemp);
610 time_status |= STA_MODE;
611 }
612 time_reftime = time_second;
613 if (L_GINT(time_freq) > MAXFREQ)
614 L_LINT(time_freq, MAXFREQ);
615 else if (L_GINT(time_freq) < -MAXFREQ)
616 L_LINT(time_freq, -MAXFREQ);
617}
618
619#ifdef PPS_SYNC
620/*
621 * hardpps() - discipline CPU clock oscillator to external PPS signal
622 *
623 * This routine is called at each PPS interrupt in order to discipline
624 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
625 * and leaves it in a handy spot for the hardclock() routine. It
626 * integrates successive PPS phase differences and calculates the
627 * frequency offset. This is used in hardclock() to discipline the CPU
628 * clock oscillator so that the intrinsic frequency error is cancelled
629 * out. The code requires the caller to capture the time and
630 * architecture-dependent hardware counter values in nanoseconds at the
631 * on-time PPS signal transition.
632 *
633 * Note that, on some Unix systems this routine runs at an interrupt
634 * priority level higher than the timer interrupt routine hardclock().
635 * Therefore, the variables used are distinct from the hardclock()
636 * variables, except for the actual time and frequency variables, which
637 * are determined by this routine and updated atomically.
638 */
639void
640hardpps(tsp, nsec)
641 struct timespec *tsp; /* time at PPS */
642 long nsec; /* hardware counter at PPS */
643{
644 long u_sec, u_nsec, v_nsec; /* temps */
645 l_fp ftemp;
646
647 /*
648 * The signal is first processed by a frequency discriminator
649 * which rejects noise and input signals with frequencies
650 * outside the range 1 +-MAXFREQ PPS. If two hits occur in the
651 * same second, we ignore the later hit; if not and a hit occurs
652 * outside the range gate, keep the later hit but do not
653 * process it.
654 */
655 time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
656 time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
657 pps_valid = PPS_VALID;
658 u_sec = tsp->tv_sec;
659 u_nsec = tsp->tv_nsec;
660 if (u_nsec >= (NANOSECOND >> 1)) {
661 u_nsec -= NANOSECOND;
662 u_sec++;
663 }
664 v_nsec = u_nsec - pps_tf[0].tv_nsec;
665 if (u_sec == pps_tf[0].tv_sec && v_nsec < -MAXFREQ) {
666 return;
667 }
668 pps_tf[2] = pps_tf[1];
669 pps_tf[1] = pps_tf[0];
670 pps_tf[0].tv_sec = u_sec;
671 pps_tf[0].tv_nsec = u_nsec;
672
673 /*
674 * Compute the difference between the current and previous
675 * counter values. If the difference exceeds 0.5 s, assume it
676 * has wrapped around, so correct 1.0 s. If the result exceeds
677 * the tick interval, the sample point has crossed a tick
678 * boundary during the last second, so correct the tick. Very
679 * intricate.
680 */
681 u_nsec = nsec;
682 if (u_nsec > (NANOSECOND >> 1))
683 u_nsec -= NANOSECOND;
684 else if (u_nsec < -(NANOSECOND >> 1))
685 u_nsec += NANOSECOND;
686 pps_fcount += u_nsec;
687 if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ) {
688 return;
689 }
690 time_status &= ~STA_PPSJITTER;
691
692 /*
693 * A three-stage median filter is used to help denoise the PPS
694 * time. The median sample becomes the time offset estimate; the
695 * difference between the other two samples becomes the time
696 * dispersion (jitter) estimate.
697 */
698 if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
699 if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
700 v_nsec = pps_tf[1].tv_nsec; /* 0 1 2 */
701 u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
702 } else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
703 v_nsec = pps_tf[0].tv_nsec; /* 2 0 1 */
704 u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
705 } else {
706 v_nsec = pps_tf[2].tv_nsec; /* 0 2 1 */
707 u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
708 }
709 } else {
710 if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
711 v_nsec = pps_tf[1].tv_nsec; /* 2 1 0 */
712 u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
713 } else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
714 v_nsec = pps_tf[0].tv_nsec; /* 1 0 2 */
715 u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
716 } else {
717 v_nsec = pps_tf[2].tv_nsec; /* 1 2 0 */
718 u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
719 }
720 }
721
722 /*
723 * Nominal jitter is due to PPS signal noise and interrupt
724 * latency. If it exceeds the popcorn threshold,
725 * the sample is discarded. otherwise, if so enabled, the time
726 * offset is updated. We can tolerate a modest loss of data here
727 * without degrading time accuracy.
728 */
729 if (u_nsec > (pps_jitter << PPS_POPCORN)) {
730 time_status |= STA_PPSJITTER;
731 pps_jitcnt++;
732 } else if (time_status & STA_PPSTIME) {
733 L_LINT(time_offset, -v_nsec);
497 L_RSHIFT(time_adj, SHIFT_PLL + time_constant);
498 L_SUB(time_offset, time_adj);
499#endif /* PPS_SYNC */
500 L_ADD(time_adj, time_freq);
501 tcp->tc_adjustment = time_adj;
502#ifdef PPS_SYNC
503 if (pps_valid > 0)
504 pps_valid--;
505 else
506 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
507 STA_PPSWANDER | STA_PPSERROR);
508#endif /* PPS_SYNC */
509}
510
511/*
512 * ntp_init() - initialize variables and structures
513 *
514 * This routine must be called after the kernel variables hz and tick
515 * are set or changed and before the next tick interrupt. In this
516 * particular implementation, these values are assumed set elsewhere in
517 * the kernel. The design allows the clock frequency and tick interval
518 * to be changed while the system is running. So, this routine should
519 * probably be integrated with the code that does that.
520 */
521static void
522ntp_init()
523{
524
525 /*
526 * The following variable must be initialized any time the
527 * kernel variable hz is changed.
528 */
529 time_tick = NANOSECOND / hz;
530
531 /*
532 * The following variables are initialized only at startup. Only
533 * those structures not cleared by the compiler need to be
534 * initialized, and these only in the simulator. In the actual
535 * kernel, any nonzero values here will quickly evaporate.
536 */
537 L_CLR(time_offset);
538 L_CLR(time_freq);
539#ifdef PPS_SYNC
540 pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
541 pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
542 pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
543 pps_fcount = 0;
544 L_CLR(pps_freq);
545#endif /* PPS_SYNC */
546}
547
548SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
549
550/*
551 * hardupdate() - local clock update
552 *
553 * This routine is called by ntp_adjtime() to update the local clock
554 * phase and frequency. The implementation is of an adaptive-parameter,
555 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
556 * time and frequency offset estimates for each call. If the kernel PPS
557 * discipline code is configured (PPS_SYNC), the PPS signal itself
558 * determines the new time offset, instead of the calling argument.
559 * Presumably, calls to ntp_adjtime() occur only when the caller
560 * believes the local clock is valid within some bound (+-128 ms with
561 * NTP). If the caller's time is far different than the PPS time, an
562 * argument will ensue, and it's not clear who will lose.
563 *
564 * For uncompensated quartz crystal oscillators and nominal update
565 * intervals less than 256 s, operation should be in phase-lock mode,
566 * where the loop is disciplined to phase. For update intervals greater
567 * than 1024 s, operation should be in frequency-lock mode, where the
568 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
569 * is selected by the STA_MODE status bit.
570 */
571static void
572hardupdate(offset)
573 long offset; /* clock offset (ns) */
574{
575 long ltemp, mtemp;
576 l_fp ftemp;
577
578 /*
579 * Select how the phase is to be controlled and from which
580 * source. If the PPS signal is present and enabled to
581 * discipline the time, the PPS offset is used; otherwise, the
582 * argument offset is used.
583 */
584 if (!(time_status & STA_PLL))
585 return;
586 ltemp = offset;
587 if (ltemp > MAXPHASE)
588 ltemp = MAXPHASE;
589 else if (ltemp < -MAXPHASE)
590 ltemp = -MAXPHASE;
591 if (!(time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL))
592 L_LINT(time_offset, ltemp);
593
594 /*
595 * Select how the frequency is to be controlled and in which
596 * mode (PLL or FLL). If the PPS signal is present and enabled
597 * to discipline the frequency, the PPS frequency is used;
598 * otherwise, the argument offset is used to compute it.
599 */
600 if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
601 time_reftime = time_second;
602 return;
603 }
604 if (time_status & STA_FREQHOLD || time_reftime == 0)
605 time_reftime = time_second;
606 mtemp = time_second - time_reftime;
607 L_LINT(ftemp, ltemp);
608 L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
609 L_MPY(ftemp, mtemp);
610 L_ADD(time_freq, ftemp);
611 time_status &= ~STA_MODE;
612 if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) {
613 L_LINT(ftemp, (ltemp << 4) / mtemp);
614 L_RSHIFT(ftemp, SHIFT_FLL + 4);
615 L_ADD(time_freq, ftemp);
616 time_status |= STA_MODE;
617 }
618 time_reftime = time_second;
619 if (L_GINT(time_freq) > MAXFREQ)
620 L_LINT(time_freq, MAXFREQ);
621 else if (L_GINT(time_freq) < -MAXFREQ)
622 L_LINT(time_freq, -MAXFREQ);
623}
624
625#ifdef PPS_SYNC
626/*
627 * hardpps() - discipline CPU clock oscillator to external PPS signal
628 *
629 * This routine is called at each PPS interrupt in order to discipline
630 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
631 * and leaves it in a handy spot for the hardclock() routine. It
632 * integrates successive PPS phase differences and calculates the
633 * frequency offset. This is used in hardclock() to discipline the CPU
634 * clock oscillator so that the intrinsic frequency error is cancelled
635 * out. The code requires the caller to capture the time and
636 * architecture-dependent hardware counter values in nanoseconds at the
637 * on-time PPS signal transition.
638 *
639 * Note that, on some Unix systems this routine runs at an interrupt
640 * priority level higher than the timer interrupt routine hardclock().
641 * Therefore, the variables used are distinct from the hardclock()
642 * variables, except for the actual time and frequency variables, which
643 * are determined by this routine and updated atomically.
644 */
645void
646hardpps(tsp, nsec)
647 struct timespec *tsp; /* time at PPS */
648 long nsec; /* hardware counter at PPS */
649{
650 long u_sec, u_nsec, v_nsec; /* temps */
651 l_fp ftemp;
652
653 /*
654 * The signal is first processed by a frequency discriminator
655 * which rejects noise and input signals with frequencies
656 * outside the range 1 +-MAXFREQ PPS. If two hits occur in the
657 * same second, we ignore the later hit; if not and a hit occurs
658 * outside the range gate, keep the later hit but do not
659 * process it.
660 */
661 time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
662 time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
663 pps_valid = PPS_VALID;
664 u_sec = tsp->tv_sec;
665 u_nsec = tsp->tv_nsec;
666 if (u_nsec >= (NANOSECOND >> 1)) {
667 u_nsec -= NANOSECOND;
668 u_sec++;
669 }
670 v_nsec = u_nsec - pps_tf[0].tv_nsec;
671 if (u_sec == pps_tf[0].tv_sec && v_nsec < -MAXFREQ) {
672 return;
673 }
674 pps_tf[2] = pps_tf[1];
675 pps_tf[1] = pps_tf[0];
676 pps_tf[0].tv_sec = u_sec;
677 pps_tf[0].tv_nsec = u_nsec;
678
679 /*
680 * Compute the difference between the current and previous
681 * counter values. If the difference exceeds 0.5 s, assume it
682 * has wrapped around, so correct 1.0 s. If the result exceeds
683 * the tick interval, the sample point has crossed a tick
684 * boundary during the last second, so correct the tick. Very
685 * intricate.
686 */
687 u_nsec = nsec;
688 if (u_nsec > (NANOSECOND >> 1))
689 u_nsec -= NANOSECOND;
690 else if (u_nsec < -(NANOSECOND >> 1))
691 u_nsec += NANOSECOND;
692 pps_fcount += u_nsec;
693 if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ) {
694 return;
695 }
696 time_status &= ~STA_PPSJITTER;
697
698 /*
699 * A three-stage median filter is used to help denoise the PPS
700 * time. The median sample becomes the time offset estimate; the
701 * difference between the other two samples becomes the time
702 * dispersion (jitter) estimate.
703 */
704 if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
705 if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
706 v_nsec = pps_tf[1].tv_nsec; /* 0 1 2 */
707 u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
708 } else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
709 v_nsec = pps_tf[0].tv_nsec; /* 2 0 1 */
710 u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
711 } else {
712 v_nsec = pps_tf[2].tv_nsec; /* 0 2 1 */
713 u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
714 }
715 } else {
716 if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
717 v_nsec = pps_tf[1].tv_nsec; /* 2 1 0 */
718 u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
719 } else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
720 v_nsec = pps_tf[0].tv_nsec; /* 1 0 2 */
721 u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
722 } else {
723 v_nsec = pps_tf[2].tv_nsec; /* 1 2 0 */
724 u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
725 }
726 }
727
728 /*
729 * Nominal jitter is due to PPS signal noise and interrupt
730 * latency. If it exceeds the popcorn threshold,
731 * the sample is discarded. otherwise, if so enabled, the time
732 * offset is updated. We can tolerate a modest loss of data here
733 * without degrading time accuracy.
734 */
735 if (u_nsec > (pps_jitter << PPS_POPCORN)) {
736 time_status |= STA_PPSJITTER;
737 pps_jitcnt++;
738 } else if (time_status & STA_PPSTIME) {
739 L_LINT(time_offset, -v_nsec);
740 L_LINT(pps_offset, -v_nsec);
734 }
735 pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
736 u_sec = pps_tf[0].tv_sec - pps_lastsec;
737 if (u_sec < (1 << pps_shift))
738 return;
739
740 /*
741 * At the end of the calibration interval the difference between
742 * the first and last counter values becomes the scaled
743 * frequency. It will later be divided by the length of the
744 * interval to determine the frequency update. If the frequency
745 * exceeds a sanity threshold, or if the actual calibration
746 * interval is not equal to the expected length, the data are
747 * discarded. We can tolerate a modest loss of data here without
748 * degrading frequency ccuracy.
749 */
750 pps_calcnt++;
751 v_nsec = -pps_fcount;
752 pps_lastsec = pps_tf[0].tv_sec;
753 pps_fcount = 0;
754 u_nsec = MAXFREQ << pps_shift;
755 if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
756 pps_shift)) {
757 time_status |= STA_PPSERROR;
758 pps_errcnt++;
759 return;
760 }
761
762 /*
763 * Here the raw frequency offset and wander (stability) is
764 * calculated. If the wander is less than the wander threshold
765 * for four consecutive averaging intervals, the interval is
766 * doubled; if it is greater than the threshold for four
767 * consecutive intervals, the interval is halved. The scaled
768 * frequency offset is converted to frequency offset. The
769 * stability metric is calculated as the average of recent
770 * frequency changes, but is used only for performance
771 * monitoring.
772 */
773 L_LINT(ftemp, v_nsec);
774 L_RSHIFT(ftemp, pps_shift);
775 L_SUB(ftemp, pps_freq);
776 u_nsec = L_GINT(ftemp);
777 if (u_nsec > PPS_MAXWANDER) {
778 L_LINT(ftemp, PPS_MAXWANDER);
779 pps_intcnt--;
780 time_status |= STA_PPSWANDER;
781 pps_stbcnt++;
782 } else if (u_nsec < -PPS_MAXWANDER) {
783 L_LINT(ftemp, -PPS_MAXWANDER);
784 pps_intcnt--;
785 time_status |= STA_PPSWANDER;
786 pps_stbcnt++;
787 } else {
788 pps_intcnt++;
789 }
790 if (pps_shift > pps_shiftmax) {
791 /* If we lowered pps_shiftmax */
792 pps_shift = pps_shiftmax;
793 pps_intcnt = 0;
794 } else if (pps_intcnt >= 4) {
795 pps_intcnt = 4;
796 if (pps_shift < pps_shiftmax) {
797 pps_shift++;
798 pps_intcnt = 0;
799 }
800 } else if (pps_intcnt <= -4) {
801 pps_intcnt = -4;
802 if (pps_shift > PPS_FAVG) {
803 pps_shift--;
804 pps_intcnt = 0;
805 }
806 }
807 if (u_nsec < 0)
808 u_nsec = -u_nsec;
809 pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
810
811 /*
812 * The PPS frequency is recalculated and clamped to the maximum
813 * MAXFREQ. If enabled, the system clock frequency is updated as
814 * well.
815 */
816 L_ADD(pps_freq, ftemp);
817 u_nsec = L_GINT(pps_freq);
818 if (u_nsec > MAXFREQ)
819 L_LINT(pps_freq, MAXFREQ);
820 else if (u_nsec < -MAXFREQ)
821 L_LINT(pps_freq, -MAXFREQ);
822 if (time_status & STA_PPSFREQ)
823 time_freq = pps_freq;
824}
825#endif /* PPS_SYNC */
741 }
742 pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
743 u_sec = pps_tf[0].tv_sec - pps_lastsec;
744 if (u_sec < (1 << pps_shift))
745 return;
746
747 /*
748 * At the end of the calibration interval the difference between
749 * the first and last counter values becomes the scaled
750 * frequency. It will later be divided by the length of the
751 * interval to determine the frequency update. If the frequency
752 * exceeds a sanity threshold, or if the actual calibration
753 * interval is not equal to the expected length, the data are
754 * discarded. We can tolerate a modest loss of data here without
755 * degrading frequency ccuracy.
756 */
757 pps_calcnt++;
758 v_nsec = -pps_fcount;
759 pps_lastsec = pps_tf[0].tv_sec;
760 pps_fcount = 0;
761 u_nsec = MAXFREQ << pps_shift;
762 if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
763 pps_shift)) {
764 time_status |= STA_PPSERROR;
765 pps_errcnt++;
766 return;
767 }
768
769 /*
770 * Here the raw frequency offset and wander (stability) is
771 * calculated. If the wander is less than the wander threshold
772 * for four consecutive averaging intervals, the interval is
773 * doubled; if it is greater than the threshold for four
774 * consecutive intervals, the interval is halved. The scaled
775 * frequency offset is converted to frequency offset. The
776 * stability metric is calculated as the average of recent
777 * frequency changes, but is used only for performance
778 * monitoring.
779 */
780 L_LINT(ftemp, v_nsec);
781 L_RSHIFT(ftemp, pps_shift);
782 L_SUB(ftemp, pps_freq);
783 u_nsec = L_GINT(ftemp);
784 if (u_nsec > PPS_MAXWANDER) {
785 L_LINT(ftemp, PPS_MAXWANDER);
786 pps_intcnt--;
787 time_status |= STA_PPSWANDER;
788 pps_stbcnt++;
789 } else if (u_nsec < -PPS_MAXWANDER) {
790 L_LINT(ftemp, -PPS_MAXWANDER);
791 pps_intcnt--;
792 time_status |= STA_PPSWANDER;
793 pps_stbcnt++;
794 } else {
795 pps_intcnt++;
796 }
797 if (pps_shift > pps_shiftmax) {
798 /* If we lowered pps_shiftmax */
799 pps_shift = pps_shiftmax;
800 pps_intcnt = 0;
801 } else if (pps_intcnt >= 4) {
802 pps_intcnt = 4;
803 if (pps_shift < pps_shiftmax) {
804 pps_shift++;
805 pps_intcnt = 0;
806 }
807 } else if (pps_intcnt <= -4) {
808 pps_intcnt = -4;
809 if (pps_shift > PPS_FAVG) {
810 pps_shift--;
811 pps_intcnt = 0;
812 }
813 }
814 if (u_nsec < 0)
815 u_nsec = -u_nsec;
816 pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
817
818 /*
819 * The PPS frequency is recalculated and clamped to the maximum
820 * MAXFREQ. If enabled, the system clock frequency is updated as
821 * well.
822 */
823 L_ADD(pps_freq, ftemp);
824 u_nsec = L_GINT(pps_freq);
825 if (u_nsec > MAXFREQ)
826 L_LINT(pps_freq, MAXFREQ);
827 else if (u_nsec < -MAXFREQ)
828 L_LINT(pps_freq, -MAXFREQ);
829 if (time_status & STA_PPSFREQ)
830 time_freq = pps_freq;
831}
832#endif /* PPS_SYNC */