ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / kernel / time.c
1 /*
2  *  linux/kernel/time.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  *
6  *  This file contains the interface functions for the various
7  *  time related system calls: time, stime, gettimeofday, settimeofday,
8  *                             adjtime
9  */
10 /*
11  * Modification history kernel/time.c
12  * 
13  * 1993-09-02    Philip Gladstone
14  *      Created file with time related functions from sched.c and adjtimex() 
15  * 1993-10-08    Torsten Duwe
16  *      adjtime interface update and CMOS clock write code
17  * 1995-08-13    Torsten Duwe
18  *      kernel PLL updated to 1994-12-13 specs (rfc-1589)
19  * 1999-01-16    Ulrich Windl
20  *      Introduced error checking for many cases in adjtimex().
21  *      Updated NTP code according to technical memorandum Jan '96
22  *      "A Kernel Model for Precision Timekeeping" by Dave Mills
23  *      Allow time_constant larger than MAXTC(6) for NTP v4 (MAXTC == 10)
24  *      (Even though the technical memorandum forbids it)
25  */
26
27 #include <linux/module.h>
28 #include <linux/timex.h>
29 #include <linux/errno.h>
30 #include <linux/smp_lock.h>
31 #include <asm/uaccess.h>
32
33 /* 
34  * The timezone where the local system is located.  Used as a default by some
35  * programs who obtain this value by using gettimeofday.
36  */
37 struct timezone sys_tz;
38
39 EXPORT_SYMBOL(sys_tz);
40
41 #if !defined(__alpha__) && !defined(__ia64__)
42
43 /*
44  * sys_time() can be implemented in user-level using
45  * sys_gettimeofday().  Is this for backwards compatibility?  If so,
46  * why not move it into the appropriate arch directory (for those
47  * architectures that need it).
48  *
49  * XXX This function is NOT 64-bit clean!
50  */
51 asmlinkage long sys_time(int * tloc)
52 {
53         int i;
54         struct timeval tv;
55
56         do_gettimeofday(&tv);
57         i = tv.tv_sec;
58
59         if (tloc) {
60                 if (put_user(i,tloc))
61                         i = -EFAULT;
62         }
63         return i;
64 }
65
66 /*
67  * sys_stime() can be implemented in user-level using
68  * sys_settimeofday().  Is this for backwards compatibility?  If so,
69  * why not move it into the appropriate arch directory (for those
70  * architectures that need it).
71  */
72  
73 asmlinkage long sys_stime(time_t *tptr)
74 {
75         struct timespec tv;
76
77         if (!capable(CAP_SYS_TIME))
78                 return -EPERM;
79         if (get_user(tv.tv_sec, tptr))
80                 return -EFAULT;
81
82         tv.tv_nsec = 0;
83         do_settimeofday(&tv);
84         return 0;
85 }
86
87 #endif
88
89 asmlinkage long sys_gettimeofday(struct timeval __user *tv, struct timezone __user *tz)
90 {
91         if (likely(tv != NULL)) {
92                 struct timeval ktv;
93                 do_gettimeofday(&ktv);
94                 if (copy_to_user(tv, &ktv, sizeof(ktv)))
95                         return -EFAULT;
96         }
97         if (unlikely(tz != NULL)) {
98                 if (copy_to_user(tz, &sys_tz, sizeof(sys_tz)))
99                         return -EFAULT;
100         }
101         return 0;
102 }
103
104 /*
105  * Adjust the time obtained from the CMOS to be UTC time instead of
106  * local time.
107  * 
108  * This is ugly, but preferable to the alternatives.  Otherwise we
109  * would either need to write a program to do it in /etc/rc (and risk
110  * confusion if the program gets run more than once; it would also be 
111  * hard to make the program warp the clock precisely n hours)  or
112  * compile in the timezone information into the kernel.  Bad, bad....
113  *
114  *                                              - TYT, 1992-01-01
115  *
116  * The best thing to do is to keep the CMOS clock in universal time (UTC)
117  * as real UNIX machines always do it. This avoids all headaches about
118  * daylight saving times and warping kernel clocks.
119  */
120 inline static void warp_clock(void)
121 {
122         write_seqlock_irq(&xtime_lock);
123         wall_to_monotonic.tv_sec -= sys_tz.tz_minuteswest * 60;
124         xtime.tv_sec += sys_tz.tz_minuteswest * 60;
125         time_interpolator_update(sys_tz.tz_minuteswest * 60 * NSEC_PER_SEC);
126         write_sequnlock_irq(&xtime_lock);
127         clock_was_set();
128 }
129
130 /*
131  * In case for some reason the CMOS clock has not already been running
132  * in UTC, but in some local time: The first time we set the timezone,
133  * we will warp the clock so that it is ticking UTC time instead of
134  * local time. Presumably, if someone is setting the timezone then we
135  * are running in an environment where the programs understand about
136  * timezones. This should be done at boot time in the /etc/rc script,
137  * as soon as possible, so that the clock can be set right. Otherwise,
138  * various programs will get confused when the clock gets warped.
139  */
140
141 int do_sys_settimeofday(struct timespec *tv, struct timezone *tz)
142 {
143         static int firsttime = 1;
144
145         if (!capable(CAP_SYS_TIME))
146                 return -EPERM;
147                 
148         if (tz) {
149                 /* SMP safe, global irq locking makes it work. */
150                 sys_tz = *tz;
151                 if (firsttime) {
152                         firsttime = 0;
153                         if (!tv)
154                                 warp_clock();
155                 }
156         }
157         if (tv)
158         {
159                 /* SMP safe, again the code in arch/foo/time.c should
160                  * globally block out interrupts when it runs.
161                  */
162                 return do_settimeofday(tv);
163         }
164         return 0;
165 }
166
167 asmlinkage long sys_settimeofday(struct timeval __user *tv,
168                                 struct timezone __user *tz)
169 {
170         struct timeval user_tv;
171         struct timespec new_ts;
172         struct timezone new_tz;
173
174         if (tv) {
175                 if (copy_from_user(&user_tv, tv, sizeof(*tv)))
176                         return -EFAULT;
177                 new_ts.tv_sec = user_tv.tv_sec;
178                 new_ts.tv_nsec = user_tv.tv_usec * NSEC_PER_USEC;
179         }
180         if (tz) {
181                 if (copy_from_user(&new_tz, tz, sizeof(*tz)))
182                         return -EFAULT;
183         }
184
185         return do_sys_settimeofday(tv ? &new_ts : NULL, tz ? &new_tz : NULL);
186 }
187
188 long pps_offset;                /* pps time offset (us) */
189 long pps_jitter = MAXTIME;      /* time dispersion (jitter) (us) */
190
191 long pps_freq;                  /* frequency offset (scaled ppm) */
192 long pps_stabil = MAXFREQ;      /* frequency dispersion (scaled ppm) */
193
194 long pps_valid = PPS_VALID;     /* pps signal watchdog counter */
195
196 int pps_shift = PPS_SHIFT;      /* interval duration (s) (shift) */
197
198 long pps_jitcnt;                /* jitter limit exceeded */
199 long pps_calcnt;                /* calibration intervals */
200 long pps_errcnt;                /* calibration errors */
201 long pps_stbcnt;                /* stability limit exceeded */
202
203 /* hook for a loadable hardpps kernel module */
204 void (*hardpps_ptr)(struct timeval *);
205
206 /* adjtimex mainly allows reading (and writing, if superuser) of
207  * kernel time-keeping variables. used by xntpd.
208  */
209 int do_adjtimex(struct timex *txc)
210 {
211         long ltemp, mtemp, save_adjust;
212         int result;
213
214         /* In order to modify anything, you gotta be super-user! */
215         if (txc->modes && !capable(CAP_SYS_TIME))
216                 return -EPERM;
217                 
218         /* Now we validate the data before disabling interrupts */
219
220         if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT)
221           /* singleshot must not be used with any other mode bits */
222                 if (txc->modes != ADJ_OFFSET_SINGLESHOT)
223                         return -EINVAL;
224
225         if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET))
226           /* adjustment Offset limited to +- .512 seconds */
227                 if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE )
228                         return -EINVAL; 
229
230         /* if the quartz is off by more than 10% something is VERY wrong ! */
231         if (txc->modes & ADJ_TICK)
232                 if (txc->tick <  900000/USER_HZ ||
233                     txc->tick > 1100000/USER_HZ)
234                         return -EINVAL;
235
236         write_seqlock_irq(&xtime_lock);
237         result = time_state;    /* mostly `TIME_OK' */
238
239         /* Save for later - semantics of adjtime is to return old value */
240         save_adjust = time_next_adjust ? time_next_adjust : time_adjust;
241
242 #if 0   /* STA_CLOCKERR is never set yet */
243         time_status &= ~STA_CLOCKERR;           /* reset STA_CLOCKERR */
244 #endif
245         /* If there are input parameters, then process them */
246         if (txc->modes)
247         {
248             if (txc->modes & ADJ_STATUS)        /* only set allowed bits */
249                 time_status =  (txc->status & ~STA_RONLY) |
250                               (time_status & STA_RONLY);
251
252             if (txc->modes & ADJ_FREQUENCY) {   /* p. 22 */
253                 if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) {
254                     result = -EINVAL;
255                     goto leave;
256                 }
257                 time_freq = txc->freq - pps_freq;
258             }
259
260             if (txc->modes & ADJ_MAXERROR) {
261                 if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) {
262                     result = -EINVAL;
263                     goto leave;
264                 }
265                 time_maxerror = txc->maxerror;
266             }
267
268             if (txc->modes & ADJ_ESTERROR) {
269                 if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) {
270                     result = -EINVAL;
271                     goto leave;
272                 }
273                 time_esterror = txc->esterror;
274             }
275
276             if (txc->modes & ADJ_TIMECONST) {   /* p. 24 */
277                 if (txc->constant < 0) {        /* NTP v4 uses values > 6 */
278                     result = -EINVAL;
279                     goto leave;
280                 }
281                 time_constant = txc->constant;
282             }
283
284             if (txc->modes & ADJ_OFFSET) {      /* values checked earlier */
285                 if (txc->modes == ADJ_OFFSET_SINGLESHOT) {
286                     /* adjtime() is independent from ntp_adjtime() */
287                     if ((time_next_adjust = txc->offset) == 0)
288                          time_adjust = 0;
289                 }
290                 else if ( time_status & (STA_PLL | STA_PPSTIME) ) {
291                     ltemp = (time_status & (STA_PPSTIME | STA_PPSSIGNAL)) ==
292                             (STA_PPSTIME | STA_PPSSIGNAL) ?
293                             pps_offset : txc->offset;
294
295                     /*
296                      * Scale the phase adjustment and
297                      * clamp to the operating range.
298                      */
299                     if (ltemp > MAXPHASE)
300                         time_offset = MAXPHASE << SHIFT_UPDATE;
301                     else if (ltemp < -MAXPHASE)
302                         time_offset = -(MAXPHASE << SHIFT_UPDATE);
303                     else
304                         time_offset = ltemp << SHIFT_UPDATE;
305
306                     /*
307                      * Select whether the frequency is to be controlled
308                      * and in which mode (PLL or FLL). Clamp to the operating
309                      * range. Ugly multiply/divide should be replaced someday.
310                      */
311
312                     if (time_status & STA_FREQHOLD || time_reftime == 0)
313                         time_reftime = xtime.tv_sec;
314                     mtemp = xtime.tv_sec - time_reftime;
315                     time_reftime = xtime.tv_sec;
316                     if (time_status & STA_FLL) {
317                         if (mtemp >= MINSEC) {
318                             ltemp = (time_offset / mtemp) << (SHIFT_USEC -
319                                                               SHIFT_UPDATE);
320                             if (ltemp < 0)
321                                 time_freq -= -ltemp >> SHIFT_KH;
322                             else
323                                 time_freq += ltemp >> SHIFT_KH;
324                         } else /* calibration interval too short (p. 12) */
325                                 result = TIME_ERROR;
326                     } else {    /* PLL mode */
327                         if (mtemp < MAXSEC) {
328                             ltemp *= mtemp;
329                             if (ltemp < 0)
330                                 time_freq -= -ltemp >> (time_constant +
331                                                         time_constant +
332                                                         SHIFT_KF - SHIFT_USEC);
333                             else
334                                 time_freq += ltemp >> (time_constant +
335                                                        time_constant +
336                                                        SHIFT_KF - SHIFT_USEC);
337                         } else /* calibration interval too long (p. 12) */
338                                 result = TIME_ERROR;
339                     }
340                     if (time_freq > time_tolerance)
341                         time_freq = time_tolerance;
342                     else if (time_freq < -time_tolerance)
343                         time_freq = -time_tolerance;
344                 } /* STA_PLL || STA_PPSTIME */
345             } /* txc->modes & ADJ_OFFSET */
346             if (txc->modes & ADJ_TICK) {
347                 tick_usec = txc->tick;
348                 tick_nsec = TICK_USEC_TO_NSEC(tick_usec);
349             }
350         } /* txc->modes */
351 leave:  if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0
352             || ((time_status & (STA_PPSFREQ|STA_PPSTIME)) != 0
353                 && (time_status & STA_PPSSIGNAL) == 0)
354             /* p. 24, (b) */
355             || ((time_status & (STA_PPSTIME|STA_PPSJITTER))
356                 == (STA_PPSTIME|STA_PPSJITTER))
357             /* p. 24, (c) */
358             || ((time_status & STA_PPSFREQ) != 0
359                 && (time_status & (STA_PPSWANDER|STA_PPSERROR)) != 0))
360             /* p. 24, (d) */
361                 result = TIME_ERROR;
362         
363         if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT)
364             txc->offset    = save_adjust;
365         else {
366             if (time_offset < 0)
367                 txc->offset = -(-time_offset >> SHIFT_UPDATE);
368             else
369                 txc->offset = time_offset >> SHIFT_UPDATE;
370         }
371         txc->freq          = time_freq + pps_freq;
372         txc->maxerror      = time_maxerror;
373         txc->esterror      = time_esterror;
374         txc->status        = time_status;
375         txc->constant      = time_constant;
376         txc->precision     = time_precision;
377         txc->tolerance     = time_tolerance;
378         txc->tick          = tick_usec;
379         txc->ppsfreq       = pps_freq;
380         txc->jitter        = pps_jitter >> PPS_AVG;
381         txc->shift         = pps_shift;
382         txc->stabil        = pps_stabil;
383         txc->jitcnt        = pps_jitcnt;
384         txc->calcnt        = pps_calcnt;
385         txc->errcnt        = pps_errcnt;
386         txc->stbcnt        = pps_stbcnt;
387         write_sequnlock_irq(&xtime_lock);
388         do_gettimeofday(&txc->time);
389         return(result);
390 }
391
392 asmlinkage long sys_adjtimex(struct timex __user *txc_p)
393 {
394         struct timex txc;               /* Local copy of parameter */
395         int ret;
396
397         /* Copy the user data space into the kernel copy
398          * structure. But bear in mind that the structures
399          * may change
400          */
401         if(copy_from_user(&txc, txc_p, sizeof(struct timex)))
402                 return -EFAULT;
403         ret = do_adjtimex(&txc);
404         return copy_to_user(txc_p, &txc, sizeof(struct timex)) ? -EFAULT : ret;
405 }
406
407 struct timespec current_kernel_time(void)
408 {
409         struct timespec now;
410         unsigned long seq;
411
412         do {
413                 seq = read_seqbegin(&xtime_lock);
414                 
415                 now = xtime;
416         } while (read_seqretry(&xtime_lock, seq));
417
418         return now; 
419 }
420
421 EXPORT_SYMBOL(current_kernel_time);
422
423 #if (BITS_PER_LONG < 64)
424 u64 get_jiffies_64(void)
425 {
426         unsigned long seq;
427         u64 ret;
428
429         do {
430                 seq = read_seqbegin(&xtime_lock);
431                 ret = jiffies_64;
432         } while (read_seqretry(&xtime_lock, seq));
433         return ret;
434 }
435
436 EXPORT_SYMBOL(get_jiffies_64);
437 #endif
438
439 EXPORT_SYMBOL(jiffies);