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"
58 #include <sys/param.h>
59 #include <sys/systm.h>
61 #include <sys/timetc.h>
62 #include <sys/kernel.h>
66 #include <sys/sysctl.h>
69 #include <machine/clock.h>
70 #ifdef CLK_CALIBRATION_LOOP
72 #include <machine/cputypes.h>
73 #include <machine/frame.h>
74 #include <machine/ipl.h>
75 #include <machine/limits.h>
76 #include <machine/md_var.h>
77 #include <machine/psl.h>
79 #include <machine/segments.h>
81 #if defined(SMP) || defined(APIC_IO)
82 #include <machine/smp.h>
83 #endif /* SMP || APIC_IO */
84 #include <machine/specialreg.h>
86 #include <i386/isa/icu.h>
88 #include <pc98/pc98/pc98.h>
89 #include <pc98/pc98/pc98_machdep.h>
90 #include <i386/isa/isa_device.h>
92 #include <i386/isa/isa.h>
95 #include <i386/isa/timerreg.h>
97 #include <i386/isa/intr_machdep.h>
101 #include <i386/isa/mca_machdep.h>
105 #define disable_intr() CLOCK_DISABLE_INTR()
106 #define enable_intr() CLOCK_ENABLE_INTR()
109 #include <i386/isa/intr_machdep.h>
110 /* The interrupt triggered by the 8254 (timer) chip */
112 static u_long read_intr_count __P((int vec));
113 static void setup_8254_mixed_mode __P((void));
118 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
119 * can use a simple formula for leap years.
121 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
122 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
124 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
127 * Time in timer cycles that it takes for microtime() to disable interrupts
128 * and latch the count. microtime() currently uses "cli; outb ..." so it
129 * normally takes less than 2 timer cycles. Add a few for cache misses.
130 * Add a few more to allow for latency in bogus calls to microtime() with
131 * interrupts already disabled.
133 #define TIMER0_LATCH_COUNT 20
136 * Maximum frequency that we are willing to allow for timer0. Must be
137 * low enough to guarantee that the timer interrupt handler returns
138 * before the next timer interrupt.
140 #define TIMER0_MAX_FREQ 20000
142 int adjkerntz; /* local offset from GMT in seconds */
144 int disable_rtc_set; /* disable resettodr() if != 0 */
145 volatile u_int idelayed;
146 int statclock_disable;
147 u_int stat_imask = SWI_CLOCK_MASK;
150 #define TIMER_FREQ 2457600;
152 #define TIMER_FREQ 1193182;
155 u_int timer_freq = TIMER_FREQ;
156 int timer0_max_count;
159 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
161 static int beeping = 0;
162 static u_int clk_imask = HWI_MASK | SWI_MASK;
163 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
164 static u_int hardclock_max_count;
165 static u_int32_t i8254_lastcount;
166 static u_int32_t i8254_offset;
167 static int i8254_ticked;
169 * XXX new_function and timer_func should not handle clockframes, but
170 * timer_func currently needs to hold hardclock to handle the
171 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
172 * to switch between clkintr() and a slightly different timerintr().
174 static void (*new_function) __P((struct clockframe *frame));
175 static u_int new_rate;
177 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
178 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
180 static u_int timer0_prescaler_count;
182 /* Values for timerX_state: */
184 #define RELEASE_PENDING 1
186 #define ACQUIRE_PENDING 3
188 static u_char timer0_state;
190 static u_char timer1_state;
192 static u_char timer2_state;
193 static void (*timer_func) __P((struct clockframe *frame)) = hardclock;
195 static void rtc_serialcombit __P((int));
196 static void rtc_serialcom __P((int));
197 static int rtc_inb __P((void));
198 static void rtc_outb __P((int));
200 static u_int tsc_present;
202 static unsigned i8254_get_timecount __P((struct timecounter *tc));
203 static unsigned tsc_get_timecount __P((struct timecounter *tc));
204 static void set_timer_freq(u_int freq, int intr_freq);
206 static struct timecounter tsc_timecounter = {
207 tsc_get_timecount, /* get_timecount */
209 ~0u, /* counter_mask */
214 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD,
215 &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
217 static struct timecounter i8254_timecounter = {
218 i8254_get_timecount, /* get_timecount */
220 ~0u, /* counter_mask */
225 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD,
226 &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
229 clkintr(struct clockframe frame)
231 if (timecounter->tc_get_timecount == i8254_get_timecount) {
236 i8254_offset += timer0_max_count;
243 switch (timer0_state) {
250 if ((timer0_prescaler_count += timer0_max_count)
251 >= hardclock_max_count) {
252 timer0_prescaler_count -= hardclock_max_count;
258 case ACQUIRE_PENDING:
260 i8254_offset = i8254_get_timecount(NULL);
262 timer0_max_count = TIMER_DIV(new_rate);
263 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
264 outb(TIMER_CNTR0, timer0_max_count & 0xff);
265 outb(TIMER_CNTR0, timer0_max_count >> 8);
267 timer_func = new_function;
268 timer0_state = ACQUIRED;
272 case RELEASE_PENDING:
273 if ((timer0_prescaler_count += timer0_max_count)
274 >= hardclock_max_count) {
276 i8254_offset = i8254_get_timecount(NULL);
278 timer0_max_count = hardclock_max_count;
280 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
281 outb(TIMER_CNTR0, timer0_max_count & 0xff);
282 outb(TIMER_CNTR0, timer0_max_count >> 8);
284 timer0_prescaler_count = 0;
285 timer_func = hardclock;
286 timer0_state = RELEASED;
293 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
295 outb(0x61, inb(0x61) | 0x80);
300 * The acquire and release functions must be called at ipl >= splclock().
303 acquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
307 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
309 switch (timer0_state) {
312 timer0_state = ACQUIRE_PENDING;
315 case RELEASE_PENDING:
316 if (rate != old_rate)
319 * The timer has been released recently, but is being
320 * re-acquired before the release completed. In this
321 * case, we simply reclaim it as if it had not been
324 timer0_state = ACQUIRED;
328 return (-1); /* busy */
330 new_function = function;
331 old_rate = new_rate = rate;
337 acquire_timer1(int mode)
340 if (timer1_state != RELEASED)
342 timer1_state = ACQUIRED;
345 * This access to the timer registers is as atomic as possible
346 * because it is a single instruction. We could do better if we
347 * knew the rate. Use of splclock() limits glitches to 10-100us,
348 * and this is probably good enough for timer2, so we aren't as
349 * careful with it as with timer0.
351 outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
358 acquire_timer2(int mode)
361 if (timer2_state != RELEASED)
363 timer2_state = ACQUIRED;
366 * This access to the timer registers is as atomic as possible
367 * because it is a single instruction. We could do better if we
368 * knew the rate. Use of splclock() limits glitches to 10-100us,
369 * and this is probably good enough for timer2, so we aren't as
370 * careful with it as with timer0.
372 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
380 switch (timer0_state) {
383 timer0_state = RELEASE_PENDING;
386 case ACQUIRE_PENDING:
387 /* Nothing happened yet, release quickly. */
388 timer0_state = RELEASED;
402 if (timer1_state != ACQUIRED)
404 timer1_state = RELEASED;
405 outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
414 if (timer2_state != ACQUIRED)
416 timer2_state = RELEASED;
417 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
423 * This routine receives statistical clock interrupts from the RTC.
424 * As explained above, these occur at 128 interrupts per second.
425 * When profiling, we receive interrupts at a rate of 1024 Hz.
427 * This does not actually add as much overhead as it sounds, because
428 * when the statistical clock is active, the hardclock driver no longer
429 * needs to keep (inaccurate) statistics on its own. This decouples
430 * statistics gathering from scheduling interrupts.
432 * The RTC chip requires that we read status register C (RTC_INTR)
433 * to acknowledge an interrupt, before it will generate the next one.
434 * Under high interrupt load, rtcintr() can be indefinitely delayed and
435 * the clock can tick immediately after the read from RTC_INTR. In this
436 * case, the mc146818A interrupt signal will not drop for long enough
437 * to register with the 8259 PIC. If an interrupt is missed, the stat
438 * clock will halt, considerably degrading system performance. This is
439 * why we use 'while' rather than a more straightforward 'if' below.
440 * Stat clock ticks can still be lost, causing minor loss of accuracy
441 * in the statistics, but the stat clock will no longer stop.
444 rtcintr(struct clockframe frame)
446 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
454 DB_SHOW_COMMAND(rtc, rtc)
456 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
457 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
458 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
459 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
462 #endif /* for PC98 */
473 /* Select timer0 and latch counter value. */
474 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
476 low = inb(TIMER_CNTR0);
477 high = inb(TIMER_CNTR0);
481 return ((high << 8) | low);
485 * Wait "n" microseconds.
486 * Relies on timer 1 counting down from (timer_freq / hz)
487 * Note: timer had better have been programmed before this is first used!
492 int delta, prev_tick, tick, ticks_left;
497 static int state = 0;
501 for (n1 = 1; n1 <= 10000000; n1 *= 10)
506 printf("DELAY(%d)...", n);
509 * Guard against the timer being uninitialized if we are called
510 * early for console i/o.
512 if (timer0_max_count == 0)
513 set_timer_freq(timer_freq, hz);
516 * Read the counter first, so that the rest of the setup overhead is
517 * counted. Guess the initial overhead is 20 usec (on most systems it
518 * takes about 1.5 usec for each of the i/o's in getit(). The loop
519 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
520 * multiplications and divisions to scale the count take a while).
523 n -= 0; /* XXX actually guess no initial overhead */
525 * Calculate (n * (timer_freq / 1e6)) without using floating point
526 * and without any avoidable overflows.
532 * Use fixed point to avoid a slow division by 1000000.
533 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
534 * 2^15 is the first power of 2 that gives exact results
535 * for n between 0 and 256.
537 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
540 * Don't bother using fixed point, although gcc-2.7.2
541 * generates particularly poor code for the long long
542 * division, since even the slow way will complete long
543 * before the delay is up (unless we're interrupted).
545 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
548 while (ticks_left > 0) {
553 delta = prev_tick - tick;
556 delta += timer0_max_count;
558 * Guard against timer0_max_count being wrong.
559 * This shouldn't happen in normal operation,
560 * but it may happen if set_timer_freq() is
570 printf(" %d calls to getit() at %d usec each\n",
571 getit_calls, (n + 5) / getit_calls);
576 sysbeepstop(void *chan)
578 #ifdef PC98 /* PC98 */
579 outb(IO_PPI, inb(IO_PPI)|0x08); /* disable counter1 output to speaker */
582 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
589 sysbeep(int pitch, int period)
594 if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
596 /* Something else owns it. */
598 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
602 outb(0x3fdb, (pitch>>8));
605 /* enable counter1 output to speaker */
606 outb(IO_PPI, (inb(IO_PPI) & 0xf7));
608 timeout(sysbeepstop, (void *)NULL, period);
611 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
613 /* Something else owns it. */
615 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
618 outb(TIMER_CNTR2, pitch);
619 outb(TIMER_CNTR2, (pitch>>8));
622 /* enable counter2 output to speaker */
623 outb(IO_PPI, inb(IO_PPI) | 3);
625 timeout(sysbeepstop, (void *)NULL, period);
634 * RTC support routines
647 val = inb(IO_RTC + 1);
654 writertc(u_char reg, u_char val)
662 outb(IO_RTC + 1, val);
663 inb(0x84); /* XXX work around wrong order in rtcin() */
670 return(bcd2bin(rtcin(port)));
675 unsigned int delaycount;
676 #define FIRST_GUESS 0x2000
677 static void findcpuspeed(void)
682 /* Put counter in count down mode */
683 outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
684 outb(TIMER_CNTR0, 0xff);
685 outb(TIMER_CNTR0, 0xff);
686 for (i = FIRST_GUESS; i; i--)
689 delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
695 calibrate_clocks(void)
698 u_int count, prev_count, tot_count;
699 u_short sec, start_sec;
702 printf("Calibrating clock(s) ... ");
704 if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
705 !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
709 /* Read the ARTIC. */
712 /* Wait for the ARTIC to changes. */
716 if (sec != start_sec)
721 prev_count = getit();
722 if (prev_count == 0 || prev_count > timer0_max_count)
727 wrmsr(0x10, 0LL); /* XXX 0x10 is the MSR for the TSC */
732 if (count == 0 || count > timer0_max_count)
734 if (count > prev_count)
735 tot_count += prev_count - (count - timer0_max_count);
737 tot_count += prev_count - count;
739 if ((sec == start_sec + 1200) ||
741 (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
747 * Read the cpu cycle counter. The timing considerations are
748 * similar to those for the i8254 clock.
755 printf("TSC clock: %u Hz, ", tsc_freq);
756 printf("i8254 clock: %u Hz\n", tot_count);
762 printf("failed, using default i8254 clock of %u Hz\n",
768 calibrate_clocks(void)
771 u_int count, prev_count, tot_count;
772 int sec, start_sec, timeout;
775 printf("Calibrating clock(s) ... ");
776 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
780 /* Read the mc146818A seconds counter. */
782 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
783 sec = rtcin(RTC_SEC);
790 /* Wait for the mC146818A seconds counter to change. */
793 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
794 sec = rtcin(RTC_SEC);
795 if (sec != start_sec)
802 /* Start keeping track of the i8254 counter. */
803 prev_count = getit();
804 if (prev_count == 0 || prev_count > timer0_max_count)
811 old_tsc = 0; /* shut up gcc */
814 * Wait for the mc146818A seconds counter to change. Read the i8254
815 * counter for each iteration since this is convenient and only
816 * costs a few usec of inaccuracy. The timing of the final reads
817 * of the counters almost matches the timing of the initial reads,
818 * so the main cause of inaccuracy is the varying latency from
819 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
820 * rtcin(RTC_SEC) that returns a changed seconds count. The
821 * maximum inaccuracy from this cause is < 10 usec on 486's.
825 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
826 sec = rtcin(RTC_SEC);
828 if (count == 0 || count > timer0_max_count)
830 if (count > prev_count)
831 tot_count += prev_count - (count - timer0_max_count);
833 tot_count += prev_count - count;
835 if (sec != start_sec)
842 * Read the cpu cycle counter. The timing considerations are
843 * similar to those for the i8254 clock.
846 tsc_freq = rdtsc() - old_tsc;
850 printf("TSC clock: %u Hz, ", tsc_freq);
851 printf("i8254 clock: %u Hz\n", tot_count);
857 printf("failed, using default i8254 clock of %u Hz\n",
864 set_timer_freq(u_int freq, int intr_freq)
867 int new_timer0_max_count;
872 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
873 if (new_timer0_max_count != timer0_max_count) {
874 timer0_max_count = new_timer0_max_count;
875 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
876 outb(TIMER_CNTR0, timer0_max_count & 0xff);
877 outb(TIMER_CNTR0, timer0_max_count >> 8);
884 * i8254_restore is called from apm_default_resume() to reload
885 * the countdown register.
886 * this should not be necessary but there are broken laptops that
887 * do not restore the countdown register on resume.
888 * when it happnes, it messes up the hardclock interval and system clock,
889 * which leads to the infamous "calcru: negative time" problem.
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);
906 * Initialize 8254 timer 0 early so that it can be used in DELAY().
907 * XXX initialization of other timers is unintentionally left blank.
916 if (pc98_machine_type & M_8M)
917 timer_freq = 1996800L; /* 1.9968 MHz */
919 timer_freq = 2457600L; /* 2.4576 MHz */
922 if (cpu_feature & CPUID_TSC)
928 writertc(RTC_STATUSA, rtc_statusa);
929 writertc(RTC_STATUSB, RTCSB_24HR);
932 set_timer_freq(timer_freq, hz);
933 freq = calibrate_clocks();
934 #ifdef CLK_CALIBRATION_LOOP
937 "Press a key on the console to abort clock calibration\n");
938 while (cncheckc() == -1)
944 * Use the calibrated i8254 frequency if it seems reasonable.
945 * Otherwise use the default, and don't use the calibrated i586
948 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
949 if (delta < timer_freq / 100) {
950 #ifndef CLK_USE_I8254_CALIBRATION
953 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
960 "%d Hz differs from default of %d Hz by more than 1%%\n",
965 set_timer_freq(timer_freq, hz);
966 i8254_timecounter.tc_frequency = timer_freq;
967 tc_init(&i8254_timecounter);
969 #ifndef CLK_USE_TSC_CALIBRATION
973 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
977 if (tsc_present && tsc_freq == 0) {
979 * Calibration of the i586 clock relative to the mc146818A
980 * clock failed. Do a less accurate calibration relative
981 * to the i8254 clock.
983 u_int64_t old_tsc = rdtsc();
986 tsc_freq = rdtsc() - old_tsc;
987 #ifdef CLK_USE_TSC_CALIBRATION
989 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
995 * We can not use the TSC in SMP mode, until we figure out a
996 * cheap (impossible), reliable and precise (yeah right!) way
997 * to synchronize the TSCs of all the CPUs.
998 * Curse Intel for leaving the counter out of the I/O APIC.
1003 * We can not use the TSC if we support APM. Precise timekeeping
1004 * on an APM'ed machine is at best a fools pursuit, since
1005 * any and all of the time spent in various SMM code can't
1006 * be reliably accounted for. Reading the RTC is your only
1007 * source of reliable time info. The i8254 looses too of course
1008 * but we need to have some kind of time...
1009 * We don't know at this point whether APM is going to be used
1010 * or not, nor when it might be activated. Play it safe.
1013 #endif /* NAPM > 0 */
1015 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
1016 tsc_timecounter.tc_frequency = tsc_freq;
1017 tc_init(&tsc_timecounter);
1020 #endif /* !defined(SMP) */
1025 rtc_serialcombit(int i)
1027 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1029 outb(IO_RTC, ((i&0x01)<<5)|0x17);
1031 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1036 rtc_serialcom(int i)
1038 rtc_serialcombit(i&0x01);
1039 rtc_serialcombit((i&0x02)>>1);
1040 rtc_serialcombit((i&0x04)>>2);
1041 rtc_serialcombit((i&0x08)>>3);
1057 sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
1058 outb(IO_RTC, sa); /* set DI & CLK 0 */
1060 outb(IO_RTC, sa | 0x10); /* CLK 1 */
1063 outb(IO_RTC, sa & 0xef); /* CLK 0 */
1073 sa |= ((inb(0x33) & 0x01) << s);
1074 outb(IO_RTC, 0x17); /* CLK 1 */
1076 outb(IO_RTC, 0x07); /* CLK 0 */
1084 * Initialize the time of day register, based on the time base which is, e.g.
1085 * from a filesystem.
1088 inittodr(time_t base)
1090 unsigned long sec, days;
1098 int second, min, hour;
1110 rtc_serialcom(0x03); /* Time Read */
1111 rtc_serialcom(0x01); /* Register shift command. */
1114 second = bcd2bin(rtc_inb() & 0xff); /* sec */
1115 min = bcd2bin(rtc_inb() & 0xff); /* min */
1116 hour = bcd2bin(rtc_inb() & 0xff); /* hour */
1117 days = bcd2bin(rtc_inb() & 0xff) - 1; /* date */
1119 month = (rtc_inb() >> 4) & 0x0f; /* month */
1120 for (m = 1; m < month; m++)
1121 days += daysinmonth[m-1];
1122 year = bcd2bin(rtc_inb() & 0xff) + 1900; /* year */
1123 /* 2000 year problem */
1128 for (y = 1970; y < year; y++)
1129 days += DAYSPERYEAR + LEAPYEAR(y);
1130 if ((month > 2) && LEAPYEAR(year))
1132 sec = ((( days * 24 +
1136 /* sec now contains the number of seconds, since Jan 1 1970,
1137 in the local time zone */
1139 /* Look if we have a RTC present and the time is valid */
1140 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
1143 /* wait for time update to complete */
1144 /* If RTCSA_TUP is zero, we have at least 244us before next update */
1146 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
1152 #ifdef USE_RTC_CENTURY
1153 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
1155 year = readrtc(RTC_YEAR) + 1900;
1163 month = readrtc(RTC_MONTH);
1164 for (m = 1; m < month; m++)
1165 days += daysinmonth[m-1];
1166 if ((month > 2) && LEAPYEAR(year))
1168 days += readrtc(RTC_DAY) - 1;
1170 for (y = 1970; y < year; y++)
1171 days += DAYSPERYEAR + LEAPYEAR(y);
1172 sec = ((( days * 24 +
1173 readrtc(RTC_HRS)) * 60 +
1174 readrtc(RTC_MIN)) * 60 +
1176 /* sec now contains the number of seconds, since Jan 1 1970,
1177 in the local time zone */
1180 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1182 y = time_second - sec;
1183 if (y <= -2 || y >= 2) {
1184 /* badly off, adjust it */
1193 printf("Invalid time in real time clock.\n");
1194 printf("Check and reset the date immediately!\n");
1198 * Write system time back to RTC
1209 if (disable_rtc_set)
1217 rtc_serialcom(0x01); /* Register shift command. */
1219 /* Calculate local time to put in RTC */
1221 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1223 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1224 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1225 rtc_outb(bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1227 /* We have now the days since 01-01-1970 in tm */
1229 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1231 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1234 /* Now we have the years in y and the day-of-the-year in tm */
1235 for (m = 0; ; m++) {
1238 ml = daysinmonth[m];
1239 if (m == 1 && LEAPYEAR(y))
1247 rtc_outb(bin2bcd(tm+1)); /* Write back Day */
1248 rtc_outb((m << 4) | wd); /* Write back Month & Weekday */
1249 rtc_outb(bin2bcd(y%100)); /* Write back Year */
1251 rtc_serialcom(0x02); /* Time set & Counter hold command. */
1252 rtc_serialcom(0x00); /* Register hold command. */
1254 /* Disable RTC updates and interrupts. */
1255 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1257 /* Calculate local time to put in RTC */
1259 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1261 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1262 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1263 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1265 /* We have now the days since 01-01-1970 in tm */
1266 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
1267 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1269 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1272 /* Now we have the years in y and the day-of-the-year in tm */
1273 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
1274 #ifdef USE_RTC_CENTURY
1275 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1277 for (m = 0; ; m++) {
1280 ml = daysinmonth[m];
1281 if (m == 1 && LEAPYEAR(y))
1288 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1289 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1291 /* Reenable RTC updates and interrupts. */
1292 writertc(RTC_STATUSB, rtc_statusb);
1298 * Start both clocks running.
1304 int apic_8254_trial;
1305 struct intrec *clkdesc;
1306 #endif /* APIC_IO */
1310 if (statclock_disable) {
1312 * The stat interrupt mask is different without the
1313 * statistics clock. Also, don't set the interrupt
1314 * flag which would normally cause the RTC to generate
1317 stat_imask = HWI_MASK | SWI_MASK;
1318 rtc_statusb = RTCSB_24HR;
1320 /* Setting stathz to nonzero early helps avoid races. */
1321 stathz = RTC_NOPROFRATE;
1322 profhz = RTC_PROFRATE;
1326 /* Finish initializing 8253 timer 0. */
1329 apic_8254_intr = isa_apic_irq(0);
1330 apic_8254_trial = 0;
1331 if (apic_8254_intr >= 0 ) {
1332 if (apic_int_type(0, 0) == 3)
1333 apic_8254_trial = 1;
1335 /* look for ExtInt on pin 0 */
1336 if (apic_int_type(0, 0) == 3) {
1337 apic_8254_intr = apic_irq(0, 0);
1338 setup_8254_mixed_mode();
1340 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1343 clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
1344 NULL, &clk_imask, INTR_EXCL);
1345 INTREN(1 << apic_8254_intr);
1349 inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
1353 #endif /* APIC_IO */
1356 /* Initialize RTC. */
1357 writertc(RTC_STATUSA, rtc_statusa);
1358 writertc(RTC_STATUSB, RTCSB_24HR);
1360 /* Don't bother enabling the statistics clock. */
1361 if (statclock_disable)
1363 diag = rtcin(RTC_DIAG);
1365 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1368 if (isa_apic_irq(8) != 8)
1369 panic("APIC RTC != 8");
1370 #endif /* APIC_IO */
1372 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
1379 #endif /* APIC_IO */
1381 writertc(RTC_STATUSB, rtc_statusb);
1385 if (apic_8254_trial) {
1387 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1388 while (read_intr_count(8) < 6)
1390 if (read_intr_count(apic_8254_intr) < 3) {
1392 * The MP table is broken.
1393 * The 8254 was not connected to the specified pin
1395 * Workaround: Limited variant of mixed mode.
1397 INTRDIS(1 << apic_8254_intr);
1398 inthand_remove(clkdesc);
1399 printf("APIC_IO: Broken MP table detected: "
1400 "8254 is not connected to "
1401 "IOAPIC #%d intpin %d\n",
1402 int_to_apicintpin[apic_8254_intr].ioapic,
1403 int_to_apicintpin[apic_8254_intr].int_pin);
1405 * Revoke current ISA IRQ 0 assignment and
1406 * configure a fallback interrupt routing from
1407 * the 8254 Timer via the 8259 PIC to the
1408 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1409 * We reuse the low level interrupt handler number.
1411 if (apic_irq(0, 0) < 0) {
1412 revoke_apic_irq(apic_8254_intr);
1413 assign_apic_irq(0, 0, apic_8254_intr);
1415 apic_8254_intr = apic_irq(0, 0);
1416 setup_8254_mixed_mode();
1417 inthand_add("clk", apic_8254_intr,
1418 (inthand2_t *)clkintr,
1419 NULL, &clk_imask, INTR_EXCL);
1420 INTREN(1 << apic_8254_intr);
1424 if (apic_int_type(0, 0) != 3 ||
1425 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1426 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1427 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1428 int_to_apicintpin[apic_8254_intr].ioapic,
1429 int_to_apicintpin[apic_8254_intr].int_pin);
1432 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1439 read_intr_count(int vec)
1442 up = intr_countp[vec];
1449 setup_8254_mixed_mode()
1452 * Allow 8254 timer to INTerrupt 8259:
1453 * re-initialize master 8259:
1454 * reset; prog 4 bytes, single ICU, edge triggered
1456 outb(IO_ICU1, 0x13);
1458 outb(IO_ICU1 + 2, NRSVIDT); /* start vector (unused) */
1459 outb(IO_ICU1 + 2, 0x00); /* ignore slave */
1460 outb(IO_ICU1 + 2, 0x03); /* auto EOI, 8086 */
1461 outb(IO_ICU1 + 2, 0xfe); /* unmask INT0 */
1463 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1464 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1465 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1466 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1468 /* program IO APIC for type 3 INT on INT0 */
1469 if (ext_int_setup(0, 0) < 0)
1470 panic("8254 redirect via APIC pin0 impossible!");
1475 setstatclockrate(int newhz)
1478 if (newhz == RTC_PROFRATE)
1479 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1481 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1482 writertc(RTC_STATUSA, rtc_statusa);
1487 sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
1493 * Use `i8254' instead of `timer' in external names because `timer'
1494 * is is too generic. Should use it everywhere.
1497 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1498 if (error == 0 && req->newptr != NULL) {
1499 if (timer0_state != RELEASED)
1500 return (EBUSY); /* too much trouble to handle */
1501 set_timer_freq(freq, hz);
1502 i8254_timecounter.tc_frequency = freq;
1503 tc_update(&i8254_timecounter);
1508 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1509 0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1512 sysctl_machdep_tsc_freq SYSCTL_HANDLER_ARGS
1517 if (tsc_timecounter.tc_frequency == 0)
1518 return (EOPNOTSUPP);
1520 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1521 if (error == 0 && req->newptr != NULL) {
1523 tsc_timecounter.tc_frequency = tsc_freq;
1524 tc_update(&tsc_timecounter);
1529 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1530 0, sizeof(u_int), sysctl_machdep_tsc_freq, "I", "");
1533 i8254_get_timecount(struct timecounter *tc)
1542 /* Select timer0 and latch counter value. */
1543 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1545 low = inb(TIMER_CNTR0);
1546 high = inb(TIMER_CNTR0);
1547 count = timer0_max_count - ((high << 8) | low);
1548 if (count < i8254_lastcount ||
1549 (!i8254_ticked && (clkintr_pending ||
1550 ((count < 20 || (!(ef & PSL_I) && count < timer0_max_count / 2u)) &&
1552 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1553 /* XXX this assumes that apic_8254_intr is < 24. */
1554 (lapic_irr1 & (1 << apic_8254_intr))))
1556 (inb(IO_ICU1) & 1)))
1560 i8254_offset += timer0_max_count;
1562 i8254_lastcount = count;
1563 count += i8254_offset;
1570 tsc_get_timecount(struct timecounter *tc)