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