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/kernel.h>
65 #include <sys/sysctl.h>
68 #include <machine/clock.h>
69 #ifdef CLK_CALIBRATION_LOOP
71 #include <machine/cputypes.h>
72 #include <machine/frame.h>
73 #include <machine/ipl.h>
74 #include <machine/limits.h>
75 #include <machine/md_var.h>
76 #include <machine/psl.h>
78 #include <machine/segments.h>
80 #if defined(SMP) || defined(APIC_IO)
81 #include <machine/smp.h>
82 #endif /* SMP || APIC_IO */
83 #include <machine/specialreg.h>
85 #include <i386/isa/icu.h>
87 #include <pc98/pc98/pc98.h>
88 #include <pc98/pc98/pc98_machdep.h>
89 #include <i386/isa/isa_device.h>
91 #include <i386/isa/isa.h>
94 #include <i386/isa/timerreg.h>
96 #include <i386/isa/intr_machdep.h>
100 #include <i386/isa/mca_machdep.h>
104 #define disable_intr() CLOCK_DISABLE_INTR()
105 #define enable_intr() CLOCK_ENABLE_INTR()
108 #include <i386/isa/intr_machdep.h>
109 /* The interrupt triggered by the 8254 (timer) chip */
111 static u_long read_intr_count __P((int vec));
112 static void setup_8254_mixed_mode __P((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 volatile u_int idelayed;
145 int statclock_disable;
146 u_int stat_imask = SWI_CLOCK_MASK;
149 #define TIMER_FREQ 2457600;
151 #define TIMER_FREQ 1193182;
154 u_int timer_freq = TIMER_FREQ;
155 int timer0_max_count;
158 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
160 static int beeping = 0;
161 static u_int clk_imask = HWI_MASK | SWI_MASK;
162 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
163 static u_int hardclock_max_count;
164 static u_int32_t i8254_lastcount;
165 static u_int32_t i8254_offset;
166 static int i8254_ticked;
168 * XXX new_function and timer_func should not handle clockframes, but
169 * timer_func currently needs to hold hardclock to handle the
170 * timer0_state == 0 case. We should use register_intr()/unregister_intr()
171 * to switch between clkintr() and a slightly different timerintr().
173 static void (*new_function) __P((struct clockframe *frame));
174 static u_int new_rate;
176 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
177 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
179 static u_int timer0_prescaler_count;
181 /* Values for timerX_state: */
183 #define RELEASE_PENDING 1
185 #define ACQUIRE_PENDING 3
187 static u_char timer0_state;
189 static u_char timer1_state;
191 static u_char timer2_state;
192 static void (*timer_func) __P((struct clockframe *frame)) = hardclock;
194 static void rtc_serialcombit __P((int));
195 static void rtc_serialcom __P((int));
196 static int rtc_inb __P((void));
197 static void rtc_outb __P((int));
199 static u_int tsc_present;
201 static unsigned i8254_get_timecount __P((struct timecounter *tc));
202 static unsigned tsc_get_timecount __P((struct timecounter *tc));
203 static void set_timer_freq(u_int freq, int intr_freq);
205 static struct timecounter tsc_timecounter = {
206 tsc_get_timecount, /* get_timecount */
208 ~0u, /* counter_mask */
213 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD,
214 &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
216 static struct timecounter i8254_timecounter = {
217 i8254_get_timecount, /* get_timecount */
219 ~0u, /* counter_mask */
224 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD,
225 &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
228 clkintr(struct clockframe frame)
230 if (timecounter->tc_get_timecount == i8254_get_timecount) {
235 i8254_offset += timer0_max_count;
242 switch (timer0_state) {
249 if ((timer0_prescaler_count += timer0_max_count)
250 >= hardclock_max_count) {
251 timer0_prescaler_count -= hardclock_max_count;
257 case ACQUIRE_PENDING:
259 i8254_offset = i8254_get_timecount(NULL);
261 timer0_max_count = TIMER_DIV(new_rate);
262 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
263 outb(TIMER_CNTR0, timer0_max_count & 0xff);
264 outb(TIMER_CNTR0, timer0_max_count >> 8);
266 timer_func = new_function;
267 timer0_state = ACQUIRED;
271 case RELEASE_PENDING:
272 if ((timer0_prescaler_count += timer0_max_count)
273 >= hardclock_max_count) {
275 i8254_offset = i8254_get_timecount(NULL);
277 timer0_max_count = hardclock_max_count;
279 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
280 outb(TIMER_CNTR0, timer0_max_count & 0xff);
281 outb(TIMER_CNTR0, timer0_max_count >> 8);
283 timer0_prescaler_count = 0;
284 timer_func = hardclock;
285 timer0_state = RELEASED;
292 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
294 outb(0x61, inb(0x61) | 0x80);
299 * The acquire and release functions must be called at ipl >= splclock().
302 acquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
306 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
308 switch (timer0_state) {
311 timer0_state = ACQUIRE_PENDING;
314 case RELEASE_PENDING:
315 if (rate != old_rate)
318 * The timer has been released recently, but is being
319 * re-acquired before the release completed. In this
320 * case, we simply reclaim it as if it had not been
323 timer0_state = ACQUIRED;
327 return (-1); /* busy */
329 new_function = function;
330 old_rate = new_rate = rate;
336 acquire_timer1(int mode)
339 if (timer1_state != RELEASED)
341 timer1_state = ACQUIRED;
344 * This access to the timer registers is as atomic as possible
345 * because it is a single instruction. We could do better if we
346 * knew the rate. Use of splclock() limits glitches to 10-100us,
347 * and this is probably good enough for timer2, so we aren't as
348 * careful with it as with timer0.
350 outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
357 acquire_timer2(int mode)
360 if (timer2_state != RELEASED)
362 timer2_state = ACQUIRED;
365 * This access to the timer registers is as atomic as possible
366 * because it is a single instruction. We could do better if we
367 * knew the rate. Use of splclock() limits glitches to 10-100us,
368 * and this is probably good enough for timer2, so we aren't as
369 * careful with it as with timer0.
371 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
379 switch (timer0_state) {
382 timer0_state = RELEASE_PENDING;
385 case ACQUIRE_PENDING:
386 /* Nothing happened yet, release quickly. */
387 timer0_state = RELEASED;
401 if (timer1_state != ACQUIRED)
403 timer1_state = RELEASED;
404 outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
413 if (timer2_state != ACQUIRED)
415 timer2_state = RELEASED;
416 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
422 * This routine receives statistical clock interrupts from the RTC.
423 * As explained above, these occur at 128 interrupts per second.
424 * When profiling, we receive interrupts at a rate of 1024 Hz.
426 * This does not actually add as much overhead as it sounds, because
427 * when the statistical clock is active, the hardclock driver no longer
428 * needs to keep (inaccurate) statistics on its own. This decouples
429 * statistics gathering from scheduling interrupts.
431 * The RTC chip requires that we read status register C (RTC_INTR)
432 * to acknowledge an interrupt, before it will generate the next one.
433 * Under high interrupt load, rtcintr() can be indefinitely delayed and
434 * the clock can tick immediately after the read from RTC_INTR. In this
435 * case, the mc146818A interrupt signal will not drop for long enough
436 * to register with the 8259 PIC. If an interrupt is missed, the stat
437 * clock will halt, considerably degrading system performance. This is
438 * why we use 'while' rather than a more straightforward 'if' below.
439 * Stat clock ticks can still be lost, causing minor loss of accuracy
440 * in the statistics, but the stat clock will no longer stop.
443 rtcintr(struct clockframe frame)
445 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
453 DB_SHOW_COMMAND(rtc, rtc)
455 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
456 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
457 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
458 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
461 #endif /* for PC98 */
472 /* Select timer0 and latch counter value. */
473 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
475 low = inb(TIMER_CNTR0);
476 high = inb(TIMER_CNTR0);
480 return ((high << 8) | low);
484 * Wait "n" microseconds.
485 * Relies on timer 1 counting down from (timer_freq / hz)
486 * Note: timer had better have been programmed before this is first used!
491 int delta, prev_tick, tick, ticks_left;
496 static int state = 0;
500 for (n1 = 1; n1 <= 10000000; n1 *= 10)
505 printf("DELAY(%d)...", n);
508 * Guard against the timer being uninitialized if we are called
509 * early for console i/o.
511 if (timer0_max_count == 0)
512 set_timer_freq(timer_freq, hz);
515 * Read the counter first, so that the rest of the setup overhead is
516 * counted. Guess the initial overhead is 20 usec (on most systems it
517 * takes about 1.5 usec for each of the i/o's in getit(). The loop
518 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
519 * multiplications and divisions to scale the count take a while).
522 n -= 0; /* XXX actually guess no initial overhead */
524 * Calculate (n * (timer_freq / 1e6)) without using floating point
525 * and without any avoidable overflows.
531 * Use fixed point to avoid a slow division by 1000000.
532 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
533 * 2^15 is the first power of 2 that gives exact results
534 * for n between 0 and 256.
536 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
539 * Don't bother using fixed point, although gcc-2.7.2
540 * generates particularly poor code for the long long
541 * division, since even the slow way will complete long
542 * before the delay is up (unless we're interrupted).
544 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
547 while (ticks_left > 0) {
552 delta = prev_tick - tick;
555 delta += timer0_max_count;
557 * Guard against timer0_max_count being wrong.
558 * This shouldn't happen in normal operation,
559 * but it may happen if set_timer_freq() is
569 printf(" %d calls to getit() at %d usec each\n",
570 getit_calls, (n + 5) / getit_calls);
575 sysbeepstop(void *chan)
577 #ifdef PC98 /* PC98 */
578 outb(IO_PPI, inb(IO_PPI)|0x08); /* disable counter1 output to speaker */
581 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
588 sysbeep(int pitch, int period)
593 if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
595 /* Something else owns it. */
597 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
601 outb(0x3fdb, (pitch>>8));
604 /* enable counter1 output to speaker */
605 outb(IO_PPI, (inb(IO_PPI) & 0xf7));
607 timeout(sysbeepstop, (void *)NULL, period);
610 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
612 /* Something else owns it. */
614 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
617 outb(TIMER_CNTR2, pitch);
618 outb(TIMER_CNTR2, (pitch>>8));
621 /* enable counter2 output to speaker */
622 outb(IO_PPI, inb(IO_PPI) | 3);
624 timeout(sysbeepstop, (void *)NULL, period);
633 * RTC support routines
644 val = inb(IO_RTC + 1);
650 writertc(u_char reg, u_char val)
655 outb(IO_RTC + 1, val);
656 inb(0x84); /* XXX work around wrong order in rtcin() */
662 return(bcd2bin(rtcin(port)));
667 unsigned int delaycount;
668 #define FIRST_GUESS 0x2000
669 static void findcpuspeed(void)
674 /* Put counter in count down mode */
675 outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
676 outb(TIMER_CNTR0, 0xff);
677 outb(TIMER_CNTR0, 0xff);
678 for (i = FIRST_GUESS; i; i--)
681 delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
687 calibrate_clocks(void)
690 u_int count, prev_count, tot_count;
691 u_short sec, start_sec;
694 printf("Calibrating clock(s) ... ");
696 if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
697 !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
701 /* Read the ARTIC. */
704 /* Wait for the ARTIC to changes. */
708 if (sec != start_sec)
713 prev_count = getit();
714 if (prev_count == 0 || prev_count > timer0_max_count)
719 wrmsr(0x10, 0LL); /* XXX 0x10 is the MSR for the TSC */
724 if (count == 0 || count > timer0_max_count)
726 if (count > prev_count)
727 tot_count += prev_count - (count - timer0_max_count);
729 tot_count += prev_count - count;
731 if ((sec == start_sec + 1200) ||
733 (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
739 * Read the cpu cycle counter. The timing considerations are
740 * similar to those for the i8254 clock.
747 printf("TSC clock: %u Hz, ", tsc_freq);
748 printf("i8254 clock: %u Hz\n", tot_count);
754 printf("failed, using default i8254 clock of %u Hz\n",
760 calibrate_clocks(void)
763 u_int count, prev_count, tot_count;
764 int sec, start_sec, timeout;
767 printf("Calibrating clock(s) ... ");
768 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
772 /* Read the mc146818A seconds counter. */
774 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
775 sec = rtcin(RTC_SEC);
782 /* Wait for the mC146818A seconds counter to change. */
785 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
786 sec = rtcin(RTC_SEC);
787 if (sec != start_sec)
794 /* Start keeping track of the i8254 counter. */
795 prev_count = getit();
796 if (prev_count == 0 || prev_count > timer0_max_count)
803 old_tsc = 0; /* shut up gcc */
806 * Wait for the mc146818A seconds counter to change. Read the i8254
807 * counter for each iteration since this is convenient and only
808 * costs a few usec of inaccuracy. The timing of the final reads
809 * of the counters almost matches the timing of the initial reads,
810 * so the main cause of inaccuracy is the varying latency from
811 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
812 * rtcin(RTC_SEC) that returns a changed seconds count. The
813 * maximum inaccuracy from this cause is < 10 usec on 486's.
817 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
818 sec = rtcin(RTC_SEC);
820 if (count == 0 || count > timer0_max_count)
822 if (count > prev_count)
823 tot_count += prev_count - (count - timer0_max_count);
825 tot_count += prev_count - count;
827 if (sec != start_sec)
834 * Read the cpu cycle counter. The timing considerations are
835 * similar to those for the i8254 clock.
838 tsc_freq = rdtsc() - old_tsc;
842 printf("TSC clock: %u Hz, ", tsc_freq);
843 printf("i8254 clock: %u Hz\n", tot_count);
849 printf("failed, using default i8254 clock of %u Hz\n",
856 set_timer_freq(u_int freq, int intr_freq)
859 int new_timer0_max_count;
864 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
865 if (new_timer0_max_count != timer0_max_count) {
866 timer0_max_count = new_timer0_max_count;
867 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
868 outb(TIMER_CNTR0, timer0_max_count & 0xff);
869 outb(TIMER_CNTR0, timer0_max_count >> 8);
876 * i8254_restore is called from apm_default_resume() to reload
877 * the countdown register.
878 * this should not be necessary but there are broken laptops that
879 * do not restore the countdown register on resume.
880 * when it happnes, it messes up the hardclock interval and system clock,
881 * which leads to the infamous "calcru: negative time" problem.
890 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
891 outb(TIMER_CNTR0, timer0_max_count & 0xff);
892 outb(TIMER_CNTR0, timer0_max_count >> 8);
898 * Initialize 8254 timer 0 early so that it can be used in DELAY().
899 * XXX initialization of other timers is unintentionally left blank.
908 if (pc98_machine_type & M_8M)
909 timer_freq = 1996800L; /* 1.9968 MHz */
911 timer_freq = 2457600L; /* 2.4576 MHz */
914 if (cpu_feature & CPUID_TSC)
920 writertc(RTC_STATUSA, rtc_statusa);
921 writertc(RTC_STATUSB, RTCSB_24HR);
924 set_timer_freq(timer_freq, hz);
925 freq = calibrate_clocks();
926 #ifdef CLK_CALIBRATION_LOOP
929 "Press a key on the console to abort clock calibration\n");
930 while (cncheckc() == -1)
936 * Use the calibrated i8254 frequency if it seems reasonable.
937 * Otherwise use the default, and don't use the calibrated i586
940 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
941 if (delta < timer_freq / 100) {
942 #ifndef CLK_USE_I8254_CALIBRATION
945 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
952 "%d Hz differs from default of %d Hz by more than 1%%\n",
957 set_timer_freq(timer_freq, hz);
958 i8254_timecounter.tc_frequency = timer_freq;
959 init_timecounter(&i8254_timecounter);
961 #ifndef CLK_USE_TSC_CALIBRATION
965 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
969 if (tsc_present && tsc_freq == 0) {
971 * Calibration of the i586 clock relative to the mc146818A
972 * clock failed. Do a less accurate calibration relative
973 * to the i8254 clock.
975 u_int64_t old_tsc = rdtsc();
978 tsc_freq = rdtsc() - old_tsc;
979 #ifdef CLK_USE_TSC_CALIBRATION
981 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
987 * We can not use the TSC in SMP mode, until we figure out a
988 * cheap (impossible), reliable and precise (yeah right!) way
989 * to synchronize the TSCs of all the CPUs.
990 * Curse Intel for leaving the counter out of the I/O APIC.
995 * We can not use the TSC if we support APM. Precise timekeeping
996 * on an APM'ed machine is at best a fools pursuit, since
997 * any and all of the time spent in various SMM code can't
998 * be reliably accounted for. Reading the RTC is your only
999 * source of reliable time info. The i8254 looses too of course
1000 * but we need to have some kind of time...
1001 * We don't know at this point whether APM is going to be used
1002 * or not, nor when it might be activated. Play it safe.
1005 #endif /* NAPM > 0 */
1007 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
1008 tsc_timecounter.tc_frequency = tsc_freq;
1009 init_timecounter(&tsc_timecounter);
1012 #endif /* !defined(SMP) */
1017 rtc_serialcombit(int i)
1019 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1021 outb(IO_RTC, ((i&0x01)<<5)|0x17);
1023 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1028 rtc_serialcom(int i)
1030 rtc_serialcombit(i&0x01);
1031 rtc_serialcombit((i&0x02)>>1);
1032 rtc_serialcombit((i&0x04)>>2);
1033 rtc_serialcombit((i&0x08)>>3);
1049 sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
1050 outb(IO_RTC, sa); /* set DI & CLK 0 */
1052 outb(IO_RTC, sa | 0x10); /* CLK 1 */
1055 outb(IO_RTC, sa & 0xef); /* CLK 0 */
1065 sa |= ((inb(0x33) & 0x01) << s);
1066 outb(IO_RTC, 0x17); /* CLK 1 */
1068 outb(IO_RTC, 0x07); /* CLK 0 */
1076 * Initialize the time of day register, based on the time base which is, e.g.
1077 * from a filesystem.
1080 inittodr(time_t base)
1082 unsigned long sec, days;
1090 int second, min, hour;
1097 set_timecounter(&ts);
1102 rtc_serialcom(0x03); /* Time Read */
1103 rtc_serialcom(0x01); /* Register shift command. */
1106 second = bcd2bin(rtc_inb() & 0xff); /* sec */
1107 min = bcd2bin(rtc_inb() & 0xff); /* min */
1108 hour = bcd2bin(rtc_inb() & 0xff); /* hour */
1109 days = bcd2bin(rtc_inb() & 0xff) - 1; /* date */
1111 month = (rtc_inb() >> 4) & 0x0f; /* month */
1112 for (m = 1; m < month; m++)
1113 days += daysinmonth[m-1];
1114 year = bcd2bin(rtc_inb() & 0xff) + 1900; /* year */
1115 /* 2000 year problem */
1120 for (y = 1970; y < year; y++)
1121 days += DAYSPERYEAR + LEAPYEAR(y);
1122 if ((month > 2) && LEAPYEAR(year))
1124 sec = ((( days * 24 +
1128 /* sec now contains the number of seconds, since Jan 1 1970,
1129 in the local time zone */
1131 /* Look if we have a RTC present and the time is valid */
1132 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
1135 /* wait for time update to complete */
1136 /* If RTCSA_TUP is zero, we have at least 244us before next update */
1137 while (rtcin(RTC_STATUSA) & RTCSA_TUP);
1140 #ifdef USE_RTC_CENTURY
1141 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
1143 year = readrtc(RTC_YEAR) + 1900;
1149 month = readrtc(RTC_MONTH);
1150 for (m = 1; m < month; m++)
1151 days += daysinmonth[m-1];
1152 if ((month > 2) && LEAPYEAR(year))
1154 days += readrtc(RTC_DAY) - 1;
1156 for (y = 1970; y < year; y++)
1157 days += DAYSPERYEAR + LEAPYEAR(y);
1158 sec = ((( days * 24 +
1159 readrtc(RTC_HRS)) * 60 +
1160 readrtc(RTC_MIN)) * 60 +
1162 /* sec now contains the number of seconds, since Jan 1 1970,
1163 in the local time zone */
1166 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1168 y = time_second - sec;
1169 if (y <= -2 || y >= 2) {
1170 /* badly off, adjust it */
1174 set_timecounter(&ts);
1180 printf("Invalid time in real time clock.\n");
1181 printf("Check and reset the date immediately!\n");
1185 * Write system time back to RTC
1196 if (disable_rtc_set)
1204 rtc_serialcom(0x01); /* Register shift command. */
1206 /* Calculate local time to put in RTC */
1208 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1210 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1211 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1212 rtc_outb(bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1214 /* We have now the days since 01-01-1970 in tm */
1216 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1218 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1221 /* Now we have the years in y and the day-of-the-year in tm */
1222 for (m = 0; ; m++) {
1225 ml = daysinmonth[m];
1226 if (m == 1 && LEAPYEAR(y))
1234 rtc_outb(bin2bcd(tm+1)); /* Write back Day */
1235 rtc_outb((m << 4) | wd); /* Write back Month & Weekday */
1236 rtc_outb(bin2bcd(y%100)); /* Write back Year */
1238 rtc_serialcom(0x02); /* Time set & Counter hold command. */
1239 rtc_serialcom(0x00); /* Register hold command. */
1241 /* Disable RTC updates and interrupts. */
1242 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1244 /* Calculate local time to put in RTC */
1246 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1248 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1249 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1250 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1252 /* We have now the days since 01-01-1970 in tm */
1253 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
1254 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1256 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1259 /* Now we have the years in y and the day-of-the-year in tm */
1260 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
1261 #ifdef USE_RTC_CENTURY
1262 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1264 for (m = 0; ; m++) {
1267 ml = daysinmonth[m];
1268 if (m == 1 && LEAPYEAR(y))
1275 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1276 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1278 /* Reenable RTC updates and interrupts. */
1279 writertc(RTC_STATUSB, rtc_statusb);
1285 * Start both clocks running.
1291 int apic_8254_trial;
1292 struct intrec *clkdesc;
1293 #endif /* APIC_IO */
1297 if (statclock_disable) {
1299 * The stat interrupt mask is different without the
1300 * statistics clock. Also, don't set the interrupt
1301 * flag which would normally cause the RTC to generate
1304 stat_imask = HWI_MASK | SWI_MASK;
1305 rtc_statusb = RTCSB_24HR;
1307 /* Setting stathz to nonzero early helps avoid races. */
1308 stathz = RTC_NOPROFRATE;
1309 profhz = RTC_PROFRATE;
1313 /* Finish initializing 8253 timer 0. */
1316 apic_8254_intr = isa_apic_irq(0);
1317 apic_8254_trial = 0;
1318 if (apic_8254_intr >= 0 ) {
1319 if (apic_int_type(0, 0) == 3)
1320 apic_8254_trial = 1;
1322 /* look for ExtInt on pin 0 */
1323 if (apic_int_type(0, 0) == 3) {
1325 setup_8254_mixed_mode();
1327 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1330 clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
1331 NULL, &clk_imask, INTR_EXCL);
1332 INTREN(1 << apic_8254_intr);
1336 inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
1340 #endif /* APIC_IO */
1343 /* Initialize RTC. */
1344 writertc(RTC_STATUSA, rtc_statusa);
1345 writertc(RTC_STATUSB, RTCSB_24HR);
1347 /* Don't bother enabling the statistics clock. */
1348 if (statclock_disable)
1350 diag = rtcin(RTC_DIAG);
1352 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1355 if (isa_apic_irq(8) != 8)
1356 panic("APIC RTC != 8");
1357 #endif /* APIC_IO */
1359 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
1366 #endif /* APIC_IO */
1368 writertc(RTC_STATUSB, rtc_statusb);
1372 if (apic_8254_trial) {
1374 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1375 while (read_intr_count(8) < 6)
1377 if (read_intr_count(apic_8254_intr) < 3) {
1379 * The MP table is broken.
1380 * The 8254 was not connected to the specified pin
1382 * Workaround: Limited variant of mixed mode.
1384 INTRDIS(1 << apic_8254_intr);
1385 inthand_remove(clkdesc);
1386 printf("APIC_IO: Broken MP table detected: "
1387 "8254 is not connected to IO APIC int pin %d\n",
1391 setup_8254_mixed_mode();
1392 inthand_add("clk", apic_8254_intr,(inthand2_t *)clkintr,
1393 NULL, &clk_imask, INTR_EXCL);
1394 INTREN(1 << apic_8254_intr);
1399 printf("APIC_IO: routing 8254 via pin %d\n",apic_8254_intr);
1401 printf("APIC_IO: routing 8254 via 8259 on pin 0\n");
1408 read_intr_count(int vec)
1411 up = intr_countp[vec];
1418 setup_8254_mixed_mode()
1421 * Allow 8254 timer to INTerrupt 8259:
1422 * re-initialize master 8259:
1423 * reset; prog 4 bytes, single ICU, edge triggered
1425 outb(IO_ICU1, 0x13);
1427 outb(IO_ICU1 + 2, NRSVIDT); /* start vector (unused) */
1428 outb(IO_ICU1 + 2, 0x00); /* ignore slave */
1429 outb(IO_ICU1 + 2, 0x03); /* auto EOI, 8086 */
1430 outb(IO_ICU1 + 2, 0xfe); /* unmask INT0 */
1432 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1433 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1434 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1435 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1437 /* program IO APIC for type 3 INT on INT0 */
1438 if (ext_int_setup(0, 0) < 0)
1439 panic("8254 redirect via APIC pin0 impossible!");
1444 setstatclockrate(int newhz)
1447 if (newhz == RTC_PROFRATE)
1448 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1450 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1451 writertc(RTC_STATUSA, rtc_statusa);
1456 sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
1462 * Use `i8254' instead of `timer' in external names because `timer'
1463 * is is too generic. Should use it everywhere.
1466 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1467 if (error == 0 && req->newptr != NULL) {
1468 if (timer0_state != RELEASED)
1469 return (EBUSY); /* too much trouble to handle */
1470 set_timer_freq(freq, hz);
1471 i8254_timecounter.tc_frequency = freq;
1472 update_timecounter(&i8254_timecounter);
1477 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1478 0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1481 sysctl_machdep_tsc_freq SYSCTL_HANDLER_ARGS
1486 if (tsc_timecounter.tc_frequency == 0)
1487 return (EOPNOTSUPP);
1489 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1490 if (error == 0 && req->newptr != NULL) {
1492 tsc_timecounter.tc_frequency = tsc_freq;
1493 update_timecounter(&tsc_timecounter);
1498 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1499 0, sizeof(u_int), sysctl_machdep_tsc_freq, "I", "");
1502 i8254_get_timecount(struct timecounter *tc)
1511 /* Select timer0 and latch counter value. */
1512 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1514 low = inb(TIMER_CNTR0);
1515 high = inb(TIMER_CNTR0);
1516 count = timer0_max_count - ((high << 8) | low);
1517 if (count < i8254_lastcount ||
1518 (!i8254_ticked && (clkintr_pending ||
1519 ((count < 20 || (!(ef & PSL_I) && count < timer0_max_count / 2u)) &&
1521 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1522 /* XXX this assumes that apic_8254_intr is < 24. */
1523 (lapic_irr1 & (1 << apic_8254_intr))))
1525 (inb(IO_ICU1) & 1)))
1529 i8254_offset += timer0_max_count;
1531 i8254_lastcount = count;
1532 count += i8254_offset;
1539 tsc_get_timecount(struct timecounter *tc)