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