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

Cache object: 5a61c52ba792a56151189d5d53d45ccc


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