root/kernel/time.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. mktime
  2. time_init
  3. sys_time
  4. sys_stime
  5. do_gettimeoffset
  6. do_gettimeofday
  7. sys_gettimeofday
  8. warp_clock
  9. sys_settimeofday
  10. sys_adjtimex
  11. set_rtc_mmss

   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  * 1994-07-02    Alan Modra
  18  *      fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
  19  * 1995-03-26    Markus Kuhn
  20  *      fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887
  21  *      precision CMOS clock update
  22  *
  23  * to do: adjtimex() has to be updated to recent (1994-12-13) revision
  24  *        of David Mill's kernel clock model. For more information, check
  25  *        <ftp://louie.udel.edu/pub/ntp/kernel.tar.Z>. 
  26  */
  27 
  28 #include <linux/errno.h>
  29 #include <linux/sched.h>
  30 #include <linux/kernel.h>
  31 #include <linux/param.h>
  32 #include <linux/string.h>
  33 #include <linux/mm.h>
  34 
  35 #include <asm/segment.h>
  36 #include <asm/io.h>
  37 
  38 #include <linux/mc146818rtc.h>
  39 #include <linux/timex.h>
  40 
  41 /* Converts Gregorian date to seconds since 1970-01-01 00:00:00.
  42  * Assumes input in normal date format, i.e. 1980-12-31 23:59:59
  43  * => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
  44  *
  45  * [For the Julian calendar (which was used in Russia before 1917,
  46  * Britain & colonies before 1752, anywhere else before 1582,
  47  * and is still in use by some communities) leave out the
  48  * -year/100+year/400 terms, and add 10.]
  49  *
  50  * This algorithm was first published by Gauss (I think).
  51  *
  52  * WARNING: this function will overflow on 2106-02-07 06:28:16 on
  53  * machines were long is 32-bit! (However, as time_t is signed, we
  54  * will already get problems at other places on 2038-01-19 03:14:08)
  55  */
  56 static inline unsigned long mktime(unsigned int year, unsigned int mon,
     /* [previous][next][first][last][top][bottom][index][help] */
  57         unsigned int day, unsigned int hour,
  58         unsigned int min, unsigned int sec)
  59 {
  60         if (0 >= (int) (mon -= 2)) {    /* 1..12 -> 11,12,1..10 */
  61                 mon += 12;      /* Puts Feb last since it has leap day */
  62                 year -= 1;
  63         }
  64         return (((
  65             (unsigned long)(year/4 - year/100 + year/400 + 367*mon/12 + day) +
  66               year*365 - 719499
  67             )*24 + hour /* now have hours */
  68            )*60 + min /* now have minutes */
  69           )*60 + sec; /* finally seconds */
  70 }
  71 
  72 void time_init(void)
     /* [previous][next][first][last][top][bottom][index][help] */
  73 {
  74         unsigned int year, mon, day, hour, min, sec;
  75         int i;
  76 
  77         /* The Linux interpretation of the CMOS clock register contents:
  78          * When the Update-In-Progress (UIP) flag goes from 1 to 0, the
  79          * RTC registers show the second which has precisely just started.
  80          * Let's hope other operating systems interpret the RTC the same way.
  81          */
  82         /* read RTC exactly on falling edge of update flag */
  83         for (i = 0 ; i < 1000000 ; i++) /* may take up to 1 second... */
  84                 if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP)
  85                         break;
  86         for (i = 0 ; i < 1000000 ; i++) /* must try at least 2.228 ms */
  87                 if (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP))
  88                         break;
  89         do { /* Isn't this overkill ? UIP above should guarantee consistency */
  90                 sec = CMOS_READ(RTC_SECONDS);
  91                 min = CMOS_READ(RTC_MINUTES);
  92                 hour = CMOS_READ(RTC_HOURS);
  93                 day = CMOS_READ(RTC_DAY_OF_MONTH);
  94                 mon = CMOS_READ(RTC_MONTH);
  95                 year = CMOS_READ(RTC_YEAR);
  96         } while (sec != CMOS_READ(RTC_SECONDS));
  97         if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
  98           {
  99             BCD_TO_BIN(sec);
 100             BCD_TO_BIN(min);
 101             BCD_TO_BIN(hour);
 102             BCD_TO_BIN(day);
 103             BCD_TO_BIN(mon);
 104             BCD_TO_BIN(year);
 105           }
 106 #if defined(__alpha__) && defined(CONFIG_PCI)
 107         /*
 108          * The meaning of life, the universe, and everything. Plus
 109          * this makes the year come out right.
 110          */
 111         year -= 42;
 112 #endif
 113         if ((year += 1900) < 1970)
 114                 year += 100;
 115         xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
 116         xtime.tv_usec = 0;
 117 }
 118 
 119 /* 
 120  * The timezone where the local system is located.  Used as a default by some
 121  * programs who obtain this value by using gettimeofday.
 122  */
 123 struct timezone sys_tz = { 0, 0};
 124 
 125 asmlinkage int sys_time(long * tloc)
     /* [previous][next][first][last][top][bottom][index][help] */
 126 {
 127         int i, error;
 128 
 129         i = CURRENT_TIME;
 130         if (tloc) {
 131                 error = verify_area(VERIFY_WRITE, tloc, 4);
 132                 if (error)
 133                         return error;
 134                 put_fs_long(i,(unsigned long *)tloc);
 135         }
 136         return i;
 137 }
 138 
 139 asmlinkage int sys_stime(unsigned long * tptr)
     /* [previous][next][first][last][top][bottom][index][help] */
 140 {
 141         int error;
 142         unsigned long value;
 143 
 144         if (!suser())
 145                 return -EPERM;
 146         error = verify_area(VERIFY_READ, tptr, sizeof(*tptr));
 147         if (error)
 148                 return error;
 149         value = get_fs_long(tptr);
 150         cli();
 151         xtime.tv_sec = value;
 152         xtime.tv_usec = 0;
 153         time_status = TIME_BAD;
 154         time_maxerror = 0x70000000;
 155         time_esterror = 0x70000000;
 156         sti();
 157         return 0;
 158 }
 159 
 160 /* This function must be called with interrupts disabled 
 161  * It was inspired by Steve McCanne's microtime-i386 for BSD.  -- jrs
 162  * 
 163  * However, the pc-audio speaker driver changes the divisor so that
 164  * it gets interrupted rather more often - it loads 64 into the
 165  * counter rather than 11932! This has an adverse impact on
 166  * do_gettimeoffset() -- it stops working! What is also not
 167  * good is that the interval that our timer function gets called
 168  * is no longer 10.0002 ms, but 9.9767 ms. To get around this
 169  * would require using a different timing source. Maybe someone
 170  * could use the RTC - I know that this can interrupt at frequencies
 171  * ranging from 8192Hz to 2Hz. If I had the energy, I'd somehow fix
 172  * it so that at startup, the timer code in sched.c would select
 173  * using either the RTC or the 8253 timer. The decision would be
 174  * based on whether there was any other device around that needed
 175  * to trample on the 8253. I'd set up the RTC to interrupt at 1024 Hz,
 176  * and then do some jiggery to have a version of do_timer that 
 177  * advanced the clock by 1/1024 s. Every time that reached over 1/100
 178  * of a second, then do all the old code. If the time was kept correct
 179  * then do_gettimeoffset could just return 0 - there is no low order
 180  * divider that can be accessed.
 181  *
 182  * Ideally, you would be able to use the RTC for the speaker driver,
 183  * but it appears that the speaker driver really needs interrupt more
 184  * often than every 120 us or so.
 185  *
 186  * Anyway, this needs more thought....          pjsg (1993-08-28)
 187  * 
 188  * If you are really that interested, you should be reading
 189  * comp.protocols.time.ntp!
 190  */
 191 
 192 #define TICK_SIZE tick
 193 
 194 static inline unsigned long do_gettimeoffset(void)
     /* [previous][next][first][last][top][bottom][index][help] */
 195 {
 196         int count;
 197         unsigned long offset = 0;
 198 
 199         /* timer count may underflow right here */
 200         outb_p(0x00, 0x43);     /* latch the count ASAP */
 201         count = inb_p(0x40);    /* read the latched count */
 202         count |= inb(0x40) << 8;
 203         /* we know probability of underflow is always MUCH less than 1% */
 204         if (count > (LATCH - LATCH/100)) {
 205                 /* check for pending timer interrupt */
 206                 outb_p(0x0a, 0x20);
 207                 if (inb(0x20) & 1)
 208                         offset = TICK_SIZE;
 209         }
 210         count = ((LATCH-1) - count) * TICK_SIZE;
 211         count = (count + LATCH/2) / LATCH;
 212         return offset + count;
 213 }
 214 
 215 /*
 216  * This version of gettimeofday has near microsecond resolution.
 217  */
 218 void do_gettimeofday(struct timeval *tv)
     /* [previous][next][first][last][top][bottom][index][help] */
 219 {
 220         unsigned long flags;
 221 
 222         save_flags(flags);
 223         cli();
 224         *tv = xtime;
 225 #if defined (__i386__) || defined (__mips__)
 226         tv->tv_usec += do_gettimeoffset();
 227         if (tv->tv_usec >= 1000000) {
 228                 tv->tv_usec -= 1000000;
 229                 tv->tv_sec++;
 230         }
 231 #endif /* !defined (__i386__) && !defined (__mips__) */
 232         restore_flags(flags);
 233 }
 234 
 235 asmlinkage int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
     /* [previous][next][first][last][top][bottom][index][help] */
 236 {
 237         int error;
 238 
 239         if (tv) {
 240                 struct timeval ktv;
 241                 error = verify_area(VERIFY_WRITE, tv, sizeof *tv);
 242                 if (error)
 243                         return error;
 244                 do_gettimeofday(&ktv);
 245                 memcpy_tofs(tv, &ktv, sizeof(ktv));
 246         }
 247         if (tz) {
 248                 error = verify_area(VERIFY_WRITE, tz, sizeof *tz);
 249                 if (error)
 250                         return error;
 251                 memcpy_tofs(tz, &sys_tz, sizeof(sys_tz));
 252         }
 253         return 0;
 254 }
 255 
 256 /*
 257  * Adjust the time obtained from the CMOS to be UTC time instead of
 258  * local time.
 259  * 
 260  * This is ugly, but preferable to the alternatives.  Otherwise we
 261  * would either need to write a program to do it in /etc/rc (and risk
 262  * confusion if the program gets run more than once; it would also be 
 263  * hard to make the program warp the clock precisely n hours)  or
 264  * compile in the timezone information into the kernel.  Bad, bad....
 265  *
 266  *                                              - TYT, 1992-01-01
 267  *
 268  * The best thing to do is to keep the CMOS clock in universal time (UTC)
 269  * as real UNIX machines always do it. This avoids all headaches about
 270  * daylight saving times and warping kernel clocks.
 271  */
 272 inline static void warp_clock(void)
     /* [previous][next][first][last][top][bottom][index][help] */
 273 {
 274         cli();
 275         xtime.tv_sec += sys_tz.tz_minuteswest * 60;
 276         sti();
 277 }
 278 
 279 /*
 280  * In case for some reason the CMOS clock has not already been running
 281  * in UTC, but in some local time: The first time we set the timezone,
 282  * we will warp the clock so that it is ticking UTC time instead of
 283  * local time. Presumably, if someone is setting the timezone then we
 284  * are running in an environment where the programs understand about
 285  * timezones. This should be done at boot time in the /etc/rc script,
 286  * as soon as possible, so that the clock can be set right. Otherwise,
 287  * various programs will get confused when the clock gets warped.
 288  */
 289 asmlinkage int sys_settimeofday(struct timeval *tv, struct timezone *tz)
     /* [previous][next][first][last][top][bottom][index][help] */
 290 {
 291         static int      firsttime = 1;
 292         struct timeval  new_tv;
 293         struct timezone new_tz;
 294 
 295         if (!suser())
 296                 return -EPERM;
 297         if (tv) {
 298                 int error = verify_area(VERIFY_READ, tv, sizeof(*tv));
 299                 if (error)
 300                         return error;
 301                 memcpy_fromfs(&new_tv, tv, sizeof(*tv));
 302         }
 303         if (tz) {
 304                 int error = verify_area(VERIFY_READ, tz, sizeof(*tz));
 305                 if (error)
 306                         return error;
 307                 memcpy_fromfs(&new_tz, tz, sizeof(*tz));
 308         }
 309         if (tz) {
 310                 sys_tz = new_tz;
 311                 if (firsttime) {
 312                         firsttime = 0;
 313                         if (!tv)
 314                                 warp_clock();
 315                 }
 316         }
 317         if (tv) {
 318                 cli();
 319                 /* This is revolting. We need to set the xtime.tv_usec
 320                  * correctly. However, the value in this location is
 321                  * is value at the last tick.
 322                  * Discover what correction gettimeofday
 323                  * would have done, and then undo it!
 324                  */
 325                 new_tv.tv_usec -= do_gettimeoffset();
 326 
 327                 if (new_tv.tv_usec < 0) {
 328                         new_tv.tv_usec += 1000000;
 329                         new_tv.tv_sec--;
 330                 }
 331 
 332                 xtime = new_tv;
 333                 time_status = TIME_BAD;
 334                 time_maxerror = 0x70000000;
 335                 time_esterror = 0x70000000;
 336                 sti();
 337         }
 338         return 0;
 339 }
 340 
 341 /* adjtimex mainly allows reading (and writing, if superuser) of
 342  * kernel time-keeping variables. used by xntpd.
 343  */
 344 asmlinkage int sys_adjtimex(struct timex *txc_p)
     /* [previous][next][first][last][top][bottom][index][help] */
 345 {
 346         long ltemp, mtemp, save_adjust;
 347         int error;
 348 
 349         /* Local copy of parameter */
 350         struct timex txc;
 351 
 352         error = verify_area(VERIFY_WRITE, txc_p, sizeof(struct timex));
 353         if (error)
 354           return error;
 355 
 356         /* Copy the user data space into the kernel copy
 357          * structure. But bear in mind that the structures
 358          * may change
 359          */
 360         memcpy_fromfs(&txc, txc_p, sizeof(struct timex));
 361 
 362         /* In order to modify anything, you gotta be super-user! */
 363         if (txc.mode && !suser())
 364                 return -EPERM;
 365 
 366         /* Now we validate the data before disabling interrupts
 367          */
 368 
 369         if (txc.mode != ADJ_OFFSET_SINGLESHOT && (txc.mode & ADJ_OFFSET))
 370           /* Microsec field limited to -131000 .. 131000 usecs */
 371           if (txc.offset <= -(1 << (31 - SHIFT_UPDATE))
 372               || txc.offset >= (1 << (31 - SHIFT_UPDATE)))
 373             return -EINVAL;
 374 
 375         /* time_status must be in a fairly small range */
 376         if (txc.mode & ADJ_STATUS)
 377           if (txc.status < TIME_OK || txc.status > TIME_BAD)
 378             return -EINVAL;
 379 
 380         /* if the quartz is off by more than 10% something is VERY wrong ! */
 381         if (txc.mode & ADJ_TICK)
 382           if (txc.tick < 900000/HZ || txc.tick > 1100000/HZ)
 383             return -EINVAL;
 384 
 385         cli();
 386 
 387         /* Save for later - semantics of adjtime is to return old value */
 388         save_adjust = time_adjust;
 389 
 390         /* If there are input parameters, then process them */
 391         if (txc.mode)
 392         {
 393             if (time_status == TIME_BAD)
 394                 time_status = TIME_OK;
 395 
 396             if (txc.mode & ADJ_STATUS)
 397                 time_status = txc.status;
 398 
 399             if (txc.mode & ADJ_FREQUENCY)
 400                 time_freq = txc.frequency << (SHIFT_KF - 16);
 401 
 402             if (txc.mode & ADJ_MAXERROR)
 403                 time_maxerror = txc.maxerror;
 404 
 405             if (txc.mode & ADJ_ESTERROR)
 406                 time_esterror = txc.esterror;
 407 
 408             if (txc.mode & ADJ_TIMECONST)
 409                 time_constant = txc.time_constant;
 410 
 411             if (txc.mode & ADJ_OFFSET)
 412               if (txc.mode == ADJ_OFFSET_SINGLESHOT)
 413                 {
 414                   time_adjust = txc.offset;
 415                 }
 416               else /* XXX should give an error if other bits set */
 417                 {
 418                   time_offset = txc.offset << SHIFT_UPDATE;
 419                   mtemp = xtime.tv_sec - time_reftime;
 420                   time_reftime = xtime.tv_sec;
 421                   if (mtemp > (MAXSEC+2) || mtemp < 0)
 422                     mtemp = 0;
 423 
 424                   if (txc.offset < 0)
 425                     time_freq -= (-txc.offset * mtemp) >>
 426                       (time_constant + time_constant);
 427                   else
 428                     time_freq += (txc.offset * mtemp) >>
 429                       (time_constant + time_constant);
 430 
 431                   ltemp = time_tolerance << SHIFT_KF;
 432 
 433                   if (time_freq > ltemp)
 434                     time_freq = ltemp;
 435                   else if (time_freq < -ltemp)
 436                     time_freq = -ltemp;
 437                 }
 438             if (txc.mode & ADJ_TICK)
 439               tick = txc.tick;
 440 
 441         }
 442         txc.offset         = save_adjust;
 443         txc.frequency      = ((time_freq+1) >> (SHIFT_KF - 16));
 444         txc.maxerror       = time_maxerror;
 445         txc.esterror       = time_esterror;
 446         txc.status         = time_status;
 447         txc.time_constant  = time_constant;
 448         txc.precision      = time_precision;
 449         txc.tolerance      = time_tolerance;
 450         txc.time           = xtime;
 451         txc.tick           = tick;
 452 
 453         sti();
 454 
 455         memcpy_tofs(txc_p, &txc, sizeof(struct timex));
 456         return time_status;
 457 }
 458 
 459 /*
 460  * In order to set the CMOS clock precisely, set_rtc_mmss has to be
 461  * called 500 ms after the second nowtime has started, because when
 462  * nowtime is written into the registers of the CMOS clock, it will
 463  * jump to the next second precisely 500 ms later. Check the Motorola
 464  * MC146818A or Dallas DS12887 data sheet for details.
 465  */
 466 int set_rtc_mmss(unsigned long nowtime)
     /* [previous][next][first][last][top][bottom][index][help] */
 467 {
 468   int retval = 0;
 469   int real_seconds, real_minutes, cmos_minutes;
 470   unsigned char save_control, save_freq_select;
 471 
 472   save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being set */
 473   CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
 474 
 475   save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset prescaler */
 476   CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
 477 
 478   cmos_minutes = CMOS_READ(RTC_MINUTES);
 479   if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
 480     BCD_TO_BIN(cmos_minutes);
 481 
 482   /* since we're only adjusting minutes and seconds,
 483    * don't interfere with hour overflow. This avoids
 484    * messing with unknown time zones but requires your
 485    * RTC not to be off by more than 15 minutes
 486    */
 487   real_seconds = nowtime % 60;
 488   real_minutes = nowtime / 60;
 489   if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1)
 490     real_minutes += 30;         /* correct for half hour time zone */
 491   real_minutes %= 60;
 492 
 493   if (abs(real_minutes - cmos_minutes) < 30)
 494     {
 495       if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
 496         {
 497           BIN_TO_BCD(real_seconds);
 498           BIN_TO_BCD(real_minutes);
 499         }
 500       CMOS_WRITE(real_seconds,RTC_SECONDS);
 501       CMOS_WRITE(real_minutes,RTC_MINUTES);
 502     }
 503   else
 504     retval = -1;
 505 
 506   /* The following flags have to be released exactly in this order,
 507    * otherwise the DS12887 (popular MC146818A clone with integrated
 508    * battery and quartz) will not reset the oscillator and will not
 509    * update precisely 500 ms later. You won't find this mentioned in
 510    * the Dallas Semiconductor data sheets, but who believes data
 511    * sheets anyway ...                           -- Markus Kuhn
 512    */
 513   CMOS_WRITE(save_control, RTC_CONTROL);
 514   CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
 515 
 516   return retval;
 517 }

/* [previous][next][first][last][top][bottom][index][help] */