The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/i386/isa/clock.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1990 The Regents of the University of California.
    3  * All rights reserved.
    4  *
    5  * This code is derived from software contributed to Berkeley by
    6  * William Jolitz and Don Ahn.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  * 3. All advertising materials mentioning features or use of this software
   17  *    must display the following acknowledgement:
   18  *      This product includes software developed by the University of
   19  *      California, Berkeley and its contributors.
   20  * 4. Neither the name of the University nor the names of its contributors
   21  *    may be used to endorse or promote products derived from this software
   22  *    without specific prior written permission.
   23  *
   24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   34  * SUCH DAMAGE.
   35  *
   36  *      from: @(#)clock.c       7.2 (Berkeley) 5/12/91
   37  */
   38 
   39 #include <sys/cdefs.h>
   40 __FBSDID("$FreeBSD: releng/5.2/sys/i386/isa/clock.c 122609 2003-11-13 10:02:12Z phk $");
   41 
   42 /*
   43  * Routines to handle clock hardware.
   44  */
   45 
   46 /*
   47  * inittodr, settodr and support routines written
   48  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
   49  *
   50  * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
   51  */
   52 
   53 #include "opt_clock.h"
   54 #include "opt_isa.h"
   55 #include "opt_mca.h"
   56 
   57 #include <sys/param.h>
   58 #include <sys/systm.h>
   59 #include <sys/bus.h>
   60 #include <sys/lock.h>
   61 #include <sys/mutex.h>
   62 #include <sys/proc.h>
   63 #include <sys/time.h>
   64 #include <sys/timetc.h>
   65 #include <sys/kernel.h>
   66 #include <sys/limits.h>
   67 #include <sys/sysctl.h>
   68 #include <sys/cons.h>
   69 #include <sys/power.h>
   70 
   71 #include <machine/clock.h>
   72 #include <machine/cputypes.h>
   73 #include <machine/frame.h>
   74 #include <machine/intr_machdep.h>
   75 #include <machine/md_var.h>
   76 #include <machine/psl.h>
   77 #if defined(SMP)
   78 #include <machine/smp.h>
   79 #endif
   80 #include <machine/specialreg.h>
   81 
   82 #include <i386/isa/icu.h>
   83 #include <i386/isa/isa.h>
   84 #include <isa/rtc.h>
   85 #ifdef DEV_ISA
   86 #include <isa/isavar.h>
   87 #endif
   88 #include <i386/isa/timerreg.h>
   89 
   90 #ifdef DEV_MCA
   91 #include <i386/bios/mca_machdep.h>
   92 #endif
   93 
   94 /*
   95  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
   96  * can use a simple formula for leap years.
   97  */
   98 #define LEAPYEAR(y) (((u_int)(y) % 4 == 0) ? 1 : 0)
   99 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
  100 
  101 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
  102 
  103 #ifndef BURN_BRIDGES
  104 /*
  105  * Time in timer cycles that it takes for microtime() to disable interrupts
  106  * and latch the count.  microtime() currently uses "cli; outb ..." so it
  107  * normally takes less than 2 timer cycles.  Add a few for cache misses.
  108  * Add a few more to allow for latency in bogus calls to microtime() with
  109  * interrupts already disabled.
  110  */
  111 #define TIMER0_LATCH_COUNT      20
  112 
  113 /*
  114  * Maximum frequency that we are willing to allow for timer0.  Must be
  115  * low enough to guarantee that the timer interrupt handler returns
  116  * before the next timer interrupt.
  117  */
  118 #define TIMER0_MAX_FREQ         20000
  119 #endif
  120 
  121 int     adjkerntz;              /* local offset from GMT in seconds */
  122 int     clkintr_pending;
  123 int     disable_rtc_set;        /* disable resettodr() if != 0 */
  124 int     pscnt = 1;
  125 int     psdiv = 1;
  126 int     statclock_disable;
  127 #ifndef TIMER_FREQ
  128 #define TIMER_FREQ   1193182
  129 #endif
  130 u_int   timer_freq = TIMER_FREQ;
  131 int     timer0_max_count;
  132 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
  133 struct mtx clock_lock;
  134 
  135 static  int     beeping = 0;
  136 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
  137 static  u_int   hardclock_max_count;
  138 static  u_int32_t i8254_lastcount;
  139 static  u_int32_t i8254_offset;
  140 static  int     i8254_ticked;
  141 static  struct intsrc *i8254_intsrc;
  142 #ifndef BURN_BRIDGES
  143 /*
  144  * XXX new_function and timer_func should not handle clockframes, but
  145  * timer_func currently needs to hold hardclock to handle the
  146  * timer0_state == 0 case.  We should use inthand_add()/inthand_remove()
  147  * to switch between clkintr() and a slightly different timerintr().
  148  */
  149 static  void    (*new_function)(struct clockframe *frame);
  150 static  u_int   new_rate;
  151 static  u_int   timer0_prescaler_count;
  152 static  u_char  timer0_state;
  153 #endif
  154 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
  155 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
  156 
  157 /* Values for timerX_state: */
  158 #define RELEASED        0
  159 #define RELEASE_PENDING 1
  160 #define ACQUIRED        2
  161 #define ACQUIRE_PENDING 3
  162 
  163 static  u_char  timer2_state;
  164 static  void    (*timer_func)(struct clockframe *frame) = hardclock;
  165 
  166 static  unsigned i8254_get_timecount(struct timecounter *tc);
  167 static  void    set_timer_freq(u_int freq, int intr_freq);
  168 
  169 static struct timecounter i8254_timecounter = {
  170         i8254_get_timecount,    /* get_timecount */
  171         0,                      /* no poll_pps */
  172         ~0u,                    /* counter_mask */
  173         0,                      /* frequency */
  174         "i8254",                /* name */
  175         0                       /* quality */
  176 };
  177 
  178 static void
  179 clkintr(struct clockframe *frame)
  180 {
  181 
  182         if (timecounter->tc_get_timecount == i8254_get_timecount) {
  183                 mtx_lock_spin(&clock_lock);
  184                 if (i8254_ticked)
  185                         i8254_ticked = 0;
  186                 else {
  187                         i8254_offset += timer0_max_count;
  188                         i8254_lastcount = 0;
  189                 }
  190                 clkintr_pending = 0;
  191                 mtx_unlock_spin(&clock_lock);
  192         }
  193         timer_func(frame);
  194 #ifdef SMP
  195         if (timer_func == hardclock)
  196                 forward_hardclock();
  197 #endif
  198 #ifndef BURN_BRIDGES
  199         switch (timer0_state) {
  200 
  201         case RELEASED:
  202                 break;
  203 
  204         case ACQUIRED:
  205                 if ((timer0_prescaler_count += timer0_max_count)
  206                     >= hardclock_max_count) {
  207                         timer0_prescaler_count -= hardclock_max_count;
  208                         hardclock(frame);
  209 #ifdef SMP
  210                         forward_hardclock();
  211 #endif
  212                 }
  213                 break;
  214 
  215         case ACQUIRE_PENDING:
  216                 mtx_lock_spin(&clock_lock);
  217                 i8254_offset = i8254_get_timecount(NULL);
  218                 i8254_lastcount = 0;
  219                 timer0_max_count = TIMER_DIV(new_rate);
  220                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
  221                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
  222                 outb(TIMER_CNTR0, timer0_max_count >> 8);
  223                 mtx_unlock_spin(&clock_lock);
  224                 timer_func = new_function;
  225                 timer0_state = ACQUIRED;
  226                 break;
  227 
  228         case RELEASE_PENDING:
  229                 if ((timer0_prescaler_count += timer0_max_count)
  230                     >= hardclock_max_count) {
  231                         mtx_lock_spin(&clock_lock);
  232                         i8254_offset = i8254_get_timecount(NULL);
  233                         i8254_lastcount = 0;
  234                         timer0_max_count = hardclock_max_count;
  235                         outb(TIMER_MODE,
  236                              TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
  237                         outb(TIMER_CNTR0, timer0_max_count & 0xff);
  238                         outb(TIMER_CNTR0, timer0_max_count >> 8);
  239                         mtx_unlock_spin(&clock_lock);
  240                         timer0_prescaler_count = 0;
  241                         timer_func = hardclock;
  242                         timer0_state = RELEASED;
  243                         hardclock(frame);
  244 #ifdef SMP
  245                         forward_hardclock();
  246 #endif
  247                 }
  248                 break;
  249         }
  250 #endif
  251 #ifdef DEV_MCA
  252         /* Reset clock interrupt by asserting bit 7 of port 0x61 */
  253         if (MCA_system)
  254                 outb(0x61, inb(0x61) | 0x80);
  255 #endif
  256 }
  257 
  258 #ifndef BURN_BRIDGES
  259 /*
  260  * The acquire and release functions must be called at ipl >= splclock().
  261  */
  262 int
  263 acquire_timer0(int rate, void (*function)(struct clockframe *frame))
  264 {
  265         static int old_rate;
  266 
  267         if (rate <= 0 || rate > TIMER0_MAX_FREQ)
  268                 return (-1);
  269         switch (timer0_state) {
  270 
  271         case RELEASED:
  272                 timer0_state = ACQUIRE_PENDING;
  273                 break;
  274 
  275         case RELEASE_PENDING:
  276                 if (rate != old_rate)
  277                         return (-1);
  278                 /*
  279                  * The timer has been released recently, but is being
  280                  * re-acquired before the release completed.  In this
  281                  * case, we simply reclaim it as if it had not been
  282                  * released at all.
  283                  */
  284                 timer0_state = ACQUIRED;
  285                 break;
  286 
  287         default:
  288                 return (-1);    /* busy */
  289         }
  290         new_function = function;
  291         old_rate = new_rate = rate;
  292         return (0);
  293 }
  294 #endif
  295 
  296 int
  297 acquire_timer2(int mode)
  298 {
  299 
  300         if (timer2_state != RELEASED)
  301                 return (-1);
  302         timer2_state = ACQUIRED;
  303 
  304         /*
  305          * This access to the timer registers is as atomic as possible
  306          * because it is a single instruction.  We could do better if we
  307          * knew the rate.  Use of splclock() limits glitches to 10-100us,
  308          * and this is probably good enough for timer2, so we aren't as
  309          * careful with it as with timer0.
  310          */
  311         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
  312 
  313         return (0);
  314 }
  315 
  316 #ifndef BURN_BRIDGES
  317 int
  318 release_timer0()
  319 {
  320         switch (timer0_state) {
  321 
  322         case ACQUIRED:
  323                 timer0_state = RELEASE_PENDING;
  324                 break;
  325 
  326         case ACQUIRE_PENDING:
  327                 /* Nothing happened yet, release quickly. */
  328                 timer0_state = RELEASED;
  329                 break;
  330 
  331         default:
  332                 return (-1);
  333         }
  334         return (0);
  335 }
  336 #endif
  337 
  338 int
  339 release_timer2()
  340 {
  341 
  342         if (timer2_state != ACQUIRED)
  343                 return (-1);
  344         timer2_state = RELEASED;
  345         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
  346         return (0);
  347 }
  348 
  349 /*
  350  * This routine receives statistical clock interrupts from the RTC.
  351  * As explained above, these occur at 128 interrupts per second.
  352  * When profiling, we receive interrupts at a rate of 1024 Hz.
  353  *
  354  * This does not actually add as much overhead as it sounds, because
  355  * when the statistical clock is active, the hardclock driver no longer
  356  * needs to keep (inaccurate) statistics on its own.  This decouples
  357  * statistics gathering from scheduling interrupts.
  358  *
  359  * The RTC chip requires that we read status register C (RTC_INTR)
  360  * to acknowledge an interrupt, before it will generate the next one.
  361  * Under high interrupt load, rtcintr() can be indefinitely delayed and
  362  * the clock can tick immediately after the read from RTC_INTR.  In this
  363  * case, the mc146818A interrupt signal will not drop for long enough
  364  * to register with the 8259 PIC.  If an interrupt is missed, the stat
  365  * clock will halt, considerably degrading system performance.  This is
  366  * why we use 'while' rather than a more straightforward 'if' below.
  367  * Stat clock ticks can still be lost, causing minor loss of accuracy
  368  * in the statistics, but the stat clock will no longer stop.
  369  */
  370 static void
  371 rtcintr(struct clockframe *frame)
  372 {
  373         while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
  374                 if (profprocs != 0) {
  375                         if (--pscnt == 0)
  376                                 pscnt = psdiv;
  377                         profclock(frame);
  378                 }
  379                 if (pscnt == psdiv)
  380                         statclock(frame);
  381 #ifdef SMP
  382                 forward_statclock();
  383 #endif
  384         }
  385 }
  386 
  387 #include "opt_ddb.h"
  388 #ifdef DDB
  389 #include <ddb/ddb.h>
  390 
  391 DB_SHOW_COMMAND(rtc, rtc)
  392 {
  393         printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
  394                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
  395                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
  396                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
  397 }
  398 #endif /* DDB */
  399 
  400 static int
  401 getit(void)
  402 {
  403         int high, low;
  404 
  405         mtx_lock_spin(&clock_lock);
  406 
  407         /* Select timer0 and latch counter value. */
  408         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
  409 
  410         low = inb(TIMER_CNTR0);
  411         high = inb(TIMER_CNTR0);
  412 
  413         mtx_unlock_spin(&clock_lock);
  414         return ((high << 8) | low);
  415 }
  416 
  417 /*
  418  * Wait "n" microseconds.
  419  * Relies on timer 1 counting down from (timer_freq / hz)
  420  * Note: timer had better have been programmed before this is first used!
  421  */
  422 void
  423 DELAY(int n)
  424 {
  425         int delta, prev_tick, tick, ticks_left;
  426 
  427 #ifdef DELAYDEBUG
  428         int getit_calls = 1;
  429         int n1;
  430         static int state = 0;
  431 
  432         if (state == 0) {
  433                 state = 1;
  434                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
  435                         DELAY(n1);
  436                 state = 2;
  437         }
  438         if (state == 1)
  439                 printf("DELAY(%d)...", n);
  440 #endif
  441         /*
  442          * Guard against the timer being uninitialized if we are called
  443          * early for console i/o.
  444          */
  445         if (timer0_max_count == 0)
  446                 set_timer_freq(timer_freq, hz);
  447 
  448         /*
  449          * Read the counter first, so that the rest of the setup overhead is
  450          * counted.  Guess the initial overhead is 20 usec (on most systems it
  451          * takes about 1.5 usec for each of the i/o's in getit().  The loop
  452          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
  453          * multiplications and divisions to scale the count take a while).
  454          *
  455          * However, if ddb is active then use a fake counter since reading
  456          * the i8254 counter involves acquiring a lock.  ddb must not go
  457          * locking for many reasons, but it calls here for at least atkbd
  458          * input.
  459          */
  460 #ifdef DDB
  461         if (db_active)
  462                 prev_tick = 0;
  463         else
  464 #endif
  465                 prev_tick = getit();
  466         n -= 0;                 /* XXX actually guess no initial overhead */
  467         /*
  468          * Calculate (n * (timer_freq / 1e6)) without using floating point
  469          * and without any avoidable overflows.
  470          */
  471         if (n <= 0)
  472                 ticks_left = 0;
  473         else if (n < 256)
  474                 /*
  475                  * Use fixed point to avoid a slow division by 1000000.
  476                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
  477                  * 2^15 is the first power of 2 that gives exact results
  478                  * for n between 0 and 256.
  479                  */
  480                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
  481         else
  482                 /*
  483                  * Don't bother using fixed point, although gcc-2.7.2
  484                  * generates particularly poor code for the long long
  485                  * division, since even the slow way will complete long
  486                  * before the delay is up (unless we're interrupted).
  487                  */
  488                 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
  489                              / 1000000;
  490 
  491         while (ticks_left > 0) {
  492 #ifdef DDB
  493                 if (db_active) {
  494                         inb(0x84);
  495                         tick = prev_tick + 1;
  496                 } else
  497 #endif
  498                         tick = getit();
  499 #ifdef DELAYDEBUG
  500                 ++getit_calls;
  501 #endif
  502                 delta = prev_tick - tick;
  503                 prev_tick = tick;
  504                 if (delta < 0) {
  505                         delta += timer0_max_count;
  506                         /*
  507                          * Guard against timer0_max_count being wrong.
  508                          * This shouldn't happen in normal operation,
  509                          * but it may happen if set_timer_freq() is
  510                          * traced.
  511                          */
  512                         if (delta < 0)
  513                                 delta = 0;
  514                 }
  515                 ticks_left -= delta;
  516         }
  517 #ifdef DELAYDEBUG
  518         if (state == 1)
  519                 printf(" %d calls to getit() at %d usec each\n",
  520                        getit_calls, (n + 5) / getit_calls);
  521 #endif
  522 }
  523 
  524 static void
  525 sysbeepstop(void *chan)
  526 {
  527         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
  528         release_timer2();
  529         beeping = 0;
  530 }
  531 
  532 int
  533 sysbeep(int pitch, int period)
  534 {
  535         int x = splclock();
  536 
  537         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
  538                 if (!beeping) {
  539                         /* Something else owns it. */
  540                         splx(x);
  541                         return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
  542                 }
  543         mtx_lock_spin(&clock_lock);
  544         outb(TIMER_CNTR2, pitch);
  545         outb(TIMER_CNTR2, (pitch>>8));
  546         mtx_unlock_spin(&clock_lock);
  547         if (!beeping) {
  548                 /* enable counter2 output to speaker */
  549                 outb(IO_PPI, inb(IO_PPI) | 3);
  550                 beeping = period;
  551                 timeout(sysbeepstop, (void *)NULL, period);
  552         }
  553         splx(x);
  554         return (0);
  555 }
  556 
  557 /*
  558  * RTC support routines
  559  */
  560 
  561 int
  562 rtcin(reg)
  563         int reg;
  564 {
  565         int s;
  566         u_char val;
  567 
  568         s = splhigh();
  569         outb(IO_RTC, reg);
  570         inb(0x84);
  571         val = inb(IO_RTC + 1);
  572         inb(0x84);
  573         splx(s);
  574         return (val);
  575 }
  576 
  577 static __inline void
  578 writertc(u_char reg, u_char val)
  579 {
  580         int s;
  581 
  582         s = splhigh();
  583         inb(0x84);
  584         outb(IO_RTC, reg);
  585         inb(0x84);
  586         outb(IO_RTC + 1, val);
  587         inb(0x84);              /* XXX work around wrong order in rtcin() */
  588         splx(s);
  589 }
  590 
  591 static __inline int
  592 readrtc(int port)
  593 {
  594         return(bcd2bin(rtcin(port)));
  595 }
  596 
  597 static u_int
  598 calibrate_clocks(void)
  599 {
  600         u_int count, prev_count, tot_count;
  601         int sec, start_sec, timeout;
  602 
  603         if (bootverbose)
  604                 printf("Calibrating clock(s) ... ");
  605         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
  606                 goto fail;
  607         timeout = 100000000;
  608 
  609         /* Read the mc146818A seconds counter. */
  610         for (;;) {
  611                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
  612                         sec = rtcin(RTC_SEC);
  613                         break;
  614                 }
  615                 if (--timeout == 0)
  616                         goto fail;
  617         }
  618 
  619         /* Wait for the mC146818A seconds counter to change. */
  620         start_sec = sec;
  621         for (;;) {
  622                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
  623                         sec = rtcin(RTC_SEC);
  624                         if (sec != start_sec)
  625                                 break;
  626                 }
  627                 if (--timeout == 0)
  628                         goto fail;
  629         }
  630 
  631         /* Start keeping track of the i8254 counter. */
  632         prev_count = getit();
  633         if (prev_count == 0 || prev_count > timer0_max_count)
  634                 goto fail;
  635         tot_count = 0;
  636 
  637         /*
  638          * Wait for the mc146818A seconds counter to change.  Read the i8254
  639          * counter for each iteration since this is convenient and only
  640          * costs a few usec of inaccuracy. The timing of the final reads
  641          * of the counters almost matches the timing of the initial reads,
  642          * so the main cause of inaccuracy is the varying latency from 
  643          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
  644          * rtcin(RTC_SEC) that returns a changed seconds count.  The
  645          * maximum inaccuracy from this cause is < 10 usec on 486's.
  646          */
  647         start_sec = sec;
  648         for (;;) {
  649                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
  650                         sec = rtcin(RTC_SEC);
  651                 count = getit();
  652                 if (count == 0 || count > timer0_max_count)
  653                         goto fail;
  654                 if (count > prev_count)
  655                         tot_count += prev_count - (count - timer0_max_count);
  656                 else
  657                         tot_count += prev_count - count;
  658                 prev_count = count;
  659                 if (sec != start_sec)
  660                         break;
  661                 if (--timeout == 0)
  662                         goto fail;
  663         }
  664 
  665         if (bootverbose) {
  666                 printf("i8254 clock: %u Hz\n", tot_count);
  667         }
  668         return (tot_count);
  669 
  670 fail:
  671         if (bootverbose)
  672                 printf("failed, using default i8254 clock of %u Hz\n",
  673                        timer_freq);
  674         return (timer_freq);
  675 }
  676 
  677 static void
  678 set_timer_freq(u_int freq, int intr_freq)
  679 {
  680         int new_timer0_max_count;
  681 
  682         mtx_lock_spin(&clock_lock);
  683         timer_freq = freq;
  684         new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
  685         if (new_timer0_max_count != timer0_max_count) {
  686                 timer0_max_count = new_timer0_max_count;
  687                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
  688                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
  689                 outb(TIMER_CNTR0, timer0_max_count >> 8);
  690         }
  691         mtx_unlock_spin(&clock_lock);
  692 }
  693 
  694 static void
  695 i8254_restore(void)
  696 {
  697 
  698         mtx_lock_spin(&clock_lock);
  699         outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
  700         outb(TIMER_CNTR0, timer0_max_count & 0xff);
  701         outb(TIMER_CNTR0, timer0_max_count >> 8);
  702         mtx_unlock_spin(&clock_lock);
  703 }
  704 
  705 static void
  706 rtc_restore(void)
  707 {
  708 
  709         /* Restore all of the RTC's "status" (actually, control) registers. */
  710         /* XXX locking is needed for RTC access. */
  711         writertc(RTC_STATUSB, RTCSB_24HR);
  712         writertc(RTC_STATUSA, rtc_statusa);
  713         writertc(RTC_STATUSB, rtc_statusb);
  714 }
  715 
  716 /*
  717  * Restore all the timers non-atomically (XXX: should be atomically).
  718  *
  719  * This function is called from pmtimer_resume() to restore all the timers.
  720  * This should not be necessary, but there are broken laptops that do not
  721  * restore all the timers on resume.
  722  */
  723 void
  724 timer_restore(void)
  725 {
  726 
  727         i8254_restore();                /* restore timer_freq and hz */
  728         rtc_restore();                  /* reenable RTC interrupts */
  729 }
  730 
  731 /*
  732  * Initialize 8254 timer 0 early so that it can be used in DELAY().
  733  * XXX initialization of other timers is unintentionally left blank.
  734  */
  735 void
  736 startrtclock()
  737 {
  738         u_int delta, freq;
  739 
  740         writertc(RTC_STATUSA, rtc_statusa);
  741         writertc(RTC_STATUSB, RTCSB_24HR);
  742 
  743         set_timer_freq(timer_freq, hz);
  744         freq = calibrate_clocks();
  745 #ifdef CLK_CALIBRATION_LOOP
  746         if (bootverbose) {
  747                 printf(
  748                 "Press a key on the console to abort clock calibration\n");
  749                 while (cncheckc() == -1)
  750                         calibrate_clocks();
  751         }
  752 #endif
  753 
  754         /*
  755          * Use the calibrated i8254 frequency if it seems reasonable.
  756          * Otherwise use the default, and don't use the calibrated i586
  757          * frequency.
  758          */
  759         delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
  760         if (delta < timer_freq / 100) {
  761 #ifndef CLK_USE_I8254_CALIBRATION
  762                 if (bootverbose)
  763                         printf(
  764 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
  765                 freq = timer_freq;
  766 #endif
  767                 timer_freq = freq;
  768         } else {
  769                 if (bootverbose)
  770                         printf(
  771                     "%d Hz differs from default of %d Hz by more than 1%%\n",
  772                                freq, timer_freq);
  773         }
  774 
  775         set_timer_freq(timer_freq, hz);
  776         i8254_timecounter.tc_frequency = timer_freq;
  777         tc_init(&i8254_timecounter);
  778 
  779         init_TSC();
  780 }
  781 
  782 /*
  783  * Initialize the time of day register, based on the time base which is, e.g.
  784  * from a filesystem.
  785  */
  786 void
  787 inittodr(time_t base)
  788 {
  789         unsigned long   sec, days;
  790         int             year, month;
  791         int             y, m, s;
  792         struct timespec ts;
  793 
  794         if (base) {
  795                 s = splclock();
  796                 ts.tv_sec = base;
  797                 ts.tv_nsec = 0;
  798                 tc_setclock(&ts);
  799                 splx(s);
  800         }
  801 
  802         /* Look if we have a RTC present and the time is valid */
  803         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
  804                 goto wrong_time;
  805 
  806         /* wait for time update to complete */
  807         /* If RTCSA_TUP is zero, we have at least 244us before next update */
  808         s = splhigh();
  809         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
  810                 splx(s);
  811                 s = splhigh();
  812         }
  813 
  814         days = 0;
  815 #ifdef USE_RTC_CENTURY
  816         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
  817 #else
  818         year = readrtc(RTC_YEAR) + 1900;
  819         if (year < 1970)
  820                 year += 100;
  821 #endif
  822         if (year < 1970) {
  823                 splx(s);
  824                 goto wrong_time;
  825         }
  826         month = readrtc(RTC_MONTH);
  827         for (m = 1; m < month; m++)
  828                 days += daysinmonth[m-1];
  829         if ((month > 2) && LEAPYEAR(year))
  830                 days ++;
  831         days += readrtc(RTC_DAY) - 1;
  832         for (y = 1970; y < year; y++)
  833                 days += DAYSPERYEAR + LEAPYEAR(y);
  834         sec = ((( days * 24 +
  835                   readrtc(RTC_HRS)) * 60 +
  836                   readrtc(RTC_MIN)) * 60 +
  837                   readrtc(RTC_SEC));
  838         /* sec now contains the number of seconds, since Jan 1 1970,
  839            in the local time zone */
  840 
  841         sec += tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
  842 
  843         y = time_second - sec;
  844         if (y <= -2 || y >= 2) {
  845                 /* badly off, adjust it */
  846                 ts.tv_sec = sec;
  847                 ts.tv_nsec = 0;
  848                 tc_setclock(&ts);
  849         }
  850         splx(s);
  851         return;
  852 
  853 wrong_time:
  854         printf("Invalid time in real time clock.\n");
  855         printf("Check and reset the date immediately!\n");
  856 }
  857 
  858 /*
  859  * Write system time back to RTC
  860  */
  861 void
  862 resettodr()
  863 {
  864         unsigned long   tm;
  865         int             y, m, s;
  866 
  867         if (disable_rtc_set)
  868                 return;
  869 
  870         s = splclock();
  871         tm = time_second;
  872         splx(s);
  873 
  874         /* Disable RTC updates and interrupts. */
  875         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
  876 
  877         /* Calculate local time to put in RTC */
  878 
  879         tm -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
  880 
  881         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
  882         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
  883         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
  884 
  885         /* We have now the days since 01-01-1970 in tm */
  886         writertc(RTC_WDAY, (tm + 4) % 7 + 1);           /* Write back Weekday */
  887         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
  888              tm >= m;
  889              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
  890              tm -= m;
  891 
  892         /* Now we have the years in y and the day-of-the-year in tm */
  893         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
  894 #ifdef USE_RTC_CENTURY
  895         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
  896 #endif
  897         for (m = 0; ; m++) {
  898                 int ml;
  899 
  900                 ml = daysinmonth[m];
  901                 if (m == 1 && LEAPYEAR(y))
  902                         ml++;
  903                 if (tm < ml)
  904                         break;
  905                 tm -= ml;
  906         }
  907 
  908         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
  909         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
  910 
  911         /* Reenable RTC updates and interrupts. */
  912         writertc(RTC_STATUSB, rtc_statusb);
  913 }
  914 
  915 
  916 /*
  917  * Start both clocks running.
  918  */
  919 void
  920 cpu_initclocks()
  921 {
  922         int diag;
  923 
  924         if (statclock_disable) {
  925                 /*
  926                  * The stat interrupt mask is different without the
  927                  * statistics clock.  Also, don't set the interrupt
  928                  * flag which would normally cause the RTC to generate
  929                  * interrupts.
  930                  */
  931                 rtc_statusb = RTCSB_24HR;
  932         } else {
  933                 /* Setting stathz to nonzero early helps avoid races. */
  934                 stathz = RTC_NOPROFRATE;
  935                 profhz = RTC_PROFRATE;
  936         }
  937 
  938         /* Finish initializing 8254 timer 0. */
  939         intr_add_handler("clk", 0, (driver_intr_t *)clkintr, NULL,
  940             INTR_TYPE_CLK | INTR_FAST, NULL);
  941 
  942         /* Initialize RTC. */
  943         writertc(RTC_STATUSA, rtc_statusa);
  944         writertc(RTC_STATUSB, RTCSB_24HR);
  945 
  946         /* Don't bother enabling the statistics clock. */
  947         if (!statclock_disable) {
  948                 diag = rtcin(RTC_DIAG);
  949                 if (diag != 0)
  950                         printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
  951 
  952                 intr_add_handler("rtc", 8, (driver_intr_t *)rtcintr, NULL,
  953                     INTR_TYPE_CLK | INTR_FAST, NULL);
  954                 i8254_intsrc = intr_lookup_source(8);
  955 
  956                 writertc(RTC_STATUSB, rtc_statusb);
  957         }
  958 
  959         init_TSC_tc();
  960 }
  961 
  962 void
  963 cpu_startprofclock(void)
  964 {
  965 
  966         rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
  967         writertc(RTC_STATUSA, rtc_statusa);
  968         psdiv = pscnt = psratio;
  969 }
  970 
  971 void
  972 cpu_stopprofclock(void)
  973 {
  974 
  975         rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
  976         writertc(RTC_STATUSA, rtc_statusa);
  977         psdiv = pscnt = 1;
  978 }
  979 
  980 static int
  981 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
  982 {
  983         int error;
  984         u_int freq;
  985 
  986         /*
  987          * Use `i8254' instead of `timer' in external names because `timer'
  988          * is is too generic.  Should use it everywhere.
  989          */
  990         freq = timer_freq;
  991         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
  992         if (error == 0 && req->newptr != NULL) {
  993 #ifndef BURN_BRIDGES
  994                 if (timer0_state != RELEASED)
  995                         return (EBUSY); /* too much trouble to handle */
  996 #endif
  997                 set_timer_freq(freq, hz);
  998                 i8254_timecounter.tc_frequency = freq;
  999         }
 1000         return (error);
 1001 }
 1002 
 1003 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
 1004     0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
 1005 
 1006 static unsigned
 1007 i8254_get_timecount(struct timecounter *tc)
 1008 {
 1009         u_int count;
 1010         u_int high, low;
 1011         u_int eflags;
 1012 
 1013         eflags = read_eflags();
 1014         mtx_lock_spin(&clock_lock);
 1015 
 1016         /* Select timer0 and latch counter value. */
 1017         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
 1018 
 1019         low = inb(TIMER_CNTR0);
 1020         high = inb(TIMER_CNTR0);
 1021         count = timer0_max_count - ((high << 8) | low);
 1022         if (count < i8254_lastcount ||
 1023             (!i8254_ticked && (clkintr_pending ||
 1024             ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
 1025             i8254_intsrc != NULL &&
 1026             i8254_intsrc->is_pic->pic_source_pending(i8254_intsrc))))) {
 1027                 i8254_ticked = 1;
 1028                 i8254_offset += timer0_max_count;
 1029         }
 1030         i8254_lastcount = count;
 1031         count += i8254_offset;
 1032         mtx_unlock_spin(&clock_lock);
 1033         return (count);
 1034 }
 1035 
 1036 #ifdef DEV_ISA
 1037 /*
 1038  * Attach to the ISA PnP descriptors for the timer and realtime clock.
 1039  */
 1040 static struct isa_pnp_id attimer_ids[] = {
 1041         { 0x0001d041 /* PNP0100 */, "AT timer" },
 1042         { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
 1043         { 0 }
 1044 };
 1045 
 1046 static int
 1047 attimer_probe(device_t dev)
 1048 {
 1049         int result;
 1050         
 1051         if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
 1052                 device_quiet(dev);
 1053         return(result);
 1054 }
 1055 
 1056 static int
 1057 attimer_attach(device_t dev)
 1058 {
 1059         return(0);
 1060 }
 1061 
 1062 static device_method_t attimer_methods[] = {
 1063         /* Device interface */
 1064         DEVMETHOD(device_probe,         attimer_probe),
 1065         DEVMETHOD(device_attach,        attimer_attach),
 1066         DEVMETHOD(device_detach,        bus_generic_detach),
 1067         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
 1068         DEVMETHOD(device_suspend,       bus_generic_suspend),   /* XXX stop statclock? */
 1069         DEVMETHOD(device_resume,        bus_generic_resume),    /* XXX restart statclock? */
 1070         { 0, 0 }
 1071 };
 1072 
 1073 static driver_t attimer_driver = {
 1074         "attimer",
 1075         attimer_methods,
 1076         1,              /* no softc */
 1077 };
 1078 
 1079 static devclass_t attimer_devclass;
 1080 
 1081 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
 1082 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
 1083 #endif /* DEV_ISA */

Cache object: a7473eb52614770b8031bfd991e2e61a


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.