2 * Copyright (c) 1990 The Regents of the University of California.
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz and Don Ahn.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
37 * $FreeBSD: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki Exp $
38 * $DragonFly: src/sys/i386/isa/Attic/clock.c,v 1.10 2004/01/08 08:11:12 dillon Exp $
42 * Routines to handle clock hardware.
46 * inittodr, settodr and support routines written
47 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
49 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
54 #include "opt_clock.h"
56 #include <sys/param.h>
57 #include <sys/systm.h>
59 #include <sys/kernel.h>
63 #include <sys/sysctl.h>
66 #include <machine/clock.h>
67 #ifdef CLK_CALIBRATION_LOOP
69 #include <machine/cputypes.h>
70 #include <machine/frame.h>
71 #include <machine/ipl.h>
72 #include <machine/limits.h>
73 #include <machine/md_var.h>
74 #include <machine/psl.h>
76 #include <machine/segments.h>
78 #if defined(SMP) || defined(APIC_IO)
79 #include <machine/smp.h>
80 #endif /* SMP || APIC_IO */
81 #include <machine/specialreg.h>
83 #include <i386/isa/icu.h>
84 #include <bus/isa/i386/isa.h>
85 #include <bus/isa/rtc.h>
86 #include <i386/isa/timerreg.h>
88 #include <i386/isa/intr_machdep.h>
91 #include <bus/mca/i386/mca_machdep.h>
95 #include <i386/isa/intr_machdep.h>
96 /* The interrupt triggered by the 8254 (timer) chip */
98 static u_long read_intr_count (int vec);
99 static void setup_8254_mixed_mode (void);
103 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
104 * can use a simple formula for leap years.
106 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
107 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
109 #define TIMER_DIV(x) (timer_freq / (x))
110 #define FRAC_ADJUST(x) (timer_freq - ((timer_freq / (x)) * (x)))
113 * Time in timer cycles that it takes for microtime() to disable interrupts
114 * and latch the count. microtime() currently uses "cli; outb ..." so it
115 * normally takes less than 2 timer cycles. Add a few for cache misses.
116 * Add a few more to allow for latency in bogus calls to microtime() with
117 * interrupts already disabled.
119 #define TIMER0_LATCH_COUNT 20
122 * Maximum frequency that we are willing to allow for timer0. Must be
123 * low enough to guarantee that the timer interrupt handler returns
124 * before the next timer interrupt.
126 #define TIMER0_MAX_FREQ 20000
128 int adjkerntz; /* local offset from GMT in seconds */
130 int disable_rtc_set; /* disable resettodr() if != 0 */
131 volatile u_int idelayed;
132 int statclock_disable;
133 u_int stat_imask = SWI_CLOCK_MASK;
135 #define TIMER_FREQ 1193182
137 u_int timer_freq = TIMER_FREQ;
138 int timer0_max_count;
139 u_int timer0_frac_freq;
142 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
144 static int beeping = 0;
145 static u_int clk_imask = HWI_MASK | SWI_MASK;
146 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
147 static u_int hardclock_max_count;
148 static u_int32_t i8254_lastcount;
149 static u_int32_t i8254_offset;
150 static int i8254_ticked;
152 * XXX new_function and timer_func should not handle clockframes, but
153 * timer_func currently needs to hold hardclock to handle the
154 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
155 * to switch between clkintr() and a slightly different timerintr().
157 static void (*new_function) (struct clockframe *frame);
158 static u_int new_rate;
159 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
160 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
161 static u_int timer0_prescaler_count;
163 /* Values for timerX_state: */
165 #define RELEASE_PENDING 1
167 #define ACQUIRE_PENDING 3
169 static u_char timer0_state;
170 static u_char timer2_state;
171 static void (*timer_func) (struct clockframe *frame) = hardclock;
172 static u_int tsc_present;
174 static unsigned i8254_get_timecount (struct timecounter *tc);
175 static unsigned tsc_get_timecount (struct timecounter *tc);
176 static void set_timer_freq(u_int freq, int intr_freq);
178 static struct timecounter tsc_timecounter = {
179 tsc_get_timecount, /* get_timecount */
181 ~0u, /* counter_mask */
186 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD,
187 &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
189 static struct timecounter i8254_timecounter = {
190 i8254_get_timecount, /* get_timecount */
192 ~0u, /* counter_mask */
197 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD,
198 &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
201 clkintr(struct clockframe frame)
206 if (timecounter->tc_get_timecount == i8254_get_timecount) {
211 i8254_offset += timer0_max_count;
215 * Lets say we are running at 100Hz. Our counter load will
216 * be 1193182 / 100 = 11931.82, which is really only 11931.
217 * The fractional code accounts for the .82 count. When it
218 * exceeds 1.00 count we adjust the reload register by + 1
219 * to compensate for the error. We must also adjust
222 * If we did not do this a high frequency would cause the
223 * actual interrupt rate to seriously diverge from 'hz'.
230 * Use the previously synchronized timecounter value to phase-sync
231 * our hz clock interrupt. We do this by reloading the initial count
232 * register of timer0, which takes effect the next time it reloads.
234 phase = 1000000 / timer0_frac_freq;
235 delta = timecounter->tc_microtime.tv_usec % phase;
238 if (delta < (phase >> 1)) {
240 * Current time is a bit past what we expect, speed up the
243 outb(TIMER_CNTR0, timer0_max_count & 0xff);
244 outb(TIMER_CNTR0, timer0_max_count >> 8);
247 * Current time is a bit before what we expect, slow down
248 * the clock interrupt.
250 outb(TIMER_CNTR0, (timer0_max_count + 1) & 0xff);
251 outb(TIMER_CNTR0, (timer0_max_count + 1) >> 8);
252 ++i8254_offset; /* take into account extra count for tc==8254*/
259 switch (timer0_state) {
264 timer0_prescaler_count += timer0_max_count;
265 if (timer0_prescaler_count >= hardclock_max_count) {
266 timer0_prescaler_count -= hardclock_max_count;
271 case ACQUIRE_PENDING:
273 i8254_offset = i8254_get_timecount(NULL);
275 timer0_max_count = TIMER_DIV(new_rate);
276 timer0_frac_freq = new_rate;
277 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
278 outb(TIMER_CNTR0, timer0_max_count & 0xff);
279 outb(TIMER_CNTR0, timer0_max_count >> 8);
281 timer_func = new_function;
282 timer0_state = ACQUIRED;
285 case RELEASE_PENDING:
286 timer0_prescaler_count += timer0_max_count;
287 if (timer0_prescaler_count >= hardclock_max_count) {
289 i8254_offset = i8254_get_timecount(NULL);
291 timer0_max_count = hardclock_max_count;
293 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
294 outb(TIMER_CNTR0, timer0_max_count & 0xff);
295 outb(TIMER_CNTR0, timer0_max_count >> 8);
297 timer0_prescaler_count = 0;
298 timer_func = hardclock;
299 timer0_state = RELEASED;
306 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
308 outb(0x61, inb(0x61) | 0x80);
313 * The acquire and release functions must be called at ipl >= splclock().
316 acquire_timer0(int rate, void (*function) (struct clockframe *frame))
320 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
322 switch (timer0_state) {
325 timer0_state = ACQUIRE_PENDING;
328 case RELEASE_PENDING:
329 if (rate != old_rate)
332 * The timer has been released recently, but is being
333 * re-acquired before the release completed. In this
334 * case, we simply reclaim it as if it had not been
337 timer0_state = ACQUIRED;
341 return (-1); /* busy */
343 new_function = function;
344 old_rate = new_rate = rate;
349 acquire_timer2(int mode)
352 if (timer2_state != RELEASED)
354 timer2_state = ACQUIRED;
357 * This access to the timer registers is as atomic as possible
358 * because it is a single instruction. We could do better if we
359 * knew the rate. Use of splclock() limits glitches to 10-100us,
360 * and this is probably good enough for timer2, so we aren't as
361 * careful with it as with timer0.
363 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
371 switch (timer0_state) {
374 timer0_state = RELEASE_PENDING;
377 case ACQUIRE_PENDING:
378 /* Nothing happened yet, release quickly. */
379 timer0_state = RELEASED;
392 if (timer2_state != ACQUIRED)
394 timer2_state = RELEASED;
395 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
400 * This routine receives statistical clock interrupts from the RTC.
401 * As explained above, these occur at 128 interrupts per second.
402 * When profiling, we receive interrupts at a rate of 1024 Hz.
404 * This does not actually add as much overhead as it sounds, because
405 * when the statistical clock is active, the hardclock driver no longer
406 * needs to keep (inaccurate) statistics on its own. This decouples
407 * statistics gathering from scheduling interrupts.
409 * The RTC chip requires that we read status register C (RTC_INTR)
410 * to acknowledge an interrupt, before it will generate the next one.
411 * Under high interrupt load, rtcintr() can be indefinitely delayed and
412 * the clock can tick immediately after the read from RTC_INTR. In this
413 * case, the mc146818A interrupt signal will not drop for long enough
414 * to register with the 8259 PIC. If an interrupt is missed, the stat
415 * clock will halt, considerably degrading system performance. This is
416 * why we use 'while' rather than a more straightforward 'if' below.
417 * Stat clock ticks can still be lost, causing minor loss of accuracy
418 * in the statistics, but the stat clock will no longer stop.
421 rtcintr(struct clockframe frame)
423 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
431 DB_SHOW_COMMAND(rtc, rtc)
433 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
434 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
435 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
436 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
447 /* Select timer0 and latch counter value. */
448 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
450 low = inb(TIMER_CNTR0);
451 high = inb(TIMER_CNTR0);
454 return ((high << 8) | low);
458 * Wait "n" microseconds.
459 * Relies on timer 1 counting down from (timer_freq / hz)
460 * Note: timer had better have been programmed before this is first used!
465 int delta, prev_tick, tick, ticks_left;
470 static int state = 0;
474 for (n1 = 1; n1 <= 10000000; n1 *= 10)
479 printf("DELAY(%d)...", n);
482 * Guard against the timer being uninitialized if we are called
483 * early for console i/o.
485 if (timer0_max_count == 0)
486 set_timer_freq(timer_freq, hz);
489 * Read the counter first, so that the rest of the setup overhead is
490 * counted. Guess the initial overhead is 20 usec (on most systems it
491 * takes about 1.5 usec for each of the i/o's in getit(). The loop
492 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
493 * multiplications and divisions to scale the count take a while).
496 n -= 0; /* XXX actually guess no initial overhead */
498 * Calculate (n * (timer_freq / 1e6)) without using floating point
499 * and without any avoidable overflows.
505 * Use fixed point to avoid a slow division by 1000000.
506 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
507 * 2^15 is the first power of 2 that gives exact results
508 * for n between 0 and 256.
510 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
513 * Don't bother using fixed point, although gcc-2.7.2
514 * generates particularly poor code for the long long
515 * division, since even the slow way will complete long
516 * before the delay is up (unless we're interrupted).
518 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
521 while (ticks_left > 0) {
526 delta = prev_tick - tick;
529 delta += timer0_max_count;
531 * Guard against timer0_max_count being wrong.
532 * This shouldn't happen in normal operation,
533 * but it may happen if set_timer_freq() is
543 printf(" %d calls to getit() at %d usec each\n",
544 getit_calls, (n + 5) / getit_calls);
549 sysbeepstop(void *chan)
551 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
557 sysbeep(int pitch, int period)
561 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
563 /* Something else owns it. */
565 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
568 outb(TIMER_CNTR2, pitch);
569 outb(TIMER_CNTR2, (pitch>>8));
572 /* enable counter2 output to speaker */
573 outb(IO_PPI, inb(IO_PPI) | 3);
575 timeout(sysbeepstop, (void *)NULL, period);
582 * RTC support routines
595 val = inb(IO_RTC + 1);
602 writertc(u_char reg, u_char val)
610 outb(IO_RTC + 1, val);
611 inb(0x84); /* XXX work around wrong order in rtcin() */
618 return(bcd2bin(rtcin(port)));
622 calibrate_clocks(void)
625 u_int count, prev_count, tot_count;
626 int sec, start_sec, timeout;
629 printf("Calibrating clock(s) ... ");
630 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
634 /* Read the mc146818A seconds counter. */
636 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
637 sec = rtcin(RTC_SEC);
644 /* Wait for the mC146818A seconds counter to change. */
647 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
648 sec = rtcin(RTC_SEC);
649 if (sec != start_sec)
656 /* Start keeping track of the i8254 counter. */
657 prev_count = getit();
658 if (prev_count == 0 || prev_count > timer0_max_count)
665 old_tsc = 0; /* shut up gcc */
668 * Wait for the mc146818A seconds counter to change. Read the i8254
669 * counter for each iteration since this is convenient and only
670 * costs a few usec of inaccuracy. The timing of the final reads
671 * of the counters almost matches the timing of the initial reads,
672 * so the main cause of inaccuracy is the varying latency from
673 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
674 * rtcin(RTC_SEC) that returns a changed seconds count. The
675 * maximum inaccuracy from this cause is < 10 usec on 486's.
679 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
680 sec = rtcin(RTC_SEC);
682 if (count == 0 || count > timer0_max_count)
684 if (count > prev_count)
685 tot_count += prev_count - (count - timer0_max_count);
687 tot_count += prev_count - count;
689 if (sec != start_sec)
696 * Read the cpu cycle counter. The timing considerations are
697 * similar to those for the i8254 clock.
700 tsc_freq = rdtsc() - old_tsc;
704 printf("TSC clock: %u Hz, ", tsc_freq);
705 printf("i8254 clock: %u Hz\n", tot_count);
711 printf("failed, using default i8254 clock of %u Hz\n",
717 set_timer_freq(u_int freq, int intr_freq)
719 int new_timer0_max_count;
723 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
724 timer0_frac_freq = intr_freq;
725 if (new_timer0_max_count != timer0_max_count) {
726 timer0_max_count = new_timer0_max_count;
727 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
728 outb(TIMER_CNTR0, timer0_max_count & 0xff);
729 outb(TIMER_CNTR0, timer0_max_count >> 8);
738 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
739 outb(TIMER_CNTR0, timer0_max_count & 0xff);
740 outb(TIMER_CNTR0, timer0_max_count >> 8);
748 /* Restore all of the RTC's "status" (actually, control) registers. */
749 writertc(RTC_STATUSB, RTCSB_24HR);
750 writertc(RTC_STATUSA, rtc_statusa);
751 writertc(RTC_STATUSB, rtc_statusb);
755 * Restore all the timers non-atomically (XXX: should be atomically).
757 * This function is called from apm_default_resume() to restore all the timers.
758 * This should not be necessary, but there are broken laptops that do not
759 * restore all the timers on resume.
765 i8254_restore(); /* restore timer_freq and hz */
766 rtc_restore(); /* reenable RTC interrupts */
770 * Initialize 8254 timer 0 early so that it can be used in DELAY().
771 * XXX initialization of other timers is unintentionally left blank.
778 if (cpu_feature & CPUID_TSC)
783 writertc(RTC_STATUSA, rtc_statusa);
784 writertc(RTC_STATUSB, RTCSB_24HR);
786 set_timer_freq(timer_freq, hz);
787 freq = calibrate_clocks();
788 #ifdef CLK_CALIBRATION_LOOP
791 "Press a key on the console to abort clock calibration\n");
792 while (cncheckc() == -1)
798 * Use the calibrated i8254 frequency if it seems reasonable.
799 * Otherwise use the default, and don't use the calibrated i586
802 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
803 if (delta < timer_freq / 100) {
804 #ifndef CLK_USE_I8254_CALIBRATION
807 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
814 "%d Hz differs from default of %d Hz by more than 1%%\n",
819 set_timer_freq(timer_freq, hz);
820 i8254_timecounter.tc_frequency = timer_freq;
821 init_timecounter(&i8254_timecounter);
823 #ifndef CLK_USE_TSC_CALIBRATION
827 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
831 if (tsc_present && tsc_freq == 0) {
833 * Calibration of the i586 clock relative to the mc146818A
834 * clock failed. Do a less accurate calibration relative
835 * to the i8254 clock.
837 u_int64_t old_tsc = rdtsc();
840 tsc_freq = rdtsc() - old_tsc;
841 #ifdef CLK_USE_TSC_CALIBRATION
843 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
849 * We can not use the TSC in SMP mode, until we figure out a
850 * cheap (impossible), reliable and precise (yeah right!) way
851 * to synchronize the TSCs of all the CPUs.
852 * Curse Intel for leaving the counter out of the I/O APIC.
857 * We can not use the TSC if we support APM. Precise timekeeping
858 * on an APM'ed machine is at best a fools pursuit, since
859 * any and all of the time spent in various SMM code can't
860 * be reliably accounted for. Reading the RTC is your only
861 * source of reliable time info. The i8254 looses too of course
862 * but we need to have some kind of time...
863 * We don't know at this point whether APM is going to be used
864 * or not, nor when it might be activated. Play it safe.
867 #endif /* NAPM > 0 */
869 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
870 tsc_timecounter.tc_frequency = tsc_freq;
871 init_timecounter(&tsc_timecounter);
874 #endif /* !defined(SMP) */
878 * Initialize the time of day register, based on the time base which is, e.g.
882 inittodr(time_t base)
884 unsigned long sec, days;
894 set_timecounter(&ts);
898 /* Look if we have a RTC present and the time is valid */
899 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
902 /* wait for time update to complete */
903 /* If RTCSA_TUP is zero, we have at least 244us before next update */
905 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
911 #ifdef USE_RTC_CENTURY
912 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
914 year = readrtc(RTC_YEAR) + 1900;
922 month = readrtc(RTC_MONTH);
923 for (m = 1; m < month; m++)
924 days += daysinmonth[m-1];
925 if ((month > 2) && LEAPYEAR(year))
927 days += readrtc(RTC_DAY) - 1;
929 for (y = 1970; y < year; y++)
930 days += DAYSPERYEAR + LEAPYEAR(y);
931 sec = ((( days * 24 +
932 readrtc(RTC_HRS)) * 60 +
933 readrtc(RTC_MIN)) * 60 +
935 /* sec now contains the number of seconds, since Jan 1 1970,
936 in the local time zone */
938 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
940 y = time_second - sec;
941 if (y <= -2 || y >= 2) {
942 /* badly off, adjust it */
945 set_timecounter(&ts);
951 printf("Invalid time in real time clock.\n");
952 printf("Check and reset the date immediately!\n");
956 * Write system time back to RTC
971 /* Disable RTC updates and interrupts. */
972 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
974 /* Calculate local time to put in RTC */
976 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
978 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
979 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
980 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
982 /* We have now the days since 01-01-1970 in tm */
983 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
984 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
986 y++, m = DAYSPERYEAR + LEAPYEAR(y))
989 /* Now we have the years in y and the day-of-the-year in tm */
990 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
991 #ifdef USE_RTC_CENTURY
992 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
998 if (m == 1 && LEAPYEAR(y))
1005 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1006 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1008 /* Reenable RTC updates and interrupts. */
1009 writertc(RTC_STATUSB, rtc_statusb);
1014 * Start both clocks running.
1021 int apic_8254_trial;
1022 struct intrec *clkdesc;
1023 #endif /* APIC_IO */
1025 if (statclock_disable) {
1027 * The stat interrupt mask is different without the
1028 * statistics clock. Also, don't set the interrupt
1029 * flag which would normally cause the RTC to generate
1032 stat_imask = HWI_MASK | SWI_MASK;
1033 rtc_statusb = RTCSB_24HR;
1035 /* Setting stathz to nonzero early helps avoid races. */
1036 stathz = RTC_NOPROFRATE;
1037 profhz = RTC_PROFRATE;
1040 /* Finish initializing 8253 timer 0. */
1043 apic_8254_intr = isa_apic_irq(0);
1044 apic_8254_trial = 0;
1045 if (apic_8254_intr >= 0 ) {
1046 if (apic_int_type(0, 0) == 3)
1047 apic_8254_trial = 1;
1049 /* look for ExtInt on pin 0 */
1050 if (apic_int_type(0, 0) == 3) {
1051 apic_8254_intr = apic_irq(0, 0);
1052 setup_8254_mixed_mode();
1054 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1057 clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
1058 NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1059 INTREN(1 << apic_8254_intr);
1063 inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
1064 INTR_EXCL | INTR_FAST);
1067 #endif /* APIC_IO */
1069 /* Initialize RTC. */
1070 writertc(RTC_STATUSA, rtc_statusa);
1071 writertc(RTC_STATUSB, RTCSB_24HR);
1073 /* Don't bother enabling the statistics clock. */
1074 if (statclock_disable)
1076 diag = rtcin(RTC_DIAG);
1078 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1081 if (isa_apic_irq(8) != 8)
1082 panic("APIC RTC != 8");
1083 #endif /* APIC_IO */
1085 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
1086 INTR_EXCL | INTR_FAST);
1092 #endif /* APIC_IO */
1094 writertc(RTC_STATUSB, rtc_statusb);
1097 if (apic_8254_trial) {
1099 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1100 while (read_intr_count(8) < 6)
1102 if (read_intr_count(apic_8254_intr) < 3) {
1104 * The MP table is broken.
1105 * The 8254 was not connected to the specified pin
1107 * Workaround: Limited variant of mixed mode.
1109 INTRDIS(1 << apic_8254_intr);
1110 inthand_remove(clkdesc);
1111 printf("APIC_IO: Broken MP table detected: "
1112 "8254 is not connected to "
1113 "IOAPIC #%d intpin %d\n",
1114 int_to_apicintpin[apic_8254_intr].ioapic,
1115 int_to_apicintpin[apic_8254_intr].int_pin);
1117 * Revoke current ISA IRQ 0 assignment and
1118 * configure a fallback interrupt routing from
1119 * the 8254 Timer via the 8259 PIC to the
1120 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1121 * We reuse the low level interrupt handler number.
1123 if (apic_irq(0, 0) < 0) {
1124 revoke_apic_irq(apic_8254_intr);
1125 assign_apic_irq(0, 0, apic_8254_intr);
1127 apic_8254_intr = apic_irq(0, 0);
1128 setup_8254_mixed_mode();
1129 inthand_add("clk", apic_8254_intr,
1130 (inthand2_t *)clkintr,
1131 NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1132 INTREN(1 << apic_8254_intr);
1136 if (apic_int_type(0, 0) != 3 ||
1137 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1138 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1139 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1140 int_to_apicintpin[apic_8254_intr].ioapic,
1141 int_to_apicintpin[apic_8254_intr].int_pin);
1144 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1151 read_intr_count(int vec)
1154 up = intr_countp[vec];
1161 setup_8254_mixed_mode()
1164 * Allow 8254 timer to INTerrupt 8259:
1165 * re-initialize master 8259:
1166 * reset; prog 4 bytes, single ICU, edge triggered
1168 outb(IO_ICU1, 0x13);
1169 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1170 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1171 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1172 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1174 /* program IO APIC for type 3 INT on INT0 */
1175 if (ext_int_setup(0, 0) < 0)
1176 panic("8254 redirect via APIC pin0 impossible!");
1181 setstatclockrate(int newhz)
1183 if (newhz == RTC_PROFRATE)
1184 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1186 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1187 writertc(RTC_STATUSA, rtc_statusa);
1191 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1197 * Use `i8254' instead of `timer' in external names because `timer'
1198 * is is too generic. Should use it everywhere.
1201 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1202 if (error == 0 && req->newptr != NULL) {
1203 if (timer0_state != RELEASED)
1204 return (EBUSY); /* too much trouble to handle */
1205 set_timer_freq(freq, hz);
1206 i8254_timecounter.tc_frequency = freq;
1207 update_timecounter(&i8254_timecounter);
1212 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1213 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
1216 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1221 if (tsc_timecounter.tc_frequency == 0)
1222 return (EOPNOTSUPP);
1224 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1225 if (error == 0 && req->newptr != NULL) {
1227 tsc_timecounter.tc_frequency = tsc_freq;
1228 update_timecounter(&tsc_timecounter);
1233 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1234 0, sizeof(u_int), sysctl_machdep_tsc_freq, "IU", "");
1237 i8254_get_timecount(struct timecounter *tc)
1247 * Select timer0 and latch counter value. Because we may reload
1248 * the counter with timer0_max_count + 1 to correct the frequency
1249 * our delta count calculation must use timer0_max_count + 1.
1251 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1253 low = inb(TIMER_CNTR0);
1254 high = inb(TIMER_CNTR0);
1255 count = timer0_max_count + 1 - ((high << 8) | low);
1256 if (count < i8254_lastcount ||
1257 (!i8254_ticked && (clkintr_pending ||
1258 ((count < 20 || (!(ef & PSL_I) && count < timer0_max_count / 2u)) &&
1260 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1261 /* XXX this assumes that apic_8254_intr is < 24. */
1262 (lapic_irr1 & (1 << apic_8254_intr))))
1264 (inb(IO_ICU1) & 1)))
1268 i8254_offset += timer0_max_count;
1270 i8254_lastcount = count;
1271 count += i8254_offset;
1277 tsc_get_timecount(struct timecounter *tc)
1282 #ifdef KERN_TIMESTAMP
1283 #define KERN_TIMESTAMP_SIZE 16384
1284 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1285 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1286 sizeof(tsc), "LU", "Kernel timestamps");
1292 tsc[i] = (u_int32_t)rdtsc();
1295 if (i >= KERN_TIMESTAMP_SIZE)
1297 tsc[i] = 0; /* mark last entry */
1299 #endif /* KERN_TIMESTAMP */