2 * Copyright (c) 1990 The Regents of the University of California.
3 * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
6 * This code is derived from software contributed to Berkeley by
7 * William Jolitz and Don Ahn.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
40 * Routines to handle clock hardware.
43 #include "opt_clock.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
51 #include <sys/mutex.h>
53 #include <sys/kernel.h>
54 #include <sys/module.h>
56 #include <sys/sched.h>
58 #include <sys/sysctl.h>
59 #include <sys/timeet.h>
60 #include <sys/timetc.h>
62 #include <machine/clock.h>
63 #include <machine/cpu.h>
64 #include <machine/intr_machdep.h>
65 #include <machine/ppireg.h>
66 #include <machine/timerreg.h>
71 #include <isa/isareg.h>
72 #include <isa/isavar.h>
77 #define TIMER_FREQ 1193182
79 u_int i8254_freq = TIMER_FREQ;
80 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
82 static int i8254_timecounter = 1;
84 struct mtx clock_lock;
85 static struct intsrc *i8254_intsrc;
86 static uint16_t i8254_lastcount;
87 static uint16_t i8254_offset;
88 static int (*i8254_pending)(struct intsrc *);
89 static int i8254_ticked;
91 struct attimer_softc {
93 int port_rid, intr_rid;
94 struct resource *port_res;
95 struct resource *intr_res;
97 struct timecounter tc;
101 #define MODE_PERIODIC 1
102 #define MODE_ONESHOT 2
105 static struct attimer_softc *attimer_sc = NULL;
107 static int timer0_period = -2;
108 static int timer0_mode = 0xffff;
109 static int timer0_last = 0xffff;
111 /* Values for timerX_state: */
113 #define RELEASE_PENDING 1
115 #define ACQUIRE_PENDING 3
117 static u_char timer2_state;
119 static unsigned i8254_get_timecount(struct timecounter *tc);
120 static void set_i8254_freq(int mode, uint32_t period);
125 /* Init the clock lock */
126 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
127 /* Init the clock in order to use DELAY */
128 init_ops.early_clock_source_init();
134 struct attimer_softc *sc = (struct attimer_softc *)arg;
136 if (i8254_timecounter && sc->period != 0) {
137 mtx_lock_spin(&clock_lock);
141 i8254_offset += i8254_max_count;
145 mtx_unlock_spin(&clock_lock);
148 if (sc->et.et_active && sc->mode != MODE_STOP)
149 sc->et.et_event_cb(&sc->et, sc->et.et_arg);
151 return (FILTER_HANDLED);
155 timer_spkr_acquire(void)
159 mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
161 if (timer2_state != RELEASED)
163 timer2_state = ACQUIRED;
166 * This access to the timer registers is as atomic as possible
167 * because it is a single instruction. We could do better if we
168 * knew the rate. Use of splclock() limits glitches to 10-100us,
169 * and this is probably good enough for timer2, so we aren't as
170 * careful with it as with timer0.
172 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
174 ppi_spkr_on(); /* enable counter2 output to speaker */
179 timer_spkr_release(void)
182 if (timer2_state != ACQUIRED)
184 timer2_state = RELEASED;
185 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
187 ppi_spkr_off(); /* disable counter2 output to speaker */
192 timer_spkr_setfreq(int freq)
195 freq = i8254_freq / freq;
196 mtx_lock_spin(&clock_lock);
197 outb(TIMER_CNTR2, freq & 0xff);
198 outb(TIMER_CNTR2, freq >> 8);
199 mtx_unlock_spin(&clock_lock);
207 mtx_lock_spin(&clock_lock);
209 /* Select timer0 and latch counter value. */
210 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
212 low = inb(TIMER_CNTR0);
213 high = inb(TIMER_CNTR0);
215 mtx_unlock_spin(&clock_lock);
216 return ((high << 8) | low);
220 * Wait "n" microseconds.
221 * Relies on timer 1 counting down from (i8254_freq / hz)
222 * Note: timer had better have been programmed before this is first used!
227 int delta, prev_tick, tick, ticks_left;
231 static int state = 0;
235 for (n1 = 1; n1 <= 10000000; n1 *= 10)
240 printf("DELAY(%d)...", n);
243 * Read the counter first, so that the rest of the setup overhead is
244 * counted. Guess the initial overhead is 20 usec (on most systems it
245 * takes about 1.5 usec for each of the i/o's in getit(). The loop
246 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
247 * multiplications and divisions to scale the count take a while).
249 * However, if ddb is active then use a fake counter since reading
250 * the i8254 counter involves acquiring a lock. ddb must not do
251 * locking for many reasons, but it calls here for at least atkbd
260 n -= 0; /* XXX actually guess no initial overhead */
262 * Calculate (n * (i8254_freq / 1e6)) without using floating point
263 * and without any avoidable overflows.
269 * Use fixed point to avoid a slow division by 1000000.
270 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
271 * 2^15 is the first power of 2 that gives exact results
272 * for n between 0 and 256.
274 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
277 * Don't bother using fixed point, although gcc-2.7.2
278 * generates particularly poor code for the long long
279 * division, since even the slow way will complete long
280 * before the delay is up (unless we're interrupted).
282 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
285 while (ticks_left > 0) {
289 tick = prev_tick - 1;
291 tick = i8254_max_count;
298 delta = prev_tick - tick;
301 delta += i8254_max_count;
303 * Guard against i8254_max_count being wrong.
304 * This shouldn't happen in normal operation,
305 * but it may happen if set_i8254_freq() is
315 printf(" %d calls to getit() at %d usec each\n",
316 getit_calls, (n + 5) / getit_calls);
321 set_i8254_freq(int mode, uint32_t period)
323 int new_count, new_mode;
325 mtx_lock_spin(&clock_lock);
326 if (mode == MODE_STOP) {
327 if (i8254_timecounter) {
328 mode = MODE_PERIODIC;
333 new_count = min(((uint64_t)i8254_freq * period +
334 0x80000000LLU) >> 32, 0x10000);
336 if (new_count == timer0_period)
338 i8254_max_count = ((new_count & ~0xffff) != 0) ? 0xffff : new_count;
339 timer0_period = (mode == MODE_PERIODIC) ? new_count : -1;
342 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
343 outb(TIMER_MODE, new_mode);
344 outb(TIMER_CNTR0, 0);
345 outb(TIMER_CNTR0, 0);
348 new_mode = TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT;
349 outb(TIMER_MODE, new_mode);
350 outb(TIMER_CNTR0, new_count & 0xff);
351 outb(TIMER_CNTR0, new_count >> 8);
354 if (new_count < 256 && timer0_last < 256) {
355 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_LSB;
356 if (new_mode != timer0_mode)
357 outb(TIMER_MODE, new_mode);
358 outb(TIMER_CNTR0, new_count & 0xff);
361 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
362 if (new_mode != timer0_mode)
363 outb(TIMER_MODE, new_mode);
364 outb(TIMER_CNTR0, new_count & 0xff);
365 outb(TIMER_CNTR0, new_count >> 8);
368 panic("set_i8254_freq: unknown operational mode");
370 timer0_mode = new_mode;
371 timer0_last = new_count;
373 mtx_unlock_spin(&clock_lock);
381 timer0_mode = 0xffff;
382 timer0_last = 0xffff;
383 if (attimer_sc != NULL)
384 set_i8254_freq(attimer_sc->mode, attimer_sc->period);
386 set_i8254_freq(MODE_STOP, 0);
391 * Restore all the timers non-atomically (XXX: should be atomically).
393 * This function is called from pmtimer_resume() to restore all the timers.
394 * This should not be necessary, but there are broken laptops that do not
395 * restore all the timers on resume. The APM spec was at best vague on the
397 * pmtimer is used only with the old APM power management, and not with
398 * acpi, which is required for amd64, so skip it in that case.
404 i8254_restore(); /* restore i8254_freq and hz */
405 atrtc_restore(); /* reenable RTC interrupts */
409 /* This is separate from startrtclock() so that it can be called early. */
414 set_i8254_freq(MODE_STOP, 0);
427 #ifdef EARLY_AP_STARTUP
432 cpu_initclocks_bsp();
442 if (sched_is_bound(td))
446 cpu_initclocks_bsp();
451 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
457 * Use `i8254' instead of `timer' in external names because `timer'
458 * is too generic. Should use it everywhere.
461 error = sysctl_handle_int(oidp, &freq, 0, req);
462 if (error == 0 && req->newptr != NULL) {
464 if (attimer_sc != NULL) {
465 set_i8254_freq(attimer_sc->mode, attimer_sc->period);
466 attimer_sc->tc.tc_frequency = freq;
468 set_i8254_freq(MODE_STOP, 0);
474 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
475 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU",
476 "i8254 timer frequency");
479 i8254_get_timecount(struct timecounter *tc)
481 device_t dev = (device_t)tc->tc_priv;
482 struct attimer_softc *sc = device_get_softc(dev);
488 return (i8254_max_count - getit());
491 flags = read_rflags();
493 flags = read_eflags();
495 mtx_lock_spin(&clock_lock);
497 /* Select timer0 and latch counter value. */
498 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
500 low = inb(TIMER_CNTR0);
501 high = inb(TIMER_CNTR0);
502 count = i8254_max_count - ((high << 8) | low);
503 if (count < i8254_lastcount ||
504 (!i8254_ticked && (clkintr_pending ||
505 ((count < 20 || (!(flags & PSL_I) &&
506 count < i8254_max_count / 2u)) &&
507 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
509 i8254_offset += i8254_max_count;
511 i8254_lastcount = count;
512 count += i8254_offset;
513 mtx_unlock_spin(&clock_lock);
518 attimer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
520 device_t dev = (device_t)et->et_priv;
521 struct attimer_softc *sc = device_get_softc(dev);
524 sc->mode = MODE_PERIODIC;
527 sc->mode = MODE_ONESHOT;
531 i8254_intsrc->is_pic->pic_enable_source(i8254_intsrc);
534 set_i8254_freq(sc->mode, sc->period);
539 attimer_stop(struct eventtimer *et)
541 device_t dev = (device_t)et->et_priv;
542 struct attimer_softc *sc = device_get_softc(dev);
544 sc->mode = MODE_STOP;
546 set_i8254_freq(sc->mode, sc->period);
552 * Attach to the ISA PnP descriptors for the timer
554 static struct isa_pnp_id attimer_ids[] = {
555 { 0x0001d041 /* PNP0100 */, "AT timer" },
560 attimer_probe(device_t dev)
564 result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
565 /* ENOENT means no PnP-ID, device is hinted. */
566 if (result == ENOENT) {
567 device_set_desc(dev, "AT timer");
568 return (BUS_PROBE_LOW_PRIORITY);
574 attimer_attach(device_t dev)
576 struct attimer_softc *sc;
580 attimer_sc = sc = device_get_softc(dev);
581 bzero(sc, sizeof(struct attimer_softc));
582 if (!(sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
583 &sc->port_rid, IO_TIMER1, IO_TIMER1 + 3, 4, RF_ACTIVE)))
584 device_printf(dev,"Warning: Couldn't map I/O.\n");
585 i8254_intsrc = intr_lookup_source(0);
586 if (i8254_intsrc != NULL)
587 i8254_pending = i8254_intsrc->is_pic->pic_source_pending;
588 resource_int_value(device_get_name(dev), device_get_unit(dev),
589 "timecounter", &i8254_timecounter);
590 set_i8254_freq(MODE_STOP, 0);
591 if (i8254_timecounter) {
592 sc->tc.tc_get_timecount = i8254_get_timecount;
593 sc->tc.tc_counter_mask = 0xffff;
594 sc->tc.tc_frequency = i8254_freq;
595 sc->tc.tc_name = "i8254";
596 sc->tc.tc_quality = 0;
597 sc->tc.tc_priv = dev;
600 if (resource_int_value(device_get_name(dev), device_get_unit(dev),
601 "clock", &i) != 0 || i != 0) {
603 while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid,
604 &s, NULL) == 0 && s != 0)
606 if (!(sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
607 &sc->intr_rid, 0, 0, 1, RF_ACTIVE))) {
608 device_printf(dev,"Can't map interrupt.\n");
611 /* Dirty hack, to make bus_setup_intr to not enable source. */
612 i8254_intsrc->is_handlers++;
613 if ((bus_setup_intr(dev, sc->intr_res,
614 INTR_MPSAFE | INTR_TYPE_CLK,
615 (driver_filter_t *)clkintr, NULL,
616 sc, &sc->intr_handler))) {
617 device_printf(dev, "Can't setup interrupt.\n");
618 i8254_intsrc->is_handlers--;
621 i8254_intsrc->is_handlers--;
622 i8254_intsrc->is_pic->pic_enable_intr(i8254_intsrc);
623 sc->et.et_name = "i8254";
624 sc->et.et_flags = ET_FLAGS_PERIODIC;
625 if (!i8254_timecounter)
626 sc->et.et_flags |= ET_FLAGS_ONESHOT;
627 sc->et.et_quality = 100;
628 sc->et.et_frequency = i8254_freq;
629 sc->et.et_min_period = (0x0002LLU << 32) / i8254_freq;
630 sc->et.et_max_period = (0xfffeLLU << 32) / i8254_freq;
631 sc->et.et_start = attimer_start;
632 sc->et.et_stop = attimer_stop;
633 sc->et.et_priv = dev;
634 et_register(&sc->et);
640 attimer_resume(device_t dev)
647 static device_method_t attimer_methods[] = {
648 /* Device interface */
649 DEVMETHOD(device_probe, attimer_probe),
650 DEVMETHOD(device_attach, attimer_attach),
651 DEVMETHOD(device_detach, bus_generic_detach),
652 DEVMETHOD(device_shutdown, bus_generic_shutdown),
653 DEVMETHOD(device_suspend, bus_generic_suspend),
654 DEVMETHOD(device_resume, attimer_resume),
658 static driver_t attimer_driver = {
661 sizeof(struct attimer_softc),
664 static devclass_t attimer_devclass;
666 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
667 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);