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