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
41 * Routines to handle clock hardware.
45 * inittodr, settodr and support routines written
46 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
48 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
52 * modified for PC98 by Kakefuda
55 #include "opt_clock.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
63 #include <sys/mutex.h>
66 #include <sys/timetc.h>
67 #include <sys/kernel.h>
68 #include <sys/sysctl.h>
70 #include <sys/power.h>
72 #include <machine/clock.h>
73 #ifdef CLK_CALIBRATION_LOOP
75 #include <machine/cputypes.h>
76 #include <machine/frame.h>
77 #include <machine/limits.h>
78 #include <machine/md_var.h>
79 #include <machine/psl.h>
81 #include <machine/segments.h>
83 #if defined(SMP) || defined(APIC_IO)
84 #include <machine/smp.h>
85 #endif /* SMP || APIC_IO */
86 #include <machine/specialreg.h>
88 #include <i386/isa/icu.h>
90 #include <pc98/pc98/pc98.h>
91 #include <pc98/pc98/pc98_machdep.h>
92 #include <i386/isa/isa_device.h>
94 #include <i386/isa/isa.h>
98 #include <isa/isavar.h>
100 #include <i386/isa/timerreg.h>
102 #include <i386/isa/intr_machdep.h>
105 #include <i386/isa/mca_machdep.h>
109 #include <i386/isa/intr_machdep.h>
110 /* The interrupt triggered by the 8254 (timer) chip */
112 static u_long read_intr_count(int vec);
113 static void setup_8254_mixed_mode(void);
117 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
118 * can use a simple formula for leap years.
120 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
121 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
123 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
126 * Time in timer cycles that it takes for microtime() to disable interrupts
127 * and latch the count. microtime() currently uses "cli; outb ..." so it
128 * normally takes less than 2 timer cycles. Add a few for cache misses.
129 * Add a few more to allow for latency in bogus calls to microtime() with
130 * interrupts already disabled.
132 #define TIMER0_LATCH_COUNT 20
135 * Maximum frequency that we are willing to allow for timer0. Must be
136 * low enough to guarantee that the timer interrupt handler returns
137 * before the next timer interrupt.
139 #define TIMER0_MAX_FREQ 20000
141 int adjkerntz; /* local offset from GMT in seconds */
143 int disable_rtc_set; /* disable resettodr() if != 0 */
144 int statclock_disable;
147 #define TIMER_FREQ 2457600
149 #define TIMER_FREQ 1193182
152 u_int timer_freq = TIMER_FREQ;
153 int timer0_max_count;
157 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
158 struct mtx clock_lock;
160 static int beeping = 0;
161 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
162 static u_int hardclock_max_count;
163 static u_int32_t i8254_lastcount;
164 static u_int32_t i8254_offset;
165 static int i8254_ticked;
167 * XXX new_function and timer_func should not handle clockframes, but
168 * timer_func currently needs to hold hardclock to handle the
169 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
170 * to switch between clkintr() and a slightly different timerintr().
172 static void (*new_function)(struct clockframe *frame);
173 static u_int new_rate;
175 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
176 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
178 static u_int timer0_prescaler_count;
180 /* Values for timerX_state: */
182 #define RELEASE_PENDING 1
184 #define ACQUIRE_PENDING 3
186 static u_char timer0_state;
188 static u_char timer1_state;
190 static u_char timer2_state;
191 static void (*timer_func)(struct clockframe *frame) = hardclock;
193 static void rtc_serialcombit(int);
194 static void rtc_serialcom(int);
195 static int rtc_inb(void);
196 static void rtc_outb(int);
199 static unsigned i8254_get_timecount(struct timecounter *tc);
200 static unsigned tsc_get_timecount(struct timecounter *tc);
201 static void set_timer_freq(u_int freq, int intr_freq);
203 static struct timecounter tsc_timecounter = {
204 tsc_get_timecount, /* get_timecount */
206 ~0u, /* counter_mask */
211 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD,
212 &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
214 static struct timecounter i8254_timecounter = {
215 i8254_get_timecount, /* get_timecount */
217 ~0u, /* counter_mask */
222 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD,
223 &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
226 clkintr(struct clockframe frame)
229 if (timecounter->tc_get_timecount == i8254_get_timecount) {
230 mtx_lock_spin(&clock_lock);
234 i8254_offset += timer0_max_count;
238 mtx_unlock_spin(&clock_lock);
242 if (timer_func == hardclock)
245 switch (timer0_state) {
251 if ((timer0_prescaler_count += timer0_max_count)
252 >= hardclock_max_count) {
253 timer0_prescaler_count -= hardclock_max_count;
261 case ACQUIRE_PENDING:
262 mtx_lock_spin(&clock_lock);
263 i8254_offset = i8254_get_timecount(NULL);
265 timer0_max_count = TIMER_DIV(new_rate);
266 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
267 outb(TIMER_CNTR0, timer0_max_count & 0xff);
268 outb(TIMER_CNTR0, timer0_max_count >> 8);
269 mtx_unlock_spin(&clock_lock);
270 timer_func = new_function;
271 timer0_state = ACQUIRED;
274 case RELEASE_PENDING:
275 if ((timer0_prescaler_count += timer0_max_count)
276 >= hardclock_max_count) {
277 mtx_lock_spin(&clock_lock);
278 i8254_offset = i8254_get_timecount(NULL);
280 timer0_max_count = hardclock_max_count;
282 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
283 outb(TIMER_CNTR0, timer0_max_count & 0xff);
284 outb(TIMER_CNTR0, timer0_max_count >> 8);
285 mtx_unlock_spin(&clock_lock);
286 timer0_prescaler_count = 0;
287 timer_func = hardclock;
288 timer0_state = RELEASED;
297 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
299 outb(0x61, inb(0x61) | 0x80);
304 * The acquire and release functions must be called at ipl >= splclock().
307 acquire_timer0(int rate, void (*function)(struct clockframe *frame))
311 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
313 switch (timer0_state) {
316 timer0_state = ACQUIRE_PENDING;
319 case RELEASE_PENDING:
320 if (rate != old_rate)
323 * The timer has been released recently, but is being
324 * re-acquired before the release completed. In this
325 * case, we simply reclaim it as if it had not been
328 timer0_state = ACQUIRED;
332 return (-1); /* busy */
334 new_function = function;
335 old_rate = new_rate = rate;
341 acquire_timer1(int mode)
344 if (timer1_state != RELEASED)
346 timer1_state = ACQUIRED;
349 * This access to the timer registers is as atomic as possible
350 * because it is a single instruction. We could do better if we
351 * knew the rate. Use of splclock() limits glitches to 10-100us,
352 * and this is probably good enough for timer2, so we aren't as
353 * careful with it as with timer0.
355 outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
362 acquire_timer2(int mode)
365 if (timer2_state != RELEASED)
367 timer2_state = ACQUIRED;
370 * This access to the timer registers is as atomic as possible
371 * because it is a single instruction. We could do better if we
372 * knew the rate. Use of splclock() limits glitches to 10-100us,
373 * and this is probably good enough for timer2, so we aren't as
374 * careful with it as with timer0.
376 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
384 switch (timer0_state) {
387 timer0_state = RELEASE_PENDING;
390 case ACQUIRE_PENDING:
391 /* Nothing happened yet, release quickly. */
392 timer0_state = RELEASED;
406 if (timer1_state != ACQUIRED)
408 timer1_state = RELEASED;
409 outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
418 if (timer2_state != ACQUIRED)
420 timer2_state = RELEASED;
421 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
427 * This routine receives statistical clock interrupts from the RTC.
428 * As explained above, these occur at 128 interrupts per second.
429 * When profiling, we receive interrupts at a rate of 1024 Hz.
431 * This does not actually add as much overhead as it sounds, because
432 * when the statistical clock is active, the hardclock driver no longer
433 * needs to keep (inaccurate) statistics on its own. This decouples
434 * statistics gathering from scheduling interrupts.
436 * The RTC chip requires that we read status register C (RTC_INTR)
437 * to acknowledge an interrupt, before it will generate the next one.
438 * Under high interrupt load, rtcintr() can be indefinitely delayed and
439 * the clock can tick immediately after the read from RTC_INTR. In this
440 * case, the mc146818A interrupt signal will not drop for long enough
441 * to register with the 8259 PIC. If an interrupt is missed, the stat
442 * clock will halt, considerably degrading system performance. This is
443 * why we use 'while' rather than a more straightforward 'if' below.
444 * Stat clock ticks can still be lost, causing minor loss of accuracy
445 * in the statistics, but the stat clock will no longer stop.
448 rtcintr(struct clockframe frame)
450 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
462 DB_SHOW_COMMAND(rtc, rtc)
464 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
465 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
466 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
467 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
470 #endif /* for PC98 */
477 mtx_lock_spin(&clock_lock);
479 /* Select timer0 and latch counter value. */
480 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
482 low = inb(TIMER_CNTR0);
483 high = inb(TIMER_CNTR0);
485 mtx_unlock_spin(&clock_lock);
486 return ((high << 8) | low);
490 * Wait "n" microseconds.
491 * Relies on timer 1 counting down from (timer_freq / hz)
492 * Note: timer had better have been programmed before this is first used!
497 int delta, prev_tick, tick, ticks_left;
502 static int state = 0;
506 for (n1 = 1; n1 <= 10000000; n1 *= 10)
511 printf("DELAY(%d)...", n);
514 * Guard against the timer being uninitialized if we are called
515 * early for console i/o.
517 if (timer0_max_count == 0)
518 set_timer_freq(timer_freq, hz);
521 * Read the counter first, so that the rest of the setup overhead is
522 * counted. Guess the initial overhead is 20 usec (on most systems it
523 * takes about 1.5 usec for each of the i/o's in getit(). The loop
524 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
525 * multiplications and divisions to scale the count take a while).
528 n -= 0; /* XXX actually guess no initial overhead */
530 * Calculate (n * (timer_freq / 1e6)) without using floating point
531 * and without any avoidable overflows.
537 * Use fixed point to avoid a slow division by 1000000.
538 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
539 * 2^15 is the first power of 2 that gives exact results
540 * for n between 0 and 256.
542 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
545 * Don't bother using fixed point, although gcc-2.7.2
546 * generates particularly poor code for the long long
547 * division, since even the slow way will complete long
548 * before the delay is up (unless we're interrupted).
550 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
553 while (ticks_left > 0) {
558 delta = prev_tick - tick;
561 delta += timer0_max_count;
563 * Guard against timer0_max_count being wrong.
564 * This shouldn't happen in normal operation,
565 * but it may happen if set_timer_freq() is
575 printf(" %d calls to getit() at %d usec each\n",
576 getit_calls, (n + 5) / getit_calls);
581 sysbeepstop(void *chan)
583 #ifdef PC98 /* PC98 */
584 outb(IO_PPI, inb(IO_PPI)|0x08); /* disable counter1 output to speaker */
587 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
594 sysbeep(int pitch, int period)
599 if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
601 /* Something else owns it. */
603 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
607 outb(0x3fdb, (pitch>>8));
610 /* enable counter1 output to speaker */
611 outb(IO_PPI, (inb(IO_PPI) & 0xf7));
613 timeout(sysbeepstop, (void *)NULL, period);
616 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
618 /* Something else owns it. */
620 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
622 mtx_lock_spin(&clock_lock);
623 outb(TIMER_CNTR2, pitch);
624 outb(TIMER_CNTR2, (pitch>>8));
625 mtx_unlock_spin(&clock_lock);
627 /* enable counter2 output to speaker */
628 outb(IO_PPI, inb(IO_PPI) | 3);
630 timeout(sysbeepstop, (void *)NULL, period);
639 * RTC support routines
652 val = inb(IO_RTC + 1);
659 writertc(u_char reg, u_char val)
667 outb(IO_RTC + 1, val);
668 inb(0x84); /* XXX work around wrong order in rtcin() */
675 return(bcd2bin(rtcin(port)));
680 unsigned int delaycount;
681 #define FIRST_GUESS 0x2000
682 static void findcpuspeed(void)
687 /* Put counter in count down mode */
688 outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
689 outb(TIMER_CNTR0, 0xff);
690 outb(TIMER_CNTR0, 0xff);
691 for (i = FIRST_GUESS; i; i--)
694 delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
700 calibrate_clocks(void)
703 u_int count, prev_count, tot_count;
704 u_short sec, start_sec;
707 printf("Calibrating clock(s) ... ");
709 if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
710 !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
714 /* Read the ARTIC. */
717 /* Wait for the ARTIC to changes. */
721 if (sec != start_sec)
726 prev_count = getit();
727 if (prev_count == 0 || prev_count > timer0_max_count)
732 wrmsr(0x10, 0LL); /* XXX 0x10 is the MSR for the TSC */
737 if (count == 0 || count > timer0_max_count)
739 if (count > prev_count)
740 tot_count += prev_count - (count - timer0_max_count);
742 tot_count += prev_count - count;
744 if ((sec == start_sec + 1200) ||
746 (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
752 * Read the cpu cycle counter. The timing considerations are
753 * similar to those for the i8254 clock.
760 printf("TSC clock: %u Hz, ", tsc_freq);
761 printf("i8254 clock: %u Hz\n", tot_count);
767 printf("failed, using default i8254 clock of %u Hz\n",
773 calibrate_clocks(void)
776 u_int count, prev_count, tot_count;
777 int sec, start_sec, timeout;
780 printf("Calibrating clock(s) ... ");
781 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
785 /* Read the mc146818A seconds counter. */
787 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
788 sec = rtcin(RTC_SEC);
795 /* Wait for the mC146818A seconds counter to change. */
798 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
799 sec = rtcin(RTC_SEC);
800 if (sec != start_sec)
807 /* Start keeping track of the i8254 counter. */
808 prev_count = getit();
809 if (prev_count == 0 || prev_count > timer0_max_count)
816 old_tsc = 0; /* shut up gcc */
819 * Wait for the mc146818A seconds counter to change. Read the i8254
820 * counter for each iteration since this is convenient and only
821 * costs a few usec of inaccuracy. The timing of the final reads
822 * of the counters almost matches the timing of the initial reads,
823 * so the main cause of inaccuracy is the varying latency from
824 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
825 * rtcin(RTC_SEC) that returns a changed seconds count. The
826 * maximum inaccuracy from this cause is < 10 usec on 486's.
830 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
831 sec = rtcin(RTC_SEC);
833 if (count == 0 || count > timer0_max_count)
835 if (count > prev_count)
836 tot_count += prev_count - (count - timer0_max_count);
838 tot_count += prev_count - count;
840 if (sec != start_sec)
847 * Read the cpu cycle counter. The timing considerations are
848 * similar to those for the i8254 clock.
851 tsc_freq = rdtsc() - old_tsc;
855 printf("TSC clock: %u Hz, ", tsc_freq);
856 printf("i8254 clock: %u Hz\n", tot_count);
862 printf("failed, using default i8254 clock of %u Hz\n",
869 set_timer_freq(u_int freq, int intr_freq)
871 int new_timer0_max_count;
873 mtx_lock_spin(&clock_lock);
875 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
876 if (new_timer0_max_count != timer0_max_count) {
877 timer0_max_count = new_timer0_max_count;
878 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
879 outb(TIMER_CNTR0, timer0_max_count & 0xff);
880 outb(TIMER_CNTR0, timer0_max_count >> 8);
882 mtx_unlock_spin(&clock_lock);
886 * i8254_restore is called from apm_default_resume() to reload
887 * the countdown register.
888 * this should not be necessary but there are broken laptops that
889 * do not restore the countdown register on resume.
890 * when it happnes, it messes up the hardclock interval and system clock,
891 * which leads to the infamous "calcru: negative time" problem.
897 mtx_lock_spin(&clock_lock);
898 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
899 outb(TIMER_CNTR0, timer0_max_count & 0xff);
900 outb(TIMER_CNTR0, timer0_max_count >> 8);
901 mtx_unlock_spin(&clock_lock);
909 /* Reenable RTC updates and interrupts. */
910 /* XXX locking is needed for RTC access? */
911 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
912 writertc(RTC_STATUSB, rtc_statusb);
917 * Restore all the timers atomically.
923 i8254_restore(); /* restore timer_freq and hz */
925 rtc_restore(); /* reenable RTC interrupts */
930 * Initialize 8254 timer 0 early so that it can be used in DELAY().
931 * XXX initialization of other timers is unintentionally left blank.
940 if (pc98_machine_type & M_8M)
941 timer_freq = 1996800L; /* 1.9968 MHz */
943 timer_freq = 2457600L; /* 2.4576 MHz */
946 if (cpu_feature & CPUID_TSC)
952 writertc(RTC_STATUSA, rtc_statusa);
953 writertc(RTC_STATUSB, RTCSB_24HR);
956 set_timer_freq(timer_freq, hz);
957 freq = calibrate_clocks();
958 #ifdef CLK_CALIBRATION_LOOP
961 "Press a key on the console to abort clock calibration\n");
962 while (cncheckc() == -1)
968 * Use the calibrated i8254 frequency if it seems reasonable.
969 * Otherwise use the default, and don't use the calibrated i586
972 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
973 if (delta < timer_freq / 100) {
974 #ifndef CLK_USE_I8254_CALIBRATION
977 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
984 "%d Hz differs from default of %d Hz by more than 1%%\n",
989 set_timer_freq(timer_freq, hz);
990 i8254_timecounter.tc_frequency = timer_freq;
991 tc_init(&i8254_timecounter);
993 #ifndef CLK_USE_TSC_CALIBRATION
997 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
1001 if (tsc_present && tsc_freq == 0) {
1003 * Calibration of the i586 clock relative to the mc146818A
1004 * clock failed. Do a less accurate calibration relative
1005 * to the i8254 clock.
1007 u_int64_t old_tsc = rdtsc();
1010 tsc_freq = rdtsc() - old_tsc;
1011 #ifdef CLK_USE_TSC_CALIBRATION
1013 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
1019 * We can not use the TSC in SMP mode, until we figure out a
1020 * cheap (impossible), reliable and precise (yeah right!) way
1021 * to synchronize the TSCs of all the CPUs.
1022 * Curse Intel for leaving the counter out of the I/O APIC.
1026 * We can not use the TSC if we support APM. Precise timekeeping
1027 * on an APM'ed machine is at best a fools pursuit, since
1028 * any and all of the time spent in various SMM code can't
1029 * be reliably accounted for. Reading the RTC is your only
1030 * source of reliable time info. The i8254 looses too of course
1031 * but we need to have some kind of time...
1032 * We don't know at this point whether APM is going to be used
1033 * or not, nor when it might be activated. Play it safe.
1035 if (power_pm_get_type() == POWER_PM_TYPE_APM) {
1037 printf("TSC initialization skipped: APM enabled.\n");
1041 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
1042 tsc_timecounter.tc_frequency = tsc_freq;
1043 tc_init(&tsc_timecounter);
1046 #endif /* !defined(SMP) */
1051 rtc_serialcombit(int i)
1053 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1055 outb(IO_RTC, ((i&0x01)<<5)|0x17);
1057 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1062 rtc_serialcom(int i)
1064 rtc_serialcombit(i&0x01);
1065 rtc_serialcombit((i&0x02)>>1);
1066 rtc_serialcombit((i&0x04)>>2);
1067 rtc_serialcombit((i&0x08)>>3);
1083 sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
1084 outb(IO_RTC, sa); /* set DI & CLK 0 */
1086 outb(IO_RTC, sa | 0x10); /* CLK 1 */
1089 outb(IO_RTC, sa & 0xef); /* CLK 0 */
1099 sa |= ((inb(0x33) & 0x01) << s);
1100 outb(IO_RTC, 0x17); /* CLK 1 */
1102 outb(IO_RTC, 0x07); /* CLK 0 */
1110 * Initialize the time of day register, based on the time base which is, e.g.
1111 * from a filesystem.
1114 inittodr(time_t base)
1116 unsigned long sec, days;
1121 int second, min, hour;
1133 rtc_serialcom(0x03); /* Time Read */
1134 rtc_serialcom(0x01); /* Register shift command. */
1137 second = bcd2bin(rtc_inb() & 0xff); /* sec */
1138 min = bcd2bin(rtc_inb() & 0xff); /* min */
1139 hour = bcd2bin(rtc_inb() & 0xff); /* hour */
1140 days = bcd2bin(rtc_inb() & 0xff) - 1; /* date */
1142 month = (rtc_inb() >> 4) & 0x0f; /* month */
1143 for (m = 1; m < month; m++)
1144 days += daysinmonth[m-1];
1145 year = bcd2bin(rtc_inb() & 0xff) + 1900; /* year */
1146 /* 2000 year problem */
1151 for (y = 1970; y < year; y++)
1152 days += DAYSPERYEAR + LEAPYEAR(y);
1153 if ((month > 2) && LEAPYEAR(year))
1155 sec = ((( days * 24 +
1159 /* sec now contains the number of seconds, since Jan 1 1970,
1160 in the local time zone */
1164 /* Look if we have a RTC present and the time is valid */
1165 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
1168 /* wait for time update to complete */
1169 /* If RTCSA_TUP is zero, we have at least 244us before next update */
1171 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
1177 #ifdef USE_RTC_CENTURY
1178 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
1180 year = readrtc(RTC_YEAR) + 1900;
1188 month = readrtc(RTC_MONTH);
1189 for (m = 1; m < month; m++)
1190 days += daysinmonth[m-1];
1191 if ((month > 2) && LEAPYEAR(year))
1193 days += readrtc(RTC_DAY) - 1;
1194 for (y = 1970; y < year; y++)
1195 days += DAYSPERYEAR + LEAPYEAR(y);
1196 sec = ((( days * 24 +
1197 readrtc(RTC_HRS)) * 60 +
1198 readrtc(RTC_MIN)) * 60 +
1200 /* sec now contains the number of seconds, since Jan 1 1970,
1201 in the local time zone */
1204 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1206 y = time_second - sec;
1207 if (y <= -2 || y >= 2) {
1208 /* badly off, adjust it */
1217 printf("Invalid time in real time clock.\n");
1218 printf("Check and reset the date immediately!\n");
1222 * Write system time back to RTC
1233 if (disable_rtc_set)
1241 rtc_serialcom(0x01); /* Register shift command. */
1243 /* Calculate local time to put in RTC */
1245 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1247 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1248 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1249 rtc_outb(bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1251 /* We have now the days since 01-01-1970 in tm */
1253 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1255 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1258 /* Now we have the years in y and the day-of-the-year in tm */
1259 for (m = 0; ; m++) {
1262 ml = daysinmonth[m];
1263 if (m == 1 && LEAPYEAR(y))
1271 rtc_outb(bin2bcd(tm+1)); /* Write back Day */
1272 rtc_outb((m << 4) | wd); /* Write back Month & Weekday */
1273 rtc_outb(bin2bcd(y%100)); /* Write back Year */
1275 rtc_serialcom(0x02); /* Time set & Counter hold command. */
1276 rtc_serialcom(0x00); /* Register hold command. */
1278 /* Disable RTC updates and interrupts. */
1279 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1281 /* Calculate local time to put in RTC */
1283 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1285 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1286 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1287 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1289 /* We have now the days since 01-01-1970 in tm */
1290 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
1291 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1293 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1296 /* Now we have the years in y and the day-of-the-year in tm */
1297 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
1298 #ifdef USE_RTC_CENTURY
1299 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1301 for (m = 0; ; m++) {
1304 ml = daysinmonth[m];
1305 if (m == 1 && LEAPYEAR(y))
1312 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1313 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1315 /* Reenable RTC updates and interrupts. */
1316 writertc(RTC_STATUSB, rtc_statusb);
1322 * Start both clocks running.
1331 int apic_8254_trial;
1333 #endif /* APIC_IO */
1337 if (statclock_disable) {
1339 * The stat interrupt mask is different without the
1340 * statistics clock. Also, don't set the interrupt
1341 * flag which would normally cause the RTC to generate
1344 rtc_statusb = RTCSB_24HR;
1346 /* Setting stathz to nonzero early helps avoid races. */
1347 stathz = RTC_NOPROFRATE;
1348 profhz = RTC_PROFRATE;
1352 /* Finish initializing 8253 timer 0. */
1355 apic_8254_intr = isa_apic_irq(0);
1356 apic_8254_trial = 0;
1357 if (apic_8254_intr >= 0 ) {
1358 if (apic_int_type(0, 0) == 3)
1359 apic_8254_trial = 1;
1361 /* look for ExtInt on pin 0 */
1362 if (apic_int_type(0, 0) == 3) {
1363 apic_8254_intr = apic_irq(0, 0);
1364 setup_8254_mixed_mode();
1366 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1369 inthand_add("clk", apic_8254_intr, (driver_intr_t *)clkintr, NULL,
1370 INTR_TYPE_CLK | INTR_FAST, &clkdesc);
1371 crit = intr_disable();
1372 mtx_lock_spin(&icu_lock);
1373 INTREN(1 << apic_8254_intr);
1374 mtx_unlock_spin(&icu_lock);
1380 * XXX Check the priority of this interrupt handler. I
1381 * couldn't find anything suitable in the BSD/OS code (grog,
1384 inthand_add("clk", 0, (driver_intr_t *)clkintr, NULL,
1385 INTR_TYPE_CLK | INTR_FAST, NULL);
1386 crit = intr_disable();
1387 mtx_lock_spin(&icu_lock);
1389 mtx_unlock_spin(&icu_lock);
1392 #endif /* APIC_IO */
1395 /* Initialize RTC. */
1396 writertc(RTC_STATUSA, rtc_statusa);
1397 writertc(RTC_STATUSB, RTCSB_24HR);
1399 /* Don't bother enabling the statistics clock. */
1400 if (statclock_disable)
1402 diag = rtcin(RTC_DIAG);
1404 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1409 if (isa_apic_irq(8) != 8)
1410 panic("APIC RTC != 8");
1411 #endif /* APIC_IO */
1413 inthand_add("rtc", 8, (driver_intr_t *)rtcintr, NULL,
1414 INTR_TYPE_CLK | INTR_FAST, NULL);
1416 crit = intr_disable();
1417 mtx_lock_spin(&icu_lock);
1422 #endif /* APIC_IO */
1423 mtx_unlock_spin(&icu_lock);
1426 writertc(RTC_STATUSB, rtc_statusb);
1430 if (apic_8254_trial) {
1432 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1433 while (read_intr_count(8) < 6)
1435 if (read_intr_count(apic_8254_intr) < 3) {
1437 * The MP table is broken.
1438 * The 8254 was not connected to the specified pin
1440 * Workaround: Limited variant of mixed mode.
1442 crit = intr_disable();
1443 mtx_lock_spin(&icu_lock);
1444 INTRDIS(1 << apic_8254_intr);
1445 mtx_unlock_spin(&icu_lock);
1447 inthand_remove(clkdesc);
1448 printf("APIC_IO: Broken MP table detected: "
1449 "8254 is not connected to "
1450 "IOAPIC #%d intpin %d\n",
1451 int_to_apicintpin[apic_8254_intr].ioapic,
1452 int_to_apicintpin[apic_8254_intr].int_pin);
1454 * Revoke current ISA IRQ 0 assignment and
1455 * configure a fallback interrupt routing from
1456 * the 8254 Timer via the 8259 PIC to the
1457 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1458 * We reuse the low level interrupt handler number.
1460 if (apic_irq(0, 0) < 0) {
1461 revoke_apic_irq(apic_8254_intr);
1462 assign_apic_irq(0, 0, apic_8254_intr);
1464 apic_8254_intr = apic_irq(0, 0);
1465 setup_8254_mixed_mode();
1466 inthand_add("clk", apic_8254_intr,
1467 (driver_intr_t *)clkintr, NULL,
1468 INTR_TYPE_CLK | INTR_FAST, NULL);
1469 crit = intr_disable();
1470 mtx_lock_spin(&icu_lock);
1471 INTREN(1 << apic_8254_intr);
1472 mtx_unlock_spin(&icu_lock);
1477 if (apic_int_type(0, 0) != 3 ||
1478 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1479 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1480 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1481 int_to_apicintpin[apic_8254_intr].ioapic,
1482 int_to_apicintpin[apic_8254_intr].int_pin);
1485 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1492 read_intr_count(int vec)
1495 up = intr_countp[vec];
1502 setup_8254_mixed_mode()
1505 * Allow 8254 timer to INTerrupt 8259:
1506 * re-initialize master 8259:
1507 * reset; prog 4 bytes, single ICU, edge triggered
1509 outb(IO_ICU1, 0x13);
1511 outb(IO_ICU1 + 2, NRSVIDT); /* start vector (unused) */
1512 outb(IO_ICU1 + 2, 0x00); /* ignore slave */
1513 outb(IO_ICU1 + 2, 0x03); /* auto EOI, 8086 */
1514 outb(IO_ICU1 + 2, 0xfe); /* unmask INT0 */
1516 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1517 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1518 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1519 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1522 /* program IO APIC for type 3 INT on INT0 */
1523 if (ext_int_setup(0, 0) < 0)
1524 panic("8254 redirect via APIC pin0 impossible!");
1529 setstatclockrate(int newhz)
1532 if (newhz == RTC_PROFRATE)
1533 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1535 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1536 writertc(RTC_STATUSA, rtc_statusa);
1541 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1547 * Use `i8254' instead of `timer' in external names because `timer'
1548 * is is too generic. Should use it everywhere.
1551 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1552 if (error == 0 && req->newptr != NULL) {
1553 if (timer0_state != RELEASED)
1554 return (EBUSY); /* too much trouble to handle */
1555 set_timer_freq(freq, hz);
1556 i8254_timecounter.tc_frequency = freq;
1561 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1562 0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1565 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1570 if (tsc_timecounter.tc_frequency == 0)
1571 return (EOPNOTSUPP);
1573 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1574 if (error == 0 && req->newptr != NULL) {
1576 tsc_timecounter.tc_frequency = tsc_freq;
1581 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1582 0, sizeof(u_int), sysctl_machdep_tsc_freq, "I", "");
1585 i8254_get_timecount(struct timecounter *tc)
1591 eflags = read_eflags();
1592 mtx_lock_spin(&clock_lock);
1594 /* Select timer0 and latch counter value. */
1595 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1597 low = inb(TIMER_CNTR0);
1598 high = inb(TIMER_CNTR0);
1599 count = timer0_max_count - ((high << 8) | low);
1600 if (count < i8254_lastcount ||
1601 (!i8254_ticked && (clkintr_pending ||
1602 ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
1604 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1605 /* XXX this assumes that apic_8254_intr is < 24. */
1606 (lapic_irr1 & (1 << apic_8254_intr))))
1608 (inb(IO_ICU1) & 1)))
1612 i8254_offset += timer0_max_count;
1614 i8254_lastcount = count;
1615 count += i8254_offset;
1616 mtx_unlock_spin(&clock_lock);
1621 tsc_get_timecount(struct timecounter *tc)
1628 * Attach to the ISA PnP descriptors for the timer and realtime clock.
1630 static struct isa_pnp_id attimer_ids[] = {
1631 { 0x0001d041 /* PNP0100 */, "AT timer" },
1632 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
1637 attimer_probe(device_t dev)
1641 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
1647 attimer_attach(device_t dev)
1652 static device_method_t attimer_methods[] = {
1653 /* Device interface */
1654 DEVMETHOD(device_probe, attimer_probe),
1655 DEVMETHOD(device_attach, attimer_attach),
1656 DEVMETHOD(device_detach, bus_generic_detach),
1657 DEVMETHOD(device_shutdown, bus_generic_shutdown),
1658 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
1659 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
1663 static driver_t attimer_driver = {
1669 static devclass_t attimer_devclass;
1671 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1673 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
1675 #endif /* DEV_ISA */