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
50 * modified for PC98 by Kakefuda
54 #include "opt_clock.h"
58 #include <sys/param.h>
59 #include <sys/systm.h>
61 #include <sys/clock.h>
64 #include <sys/mutex.h>
67 #include <sys/timetc.h>
68 #include <sys/kernel.h>
69 #include <sys/limits.h>
70 #include <sys/module.h>
71 #include <sys/sysctl.h>
73 #include <sys/power.h>
75 #include <machine/clock.h>
76 #include <machine/cpu.h>
77 #include <machine/cputypes.h>
78 #include <machine/frame.h>
79 #include <machine/intr_machdep.h>
80 #include <machine/md_var.h>
81 #include <machine/psl.h>
83 #include <machine/apicvar.h>
85 #include <machine/specialreg.h>
86 #include <machine/ppireg.h>
87 #include <machine/timerreg.h>
89 #include <i386/isa/icu.h>
90 #include <pc98/cbus/cbus.h>
91 #include <pc98/pc98/pc98_machdep.h>
93 #include <isa/isavar.h>
96 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
101 int statclock_disable;
103 #define TIMER_FREQ 2457600
105 u_int timer_freq = TIMER_FREQ;
106 int timer0_max_count;
107 int timer0_real_max_count;
109 static int beeping = 0;
110 static struct mtx clock_lock;
111 static struct intsrc *i8254_intsrc;
112 static u_int32_t i8254_lastcount;
113 static u_int32_t i8254_offset;
114 static int (*i8254_pending)(struct intsrc *);
115 static int i8254_ticked;
116 static int using_lapic_timer;
118 /* Values for timerX_state: */
120 #define RELEASE_PENDING 1
122 #define ACQUIRE_PENDING 3
124 static u_char timer1_state;
125 static u_char timer2_state;
126 static void rtc_serialcombit(int);
127 static void rtc_serialcom(int);
128 static int rtc_inb(void);
129 static void rtc_outb(int);
131 static unsigned i8254_get_timecount(struct timecounter *tc);
132 static unsigned i8254_simple_get_timecount(struct timecounter *tc);
133 static void set_timer_freq(u_int freq, int intr_freq);
135 static struct timecounter i8254_timecounter = {
136 i8254_get_timecount, /* get_timecount */
138 ~0u, /* counter_mask */
145 clkintr(struct trapframe *frame)
148 if (timecounter->tc_get_timecount == i8254_get_timecount) {
149 mtx_lock_spin(&clock_lock);
153 i8254_offset += timer0_max_count;
157 mtx_unlock_spin(&clock_lock);
159 KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
160 hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
161 return (FILTER_HANDLED);
165 acquire_timer1(int mode)
168 if (timer1_state != RELEASED)
170 timer1_state = ACQUIRED;
173 * This access to the timer registers is as atomic as possible
174 * because it is a single instruction. We could do better if we
175 * knew the rate. Use of splclock() limits glitches to 10-100us,
176 * and this is probably good enough for timer2, so we aren't as
177 * careful with it as with timer0.
179 outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
185 acquire_timer2(int mode)
188 if (timer2_state != RELEASED)
190 timer2_state = ACQUIRED;
193 * This access to the timer registers is as atomic as possible
194 * because it is a single instruction. We could do better if we
195 * knew the rate. Use of splclock() limits glitches to 10-100us,
196 * and this is probably good enough for timer2, so we aren't as
197 * careful with it as with timer0.
199 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
208 if (timer1_state != ACQUIRED)
210 timer1_state = RELEASED;
211 outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
219 if (timer2_state != ACQUIRED)
221 timer2_state = RELEASED;
222 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
232 mtx_lock_spin(&clock_lock);
234 /* Select timer0 and latch counter value. */
235 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
237 low = inb(TIMER_CNTR0);
238 high = inb(TIMER_CNTR0);
240 mtx_unlock_spin(&clock_lock);
241 return ((high << 8) | low);
245 * Wait "n" microseconds.
246 * Relies on timer 1 counting down from (timer_freq / hz)
247 * Note: timer had better have been programmed before this is first used!
252 int delta, prev_tick, tick, ticks_left;
257 static int state = 0;
261 for (n1 = 1; n1 <= 10000000; n1 *= 10)
266 printf("DELAY(%d)...", n);
269 * Read the counter first, so that the rest of the setup overhead is
270 * counted. Guess the initial overhead is 20 usec (on most systems it
271 * takes about 1.5 usec for each of the i/o's in getit(). The loop
272 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
273 * multiplications and divisions to scale the count take a while).
275 * However, if ddb is active then use a fake counter since reading
276 * the i8254 counter involves acquiring a lock. ddb must not do
277 * locking for many reasons, but it calls here for at least atkbd
286 n -= 0; /* XXX actually guess no initial overhead */
288 * Calculate (n * (timer_freq / 1e6)) without using floating point
289 * and without any avoidable overflows.
295 * Use fixed point to avoid a slow division by 1000000.
296 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
297 * 2^15 is the first power of 2 that gives exact results
298 * for n between 0 and 256.
300 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
303 * Don't bother using fixed point, although gcc-2.7.2
304 * generates particularly poor code for the long long
305 * division, since even the slow way will complete long
306 * before the delay is up (unless we're interrupted).
308 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
311 while (ticks_left > 0) {
315 tick = prev_tick - 1;
317 tick = timer0_max_count;
324 delta = prev_tick - tick;
327 delta += timer0_max_count;
329 * Guard against timer0_max_count being wrong.
330 * This shouldn't happen in normal operation,
331 * but it may happen if set_timer_freq() is
341 printf(" %d calls to getit() at %d usec each\n",
342 getit_calls, (n + 5) / getit_calls);
347 sysbeepstop(void *chan)
349 ppi_spkr_off(); /* disable counter1 output to speaker */
350 timer_spkr_release();
355 sysbeep(int pitch, int period)
359 if (timer_spkr_acquire())
361 /* Something else owns it. */
363 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
365 mtx_lock_spin(&clock_lock);
366 spkr_set_pitch(pitch);
367 mtx_unlock_spin(&clock_lock);
369 /* enable counter1 output to speaker */
372 timeout(sysbeepstop, (void *)NULL, period);
379 calibrate_clocks(void)
382 u_int count, prev_count, tot_count;
383 u_short sec, start_sec;
386 printf("Calibrating clock(s) ... ");
388 if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
389 !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
393 /* Read the ARTIC. */
396 /* Wait for the ARTIC to changes. */
400 if (sec != start_sec)
406 /* Start keeping track of the i8254 counter. */
407 prev_count = getit();
408 if (prev_count == 0 || prev_count > timer0_max_count)
416 if (count == 0 || count > timer0_max_count)
418 if (count > prev_count)
419 tot_count += prev_count - (count - timer0_max_count);
421 tot_count += prev_count - count;
423 if ((sec == start_sec + 1200) || /* 1200 = 307.2KHz >> 8 */
425 (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
432 printf("i8254 clock: %u Hz\n", tot_count);
438 printf("failed, using default i8254 clock of %u Hz\n",
444 set_timer_freq(u_int freq, int intr_freq)
446 int new_timer0_real_max_count;
448 i8254_timecounter.tc_frequency = freq;
449 mtx_lock_spin(&clock_lock);
451 if (using_lapic_timer)
452 new_timer0_real_max_count = 0x10000;
454 new_timer0_real_max_count = TIMER_DIV(intr_freq);
455 if (new_timer0_real_max_count != timer0_real_max_count) {
456 timer0_real_max_count = new_timer0_real_max_count;
457 if (timer0_real_max_count == 0x10000)
458 timer0_max_count = 0xffff;
460 timer0_max_count = timer0_real_max_count;
461 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
462 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
463 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
465 mtx_unlock_spin(&clock_lock);
472 mtx_lock_spin(&clock_lock);
473 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
474 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
475 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
476 mtx_unlock_spin(&clock_lock);
481 * Restore all the timers non-atomically (XXX: should be atomically).
483 * This function is called from pmtimer_resume() to restore all the timers.
484 * This should not be necessary, but there are broken laptops that do not
485 * restore all the timers on resume.
491 i8254_restore(); /* restore timer_freq and hz */
494 /* This is separate from startrtclock() so that it can be called early. */
499 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
501 if (pc98_machine_type & M_8M)
502 timer_freq = 1996800L; /* 1.9968 MHz */
504 timer_freq = 2457600L; /* 2.4576 MHz */
506 set_timer_freq(timer_freq, hz);
514 freq = calibrate_clocks();
515 #ifdef CLK_CALIBRATION_LOOP
518 "Press a key on the console to abort clock calibration\n");
519 while (cncheckc() == -1)
525 * Use the calibrated i8254 frequency if it seems reasonable.
526 * Otherwise use the default, and don't use the calibrated i586
529 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
530 if (delta < timer_freq / 100) {
531 #ifndef CLK_USE_I8254_CALIBRATION
534 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
541 "%d Hz differs from default of %d Hz by more than 1%%\n",
545 set_timer_freq(timer_freq, hz);
546 tc_init(&i8254_timecounter);
552 rtc_serialcombit(int i)
554 outb(IO_RTC, ((i&0x01)<<5)|0x07);
556 outb(IO_RTC, ((i&0x01)<<5)|0x17);
558 outb(IO_RTC, ((i&0x01)<<5)|0x07);
565 rtc_serialcombit(i&0x01);
566 rtc_serialcombit((i&0x02)>>1);
567 rtc_serialcombit((i&0x04)>>2);
568 rtc_serialcombit((i&0x08)>>3);
584 sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
585 outb(IO_RTC, sa); /* set DI & CLK 0 */
587 outb(IO_RTC, sa | 0x10); /* CLK 1 */
590 outb(IO_RTC, sa & 0xef); /* CLK 0 */
600 sa |= ((inb(0x33) & 0x01) << s);
601 outb(IO_RTC, 0x17); /* CLK 1 */
603 outb(IO_RTC, 0x07); /* CLK 0 */
610 * Initialize the time of day register, based on the time base which is, e.g.
614 inittodr(time_t base)
626 rtc_serialcom(0x03); /* Time Read */
627 rtc_serialcom(0x01); /* Register shift command. */
631 ct.sec = bcd2bin(rtc_inb() & 0xff); /* sec */
632 ct.min = bcd2bin(rtc_inb() & 0xff); /* min */
633 ct.hour = bcd2bin(rtc_inb() & 0xff); /* hour */
634 ct.day = bcd2bin(rtc_inb() & 0xff); /* date */
636 ct.dow = i & 0x0f; /* dow */
637 ct.mon = (i >> 4) & 0x0f; /* month */
638 ct.year = bcd2bin(rtc_inb() & 0xff) + 1900; /* year */
641 /* Set dow = -1 because some clocks don't set it correctly. */
643 if (clock_ct_to_ts(&ct, &ts)) {
644 printf("Invalid time in clock: check and reset the date!\n");
647 ts.tv_sec += utc_offset();
652 * Write system time back to RTC
664 ts.tv_sec -= utc_offset();
665 clock_ts_to_ct(&ts, &ct);
667 rtc_serialcom(0x01); /* Register shift command. */
669 rtc_outb(bin2bcd(ct.sec)); /* Write back Seconds */
670 rtc_outb(bin2bcd(ct.min)); /* Write back Minutes */
671 rtc_outb(bin2bcd(ct.hour)); /* Write back Hours */
673 rtc_outb(bin2bcd(ct.day)); /* Write back Day */
674 rtc_outb((ct.mon << 4) | ct.dow); /* Write back Month and DOW */
675 rtc_outb(bin2bcd(ct.year % 100)); /* Write back Year */
677 rtc_serialcom(0x02); /* Time set & Counter hold command. */
678 rtc_serialcom(0x00); /* Register hold command. */
683 * Start both clocks running.
690 using_lapic_timer = lapic_setup_clock();
693 * If we aren't using the local APIC timer to drive the kernel
694 * clocks, setup the interrupt handler for the 8254 timer 0 so
695 * that it can drive hardclock(). Otherwise, change the 8254
696 * timecounter to user a simpler algorithm.
698 if (!using_lapic_timer) {
699 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL,
700 NULL, INTR_TYPE_CLK, NULL);
701 i8254_intsrc = intr_lookup_source(0);
702 if (i8254_intsrc != NULL)
704 i8254_intsrc->is_pic->pic_source_pending;
706 i8254_timecounter.tc_get_timecount =
707 i8254_simple_get_timecount;
708 i8254_timecounter.tc_counter_mask = 0xffff;
709 set_timer_freq(timer_freq, hz);
716 cpu_startprofclock(void)
721 cpu_stopprofclock(void)
726 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
732 * Use `i8254' instead of `timer' in external names because `timer'
733 * is is too generic. Should use it everywhere.
736 error = sysctl_handle_int(oidp, &freq, 0, req);
737 if (error == 0 && req->newptr != NULL)
738 set_timer_freq(freq, hz);
742 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
743 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
746 i8254_simple_get_timecount(struct timecounter *tc)
749 return (timer0_max_count - getit());
753 i8254_get_timecount(struct timecounter *tc)
759 eflags = read_eflags();
760 mtx_lock_spin(&clock_lock);
762 /* Select timer0 and latch counter value. */
763 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
765 low = inb(TIMER_CNTR0);
766 high = inb(TIMER_CNTR0);
767 count = timer0_max_count - ((high << 8) | low);
768 if (count < i8254_lastcount ||
769 (!i8254_ticked && (clkintr_pending ||
770 ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
771 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
773 i8254_offset += timer0_max_count;
775 i8254_lastcount = count;
776 count += i8254_offset;
777 mtx_unlock_spin(&clock_lock);
783 * Attach to the ISA PnP descriptors for the timer and realtime clock.
785 static struct isa_pnp_id attimer_ids[] = {
786 { 0x0001d041 /* PNP0100 */, "AT timer" },
787 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
792 attimer_probe(device_t dev)
796 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
802 attimer_attach(device_t dev)
807 static device_method_t attimer_methods[] = {
808 /* Device interface */
809 DEVMETHOD(device_probe, attimer_probe),
810 DEVMETHOD(device_attach, attimer_attach),
811 DEVMETHOD(device_detach, bus_generic_detach),
812 DEVMETHOD(device_shutdown, bus_generic_shutdown),
813 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
814 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
818 static driver_t attimer_driver = {
824 static devclass_t attimer_devclass;
826 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);