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

Cache object: cf5959426fadee97b14e1f846f2882e2


[ 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.