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

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