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.
45 #include "opt_clock.h"
46 #include "opt_kdtrace.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
55 #include <sys/mutex.h>
57 #include <sys/timetc.h>
58 #include <sys/kernel.h>
59 #include <sys/module.h>
60 #include <sys/sched.h>
62 #include <sys/sysctl.h>
64 #include <machine/clock.h>
65 #include <machine/cpu.h>
66 #include <machine/intr_machdep.h>
67 #include <machine/md_var.h>
68 #include <machine/apicvar.h>
69 #include <machine/ppireg.h>
70 #include <machine/timerreg.h>
71 #include <machine/smp.h>
75 #include <isa/isareg.h>
76 #include <isa/isavar.h>
80 #include <i386/bios/mca_machdep.h>
84 #include <sys/dtrace_bsd.h>
87 #define TIMER_DIV(x) ((i8254_freq + (x) / 2) / (x))
93 #define TIMER_FREQ 1193182
95 u_int i8254_freq = TIMER_FREQ;
96 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
98 static int i8254_real_max_count;
100 static int lapic_allclocks = 1;
101 TUNABLE_INT("machdep.lapic_allclocks", &lapic_allclocks);
103 struct mtx clock_lock;
104 static struct intsrc *i8254_intsrc;
105 static u_int32_t i8254_lastcount;
106 static u_int32_t i8254_offset;
107 static int (*i8254_pending)(struct intsrc *);
108 static int i8254_ticked;
109 static int using_atrtc_timer;
110 static enum lapic_clock using_lapic_timer = LAPIC_CLOCK_NONE;
112 /* Values for timerX_state: */
114 #define RELEASE_PENDING 1
116 #define ACQUIRE_PENDING 3
118 static u_char timer2_state;
120 static unsigned i8254_get_timecount(struct timecounter *tc);
121 static unsigned i8254_simple_get_timecount(struct timecounter *tc);
122 static void set_i8254_freq(u_int freq, int intr_freq);
124 static struct timecounter i8254_timecounter = {
125 i8254_get_timecount, /* get_timecount */
127 ~0u, /* counter_mask */
134 hardclockintr(struct trapframe *frame)
137 if (PCPU_GET(cpuid) == 0)
138 hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
140 hardclock_cpu(TRAPF_USERMODE(frame));
141 return (FILTER_HANDLED);
145 statclockintr(struct trapframe *frame)
148 profclockintr(frame);
149 statclock(TRAPF_USERMODE(frame));
150 return (FILTER_HANDLED);
154 profclockintr(struct trapframe *frame)
157 if (!using_atrtc_timer)
158 hardclockintr(frame);
160 profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
161 return (FILTER_HANDLED);
165 clkintr(struct trapframe *frame)
168 if (timecounter->tc_get_timecount == i8254_get_timecount) {
169 mtx_lock_spin(&clock_lock);
173 i8254_offset += i8254_max_count;
177 mtx_unlock_spin(&clock_lock);
179 KASSERT(using_lapic_timer == LAPIC_CLOCK_NONE,
180 ("clk interrupt enabled with lapic timer"));
184 * If the DTrace hooks are configured and a callback function
185 * has been registered, then call it to process the high speed
188 int cpu = PCPU_GET(cpuid);
189 if (cyclic_clock_func[cpu] != NULL)
190 (*cyclic_clock_func[cpu])(frame);
193 if (using_atrtc_timer) {
196 ipi_all_but_self(IPI_HARDCLOCK);
198 hardclockintr(frame);
204 ipi_all_but_self(IPI_STATCLOCK);
206 statclockintr(frame);
210 ipi_all_but_self(IPI_PROFCLOCK);
212 profclockintr(frame);
217 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
219 outb(0x61, inb(0x61) | 0x80);
221 return (FILTER_HANDLED);
225 timer_spkr_acquire(void)
229 mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
231 if (timer2_state != RELEASED)
233 timer2_state = ACQUIRED;
236 * This access to the timer registers is as atomic as possible
237 * because it is a single instruction. We could do better if we
238 * knew the rate. Use of splclock() limits glitches to 10-100us,
239 * and this is probably good enough for timer2, so we aren't as
240 * careful with it as with timer0.
242 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
243 ppi_spkr_on(); /* enable counter2 output to speaker */
248 timer_spkr_release(void)
251 if (timer2_state != ACQUIRED)
253 timer2_state = RELEASED;
254 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
255 ppi_spkr_off(); /* disable counter2 output to speaker */
260 timer_spkr_setfreq(int freq)
263 freq = i8254_freq / freq;
264 mtx_lock_spin(&clock_lock);
265 outb(TIMER_CNTR2, freq & 0xff);
266 outb(TIMER_CNTR2, freq >> 8);
267 mtx_unlock_spin(&clock_lock);
271 * This routine receives statistical clock interrupts from the RTC.
272 * As explained above, these occur at 128 interrupts per second.
273 * When profiling, we receive interrupts at a rate of 1024 Hz.
275 * This does not actually add as much overhead as it sounds, because
276 * when the statistical clock is active, the hardclock driver no longer
277 * needs to keep (inaccurate) statistics on its own. This decouples
278 * statistics gathering from scheduling interrupts.
280 * The RTC chip requires that we read status register C (RTC_INTR)
281 * to acknowledge an interrupt, before it will generate the next one.
282 * Under high interrupt load, rtcintr() can be indefinitely delayed and
283 * the clock can tick immediately after the read from RTC_INTR. In this
284 * case, the mc146818A interrupt signal will not drop for long enough
285 * to register with the 8259 PIC. If an interrupt is missed, the stat
286 * clock will halt, considerably degrading system performance. This is
287 * why we use 'while' rather than a more straightforward 'if' below.
288 * Stat clock ticks can still be lost, causing minor loss of accuracy
289 * in the statistics, but the stat clock will no longer stop.
292 rtcintr(struct trapframe *frame)
296 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
302 ipi_all_but_self(IPI_STATCLOCK);
304 statclockintr(frame);
308 ipi_all_but_self(IPI_PROFCLOCK);
310 profclockintr(frame);
313 return(flag ? FILTER_HANDLED : FILTER_STRAY);
321 mtx_lock_spin(&clock_lock);
323 /* Select timer0 and latch counter value. */
324 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
326 low = inb(TIMER_CNTR0);
327 high = inb(TIMER_CNTR0);
329 mtx_unlock_spin(&clock_lock);
330 return ((high << 8) | low);
334 * Wait "n" microseconds.
335 * Relies on timer 1 counting down from (i8254_freq / hz)
336 * Note: timer had better have been programmed before this is first used!
341 int delta, prev_tick, tick, ticks_left;
346 static int state = 0;
349 if (tsc_freq != 0 && !tsc_is_broken) {
350 uint64_t start, end, now;
354 end = start + (tsc_freq * n) / 1000000;
358 } while (now < end || (now > start && end < start));
365 for (n1 = 1; n1 <= 10000000; n1 *= 10)
370 printf("DELAY(%d)...", n);
373 * Read the counter first, so that the rest of the setup overhead is
374 * counted. Guess the initial overhead is 20 usec (on most systems it
375 * takes about 1.5 usec for each of the i/o's in getit(). The loop
376 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
377 * multiplications and divisions to scale the count take a while).
379 * However, if ddb is active then use a fake counter since reading
380 * the i8254 counter involves acquiring a lock. ddb must not do
381 * locking for many reasons, but it calls here for at least atkbd
390 n -= 0; /* XXX actually guess no initial overhead */
392 * Calculate (n * (i8254_freq / 1e6)) without using floating point
393 * and without any avoidable overflows.
399 * Use fixed point to avoid a slow division by 1000000.
400 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
401 * 2^15 is the first power of 2 that gives exact results
402 * for n between 0 and 256.
404 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
407 * Don't bother using fixed point, although gcc-2.7.2
408 * generates particularly poor code for the long long
409 * division, since even the slow way will complete long
410 * before the delay is up (unless we're interrupted).
412 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
415 while (ticks_left > 0) {
419 tick = prev_tick - 1;
421 tick = i8254_max_count;
428 delta = prev_tick - tick;
431 delta += i8254_max_count;
433 * Guard against i8254_max_count being wrong.
434 * This shouldn't happen in normal operation,
435 * but it may happen if set_i8254_freq() is
445 printf(" %d calls to getit() at %d usec each\n",
446 getit_calls, (n + 5) / getit_calls);
451 set_i8254_freq(u_int freq, int intr_freq)
453 int new_i8254_real_max_count;
455 i8254_timecounter.tc_frequency = freq;
456 mtx_lock_spin(&clock_lock);
458 if (using_lapic_timer != LAPIC_CLOCK_NONE)
459 new_i8254_real_max_count = 0x10000;
461 new_i8254_real_max_count = TIMER_DIV(intr_freq);
462 if (new_i8254_real_max_count != i8254_real_max_count) {
463 i8254_real_max_count = new_i8254_real_max_count;
464 if (i8254_real_max_count == 0x10000)
465 i8254_max_count = 0xffff;
467 i8254_max_count = i8254_real_max_count;
468 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
469 outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
470 outb(TIMER_CNTR0, i8254_real_max_count >> 8);
472 mtx_unlock_spin(&clock_lock);
479 mtx_lock_spin(&clock_lock);
480 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
481 outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
482 outb(TIMER_CNTR0, i8254_real_max_count >> 8);
483 mtx_unlock_spin(&clock_lock);
488 * Restore all the timers non-atomically (XXX: should be atomically).
490 * This function is called from pmtimer_resume() to restore all the timers.
491 * This should not be necessary, but there are broken laptops that do not
492 * restore all the timers on resume.
493 * As long as pmtimer is not part of amd64 support, skip this for the amd64
500 i8254_restore(); /* restore i8254_freq and hz */
501 atrtc_restore(); /* reenable RTC interrupts */
505 /* This is separate from startrtclock() so that it can be called early. */
510 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
511 set_i8254_freq(i8254_freq, hz);
520 set_i8254_freq(i8254_freq, hz);
521 tc_init(&i8254_timecounter);
527 * Start both clocks running.
532 #if defined(__amd64__) || defined(DEV_APIC)
533 enum lapic_clock tlsca;
537 /* Initialize RTC. */
539 tasc = atrtc_setup_clock();
542 * If the atrtc successfully initialized and the users didn't force
543 * otherwise use the LAPIC in order to cater hardclock only, otherwise
544 * take in charge all the clock sources.
546 #if defined(__amd64__) || defined(DEV_APIC)
547 tlsca = (lapic_allclocks == 0 && tasc != 0) ? LAPIC_CLOCK_HARDCLOCK :
549 using_lapic_timer = lapic_setup_clock(tlsca);
552 * If we aren't using the local APIC timer to drive the kernel
553 * clocks, setup the interrupt handler for the 8254 timer 0 so
554 * that it can drive hardclock(). Otherwise, change the 8254
555 * timecounter to user a simpler algorithm.
557 if (using_lapic_timer == LAPIC_CLOCK_NONE) {
558 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL,
559 NULL, INTR_TYPE_CLK, NULL);
560 i8254_intsrc = intr_lookup_source(0);
561 if (i8254_intsrc != NULL)
563 i8254_intsrc->is_pic->pic_source_pending;
565 i8254_timecounter.tc_get_timecount =
566 i8254_simple_get_timecount;
567 i8254_timecounter.tc_counter_mask = 0xffff;
568 set_i8254_freq(i8254_freq, hz);
572 * If the separate statistics clock hasn't been explicility disabled
573 * and we aren't already using the local APIC timer to drive the
574 * kernel clocks, then setup the RTC to periodically interrupt to
575 * drive statclock() and profclock().
577 if (using_lapic_timer != LAPIC_CLOCK_ALL) {
578 using_atrtc_timer = tasc;
579 if (using_atrtc_timer) {
580 /* Enable periodic interrupts from the RTC. */
581 intr_add_handler("rtc", 8,
582 (driver_filter_t *)rtcintr, NULL, NULL,
583 INTR_TYPE_CLK, NULL);
590 stathz = hz / (hz / 128);
598 cpu_startprofclock(void)
601 if (using_lapic_timer == LAPIC_CLOCK_ALL || !using_atrtc_timer)
603 atrtc_rate(RTCSA_PROF);
604 psdiv = pscnt = psratio;
608 cpu_stopprofclock(void)
611 if (using_lapic_timer == LAPIC_CLOCK_ALL || !using_atrtc_timer)
613 atrtc_rate(RTCSA_NOPROF);
618 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
624 * Use `i8254' instead of `timer' in external names because `timer'
625 * is is too generic. Should use it everywhere.
628 error = sysctl_handle_int(oidp, &freq, 0, req);
629 if (error == 0 && req->newptr != NULL)
630 set_i8254_freq(freq, hz);
634 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
635 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
638 i8254_simple_get_timecount(struct timecounter *tc)
641 return (i8254_max_count - getit());
645 i8254_get_timecount(struct timecounter *tc)
652 flags = read_rflags();
654 flags = read_eflags();
656 mtx_lock_spin(&clock_lock);
658 /* Select timer0 and latch counter value. */
659 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
661 low = inb(TIMER_CNTR0);
662 high = inb(TIMER_CNTR0);
663 count = i8254_max_count - ((high << 8) | low);
664 if (count < i8254_lastcount ||
665 (!i8254_ticked && (clkintr_pending ||
666 ((count < 20 || (!(flags & PSL_I) &&
667 count < i8254_max_count / 2u)) &&
668 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
670 i8254_offset += i8254_max_count;
672 i8254_lastcount = count;
673 count += i8254_offset;
674 mtx_unlock_spin(&clock_lock);
680 * Attach to the ISA PnP descriptors for the timer
682 static struct isa_pnp_id attimer_ids[] = {
683 { 0x0001d041 /* PNP0100 */, "AT timer" },
688 attimer_probe(device_t dev)
692 result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
699 attimer_attach(device_t dev)
705 attimer_resume(device_t dev)
712 static device_method_t attimer_methods[] = {
713 /* Device interface */
714 DEVMETHOD(device_probe, attimer_probe),
715 DEVMETHOD(device_attach, attimer_attach),
716 DEVMETHOD(device_detach, bus_generic_detach),
717 DEVMETHOD(device_shutdown, bus_generic_shutdown),
718 DEVMETHOD(device_suspend, bus_generic_suspend),
719 DEVMETHOD(device_resume, attimer_resume),
723 static driver_t attimer_driver = {
729 static devclass_t attimer_devclass;
731 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
732 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);