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