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 #include "opt_clock.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/mutex.h>
55 #include <sys/timetc.h>
56 #include <sys/kernel.h>
57 #include <sys/module.h>
58 #include <sys/sched.h>
59 #include <sys/sysctl.h>
61 #include <machine/clock.h>
62 #include <machine/cpu.h>
63 #include <machine/frame.h>
64 #include <machine/intr_machdep.h>
65 #include <machine/md_var.h>
67 #include <machine/apicvar.h>
69 #include <machine/ppireg.h>
70 #include <machine/timerreg.h>
74 #include <isa/isareg.h>
75 #include <isa/isavar.h>
79 #include <i386/bios/mca_machdep.h>
82 #define TIMER_DIV(x) ((i8254_freq + (x) / 2) / (x))
87 int statclock_disable;
89 #define TIMER_FREQ 1193182
91 u_int i8254_freq = TIMER_FREQ;
92 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
94 static int i8254_real_max_count;
96 struct mtx clock_lock;
97 static struct intsrc *i8254_intsrc;
98 static u_int32_t i8254_lastcount;
99 static u_int32_t i8254_offset;
100 static int (*i8254_pending)(struct intsrc *);
101 static int i8254_ticked;
102 static int using_lapic_timer;
104 /* Values for timerX_state: */
106 #define RELEASE_PENDING 1
108 #define ACQUIRE_PENDING 3
110 static u_char timer2_state;
112 static unsigned i8254_get_timecount(struct timecounter *tc);
113 static unsigned i8254_simple_get_timecount(struct timecounter *tc);
114 static void set_i8254_freq(u_int freq, int intr_freq);
116 static struct timecounter i8254_timecounter = {
117 i8254_get_timecount, /* get_timecount */
119 ~0u, /* counter_mask */
126 clkintr(struct trapframe *frame)
129 if (timecounter->tc_get_timecount == i8254_get_timecount) {
130 mtx_lock_spin(&clock_lock);
134 i8254_offset += i8254_max_count;
138 mtx_unlock_spin(&clock_lock);
140 KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
141 hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
143 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
145 outb(0x61, inb(0x61) | 0x80);
147 return (FILTER_HANDLED);
151 timer_spkr_acquire(void)
155 mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
157 if (timer2_state != RELEASED)
159 timer2_state = ACQUIRED;
162 * This access to the timer registers is as atomic as possible
163 * because it is a single instruction. We could do better if we
164 * knew the rate. Use of splclock() limits glitches to 10-100us,
165 * and this is probably good enough for timer2, so we aren't as
166 * careful with it as with timer0.
168 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
169 ppi_spkr_on(); /* enable counter2 output to speaker */
174 timer_spkr_release(void)
177 if (timer2_state != ACQUIRED)
179 timer2_state = RELEASED;
180 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
181 ppi_spkr_off(); /* disable counter2 output to speaker */
186 timer_spkr_setfreq(int freq)
189 freq = i8254_freq / freq;
190 mtx_lock_spin(&clock_lock);
191 outb(TIMER_CNTR2, freq & 0xff);
192 outb(TIMER_CNTR2, freq >> 8);
193 mtx_unlock_spin(&clock_lock);
197 * This routine receives statistical clock interrupts from the RTC.
198 * As explained above, these occur at 128 interrupts per second.
199 * When profiling, we receive interrupts at a rate of 1024 Hz.
201 * This does not actually add as much overhead as it sounds, because
202 * when the statistical clock is active, the hardclock driver no longer
203 * needs to keep (inaccurate) statistics on its own. This decouples
204 * statistics gathering from scheduling interrupts.
206 * The RTC chip requires that we read status register C (RTC_INTR)
207 * to acknowledge an interrupt, before it will generate the next one.
208 * Under high interrupt load, rtcintr() can be indefinitely delayed and
209 * the clock can tick immediately after the read from RTC_INTR. In this
210 * case, the mc146818A interrupt signal will not drop for long enough
211 * to register with the 8259 PIC. If an interrupt is missed, the stat
212 * clock will halt, considerably degrading system performance. This is
213 * why we use 'while' rather than a more straightforward 'if' below.
214 * Stat clock ticks can still be lost, causing minor loss of accuracy
215 * in the statistics, but the stat clock will no longer stop.
218 rtcintr(struct trapframe *frame)
222 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
224 if (profprocs != 0) {
227 profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
230 statclock(TRAPF_USERMODE(frame));
232 return(flag ? FILTER_HANDLED : FILTER_STRAY);
240 mtx_lock_spin(&clock_lock);
242 /* Select timer0 and latch counter value. */
243 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
245 low = inb(TIMER_CNTR0);
246 high = inb(TIMER_CNTR0);
248 mtx_unlock_spin(&clock_lock);
249 return ((high << 8) | low);
253 * Wait "n" microseconds.
254 * Relies on timer 1 counting down from (i8254_freq / hz)
255 * Note: timer had better have been programmed before this is first used!
260 int delta, prev_tick, tick, ticks_left;
265 static int state = 0;
268 if (tsc_freq != 0 && !tsc_is_broken) {
269 uint64_t start, end, now;
273 end = start + (tsc_freq * n) / 1000000;
277 } while (now < end || (now > start && end < start));
284 for (n1 = 1; n1 <= 10000000; n1 *= 10)
289 printf("DELAY(%d)...", n);
292 * Read the counter first, so that the rest of the setup overhead is
293 * counted. Guess the initial overhead is 20 usec (on most systems it
294 * takes about 1.5 usec for each of the i/o's in getit(). The loop
295 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
296 * multiplications and divisions to scale the count take a while).
298 * However, if ddb is active then use a fake counter since reading
299 * the i8254 counter involves acquiring a lock. ddb must not do
300 * locking for many reasons, but it calls here for at least atkbd
309 n -= 0; /* XXX actually guess no initial overhead */
311 * Calculate (n * (i8254_freq / 1e6)) without using floating point
312 * and without any avoidable overflows.
318 * Use fixed point to avoid a slow division by 1000000.
319 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
320 * 2^15 is the first power of 2 that gives exact results
321 * for n between 0 and 256.
323 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
326 * Don't bother using fixed point, although gcc-2.7.2
327 * generates particularly poor code for the long long
328 * division, since even the slow way will complete long
329 * before the delay is up (unless we're interrupted).
331 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
334 while (ticks_left > 0) {
338 tick = prev_tick - 1;
340 tick = i8254_max_count;
347 delta = prev_tick - tick;
350 delta += i8254_max_count;
352 * Guard against i8254_max_count being wrong.
353 * This shouldn't happen in normal operation,
354 * but it may happen if set_i8254_freq() is
364 printf(" %d calls to getit() at %d usec each\n",
365 getit_calls, (n + 5) / getit_calls);
370 set_i8254_freq(u_int freq, int intr_freq)
372 int new_i8254_real_max_count;
374 i8254_timecounter.tc_frequency = freq;
375 mtx_lock_spin(&clock_lock);
377 if (using_lapic_timer)
378 new_i8254_real_max_count = 0x10000;
380 new_i8254_real_max_count = TIMER_DIV(intr_freq);
381 if (new_i8254_real_max_count != i8254_real_max_count) {
382 i8254_real_max_count = new_i8254_real_max_count;
383 if (i8254_real_max_count == 0x10000)
384 i8254_max_count = 0xffff;
386 i8254_max_count = i8254_real_max_count;
387 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
388 outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
389 outb(TIMER_CNTR0, i8254_real_max_count >> 8);
391 mtx_unlock_spin(&clock_lock);
398 mtx_lock_spin(&clock_lock);
399 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
400 outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
401 outb(TIMER_CNTR0, i8254_real_max_count >> 8);
402 mtx_unlock_spin(&clock_lock);
406 * Restore all the timers non-atomically (XXX: should be atomically).
408 * This function is called from pmtimer_resume() to restore all the timers.
409 * This should not be necessary, but there are broken laptops that do not
410 * restore all the timers on resume.
416 i8254_restore(); /* restore i8254_freq and hz */
417 atrtc_restore(); /* reenable RTC interrupts */
420 /* This is separate from startrtclock() so that it can be called early. */
425 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
426 set_i8254_freq(i8254_freq, hz);
435 set_i8254_freq(i8254_freq, hz);
436 tc_init(&i8254_timecounter);
442 * Start both clocks running.
450 using_lapic_timer = lapic_setup_clock();
453 * If we aren't using the local APIC timer to drive the kernel
454 * clocks, setup the interrupt handler for the 8254 timer 0 so
455 * that it can drive hardclock(). Otherwise, change the 8254
456 * timecounter to user a simpler algorithm.
458 if (!using_lapic_timer) {
459 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL,
460 NULL, INTR_TYPE_CLK, NULL);
461 i8254_intsrc = intr_lookup_source(0);
462 if (i8254_intsrc != NULL)
464 i8254_intsrc->is_pic->pic_source_pending;
466 i8254_timecounter.tc_get_timecount =
467 i8254_simple_get_timecount;
468 i8254_timecounter.tc_counter_mask = 0xffff;
469 set_i8254_freq(i8254_freq, hz);
472 /* Initialize RTC. */
476 * If the separate statistics clock hasn't been explicility disabled
477 * and we aren't already using the local APIC timer to drive the
478 * kernel clocks, then setup the RTC to periodically interrupt to
479 * drive statclock() and profclock().
481 if (!statclock_disable && !using_lapic_timer) {
482 diag = rtcin(RTC_DIAG);
484 printf("RTC BIOS diagnostic error %b\n",
487 /* Setting stathz to nonzero early helps avoid races. */
488 stathz = RTC_NOPROFRATE;
489 profhz = RTC_PROFRATE;
491 /* Enable periodic interrupts from the RTC. */
492 intr_add_handler("rtc", 8,
493 (driver_filter_t *)rtcintr, NULL, NULL,
494 INTR_TYPE_CLK, NULL);
502 cpu_startprofclock(void)
505 if (using_lapic_timer)
507 atrtc_rate(RTCSA_PROF);
508 psdiv = pscnt = psratio;
512 cpu_stopprofclock(void)
515 if (using_lapic_timer)
517 atrtc_rate(RTCSA_NOPROF);
522 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
528 * Use `i8254' instead of `timer' in external names because `timer'
529 * is is too generic. Should use it everywhere.
532 error = sysctl_handle_int(oidp, &freq, 0, req);
533 if (error == 0 && req->newptr != NULL)
534 set_i8254_freq(freq, hz);
538 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
539 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
542 i8254_simple_get_timecount(struct timecounter *tc)
545 return (i8254_max_count - getit());
549 i8254_get_timecount(struct timecounter *tc)
555 eflags = read_eflags();
556 mtx_lock_spin(&clock_lock);
558 /* Select timer0 and latch counter value. */
559 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
561 low = inb(TIMER_CNTR0);
562 high = inb(TIMER_CNTR0);
563 count = i8254_max_count - ((high << 8) | low);
564 if (count < i8254_lastcount ||
565 (!i8254_ticked && (clkintr_pending ||
566 ((count < 20 || (!(eflags & PSL_I) &&
567 count < i8254_max_count / 2u)) &&
568 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
570 i8254_offset += i8254_max_count;
572 i8254_lastcount = count;
573 count += i8254_offset;
574 mtx_unlock_spin(&clock_lock);
580 * Attach to the ISA PnP descriptors for the timer
582 static struct isa_pnp_id attimer_ids[] = {
583 { 0x0001d041 /* PNP0100 */, "AT timer" },
588 attimer_probe(device_t dev)
592 result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
599 attimer_attach(device_t dev)
604 static device_method_t attimer_methods[] = {
605 /* Device interface */
606 DEVMETHOD(device_probe, attimer_probe),
607 DEVMETHOD(device_attach, attimer_attach),
608 DEVMETHOD(device_detach, bus_generic_detach),
609 DEVMETHOD(device_shutdown, bus_generic_shutdown),
610 DEVMETHOD(device_suspend, bus_generic_suspend),
611 DEVMETHOD(device_resume, bus_generic_resume),
615 static driver_t attimer_driver = {
621 static devclass_t attimer_devclass;
623 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
624 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);