2 * Copyright (c) 1990 The Regents of the University of California.
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz and Don Ahn.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
36 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
37 * $FreeBSD: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki Exp $
38 * $DragonFly: src/sys/i386/isa/Attic/clock.c,v 1.5 2003/08/07 21:17:23 dillon Exp $
42 * Routines to handle clock hardware.
46 * inittodr, settodr and support routines written
47 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
49 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
54 #include "opt_clock.h"
56 #include <sys/param.h>
57 #include <sys/systm.h>
59 #include <sys/kernel.h>
63 #include <sys/sysctl.h>
66 #include <machine/clock.h>
67 #ifdef CLK_CALIBRATION_LOOP
69 #include <machine/cputypes.h>
70 #include <machine/frame.h>
71 #include <machine/ipl.h>
72 #include <machine/limits.h>
73 #include <machine/md_var.h>
74 #include <machine/psl.h>
76 #include <machine/segments.h>
78 #if defined(SMP) || defined(APIC_IO)
79 #include <machine/smp.h>
80 #endif /* SMP || APIC_IO */
81 #include <machine/specialreg.h>
83 #include <i386/isa/icu.h>
84 #include <bus/isa/i386/isa.h>
85 #include <bus/isa/rtc.h>
86 #include <i386/isa/timerreg.h>
88 #include <i386/isa/intr_machdep.h>
91 #include <bus/mca/i386/mca_machdep.h>
95 #include <i386/isa/intr_machdep.h>
96 /* The interrupt triggered by the 8254 (timer) chip */
98 static u_long read_intr_count __P((int vec));
99 static void setup_8254_mixed_mode __P((void));
103 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
104 * can use a simple formula for leap years.
106 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
107 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
109 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
112 * Time in timer cycles that it takes for microtime() to disable interrupts
113 * and latch the count. microtime() currently uses "cli; outb ..." so it
114 * normally takes less than 2 timer cycles. Add a few for cache misses.
115 * Add a few more to allow for latency in bogus calls to microtime() with
116 * interrupts already disabled.
118 #define TIMER0_LATCH_COUNT 20
121 * Maximum frequency that we are willing to allow for timer0. Must be
122 * low enough to guarantee that the timer interrupt handler returns
123 * before the next timer interrupt.
125 #define TIMER0_MAX_FREQ 20000
127 int adjkerntz; /* local offset from GMT in seconds */
129 int disable_rtc_set; /* disable resettodr() if != 0 */
130 volatile u_int idelayed;
131 int statclock_disable;
132 u_int stat_imask = SWI_CLOCK_MASK;
134 #define TIMER_FREQ 1193182
136 u_int timer_freq = TIMER_FREQ;
137 int timer0_max_count;
140 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
142 static int beeping = 0;
143 static u_int clk_imask = HWI_MASK | SWI_MASK;
144 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
145 static u_int hardclock_max_count;
146 static u_int32_t i8254_lastcount;
147 static u_int32_t i8254_offset;
148 static int i8254_ticked;
150 * XXX new_function and timer_func should not handle clockframes, but
151 * timer_func currently needs to hold hardclock to handle the
152 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
153 * to switch between clkintr() and a slightly different timerintr().
155 static void (*new_function) __P((struct clockframe *frame));
156 static u_int new_rate;
157 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
158 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
159 static u_int timer0_prescaler_count;
161 /* Values for timerX_state: */
163 #define RELEASE_PENDING 1
165 #define ACQUIRE_PENDING 3
167 static u_char timer0_state;
168 static u_char timer2_state;
169 static void (*timer_func) __P((struct clockframe *frame)) = hardclock;
170 static u_int tsc_present;
172 static unsigned i8254_get_timecount __P((struct timecounter *tc));
173 static unsigned tsc_get_timecount __P((struct timecounter *tc));
174 static void set_timer_freq(u_int freq, int intr_freq);
176 static struct timecounter tsc_timecounter = {
177 tsc_get_timecount, /* get_timecount */
179 ~0u, /* counter_mask */
184 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD,
185 &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
187 static struct timecounter i8254_timecounter = {
188 i8254_get_timecount, /* get_timecount */
190 ~0u, /* counter_mask */
195 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD,
196 &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
199 clkintr(struct clockframe frame)
201 if (timecounter->tc_get_timecount == i8254_get_timecount) {
206 i8254_offset += timer0_max_count;
213 switch (timer0_state) {
220 if ((timer0_prescaler_count += timer0_max_count)
221 >= hardclock_max_count) {
222 timer0_prescaler_count -= hardclock_max_count;
228 case ACQUIRE_PENDING:
230 i8254_offset = i8254_get_timecount(NULL);
232 timer0_max_count = TIMER_DIV(new_rate);
233 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
234 outb(TIMER_CNTR0, timer0_max_count & 0xff);
235 outb(TIMER_CNTR0, timer0_max_count >> 8);
237 timer_func = new_function;
238 timer0_state = ACQUIRED;
242 case RELEASE_PENDING:
243 if ((timer0_prescaler_count += timer0_max_count)
244 >= hardclock_max_count) {
246 i8254_offset = i8254_get_timecount(NULL);
248 timer0_max_count = hardclock_max_count;
250 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
251 outb(TIMER_CNTR0, timer0_max_count & 0xff);
252 outb(TIMER_CNTR0, timer0_max_count >> 8);
254 timer0_prescaler_count = 0;
255 timer_func = hardclock;
256 timer0_state = RELEASED;
263 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
265 outb(0x61, inb(0x61) | 0x80);
270 * The acquire and release functions must be called at ipl >= splclock().
273 acquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
277 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
279 switch (timer0_state) {
282 timer0_state = ACQUIRE_PENDING;
285 case RELEASE_PENDING:
286 if (rate != old_rate)
289 * The timer has been released recently, but is being
290 * re-acquired before the release completed. In this
291 * case, we simply reclaim it as if it had not been
294 timer0_state = ACQUIRED;
298 return (-1); /* busy */
300 new_function = function;
301 old_rate = new_rate = rate;
306 acquire_timer2(int mode)
309 if (timer2_state != RELEASED)
311 timer2_state = ACQUIRED;
314 * This access to the timer registers is as atomic as possible
315 * because it is a single instruction. We could do better if we
316 * knew the rate. Use of splclock() limits glitches to 10-100us,
317 * and this is probably good enough for timer2, so we aren't as
318 * careful with it as with timer0.
320 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
328 switch (timer0_state) {
331 timer0_state = RELEASE_PENDING;
334 case ACQUIRE_PENDING:
335 /* Nothing happened yet, release quickly. */
336 timer0_state = RELEASED;
349 if (timer2_state != ACQUIRED)
351 timer2_state = RELEASED;
352 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
357 * This routine receives statistical clock interrupts from the RTC.
358 * As explained above, these occur at 128 interrupts per second.
359 * When profiling, we receive interrupts at a rate of 1024 Hz.
361 * This does not actually add as much overhead as it sounds, because
362 * when the statistical clock is active, the hardclock driver no longer
363 * needs to keep (inaccurate) statistics on its own. This decouples
364 * statistics gathering from scheduling interrupts.
366 * The RTC chip requires that we read status register C (RTC_INTR)
367 * to acknowledge an interrupt, before it will generate the next one.
368 * Under high interrupt load, rtcintr() can be indefinitely delayed and
369 * the clock can tick immediately after the read from RTC_INTR. In this
370 * case, the mc146818A interrupt signal will not drop for long enough
371 * to register with the 8259 PIC. If an interrupt is missed, the stat
372 * clock will halt, considerably degrading system performance. This is
373 * why we use 'while' rather than a more straightforward 'if' below.
374 * Stat clock ticks can still be lost, causing minor loss of accuracy
375 * in the statistics, but the stat clock will no longer stop.
378 rtcintr(struct clockframe frame)
380 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
388 DB_SHOW_COMMAND(rtc, rtc)
390 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
391 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
392 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
393 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
404 /* Select timer0 and latch counter value. */
405 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
407 low = inb(TIMER_CNTR0);
408 high = inb(TIMER_CNTR0);
411 return ((high << 8) | low);
415 * Wait "n" microseconds.
416 * Relies on timer 1 counting down from (timer_freq / hz)
417 * Note: timer had better have been programmed before this is first used!
422 int delta, prev_tick, tick, ticks_left;
427 static int state = 0;
431 for (n1 = 1; n1 <= 10000000; n1 *= 10)
436 printf("DELAY(%d)...", n);
439 * Guard against the timer being uninitialized if we are called
440 * early for console i/o.
442 if (timer0_max_count == 0)
443 set_timer_freq(timer_freq, hz);
446 * Read the counter first, so that the rest of the setup overhead is
447 * counted. Guess the initial overhead is 20 usec (on most systems it
448 * takes about 1.5 usec for each of the i/o's in getit(). The loop
449 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
450 * multiplications and divisions to scale the count take a while).
453 n -= 0; /* XXX actually guess no initial overhead */
455 * Calculate (n * (timer_freq / 1e6)) without using floating point
456 * and without any avoidable overflows.
462 * Use fixed point to avoid a slow division by 1000000.
463 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
464 * 2^15 is the first power of 2 that gives exact results
465 * for n between 0 and 256.
467 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
470 * Don't bother using fixed point, although gcc-2.7.2
471 * generates particularly poor code for the long long
472 * division, since even the slow way will complete long
473 * before the delay is up (unless we're interrupted).
475 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
478 while (ticks_left > 0) {
483 delta = prev_tick - tick;
486 delta += timer0_max_count;
488 * Guard against timer0_max_count being wrong.
489 * This shouldn't happen in normal operation,
490 * but it may happen if set_timer_freq() is
500 printf(" %d calls to getit() at %d usec each\n",
501 getit_calls, (n + 5) / getit_calls);
506 sysbeepstop(void *chan)
508 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
514 sysbeep(int pitch, int period)
518 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
520 /* Something else owns it. */
522 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
525 outb(TIMER_CNTR2, pitch);
526 outb(TIMER_CNTR2, (pitch>>8));
529 /* enable counter2 output to speaker */
530 outb(IO_PPI, inb(IO_PPI) | 3);
532 timeout(sysbeepstop, (void *)NULL, period);
539 * RTC support routines
552 val = inb(IO_RTC + 1);
559 writertc(u_char reg, u_char val)
567 outb(IO_RTC + 1, val);
568 inb(0x84); /* XXX work around wrong order in rtcin() */
575 return(bcd2bin(rtcin(port)));
579 calibrate_clocks(void)
582 u_int count, prev_count, tot_count;
583 int sec, start_sec, timeout;
586 printf("Calibrating clock(s) ... ");
587 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
591 /* Read the mc146818A seconds counter. */
593 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
594 sec = rtcin(RTC_SEC);
601 /* Wait for the mC146818A seconds counter to change. */
604 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
605 sec = rtcin(RTC_SEC);
606 if (sec != start_sec)
613 /* Start keeping track of the i8254 counter. */
614 prev_count = getit();
615 if (prev_count == 0 || prev_count > timer0_max_count)
622 old_tsc = 0; /* shut up gcc */
625 * Wait for the mc146818A seconds counter to change. Read the i8254
626 * counter for each iteration since this is convenient and only
627 * costs a few usec of inaccuracy. The timing of the final reads
628 * of the counters almost matches the timing of the initial reads,
629 * so the main cause of inaccuracy is the varying latency from
630 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
631 * rtcin(RTC_SEC) that returns a changed seconds count. The
632 * maximum inaccuracy from this cause is < 10 usec on 486's.
636 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
637 sec = rtcin(RTC_SEC);
639 if (count == 0 || count > timer0_max_count)
641 if (count > prev_count)
642 tot_count += prev_count - (count - timer0_max_count);
644 tot_count += prev_count - count;
646 if (sec != start_sec)
653 * Read the cpu cycle counter. The timing considerations are
654 * similar to those for the i8254 clock.
657 tsc_freq = rdtsc() - old_tsc;
661 printf("TSC clock: %u Hz, ", tsc_freq);
662 printf("i8254 clock: %u Hz\n", tot_count);
668 printf("failed, using default i8254 clock of %u Hz\n",
674 set_timer_freq(u_int freq, int intr_freq)
676 int new_timer0_max_count;
680 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
681 if (new_timer0_max_count != timer0_max_count) {
682 timer0_max_count = new_timer0_max_count;
683 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
684 outb(TIMER_CNTR0, timer0_max_count & 0xff);
685 outb(TIMER_CNTR0, timer0_max_count >> 8);
694 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
695 outb(TIMER_CNTR0, timer0_max_count & 0xff);
696 outb(TIMER_CNTR0, timer0_max_count >> 8);
704 /* Restore all of the RTC's "status" (actually, control) registers. */
705 writertc(RTC_STATUSB, RTCSB_24HR);
706 writertc(RTC_STATUSA, rtc_statusa);
707 writertc(RTC_STATUSB, rtc_statusb);
711 * Restore all the timers non-atomically (XXX: should be atomically).
713 * This function is called from apm_default_resume() to restore all the timers.
714 * This should not be necessary, but there are broken laptops that do not
715 * restore all the timers on resume.
721 i8254_restore(); /* restore timer_freq and hz */
722 rtc_restore(); /* reenable RTC interrupts */
726 * Initialize 8254 timer 0 early so that it can be used in DELAY().
727 * XXX initialization of other timers is unintentionally left blank.
734 if (cpu_feature & CPUID_TSC)
739 writertc(RTC_STATUSA, rtc_statusa);
740 writertc(RTC_STATUSB, RTCSB_24HR);
742 set_timer_freq(timer_freq, hz);
743 freq = calibrate_clocks();
744 #ifdef CLK_CALIBRATION_LOOP
747 "Press a key on the console to abort clock calibration\n");
748 while (cncheckc() == -1)
754 * Use the calibrated i8254 frequency if it seems reasonable.
755 * Otherwise use the default, and don't use the calibrated i586
758 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
759 if (delta < timer_freq / 100) {
760 #ifndef CLK_USE_I8254_CALIBRATION
763 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
770 "%d Hz differs from default of %d Hz by more than 1%%\n",
775 set_timer_freq(timer_freq, hz);
776 i8254_timecounter.tc_frequency = timer_freq;
777 init_timecounter(&i8254_timecounter);
779 #ifndef CLK_USE_TSC_CALIBRATION
783 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
787 if (tsc_present && tsc_freq == 0) {
789 * Calibration of the i586 clock relative to the mc146818A
790 * clock failed. Do a less accurate calibration relative
791 * to the i8254 clock.
793 u_int64_t old_tsc = rdtsc();
796 tsc_freq = rdtsc() - old_tsc;
797 #ifdef CLK_USE_TSC_CALIBRATION
799 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
805 * We can not use the TSC in SMP mode, until we figure out a
806 * cheap (impossible), reliable and precise (yeah right!) way
807 * to synchronize the TSCs of all the CPUs.
808 * Curse Intel for leaving the counter out of the I/O APIC.
813 * We can not use the TSC if we support APM. Precise timekeeping
814 * on an APM'ed machine is at best a fools pursuit, since
815 * any and all of the time spent in various SMM code can't
816 * be reliably accounted for. Reading the RTC is your only
817 * source of reliable time info. The i8254 looses too of course
818 * but we need to have some kind of time...
819 * We don't know at this point whether APM is going to be used
820 * or not, nor when it might be activated. Play it safe.
823 #endif /* NAPM > 0 */
825 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
826 tsc_timecounter.tc_frequency = tsc_freq;
827 init_timecounter(&tsc_timecounter);
830 #endif /* !defined(SMP) */
834 * Initialize the time of day register, based on the time base which is, e.g.
838 inittodr(time_t base)
840 unsigned long sec, days;
850 set_timecounter(&ts);
854 /* Look if we have a RTC present and the time is valid */
855 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
858 /* wait for time update to complete */
859 /* If RTCSA_TUP is zero, we have at least 244us before next update */
861 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
867 #ifdef USE_RTC_CENTURY
868 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
870 year = readrtc(RTC_YEAR) + 1900;
878 month = readrtc(RTC_MONTH);
879 for (m = 1; m < month; m++)
880 days += daysinmonth[m-1];
881 if ((month > 2) && LEAPYEAR(year))
883 days += readrtc(RTC_DAY) - 1;
885 for (y = 1970; y < year; y++)
886 days += DAYSPERYEAR + LEAPYEAR(y);
887 sec = ((( days * 24 +
888 readrtc(RTC_HRS)) * 60 +
889 readrtc(RTC_MIN)) * 60 +
891 /* sec now contains the number of seconds, since Jan 1 1970,
892 in the local time zone */
894 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
896 y = time_second - sec;
897 if (y <= -2 || y >= 2) {
898 /* badly off, adjust it */
901 set_timecounter(&ts);
907 printf("Invalid time in real time clock.\n");
908 printf("Check and reset the date immediately!\n");
912 * Write system time back to RTC
927 /* Disable RTC updates and interrupts. */
928 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
930 /* Calculate local time to put in RTC */
932 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
934 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
935 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
936 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
938 /* We have now the days since 01-01-1970 in tm */
939 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
940 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
942 y++, m = DAYSPERYEAR + LEAPYEAR(y))
945 /* Now we have the years in y and the day-of-the-year in tm */
946 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
947 #ifdef USE_RTC_CENTURY
948 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
954 if (m == 1 && LEAPYEAR(y))
961 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
962 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
964 /* Reenable RTC updates and interrupts. */
965 writertc(RTC_STATUSB, rtc_statusb);
970 * Start both clocks running.
978 struct intrec *clkdesc;
981 if (statclock_disable) {
983 * The stat interrupt mask is different without the
984 * statistics clock. Also, don't set the interrupt
985 * flag which would normally cause the RTC to generate
988 stat_imask = HWI_MASK | SWI_MASK;
989 rtc_statusb = RTCSB_24HR;
991 /* Setting stathz to nonzero early helps avoid races. */
992 stathz = RTC_NOPROFRATE;
993 profhz = RTC_PROFRATE;
996 /* Finish initializing 8253 timer 0. */
999 apic_8254_intr = isa_apic_irq(0);
1000 apic_8254_trial = 0;
1001 if (apic_8254_intr >= 0 ) {
1002 if (apic_int_type(0, 0) == 3)
1003 apic_8254_trial = 1;
1005 /* look for ExtInt on pin 0 */
1006 if (apic_int_type(0, 0) == 3) {
1007 apic_8254_intr = apic_irq(0, 0);
1008 setup_8254_mixed_mode();
1010 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1013 clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
1014 NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1015 INTREN(1 << apic_8254_intr);
1019 inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
1020 INTR_EXCL | INTR_FAST);
1023 #endif /* APIC_IO */
1025 /* Initialize RTC. */
1026 writertc(RTC_STATUSA, rtc_statusa);
1027 writertc(RTC_STATUSB, RTCSB_24HR);
1029 /* Don't bother enabling the statistics clock. */
1030 if (statclock_disable)
1032 diag = rtcin(RTC_DIAG);
1034 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1037 if (isa_apic_irq(8) != 8)
1038 panic("APIC RTC != 8");
1039 #endif /* APIC_IO */
1041 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
1042 INTR_EXCL | INTR_FAST);
1048 #endif /* APIC_IO */
1050 writertc(RTC_STATUSB, rtc_statusb);
1053 if (apic_8254_trial) {
1055 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1056 while (read_intr_count(8) < 6)
1058 if (read_intr_count(apic_8254_intr) < 3) {
1060 * The MP table is broken.
1061 * The 8254 was not connected to the specified pin
1063 * Workaround: Limited variant of mixed mode.
1065 INTRDIS(1 << apic_8254_intr);
1066 inthand_remove(clkdesc);
1067 printf("APIC_IO: Broken MP table detected: "
1068 "8254 is not connected to "
1069 "IOAPIC #%d intpin %d\n",
1070 int_to_apicintpin[apic_8254_intr].ioapic,
1071 int_to_apicintpin[apic_8254_intr].int_pin);
1073 * Revoke current ISA IRQ 0 assignment and
1074 * configure a fallback interrupt routing from
1075 * the 8254 Timer via the 8259 PIC to the
1076 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1077 * We reuse the low level interrupt handler number.
1079 if (apic_irq(0, 0) < 0) {
1080 revoke_apic_irq(apic_8254_intr);
1081 assign_apic_irq(0, 0, apic_8254_intr);
1083 apic_8254_intr = apic_irq(0, 0);
1084 setup_8254_mixed_mode();
1085 inthand_add("clk", apic_8254_intr,
1086 (inthand2_t *)clkintr,
1087 NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1088 INTREN(1 << apic_8254_intr);
1092 if (apic_int_type(0, 0) != 3 ||
1093 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1094 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1095 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1096 int_to_apicintpin[apic_8254_intr].ioapic,
1097 int_to_apicintpin[apic_8254_intr].int_pin);
1100 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1107 read_intr_count(int vec)
1110 up = intr_countp[vec];
1117 setup_8254_mixed_mode()
1120 * Allow 8254 timer to INTerrupt 8259:
1121 * re-initialize master 8259:
1122 * reset; prog 4 bytes, single ICU, edge triggered
1124 outb(IO_ICU1, 0x13);
1125 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1126 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1127 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1128 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1130 /* program IO APIC for type 3 INT on INT0 */
1131 if (ext_int_setup(0, 0) < 0)
1132 panic("8254 redirect via APIC pin0 impossible!");
1137 setstatclockrate(int newhz)
1139 if (newhz == RTC_PROFRATE)
1140 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1142 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1143 writertc(RTC_STATUSA, rtc_statusa);
1147 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1153 * Use `i8254' instead of `timer' in external names because `timer'
1154 * is is too generic. Should use it everywhere.
1157 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1158 if (error == 0 && req->newptr != NULL) {
1159 if (timer0_state != RELEASED)
1160 return (EBUSY); /* too much trouble to handle */
1161 set_timer_freq(freq, hz);
1162 i8254_timecounter.tc_frequency = freq;
1163 update_timecounter(&i8254_timecounter);
1168 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1169 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
1172 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1177 if (tsc_timecounter.tc_frequency == 0)
1178 return (EOPNOTSUPP);
1180 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1181 if (error == 0 && req->newptr != NULL) {
1183 tsc_timecounter.tc_frequency = tsc_freq;
1184 update_timecounter(&tsc_timecounter);
1189 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1190 0, sizeof(u_int), sysctl_machdep_tsc_freq, "IU", "");
1193 i8254_get_timecount(struct timecounter *tc)
1202 /* Select timer0 and latch counter value. */
1203 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1205 low = inb(TIMER_CNTR0);
1206 high = inb(TIMER_CNTR0);
1207 count = timer0_max_count - ((high << 8) | low);
1208 if (count < i8254_lastcount ||
1209 (!i8254_ticked && (clkintr_pending ||
1210 ((count < 20 || (!(ef & PSL_I) && count < timer0_max_count / 2u)) &&
1212 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1213 /* XXX this assumes that apic_8254_intr is < 24. */
1214 (lapic_irr1 & (1 << apic_8254_intr))))
1216 (inb(IO_ICU1) & 1)))
1220 i8254_offset += timer0_max_count;
1222 i8254_lastcount = count;
1223 count += i8254_offset;
1229 tsc_get_timecount(struct timecounter *tc)
1234 #ifdef KERN_TIMESTAMP
1235 #define KERN_TIMESTAMP_SIZE 16384
1236 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1237 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1238 sizeof(tsc), "LU", "Kernel timestamps");
1244 tsc[i] = (u_int32_t)rdtsc();
1247 if (i >= KERN_TIMESTAMP_SIZE)
1249 tsc[i] = 0; /* mark last entry */
1251 #endif KERN_TIMESTAMP