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