xref: /linux/kernel/time/ntp.c (revision 606d099cdd1080bbb50ea50dc52d98252f8f10a1)
1 /*
2  * linux/kernel/time/ntp.c
3  *
4  * NTP state machine interfaces and logic.
5  *
6  * This code was mainly moved from kernel/timer.c and kernel/time.c
7  * Please see those files for relevant copyright info and historical
8  * changelogs.
9  */
10 
11 #include <linux/mm.h>
12 #include <linux/time.h>
13 #include <linux/timex.h>
14 
15 #include <asm/div64.h>
16 #include <asm/timex.h>
17 
18 /*
19  * Timekeeping variables
20  */
21 unsigned long tick_usec = TICK_USEC; 		/* USER_HZ period (usec) */
22 unsigned long tick_nsec;			/* ACTHZ period (nsec) */
23 static u64 tick_length, tick_length_base;
24 
25 #define MAX_TICKADJ		500		/* microsecs */
26 #define MAX_TICKADJ_SCALED	(((u64)(MAX_TICKADJ * NSEC_PER_USEC) << \
27 				  TICK_LENGTH_SHIFT) / HZ)
28 
29 /*
30  * phase-lock loop variables
31  */
32 /* TIME_ERROR prevents overwriting the CMOS clock */
33 static int time_state = TIME_OK;	/* clock synchronization status	*/
34 int time_status = STA_UNSYNC;		/* clock status bits		*/
35 static long time_offset;		/* time adjustment (ns)		*/
36 static long time_constant = 2;		/* pll time constant		*/
37 long time_maxerror = NTP_PHASE_LIMIT;	/* maximum error (us)		*/
38 long time_esterror = NTP_PHASE_LIMIT;	/* estimated error (us)		*/
39 long time_freq;				/* frequency offset (scaled ppm)*/
40 static long time_reftime;		/* time at last adjustment (s)	*/
41 long time_adjust;
42 
43 #define CLOCK_TICK_OVERFLOW	(LATCH * HZ - CLOCK_TICK_RATE)
44 #define CLOCK_TICK_ADJUST	(((s64)CLOCK_TICK_OVERFLOW * NSEC_PER_SEC) / \
45 					(s64)CLOCK_TICK_RATE)
46 
47 static void ntp_update_frequency(void)
48 {
49 	tick_length_base = (u64)(tick_usec * NSEC_PER_USEC * USER_HZ) << TICK_LENGTH_SHIFT;
50 	tick_length_base += (s64)CLOCK_TICK_ADJUST << TICK_LENGTH_SHIFT;
51 	tick_length_base += (s64)time_freq << (TICK_LENGTH_SHIFT - SHIFT_NSEC);
52 
53 	do_div(tick_length_base, HZ);
54 
55 	tick_nsec = tick_length_base >> TICK_LENGTH_SHIFT;
56 }
57 
58 /**
59  * ntp_clear - Clears the NTP state variables
60  *
61  * Must be called while holding a write on the xtime_lock
62  */
63 void ntp_clear(void)
64 {
65 	time_adjust = 0;		/* stop active adjtime() */
66 	time_status |= STA_UNSYNC;
67 	time_maxerror = NTP_PHASE_LIMIT;
68 	time_esterror = NTP_PHASE_LIMIT;
69 
70 	ntp_update_frequency();
71 
72 	tick_length = tick_length_base;
73 	time_offset = 0;
74 }
75 
76 /*
77  * this routine handles the overflow of the microsecond field
78  *
79  * The tricky bits of code to handle the accurate clock support
80  * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
81  * They were originally developed for SUN and DEC kernels.
82  * All the kudos should go to Dave for this stuff.
83  */
84 void second_overflow(void)
85 {
86 	long time_adj;
87 
88 	/* Bump the maxerror field */
89 	time_maxerror += MAXFREQ >> SHIFT_USEC;
90 	if (time_maxerror > NTP_PHASE_LIMIT) {
91 		time_maxerror = NTP_PHASE_LIMIT;
92 		time_status |= STA_UNSYNC;
93 	}
94 
95 	/*
96 	 * Leap second processing. If in leap-insert state at the end of the
97 	 * day, the system clock is set back one second; if in leap-delete
98 	 * state, the system clock is set ahead one second. The microtime()
99 	 * routine or external clock driver will insure that reported time is
100 	 * always monotonic. The ugly divides should be replaced.
101 	 */
102 	switch (time_state) {
103 	case TIME_OK:
104 		if (time_status & STA_INS)
105 			time_state = TIME_INS;
106 		else if (time_status & STA_DEL)
107 			time_state = TIME_DEL;
108 		break;
109 	case TIME_INS:
110 		if (xtime.tv_sec % 86400 == 0) {
111 			xtime.tv_sec--;
112 			wall_to_monotonic.tv_sec++;
113 			/*
114 			 * The timer interpolator will make time change
115 			 * gradually instead of an immediate jump by one second
116 			 */
117 			time_interpolator_update(-NSEC_PER_SEC);
118 			time_state = TIME_OOP;
119 			clock_was_set();
120 			printk(KERN_NOTICE "Clock: inserting leap second "
121 					"23:59:60 UTC\n");
122 		}
123 		break;
124 	case TIME_DEL:
125 		if ((xtime.tv_sec + 1) % 86400 == 0) {
126 			xtime.tv_sec++;
127 			wall_to_monotonic.tv_sec--;
128 			/*
129 			 * Use of time interpolator for a gradual change of
130 			 * time
131 			 */
132 			time_interpolator_update(NSEC_PER_SEC);
133 			time_state = TIME_WAIT;
134 			clock_was_set();
135 			printk(KERN_NOTICE "Clock: deleting leap second "
136 					"23:59:59 UTC\n");
137 		}
138 		break;
139 	case TIME_OOP:
140 		time_state = TIME_WAIT;
141 		break;
142 	case TIME_WAIT:
143 		if (!(time_status & (STA_INS | STA_DEL)))
144 		time_state = TIME_OK;
145 	}
146 
147 	/*
148 	 * Compute the phase adjustment for the next second. The offset is
149 	 * reduced by a fixed factor times the time constant.
150 	 */
151 	tick_length = tick_length_base;
152 	time_adj = shift_right(time_offset, SHIFT_PLL + time_constant);
153 	time_offset -= time_adj;
154 	tick_length += (s64)time_adj << (TICK_LENGTH_SHIFT - SHIFT_UPDATE);
155 
156 	if (unlikely(time_adjust)) {
157 		if (time_adjust > MAX_TICKADJ) {
158 			time_adjust -= MAX_TICKADJ;
159 			tick_length += MAX_TICKADJ_SCALED;
160 		} else if (time_adjust < -MAX_TICKADJ) {
161 			time_adjust += MAX_TICKADJ;
162 			tick_length -= MAX_TICKADJ_SCALED;
163 		} else {
164 			tick_length += (s64)(time_adjust * NSEC_PER_USEC /
165 					     HZ) << TICK_LENGTH_SHIFT;
166 			time_adjust = 0;
167 		}
168 	}
169 }
170 
171 /*
172  * Return how long ticks are at the moment, that is, how much time
173  * update_wall_time_one_tick will add to xtime next time we call it
174  * (assuming no calls to do_adjtimex in the meantime).
175  * The return value is in fixed-point nanoseconds shifted by the
176  * specified number of bits to the right of the binary point.
177  * This function has no side-effects.
178  */
179 u64 current_tick_length(void)
180 {
181 	return tick_length;
182 }
183 
184 
185 void __attribute__ ((weak)) notify_arch_cmos_timer(void)
186 {
187 	return;
188 }
189 
190 /* adjtimex mainly allows reading (and writing, if superuser) of
191  * kernel time-keeping variables. used by xntpd.
192  */
193 int do_adjtimex(struct timex *txc)
194 {
195 	long ltemp, mtemp, save_adjust;
196 	s64 freq_adj, temp64;
197 	int result;
198 
199 	/* In order to modify anything, you gotta be super-user! */
200 	if (txc->modes && !capable(CAP_SYS_TIME))
201 		return -EPERM;
202 
203 	/* Now we validate the data before disabling interrupts */
204 
205 	if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT)
206 	  /* singleshot must not be used with any other mode bits */
207 		if (txc->modes != ADJ_OFFSET_SINGLESHOT)
208 			return -EINVAL;
209 
210 	if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET))
211 	  /* adjustment Offset limited to +- .512 seconds */
212 		if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE )
213 			return -EINVAL;
214 
215 	/* if the quartz is off by more than 10% something is VERY wrong ! */
216 	if (txc->modes & ADJ_TICK)
217 		if (txc->tick <  900000/USER_HZ ||
218 		    txc->tick > 1100000/USER_HZ)
219 			return -EINVAL;
220 
221 	write_seqlock_irq(&xtime_lock);
222 	result = time_state;	/* mostly `TIME_OK' */
223 
224 	/* Save for later - semantics of adjtime is to return old value */
225 	save_adjust = time_adjust;
226 
227 #if 0	/* STA_CLOCKERR is never set yet */
228 	time_status &= ~STA_CLOCKERR;		/* reset STA_CLOCKERR */
229 #endif
230 	/* If there are input parameters, then process them */
231 	if (txc->modes)
232 	{
233 	    if (txc->modes & ADJ_STATUS)	/* only set allowed bits */
234 		time_status =  (txc->status & ~STA_RONLY) |
235 			      (time_status & STA_RONLY);
236 
237 	    if (txc->modes & ADJ_FREQUENCY) {	/* p. 22 */
238 		if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) {
239 		    result = -EINVAL;
240 		    goto leave;
241 		}
242 		time_freq = ((s64)txc->freq * NSEC_PER_USEC) >> (SHIFT_USEC - SHIFT_NSEC);
243 	    }
244 
245 	    if (txc->modes & ADJ_MAXERROR) {
246 		if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) {
247 		    result = -EINVAL;
248 		    goto leave;
249 		}
250 		time_maxerror = txc->maxerror;
251 	    }
252 
253 	    if (txc->modes & ADJ_ESTERROR) {
254 		if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) {
255 		    result = -EINVAL;
256 		    goto leave;
257 		}
258 		time_esterror = txc->esterror;
259 	    }
260 
261 	    if (txc->modes & ADJ_TIMECONST) {	/* p. 24 */
262 		if (txc->constant < 0) {	/* NTP v4 uses values > 6 */
263 		    result = -EINVAL;
264 		    goto leave;
265 		}
266 		time_constant = min(txc->constant + 4, (long)MAXTC);
267 	    }
268 
269 	    if (txc->modes & ADJ_OFFSET) {	/* values checked earlier */
270 		if (txc->modes == ADJ_OFFSET_SINGLESHOT) {
271 		    /* adjtime() is independent from ntp_adjtime() */
272 		    time_adjust = txc->offset;
273 		}
274 		else if (time_status & STA_PLL) {
275 		    ltemp = txc->offset * NSEC_PER_USEC;
276 
277 		    /*
278 		     * Scale the phase adjustment and
279 		     * clamp to the operating range.
280 		     */
281 		    time_offset = min(ltemp, MAXPHASE * NSEC_PER_USEC);
282 		    time_offset = max(time_offset, -MAXPHASE * NSEC_PER_USEC);
283 
284 		    /*
285 		     * Select whether the frequency is to be controlled
286 		     * and in which mode (PLL or FLL). Clamp to the operating
287 		     * range. Ugly multiply/divide should be replaced someday.
288 		     */
289 
290 		    if (time_status & STA_FREQHOLD || time_reftime == 0)
291 		        time_reftime = xtime.tv_sec;
292 		    mtemp = xtime.tv_sec - time_reftime;
293 		    time_reftime = xtime.tv_sec;
294 
295 		    freq_adj = (s64)time_offset * mtemp;
296 		    freq_adj = shift_right(freq_adj, time_constant * 2 +
297 					   (SHIFT_PLL + 2) * 2 - SHIFT_NSEC);
298 		    if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) {
299 			temp64 = (s64)time_offset << (SHIFT_NSEC - SHIFT_FLL);
300 			if (time_offset < 0) {
301 			    temp64 = -temp64;
302 			    do_div(temp64, mtemp);
303 			    freq_adj -= temp64;
304 			} else {
305 			    do_div(temp64, mtemp);
306 			    freq_adj += temp64;
307 			}
308 		    }
309 		    freq_adj += time_freq;
310 		    freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC);
311 		    time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC);
312 		    time_offset = (time_offset / HZ) << SHIFT_UPDATE;
313 		} /* STA_PLL */
314 	    } /* txc->modes & ADJ_OFFSET */
315 	    if (txc->modes & ADJ_TICK)
316 		tick_usec = txc->tick;
317 
318 	    if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
319 		    ntp_update_frequency();
320 	} /* txc->modes */
321 leave:	if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0)
322 		result = TIME_ERROR;
323 
324 	if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT)
325 	    txc->offset	   = save_adjust;
326 	else
327 	    txc->offset    = shift_right(time_offset, SHIFT_UPDATE) * HZ / 1000;
328 	txc->freq	   = (time_freq / NSEC_PER_USEC) << (SHIFT_USEC - SHIFT_NSEC);
329 	txc->maxerror	   = time_maxerror;
330 	txc->esterror	   = time_esterror;
331 	txc->status	   = time_status;
332 	txc->constant	   = time_constant;
333 	txc->precision	   = 1;
334 	txc->tolerance	   = MAXFREQ;
335 	txc->tick	   = tick_usec;
336 
337 	/* PPS is not implemented, so these are zero */
338 	txc->ppsfreq	   = 0;
339 	txc->jitter	   = 0;
340 	txc->shift	   = 0;
341 	txc->stabil	   = 0;
342 	txc->jitcnt	   = 0;
343 	txc->calcnt	   = 0;
344 	txc->errcnt	   = 0;
345 	txc->stbcnt	   = 0;
346 	write_sequnlock_irq(&xtime_lock);
347 	do_gettimeofday(&txc->time);
348 	notify_arch_cmos_timer();
349 	return(result);
350 }
351