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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
39 * Routines to handle clock hardware.
43 * inittodr, settodr and support routines written
44 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
46 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
49 #include "opt_clock.h"
52 #include <sys/param.h>
53 #include <sys/systm.h>
55 #include <sys/clock.h>
57 #include <sys/fcntl.h>
60 #include <sys/mutex.h>
63 #include <sys/timetc.h>
65 #include <sys/kernel.h>
66 #include <sys/limits.h>
67 #include <sys/module.h>
68 #include <sys/sched.h>
69 #include <sys/sysctl.h>
71 #include <sys/power.h>
73 #include <machine/clock.h>
74 #include <machine/cpu.h>
75 #include <machine/frame.h>
76 #include <machine/intr_machdep.h>
77 #include <machine/md_var.h>
78 #include <machine/psl.h>
79 #include <machine/apicvar.h>
80 #include <machine/specialreg.h>
81 #include <machine/ppireg.h>
82 #include <machine/timerreg.h>
86 #include <isa/isareg.h>
87 #include <isa/isavar.h>
91 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
92 * can use a simple formula for leap years.
94 #define LEAPYEAR(y) (((u_int)(y) % 4 == 0) ? 1 : 0)
95 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
97 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
102 int statclock_disable;
104 #define TIMER_FREQ 1193182
106 u_int timer_freq = TIMER_FREQ;
107 int timer0_max_count;
108 int timer0_real_max_count;
109 #define RTC_LOCK mtx_lock_spin(&clock_lock)
110 #define RTC_UNLOCK mtx_unlock_spin(&clock_lock)
112 static int beeping = 0;
113 static struct mtx clock_lock;
114 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
115 static struct intsrc *i8254_intsrc;
116 static u_int32_t i8254_lastcount;
117 static u_int32_t i8254_offset;
118 static int (*i8254_pending)(struct intsrc *);
119 static int i8254_ticked;
120 static int using_lapic_timer;
121 static int rtc_reg = -1;
122 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
123 static u_char rtc_statusb = RTCSB_24HR;
125 /* Values for timerX_state: */
127 #define RELEASE_PENDING 1
129 #define ACQUIRE_PENDING 3
131 static u_char timer2_state;
133 static unsigned i8254_get_timecount(struct timecounter *tc);
134 static unsigned i8254_simple_get_timecount(struct timecounter *tc);
135 static void set_timer_freq(u_int freq, int intr_freq);
137 static struct timecounter i8254_timecounter = {
138 i8254_get_timecount, /* get_timecount */
140 ~0u, /* counter_mask */
147 clkintr(struct trapframe *frame)
150 if (timecounter->tc_get_timecount == i8254_get_timecount) {
151 mtx_lock_spin(&clock_lock);
155 i8254_offset += timer0_max_count;
159 mtx_unlock_spin(&clock_lock);
161 KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
162 hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
163 return (FILTER_HANDLED);
167 acquire_timer2(int mode)
170 if (timer2_state != RELEASED)
172 timer2_state = ACQUIRED;
175 * This access to the timer registers is as atomic as possible
176 * because it is a single instruction. We could do better if we
177 * knew the rate. Use of splclock() limits glitches to 10-100us,
178 * and this is probably good enough for timer2, so we aren't as
179 * careful with it as with timer0.
181 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
190 if (timer2_state != ACQUIRED)
192 timer2_state = RELEASED;
193 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
198 * This routine receives statistical clock interrupts from the RTC.
199 * As explained above, these occur at 128 interrupts per second.
200 * When profiling, we receive interrupts at a rate of 1024 Hz.
202 * This does not actually add as much overhead as it sounds, because
203 * when the statistical clock is active, the hardclock driver no longer
204 * needs to keep (inaccurate) statistics on its own. This decouples
205 * statistics gathering from scheduling interrupts.
207 * The RTC chip requires that we read status register C (RTC_INTR)
208 * to acknowledge an interrupt, before it will generate the next one.
209 * Under high interrupt load, rtcintr() can be indefinitely delayed and
210 * the clock can tick immediately after the read from RTC_INTR. In this
211 * case, the mc146818A interrupt signal will not drop for long enough
212 * to register with the 8259 PIC. If an interrupt is missed, the stat
213 * clock will halt, considerably degrading system performance. This is
214 * why we use 'while' rather than a more straightforward 'if' below.
215 * Stat clock ticks can still be lost, causing minor loss of accuracy
216 * in the statistics, but the stat clock will no longer stop.
219 rtcintr(struct trapframe *frame)
223 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
225 if (profprocs != 0) {
228 profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
231 statclock(TRAPF_USERMODE(frame));
233 return(flag ? FILTER_HANDLED : FILTER_STRAY);
240 DB_SHOW_COMMAND(rtc, rtc)
242 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
243 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
244 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
245 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
254 mtx_lock_spin(&clock_lock);
256 /* Select timer0 and latch counter value. */
257 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
259 low = inb(TIMER_CNTR0);
260 high = inb(TIMER_CNTR0);
262 mtx_unlock_spin(&clock_lock);
263 return ((high << 8) | low);
267 * Wait "n" microseconds.
268 * Relies on timer 1 counting down from (timer_freq / hz)
269 * Note: timer had better have been programmed before this is first used!
274 int delta, prev_tick, tick, ticks_left;
279 static int state = 0;
282 if (tsc_freq != 0 && !tsc_is_broken) {
283 uint64_t start, end, now;
287 end = start + (tsc_freq * n) / 1000000;
290 } while (now < end || (now > start && end < start));
297 for (n1 = 1; n1 <= 10000000; n1 *= 10)
302 printf("DELAY(%d)...", n);
305 * Read the counter first, so that the rest of the setup overhead is
306 * counted. Guess the initial overhead is 20 usec (on most systems it
307 * takes about 1.5 usec for each of the i/o's in getit(). The loop
308 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
309 * multiplications and divisions to scale the count take a while).
311 * However, if ddb is active then use a fake counter since reading
312 * the i8254 counter involves acquiring a lock. ddb must not do
313 * locking for many reasons, but it calls here for at least atkbd
322 n -= 0; /* XXX actually guess no initial overhead */
324 * Calculate (n * (timer_freq / 1e6)) without using floating point
325 * and without any avoidable overflows.
331 * Use fixed point to avoid a slow division by 1000000.
332 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
333 * 2^15 is the first power of 2 that gives exact results
334 * for n between 0 and 256.
336 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
339 * Don't bother using fixed point, although gcc-2.7.2
340 * generates particularly poor code for the long long
341 * division, since even the slow way will complete long
342 * before the delay is up (unless we're interrupted).
344 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
347 while (ticks_left > 0) {
351 tick = prev_tick - 1;
353 tick = timer0_max_count;
360 delta = prev_tick - tick;
363 delta += timer0_max_count;
365 * Guard against timer0_max_count being wrong.
366 * This shouldn't happen in normal operation,
367 * but it may happen if set_timer_freq() is
377 printf(" %d calls to getit() at %d usec each\n",
378 getit_calls, (n + 5) / getit_calls);
383 sysbeepstop(void *chan)
385 ppi_spkr_off(); /* disable counter2 output to speaker */
386 timer_spkr_release();
391 sysbeep(int pitch, int period)
395 if (timer_spkr_acquire())
397 /* Something else owns it. */
399 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
401 mtx_lock_spin(&clock_lock);
402 spkr_set_pitch(pitch);
403 mtx_unlock_spin(&clock_lock);
405 /* enable counter2 output to speaker */
408 timeout(sysbeepstop, (void *)NULL, period);
415 * RTC support routines
425 if (rtc_reg != reg) {
431 val = inb(IO_RTC + 1);
437 writertc(int reg, u_char val)
441 if (rtc_reg != reg) {
447 outb(IO_RTC + 1, val);
455 return(bcd2bin(rtcin(port)));
459 calibrate_clocks(void)
461 u_int count, prev_count, tot_count;
462 int sec, start_sec, timeout;
465 printf("Calibrating clock(s) ... ");
466 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
470 /* Read the mc146818A seconds counter. */
472 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
473 sec = rtcin(RTC_SEC);
480 /* Wait for the mC146818A seconds counter to change. */
483 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
484 sec = rtcin(RTC_SEC);
485 if (sec != start_sec)
492 /* Start keeping track of the i8254 counter. */
493 prev_count = getit();
494 if (prev_count == 0 || prev_count > timer0_max_count)
499 * Wait for the mc146818A seconds counter to change. Read the i8254
500 * counter for each iteration since this is convenient and only
501 * costs a few usec of inaccuracy. The timing of the final reads
502 * of the counters almost matches the timing of the initial reads,
503 * so the main cause of inaccuracy is the varying latency from
504 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
505 * rtcin(RTC_SEC) that returns a changed seconds count. The
506 * maximum inaccuracy from this cause is < 10 usec on 486's.
510 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
511 sec = rtcin(RTC_SEC);
513 if (count == 0 || count > timer0_max_count)
515 if (count > prev_count)
516 tot_count += prev_count - (count - timer0_max_count);
518 tot_count += prev_count - count;
520 if (sec != start_sec)
527 printf("i8254 clock: %u Hz\n", tot_count);
533 printf("failed, using default i8254 clock of %u Hz\n",
539 set_timer_freq(u_int freq, int intr_freq)
541 int new_timer0_real_max_count;
543 i8254_timecounter.tc_frequency = freq;
544 mtx_lock_spin(&clock_lock);
546 if (using_lapic_timer)
547 new_timer0_real_max_count = 0x10000;
549 new_timer0_real_max_count = TIMER_DIV(intr_freq);
550 if (new_timer0_real_max_count != timer0_real_max_count) {
551 timer0_real_max_count = new_timer0_real_max_count;
552 if (timer0_real_max_count == 0x10000)
553 timer0_max_count = 0xffff;
555 timer0_max_count = timer0_real_max_count;
556 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
557 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
558 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
560 mtx_unlock_spin(&clock_lock);
563 /* This is separate from startrtclock() so that it can be called early. */
568 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
569 set_timer_freq(timer_freq, hz);
577 writertc(RTC_STATUSA, rtc_statusa);
578 writertc(RTC_STATUSB, RTCSB_24HR);
580 freq = calibrate_clocks();
581 #ifdef CLK_CALIBRATION_LOOP
584 "Press a key on the console to abort clock calibration\n");
585 while (cncheckc() == -1)
591 * Use the calibrated i8254 frequency if it seems reasonable.
592 * Otherwise use the default, and don't use the calibrated i586
595 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
596 if (delta < timer_freq / 100) {
597 #ifndef CLK_USE_I8254_CALIBRATION
600 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
607 "%d Hz differs from default of %d Hz by more than 1%%\n",
611 set_timer_freq(timer_freq, hz);
612 tc_init(&i8254_timecounter);
618 * Initialize the time of day register, based on the time base which is, e.g.
622 inittodr(time_t base)
624 unsigned long sec, days;
637 /* Look if we have a RTC present and the time is valid */
638 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
641 /* wait for time update to complete */
642 /* If RTCSA_TUP is zero, we have at least 244us before next update */
644 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
650 #ifdef USE_RTC_CENTURY
651 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
653 year = readrtc(RTC_YEAR) + 1900;
661 month = readrtc(RTC_MONTH);
662 for (m = 1; m < month; m++)
663 days += daysinmonth[m-1];
664 if ((month > 2) && LEAPYEAR(year))
666 days += readrtc(RTC_DAY) - 1;
667 for (y = 1970; y < year; y++)
668 days += DAYSPERYEAR + LEAPYEAR(y);
669 sec = ((( days * 24 +
670 readrtc(RTC_HRS)) * 60 +
671 readrtc(RTC_MIN)) * 60 +
673 /* sec now contains the number of seconds, since Jan 1 1970,
674 in the local time zone */
678 y = time_second - sec;
679 if (y <= -2 || y >= 2) {
680 /* badly off, adjust it */
689 printf("Invalid time in clock: check and reset the date!\n");
693 * Write system time back to RTC
708 /* Disable RTC updates and interrupts. */
709 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
711 /* Calculate local time to put in RTC */
715 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
716 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
717 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
719 /* We have now the days since 01-01-1970 in tm */
720 writertc(RTC_WDAY, (tm + 4) % 7 + 1); /* Write back Weekday */
721 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
723 y++, m = DAYSPERYEAR + LEAPYEAR(y))
726 /* Now we have the years in y and the day-of-the-year in tm */
727 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
728 #ifdef USE_RTC_CENTURY
729 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
735 if (m == 1 && LEAPYEAR(y))
742 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
743 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
745 /* Reenable RTC updates and interrupts. */
746 writertc(RTC_STATUSB, rtc_statusb);
752 * Start both clocks running.
759 using_lapic_timer = lapic_setup_clock();
761 * If we aren't using the local APIC timer to drive the kernel
762 * clocks, setup the interrupt handler for the 8254 timer 0 so
763 * that it can drive hardclock(). Otherwise, change the 8254
764 * timecounter to user a simpler algorithm.
766 if (!using_lapic_timer) {
767 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL, NULL,
768 INTR_TYPE_CLK, NULL);
769 i8254_intsrc = intr_lookup_source(0);
770 if (i8254_intsrc != NULL)
772 i8254_intsrc->is_pic->pic_source_pending;
774 i8254_timecounter.tc_get_timecount =
775 i8254_simple_get_timecount;
776 i8254_timecounter.tc_counter_mask = 0xffff;
777 set_timer_freq(timer_freq, hz);
780 /* Initialize RTC. */
781 writertc(RTC_STATUSA, rtc_statusa);
782 writertc(RTC_STATUSB, RTCSB_24HR);
785 * If the separate statistics clock hasn't been explicility disabled
786 * and we aren't already using the local APIC timer to drive the
787 * kernel clocks, then setup the RTC to periodically interrupt to
788 * drive statclock() and profclock().
790 if (!statclock_disable && !using_lapic_timer) {
791 diag = rtcin(RTC_DIAG);
793 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
795 /* Setting stathz to nonzero early helps avoid races. */
796 stathz = RTC_NOPROFRATE;
797 profhz = RTC_PROFRATE;
799 /* Enable periodic interrupts from the RTC. */
800 rtc_statusb |= RTCSB_PINTR;
801 intr_add_handler("rtc", 8, (driver_filter_t *)rtcintr, NULL, NULL,
802 INTR_TYPE_CLK, NULL);
804 writertc(RTC_STATUSB, rtc_statusb);
812 cpu_startprofclock(void)
815 if (using_lapic_timer)
817 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
818 writertc(RTC_STATUSA, rtc_statusa);
819 psdiv = pscnt = psratio;
823 cpu_stopprofclock(void)
826 if (using_lapic_timer)
828 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
829 writertc(RTC_STATUSA, rtc_statusa);
834 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
840 * Use `i8254' instead of `timer' in external names because `timer'
841 * is is too generic. Should use it everywhere.
844 error = sysctl_handle_int(oidp, &freq, 0, req);
845 if (error == 0 && req->newptr != NULL)
846 set_timer_freq(freq, hz);
850 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
851 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
854 i8254_simple_get_timecount(struct timecounter *tc)
857 return (timer0_max_count - getit());
861 i8254_get_timecount(struct timecounter *tc)
867 rflags = read_rflags();
868 mtx_lock_spin(&clock_lock);
870 /* Select timer0 and latch counter value. */
871 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
873 low = inb(TIMER_CNTR0);
874 high = inb(TIMER_CNTR0);
875 count = timer0_max_count - ((high << 8) | low);
876 if (count < i8254_lastcount ||
877 (!i8254_ticked && (clkintr_pending ||
878 ((count < 20 || (!(rflags & PSL_I) && count < timer0_max_count / 2u)) &&
879 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
881 i8254_offset += timer0_max_count;
883 i8254_lastcount = count;
884 count += i8254_offset;
885 mtx_unlock_spin(&clock_lock);
891 * Attach to the ISA PnP descriptors for the timer and realtime clock.
893 static struct isa_pnp_id attimer_ids[] = {
894 { 0x0001d041 /* PNP0100 */, "AT timer" },
895 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
900 attimer_probe(device_t dev)
904 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
910 attimer_attach(device_t dev)
915 static device_method_t attimer_methods[] = {
916 /* Device interface */
917 DEVMETHOD(device_probe, attimer_probe),
918 DEVMETHOD(device_attach, attimer_attach),
919 DEVMETHOD(device_detach, bus_generic_detach),
920 DEVMETHOD(device_shutdown, bus_generic_shutdown),
921 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
922 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
926 static driver_t attimer_driver = {
932 static devclass_t attimer_devclass;
934 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
935 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);