time: ntp: make 64-bit constants more robust
[linux-block.git] / kernel / time / ntp.c
CommitLineData
4c7ee8de 1/*
4c7ee8de 2 * NTP state machine interfaces and logic.
3 *
4 * This code was mainly moved from kernel/timer.c and kernel/time.c
5 * Please see those files for relevant copyright info and historical
6 * changelogs.
7 */
aa0ac365 8#include <linux/capability.h>
7dffa3c6 9#include <linux/clocksource.h>
eb3f938f 10#include <linux/workqueue.h>
53bbfa9e
IM
11#include <linux/hrtimer.h>
12#include <linux/jiffies.h>
13#include <linux/math64.h>
14#include <linux/timex.h>
15#include <linux/time.h>
16#include <linux/mm.h>
4c7ee8de 17
b0ee7556 18/*
53bbfa9e 19 * NTP timekeeping variables:
b0ee7556 20 */
b0ee7556 21
53bbfa9e
IM
22/* USER_HZ period (usecs): */
23unsigned long tick_usec = TICK_USEC;
24
25/* ACTHZ period (nsecs): */
26unsigned long tick_nsec;
7dffa3c6 27
53bbfa9e
IM
28u64 tick_length;
29static u64 tick_length_base;
30
31static struct hrtimer leap_timer;
32
bbd12676 33#define MAX_TICKADJ 500LL /* usecs */
53bbfa9e 34#define MAX_TICKADJ_SCALED \
bbd12676 35 (((MAX_TICKADJ * NSEC_PER_USEC) << NTP_SCALE_SHIFT) / NTP_INTERVAL_FREQ)
4c7ee8de 36
37/*
38 * phase-lock loop variables
39 */
53bbfa9e
IM
40
41/*
42 * clock synchronization status
43 *
44 * (TIME_ERROR prevents overwriting the CMOS clock)
45 */
46static int time_state = TIME_OK;
47
48/* clock status bits: */
49int time_status = STA_UNSYNC;
50
51/* TAI offset (secs): */
52static long time_tai;
53
54/* time adjustment (nsecs): */
55static s64 time_offset;
56
57/* pll time constant: */
58static long time_constant = 2;
59
60/* maximum error (usecs): */
61long time_maxerror = NTP_PHASE_LIMIT;
62
63/* estimated error (usecs): */
64long time_esterror = NTP_PHASE_LIMIT;
65
66/* frequency offset (scaled nsecs/secs): */
67static s64 time_freq;
68
69/* time at last adjustment (secs): */
70static long time_reftime;
71
72long time_adjust;
73
74static long ntp_tick_adj;
75
76/*
77 * NTP methods:
78 */
4c7ee8de 79
9ce616aa
IM
80/*
81 * Update (tick_length, tick_length_base, tick_nsec), based
82 * on (tick_usec, ntp_tick_adj, time_freq):
83 */
70bc42f9
AB
84static void ntp_update_frequency(void)
85{
9ce616aa 86 u64 second_length;
bc26c31d 87 u64 new_base;
9ce616aa
IM
88
89 second_length = (u64)(tick_usec * NSEC_PER_USEC * USER_HZ)
90 << NTP_SCALE_SHIFT;
91
92 second_length += (s64)ntp_tick_adj << NTP_SCALE_SHIFT;
93 second_length += time_freq;
70bc42f9 94
9ce616aa 95 tick_nsec = div_u64(second_length, HZ) >> NTP_SCALE_SHIFT;
bc26c31d 96 new_base = div_u64(second_length, NTP_INTERVAL_FREQ);
fdcedf7b 97
98 /*
99 * Don't wait for the next second_overflow, apply
bc26c31d 100 * the change to the tick length immediately:
fdcedf7b 101 */
bc26c31d
IM
102 tick_length += new_base - tick_length_base;
103 tick_length_base = new_base;
70bc42f9
AB
104}
105
478b7aab 106static inline s64 ntp_update_offset_fll(s64 offset64, long secs)
f939890b
IM
107{
108 time_status &= ~STA_MODE;
109
110 if (secs < MINSEC)
478b7aab 111 return 0;
f939890b
IM
112
113 if (!(time_status & STA_FLL) && (secs <= MAXSEC))
478b7aab 114 return 0;
f939890b 115
f939890b
IM
116 time_status |= STA_MODE;
117
478b7aab 118 return div_s64(offset64 << (NTP_SCALE_SHIFT - SHIFT_FLL), secs);
f939890b
IM
119}
120
ee9851b2
RZ
121static void ntp_update_offset(long offset)
122{
ee9851b2 123 s64 freq_adj;
f939890b
IM
124 s64 offset64;
125 long secs;
ee9851b2
RZ
126
127 if (!(time_status & STA_PLL))
128 return;
129
eea83d89 130 if (!(time_status & STA_NANO))
9f14f669 131 offset *= NSEC_PER_USEC;
ee9851b2
RZ
132
133 /*
134 * Scale the phase adjustment and
135 * clamp to the operating range.
136 */
9f14f669
RZ
137 offset = min(offset, MAXPHASE);
138 offset = max(offset, -MAXPHASE);
ee9851b2
RZ
139
140 /*
141 * Select how the frequency is to be controlled
142 * and in which mode (PLL or FLL).
143 */
f939890b 144 secs = xtime.tv_sec - time_reftime;
10dd31a7 145 if (unlikely(time_status & STA_FREQHOLD))
c7986acb
IM
146 secs = 0;
147
ee9851b2
RZ
148 time_reftime = xtime.tv_sec;
149
f939890b
IM
150 offset64 = offset;
151 freq_adj = (offset64 * secs) <<
152 (NTP_SCALE_SHIFT - 2 * (SHIFT_PLL + 2 + time_constant));
153
478b7aab 154 freq_adj += ntp_update_offset_fll(offset64, secs);
f939890b
IM
155
156 freq_adj = min(freq_adj + time_freq, MAXFREQ_SCALED);
157
158 time_freq = max(freq_adj, -MAXFREQ_SCALED);
159
160 time_offset = div_s64(offset64 << NTP_SCALE_SHIFT, NTP_INTERVAL_FREQ);
ee9851b2
RZ
161}
162
b0ee7556
RZ
163/**
164 * ntp_clear - Clears the NTP state variables
165 *
166 * Must be called while holding a write on the xtime_lock
167 */
168void ntp_clear(void)
169{
53bbfa9e
IM
170 time_adjust = 0; /* stop active adjtime() */
171 time_status |= STA_UNSYNC;
172 time_maxerror = NTP_PHASE_LIMIT;
173 time_esterror = NTP_PHASE_LIMIT;
b0ee7556
RZ
174
175 ntp_update_frequency();
176
53bbfa9e
IM
177 tick_length = tick_length_base;
178 time_offset = 0;
b0ee7556
RZ
179}
180
4c7ee8de 181/*
7dffa3c6
RZ
182 * Leap second processing. If in leap-insert state at the end of the
183 * day, the system clock is set back one second; if in leap-delete
184 * state, the system clock is set ahead one second.
4c7ee8de 185 */
7dffa3c6 186static enum hrtimer_restart ntp_leap_second(struct hrtimer *timer)
4c7ee8de 187{
7dffa3c6 188 enum hrtimer_restart res = HRTIMER_NORESTART;
4c7ee8de 189
ca109491 190 write_seqlock(&xtime_lock);
4c7ee8de 191
4c7ee8de 192 switch (time_state) {
193 case TIME_OK:
4c7ee8de 194 break;
195 case TIME_INS:
7dffa3c6
RZ
196 xtime.tv_sec--;
197 wall_to_monotonic.tv_sec++;
198 time_state = TIME_OOP;
53bbfa9e
IM
199 printk(KERN_NOTICE
200 "Clock: inserting leap second 23:59:60 UTC\n");
cc584b21 201 hrtimer_add_expires_ns(&leap_timer, NSEC_PER_SEC);
7dffa3c6 202 res = HRTIMER_RESTART;
4c7ee8de 203 break;
204 case TIME_DEL:
7dffa3c6
RZ
205 xtime.tv_sec++;
206 time_tai--;
207 wall_to_monotonic.tv_sec--;
208 time_state = TIME_WAIT;
53bbfa9e
IM
209 printk(KERN_NOTICE
210 "Clock: deleting leap second 23:59:59 UTC\n");
4c7ee8de 211 break;
212 case TIME_OOP:
153b5d05 213 time_tai++;
4c7ee8de 214 time_state = TIME_WAIT;
7dffa3c6 215 /* fall through */
4c7ee8de 216 case TIME_WAIT:
217 if (!(time_status & (STA_INS | STA_DEL)))
ee9851b2 218 time_state = TIME_OK;
7dffa3c6
RZ
219 break;
220 }
221 update_vsyscall(&xtime, clock);
222
ca109491 223 write_sequnlock(&xtime_lock);
7dffa3c6
RZ
224
225 return res;
226}
227
228/*
229 * this routine handles the overflow of the microsecond field
230 *
231 * The tricky bits of code to handle the accurate clock support
232 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
233 * They were originally developed for SUN and DEC kernels.
234 * All the kudos should go to Dave for this stuff.
235 */
236void second_overflow(void)
237{
238 s64 time_adj;
239
240 /* Bump the maxerror field */
241 time_maxerror += MAXFREQ / NSEC_PER_USEC;
242 if (time_maxerror > NTP_PHASE_LIMIT) {
243 time_maxerror = NTP_PHASE_LIMIT;
244 time_status |= STA_UNSYNC;
4c7ee8de 245 }
246
247 /*
f1992393
RZ
248 * Compute the phase adjustment for the next second. The offset is
249 * reduced by a fixed factor times the time constant.
4c7ee8de 250 */
53bbfa9e
IM
251 tick_length = tick_length_base;
252 time_adj = shift_right(time_offset, SHIFT_PLL + time_constant);
253 time_offset -= time_adj;
254 tick_length += time_adj;
4c7ee8de 255
3c972c24
IM
256 if (!time_adjust)
257 return;
258
259 if (time_adjust > MAX_TICKADJ) {
260 time_adjust -= MAX_TICKADJ;
261 tick_length += MAX_TICKADJ_SCALED;
262 return;
4c7ee8de 263 }
3c972c24
IM
264
265 if (time_adjust < -MAX_TICKADJ) {
266 time_adjust += MAX_TICKADJ;
267 tick_length -= MAX_TICKADJ_SCALED;
268 return;
269 }
270
271 tick_length += (s64)(time_adjust * NSEC_PER_USEC / NTP_INTERVAL_FREQ)
272 << NTP_SCALE_SHIFT;
273 time_adjust = 0;
4c7ee8de 274}
275
82644459 276#ifdef CONFIG_GENERIC_CMOS_UPDATE
4c7ee8de 277
82644459
TG
278/* Disable the cmos update - used by virtualization and embedded */
279int no_sync_cmos_clock __read_mostly;
280
eb3f938f 281static void sync_cmos_clock(struct work_struct *work);
82644459 282
eb3f938f 283static DECLARE_DELAYED_WORK(sync_cmos_work, sync_cmos_clock);
82644459 284
eb3f938f 285static void sync_cmos_clock(struct work_struct *work)
82644459
TG
286{
287 struct timespec now, next;
288 int fail = 1;
289
290 /*
291 * If we have an externally synchronized Linux clock, then update
292 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
293 * called as close as possible to 500 ms before the new second starts.
294 * This code is run on a timer. If the clock is set, that timer
295 * may not expire at the correct time. Thus, we adjust...
296 */
53bbfa9e 297 if (!ntp_synced()) {
82644459
TG
298 /*
299 * Not synced, exit, do not restart a timer (if one is
300 * running, let it run out).
301 */
302 return;
53bbfa9e 303 }
82644459
TG
304
305 getnstimeofday(&now);
fa6a1a55 306 if (abs(now.tv_nsec - (NSEC_PER_SEC / 2)) <= tick_nsec / 2)
82644459
TG
307 fail = update_persistent_clock(now);
308
4ff4b9e1 309 next.tv_nsec = (NSEC_PER_SEC / 2) - now.tv_nsec - (TICK_NSEC / 2);
82644459
TG
310 if (next.tv_nsec <= 0)
311 next.tv_nsec += NSEC_PER_SEC;
312
313 if (!fail)
314 next.tv_sec = 659;
315 else
316 next.tv_sec = 0;
317
318 if (next.tv_nsec >= NSEC_PER_SEC) {
319 next.tv_sec++;
320 next.tv_nsec -= NSEC_PER_SEC;
321 }
eb3f938f 322 schedule_delayed_work(&sync_cmos_work, timespec_to_jiffies(&next));
82644459
TG
323}
324
325static void notify_cmos_timer(void)
4c7ee8de 326{
298a5df4 327 if (!no_sync_cmos_clock)
eb3f938f 328 schedule_delayed_work(&sync_cmos_work, 0);
4c7ee8de 329}
330
82644459
TG
331#else
332static inline void notify_cmos_timer(void) { }
333#endif
334
e9629165
IM
335/*
336 * Start the leap seconds timer:
337 */
338static inline void ntp_start_leap_timer(struct timespec *ts)
339{
340 long now = ts->tv_sec;
341
342 if (time_status & STA_INS) {
343 time_state = TIME_INS;
344 now += 86400 - now % 86400;
345 hrtimer_start(&leap_timer, ktime_set(now, 0), HRTIMER_MODE_ABS);
346
347 return;
348 }
349
350 if (time_status & STA_DEL) {
351 time_state = TIME_DEL;
352 now += 86400 - (now + 1) % 86400;
353 hrtimer_start(&leap_timer, ktime_set(now, 0), HRTIMER_MODE_ABS);
354 }
355}
80f22571
IM
356
357/*
358 * Propagate a new txc->status value into the NTP state:
359 */
360static inline void process_adj_status(struct timex *txc, struct timespec *ts)
361{
80f22571
IM
362 if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
363 time_state = TIME_OK;
364 time_status = STA_UNSYNC;
365 }
366 /* only set allowed bits */
367 time_status &= STA_RONLY;
368
369 /*
370 * If we turn on PLL adjustments then reset the
371 * reference time to current time.
372 */
373 if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
374 time_reftime = xtime.tv_sec;
375
376 time_status |= txc->status & ~STA_RONLY;
377
378 switch (time_state) {
379 case TIME_OK:
e9629165 380 ntp_start_leap_timer(ts);
80f22571
IM
381 break;
382 case TIME_INS:
383 case TIME_DEL:
384 time_state = TIME_OK;
e9629165 385 ntp_start_leap_timer(ts);
80f22571
IM
386 case TIME_WAIT:
387 if (!(time_status & (STA_INS | STA_DEL)))
388 time_state = TIME_OK;
389 break;
390 case TIME_OOP:
391 hrtimer_restart(&leap_timer);
392 break;
393 }
394}
395/*
396 * Called with the xtime lock held, so we can access and modify
397 * all the global NTP state:
398 */
399static inline void process_adjtimex_modes(struct timex *txc, struct timespec *ts)
400{
401 if (txc->modes & ADJ_STATUS)
402 process_adj_status(txc, ts);
403
404 if (txc->modes & ADJ_NANO)
405 time_status |= STA_NANO;
e9629165 406
80f22571
IM
407 if (txc->modes & ADJ_MICRO)
408 time_status &= ~STA_NANO;
409
410 if (txc->modes & ADJ_FREQUENCY) {
2b9d1496 411 time_freq = txc->freq * PPM_SCALE;
80f22571
IM
412 time_freq = min(time_freq, MAXFREQ_SCALED);
413 time_freq = max(time_freq, -MAXFREQ_SCALED);
414 }
415
416 if (txc->modes & ADJ_MAXERROR)
417 time_maxerror = txc->maxerror;
e9629165 418
80f22571
IM
419 if (txc->modes & ADJ_ESTERROR)
420 time_esterror = txc->esterror;
421
422 if (txc->modes & ADJ_TIMECONST) {
423 time_constant = txc->constant;
424 if (!(time_status & STA_NANO))
425 time_constant += 4;
426 time_constant = min(time_constant, (long)MAXTC);
427 time_constant = max(time_constant, 0l);
428 }
429
430 if (txc->modes & ADJ_TAI && txc->constant > 0)
431 time_tai = txc->constant;
432
433 if (txc->modes & ADJ_OFFSET)
434 ntp_update_offset(txc->offset);
e9629165 435
80f22571
IM
436 if (txc->modes & ADJ_TICK)
437 tick_usec = txc->tick;
438
439 if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
440 ntp_update_frequency();
441}
442
53bbfa9e
IM
443/*
444 * adjtimex mainly allows reading (and writing, if superuser) of
4c7ee8de 445 * kernel time-keeping variables. used by xntpd.
446 */
447int do_adjtimex(struct timex *txc)
448{
eea83d89 449 struct timespec ts;
4c7ee8de 450 int result;
451
916c7a85
RZ
452 /* Validate the data before disabling interrupts */
453 if (txc->modes & ADJ_ADJTIME) {
eea83d89 454 /* singleshot must not be used with any other mode bits */
916c7a85 455 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
4c7ee8de 456 return -EINVAL;
916c7a85
RZ
457 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
458 !capable(CAP_SYS_TIME))
459 return -EPERM;
460 } else {
461 /* In order to modify anything, you gotta be super-user! */
462 if (txc->modes && !capable(CAP_SYS_TIME))
463 return -EPERM;
464
53bbfa9e
IM
465 /*
466 * if the quartz is off by more than 10% then
467 * something is VERY wrong!
468 */
916c7a85
RZ
469 if (txc->modes & ADJ_TICK &&
470 (txc->tick < 900000/USER_HZ ||
471 txc->tick > 1100000/USER_HZ))
e9629165 472 return -EINVAL;
916c7a85
RZ
473
474 if (txc->modes & ADJ_STATUS && time_state != TIME_OK)
475 hrtimer_cancel(&leap_timer);
52bfb360 476 }
4c7ee8de 477
7dffa3c6
RZ
478 getnstimeofday(&ts);
479
4c7ee8de 480 write_seqlock_irq(&xtime_lock);
4c7ee8de 481
916c7a85
RZ
482 if (txc->modes & ADJ_ADJTIME) {
483 long save_adjust = time_adjust;
484
485 if (!(txc->modes & ADJ_OFFSET_READONLY)) {
486 /* adjtime() is independent from ntp_adjtime() */
487 time_adjust = txc->offset;
488 ntp_update_frequency();
489 }
490 txc->offset = save_adjust;
e9629165 491 } else {
ee9851b2 492
e9629165
IM
493 /* If there are input parameters, then process them: */
494 if (txc->modes)
495 process_adjtimex_modes(txc, &ts);
eea83d89 496
e9629165 497 txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
916c7a85 498 NTP_SCALE_SHIFT);
e9629165
IM
499 if (!(time_status & STA_NANO))
500 txc->offset /= NSEC_PER_USEC;
501 }
916c7a85 502
eea83d89 503 result = time_state; /* mostly `TIME_OK' */
ee9851b2 504 if (time_status & (STA_UNSYNC|STA_CLOCKERR))
4c7ee8de 505 result = TIME_ERROR;
506
d40e944c 507 txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
2b9d1496 508 PPM_SCALE_INV, NTP_SCALE_SHIFT);
4c7ee8de 509 txc->maxerror = time_maxerror;
510 txc->esterror = time_esterror;
511 txc->status = time_status;
512 txc->constant = time_constant;
70bc42f9 513 txc->precision = 1;
074b3b87 514 txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
4c7ee8de 515 txc->tick = tick_usec;
153b5d05 516 txc->tai = time_tai;
4c7ee8de 517
518 /* PPS is not implemented, so these are zero */
519 txc->ppsfreq = 0;
520 txc->jitter = 0;
521 txc->shift = 0;
522 txc->stabil = 0;
523 txc->jitcnt = 0;
524 txc->calcnt = 0;
525 txc->errcnt = 0;
526 txc->stbcnt = 0;
e9629165 527
4c7ee8de 528 write_sequnlock_irq(&xtime_lock);
ee9851b2 529
eea83d89
RZ
530 txc->time.tv_sec = ts.tv_sec;
531 txc->time.tv_usec = ts.tv_nsec;
532 if (!(time_status & STA_NANO))
533 txc->time.tv_usec /= NSEC_PER_USEC;
ee9851b2 534
82644459 535 notify_cmos_timer();
ee9851b2
RZ
536
537 return result;
4c7ee8de 538}
10a398d0
RZ
539
540static int __init ntp_tick_adj_setup(char *str)
541{
542 ntp_tick_adj = simple_strtol(str, NULL, 0);
543 return 1;
544}
545
546__setup("ntp_tick_adj=", ntp_tick_adj_setup);
7dffa3c6
RZ
547
548void __init ntp_init(void)
549{
550 ntp_clear();
551 hrtimer_init(&leap_timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
552 leap_timer.function = ntp_leap_second;
553}