1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1990 The Regents of the University of California.
5 * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * William Jolitz and Don Ahn.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
36 */
37
38 #include <sys/cdefs.h>
39 /*
40 * Routines to handle clock hardware.
41 */
42
43 #ifdef __amd64__
44 #define DEV_APIC
45 #else
46 #include "opt_apic.h"
47 #endif
48 #include "opt_clock.h"
49 #include "opt_isa.h"
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/bus.h>
54 #include <sys/lock.h>
55 #include <sys/kdb.h>
56 #include <sys/mutex.h>
57 #include <sys/proc.h>
58 #include <sys/kernel.h>
59 #include <sys/module.h>
60 #include <sys/rman.h>
61 #include <sys/sched.h>
62 #include <sys/smp.h>
63 #include <sys/sysctl.h>
64 #include <sys/timeet.h>
65 #include <sys/timetc.h>
66
67 #include <machine/clock.h>
68 #include <machine/cpu.h>
69 #include <machine/intr_machdep.h>
70 #include <machine/ppireg.h>
71 #include <machine/timerreg.h>
72 #include <x86/apicvar.h>
73 #include <x86/init.h>
74
75 #include <isa/rtc.h>
76 #ifdef DEV_ISA
77 #include <isa/isareg.h>
78 #include <isa/isavar.h>
79 #endif
80
81 int clkintr_pending;
82 #ifndef TIMER_FREQ
83 #define TIMER_FREQ 1193182
84 #endif
85 u_int i8254_freq = TIMER_FREQ;
86 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
87 int i8254_max_count;
88 static int i8254_timecounter = 1;
89
90 static struct mtx clock_lock;
91 static struct intsrc *i8254_intsrc;
92 static uint16_t i8254_lastcount;
93 static uint16_t i8254_offset;
94 static int (*i8254_pending)(struct intsrc *);
95 static int i8254_ticked;
96
97 struct attimer_softc {
98 int intr_en;
99 int port_rid, intr_rid;
100 struct resource *port_res;
101 struct resource *intr_res;
102 void *intr_handler;
103 struct timecounter tc;
104 struct eventtimer et;
105 int mode;
106 #define MODE_STOP 0
107 #define MODE_PERIODIC 1
108 #define MODE_ONESHOT 2
109 uint32_t period;
110 };
111 static struct attimer_softc *attimer_sc = NULL;
112
113 static int timer0_period = -2;
114 static int timer0_mode = 0xffff;
115 static int timer0_last = 0xffff;
116
117 /* Values for timerX_state: */
118 #define RELEASED 0
119 #define RELEASE_PENDING 1
120 #define ACQUIRED 2
121 #define ACQUIRE_PENDING 3
122
123 static u_char timer2_state;
124
125 static unsigned i8254_get_timecount(struct timecounter *tc);
126 static void set_i8254_freq(int mode, uint32_t period);
127
128 void
clock_init(void)129 clock_init(void)
130 {
131 /* Init the clock lock */
132 mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
133 /* Init the clock in order to use DELAY */
134 init_ops.early_clock_source_init();
135 }
136
137 static int
clkintr(void * arg)138 clkintr(void *arg)
139 {
140 struct attimer_softc *sc = (struct attimer_softc *)arg;
141
142 if (i8254_timecounter && sc->period != 0) {
143 mtx_lock_spin(&clock_lock);
144 if (i8254_ticked)
145 i8254_ticked = 0;
146 else {
147 i8254_offset += i8254_max_count;
148 i8254_lastcount = 0;
149 }
150 clkintr_pending = 0;
151 mtx_unlock_spin(&clock_lock);
152 }
153
154 if (sc->et.et_active && sc->mode != MODE_STOP)
155 sc->et.et_event_cb(&sc->et, sc->et.et_arg);
156
157 return (FILTER_HANDLED);
158 }
159
160 int
timer_spkr_acquire(void)161 timer_spkr_acquire(void)
162 {
163 int mode;
164
165 mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
166
167 if (timer2_state != RELEASED)
168 return (-1);
169 timer2_state = ACQUIRED;
170
171 /*
172 * This access to the timer registers is as atomic as possible
173 * because it is a single instruction. We could do better if we
174 * knew the rate. Use of splclock() limits glitches to 10-100us,
175 * and this is probably good enough for timer2, so we aren't as
176 * careful with it as with timer0.
177 */
178 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
179
180 ppi_spkr_on(); /* enable counter2 output to speaker */
181 return (0);
182 }
183
184 int
timer_spkr_release(void)185 timer_spkr_release(void)
186 {
187
188 if (timer2_state != ACQUIRED)
189 return (-1);
190 timer2_state = RELEASED;
191 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
192
193 ppi_spkr_off(); /* disable counter2 output to speaker */
194 return (0);
195 }
196
197 void
timer_spkr_setfreq(int freq)198 timer_spkr_setfreq(int freq)
199 {
200
201 freq = i8254_freq / freq;
202 mtx_lock_spin(&clock_lock);
203 outb(TIMER_CNTR2, freq & 0xff);
204 outb(TIMER_CNTR2, freq >> 8);
205 mtx_unlock_spin(&clock_lock);
206 }
207
208 static int
getit(void)209 getit(void)
210 {
211 int high, low;
212
213 mtx_lock_spin(&clock_lock);
214
215 /* Select timer0 and latch counter value. */
216 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
217
218 low = inb(TIMER_CNTR0);
219 high = inb(TIMER_CNTR0);
220
221 mtx_unlock_spin(&clock_lock);
222 return ((high << 8) | low);
223 }
224
225 /*
226 * Wait "n" microseconds.
227 * Relies on timer 1 counting down from (i8254_freq / hz)
228 * Note: timer had better have been programmed before this is first used!
229 */
230 void
i8254_delay(int n)231 i8254_delay(int n)
232 {
233 int delta, prev_tick, tick, ticks_left;
234 #ifdef DELAYDEBUG
235 int getit_calls = 1;
236 int n1;
237 static int state = 0;
238
239 if (state == 0) {
240 state = 1;
241 for (n1 = 1; n1 <= 10000000; n1 *= 10)
242 DELAY(n1);
243 state = 2;
244 }
245 if (state == 1)
246 printf("DELAY(%d)...", n);
247 #endif
248 /*
249 * Read the counter first, so that the rest of the setup overhead is
250 * counted. Guess the initial overhead is 20 usec (on most systems it
251 * takes about 1.5 usec for each of the i/o's in getit(). The loop
252 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
253 * multiplications and divisions to scale the count take a while).
254 *
255 * However, if ddb is active then use a fake counter since reading
256 * the i8254 counter involves acquiring a lock. ddb must not do
257 * locking for many reasons, but it calls here for at least atkbd
258 * input.
259 */
260 #ifdef KDB
261 if (kdb_active)
262 prev_tick = 1;
263 else
264 #endif
265 prev_tick = getit();
266 n -= 0; /* XXX actually guess no initial overhead */
267 /*
268 * Calculate (n * (i8254_freq / 1e6)) without using floating point
269 * and without any avoidable overflows.
270 */
271 if (n <= 0)
272 ticks_left = 0;
273 else if (n < 256)
274 /*
275 * Use fixed point to avoid a slow division by 1000000.
276 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
277 * 2^15 is the first power of 2 that gives exact results
278 * for n between 0 and 256.
279 */
280 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
281 else
282 /*
283 * Don't bother using fixed point, although gcc-2.7.2
284 * generates particularly poor code for the long long
285 * division, since even the slow way will complete long
286 * before the delay is up (unless we're interrupted).
287 */
288 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
289 / 1000000;
290
291 while (ticks_left > 0) {
292 #ifdef KDB
293 if (kdb_active) {
294 inb(0x84);
295 tick = prev_tick - 1;
296 if (tick <= 0)
297 tick = i8254_max_count;
298 } else
299 #endif
300 tick = getit();
301 #ifdef DELAYDEBUG
302 ++getit_calls;
303 #endif
304 delta = prev_tick - tick;
305 prev_tick = tick;
306 if (delta < 0) {
307 delta += i8254_max_count;
308 /*
309 * Guard against i8254_max_count being wrong.
310 * This shouldn't happen in normal operation,
311 * but it may happen if set_i8254_freq() is
312 * traced.
313 */
314 if (delta < 0)
315 delta = 0;
316 }
317 ticks_left -= delta;
318 }
319 #ifdef DELAYDEBUG
320 if (state == 1)
321 printf(" %d calls to getit() at %d usec each\n",
322 getit_calls, (n + 5) / getit_calls);
323 #endif
324 }
325
326 static void
set_i8254_freq(int mode,uint32_t period)327 set_i8254_freq(int mode, uint32_t period)
328 {
329 int new_count, new_mode;
330
331 mtx_lock_spin(&clock_lock);
332 if (mode == MODE_STOP) {
333 if (i8254_timecounter) {
334 mode = MODE_PERIODIC;
335 new_count = 0x10000;
336 } else
337 new_count = -1;
338 } else {
339 new_count = min(((uint64_t)i8254_freq * period +
340 0x80000000LLU) >> 32, 0x10000);
341 }
342 if (new_count == timer0_period)
343 goto out;
344 i8254_max_count = ((new_count & ~0xffff) != 0) ? 0xffff : new_count;
345 timer0_period = (mode == MODE_PERIODIC) ? new_count : -1;
346 switch (mode) {
347 case MODE_STOP:
348 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
349 outb(TIMER_MODE, new_mode);
350 outb(TIMER_CNTR0, 0);
351 outb(TIMER_CNTR0, 0);
352 break;
353 case MODE_PERIODIC:
354 new_mode = TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT;
355 outb(TIMER_MODE, new_mode);
356 outb(TIMER_CNTR0, new_count & 0xff);
357 outb(TIMER_CNTR0, new_count >> 8);
358 break;
359 case MODE_ONESHOT:
360 if (new_count < 256 && timer0_last < 256) {
361 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_LSB;
362 if (new_mode != timer0_mode)
363 outb(TIMER_MODE, new_mode);
364 outb(TIMER_CNTR0, new_count & 0xff);
365 break;
366 }
367 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
368 if (new_mode != timer0_mode)
369 outb(TIMER_MODE, new_mode);
370 outb(TIMER_CNTR0, new_count & 0xff);
371 outb(TIMER_CNTR0, new_count >> 8);
372 break;
373 default:
374 panic("set_i8254_freq: unknown operational mode");
375 }
376 timer0_mode = new_mode;
377 timer0_last = new_count;
378 out:
379 mtx_unlock_spin(&clock_lock);
380 }
381
382 static void
i8254_restore(void)383 i8254_restore(void)
384 {
385
386 timer0_period = -2;
387 timer0_mode = 0xffff;
388 timer0_last = 0xffff;
389 if (attimer_sc != NULL)
390 set_i8254_freq(attimer_sc->mode, attimer_sc->period);
391 else
392 set_i8254_freq(MODE_STOP, 0);
393 }
394
395 /* This is separate from startrtclock() so that it can be called early. */
396 void
i8254_init(void)397 i8254_init(void)
398 {
399
400 set_i8254_freq(MODE_STOP, 0);
401 }
402
403 void
startrtclock(void)404 startrtclock(void)
405 {
406
407 start_TSC();
408 }
409
410 void
cpu_initclocks(void)411 cpu_initclocks(void)
412 {
413 #ifdef EARLY_AP_STARTUP
414 struct thread *td;
415 int i;
416
417 td = curthread;
418
419 tsc_calibrate();
420 #ifdef DEV_APIC
421 lapic_calibrate_timer();
422 #endif
423 cpu_initclocks_bsp();
424 CPU_FOREACH(i) {
425 if (i == 0)
426 continue;
427 thread_lock(td);
428 sched_bind(td, i);
429 thread_unlock(td);
430 cpu_initclocks_ap();
431 }
432 thread_lock(td);
433 if (sched_is_bound(td))
434 sched_unbind(td);
435 thread_unlock(td);
436 #else
437 tsc_calibrate();
438 #ifdef DEV_APIC
439 lapic_calibrate_timer();
440 #endif
441 cpu_initclocks_bsp();
442 #endif
443 }
444
445 static int
sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)446 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
447 {
448 int error;
449 u_int freq;
450
451 /*
452 * Use `i8254' instead of `timer' in external names because `timer'
453 * is too generic. Should use it everywhere.
454 */
455 freq = i8254_freq;
456 error = sysctl_handle_int(oidp, &freq, 0, req);
457 if (error == 0 && req->newptr != NULL) {
458 i8254_freq = freq;
459 if (attimer_sc != NULL) {
460 set_i8254_freq(attimer_sc->mode, attimer_sc->period);
461 attimer_sc->tc.tc_frequency = freq;
462 } else {
463 set_i8254_freq(MODE_STOP, 0);
464 }
465 }
466 return (error);
467 }
468
469 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq,
470 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
471 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU",
472 "i8254 timer frequency");
473
474 static unsigned
i8254_get_timecount(struct timecounter * tc)475 i8254_get_timecount(struct timecounter *tc)
476 {
477 device_t dev = (device_t)tc->tc_priv;
478 struct attimer_softc *sc = device_get_softc(dev);
479 register_t flags;
480 uint16_t count;
481 u_int high, low;
482
483 if (sc->period == 0)
484 return (i8254_max_count - getit());
485
486 #ifdef __amd64__
487 flags = read_rflags();
488 #else
489 flags = read_eflags();
490 #endif
491 mtx_lock_spin(&clock_lock);
492
493 /* Select timer0 and latch counter value. */
494 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
495
496 low = inb(TIMER_CNTR0);
497 high = inb(TIMER_CNTR0);
498 count = i8254_max_count - ((high << 8) | low);
499 if (count < i8254_lastcount ||
500 (!i8254_ticked && (clkintr_pending ||
501 ((count < 20 || (!(flags & PSL_I) &&
502 count < i8254_max_count / 2u)) &&
503 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
504 i8254_ticked = 1;
505 i8254_offset += i8254_max_count;
506 }
507 i8254_lastcount = count;
508 count += i8254_offset;
509 mtx_unlock_spin(&clock_lock);
510 return (count);
511 }
512
513 static int
attimer_start(struct eventtimer * et,sbintime_t first,sbintime_t period)514 attimer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
515 {
516 device_t dev = (device_t)et->et_priv;
517 struct attimer_softc *sc = device_get_softc(dev);
518
519 if (period != 0) {
520 sc->mode = MODE_PERIODIC;
521 sc->period = period;
522 } else {
523 sc->mode = MODE_ONESHOT;
524 sc->period = first;
525 }
526 if (!sc->intr_en) {
527 i8254_intsrc->is_pic->pic_enable_source(i8254_intsrc);
528 sc->intr_en = 1;
529 }
530 set_i8254_freq(sc->mode, sc->period);
531 return (0);
532 }
533
534 static int
attimer_stop(struct eventtimer * et)535 attimer_stop(struct eventtimer *et)
536 {
537 device_t dev = (device_t)et->et_priv;
538 struct attimer_softc *sc = device_get_softc(dev);
539
540 sc->mode = MODE_STOP;
541 sc->period = 0;
542 set_i8254_freq(sc->mode, sc->period);
543 return (0);
544 }
545
546 #ifdef DEV_ISA
547 /*
548 * Attach to the ISA PnP descriptors for the timer
549 */
550 static struct isa_pnp_id attimer_ids[] = {
551 { 0x0001d041 /* PNP0100 */, "AT timer" },
552 { 0 }
553 };
554
555 static int
attimer_probe(device_t dev)556 attimer_probe(device_t dev)
557 {
558 int result;
559
560 result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
561 /* ENOENT means no PnP-ID, device is hinted. */
562 if (result == ENOENT) {
563 device_set_desc(dev, "AT timer");
564 return (BUS_PROBE_LOW_PRIORITY);
565 }
566 return (result);
567 }
568
569 static int
attimer_attach(device_t dev)570 attimer_attach(device_t dev)
571 {
572 struct attimer_softc *sc;
573 rman_res_t s;
574 int i;
575
576 attimer_sc = sc = device_get_softc(dev);
577 bzero(sc, sizeof(struct attimer_softc));
578 if (!(sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
579 &sc->port_rid, IO_TIMER1, IO_TIMER1 + 3, 4, RF_ACTIVE)))
580 device_printf(dev,"Warning: Couldn't map I/O.\n");
581 i8254_intsrc = intr_lookup_source(0);
582 if (i8254_intsrc != NULL)
583 i8254_pending = i8254_intsrc->is_pic->pic_source_pending;
584 resource_int_value(device_get_name(dev), device_get_unit(dev),
585 "timecounter", &i8254_timecounter);
586 set_i8254_freq(MODE_STOP, 0);
587 if (i8254_timecounter) {
588 sc->tc.tc_get_timecount = i8254_get_timecount;
589 sc->tc.tc_counter_mask = 0xffff;
590 sc->tc.tc_frequency = i8254_freq;
591 sc->tc.tc_name = "i8254";
592 sc->tc.tc_quality = 0;
593 sc->tc.tc_priv = dev;
594 tc_init(&sc->tc);
595 }
596 if (resource_int_value(device_get_name(dev), device_get_unit(dev),
597 "clock", &i) != 0 || i != 0) {
598 sc->intr_rid = 0;
599 while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid,
600 &s, NULL) == 0 && s != 0)
601 sc->intr_rid++;
602 if (!(sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
603 &sc->intr_rid, 0, 0, 1, RF_ACTIVE))) {
604 device_printf(dev,"Can't map interrupt.\n");
605 return (0);
606 }
607 /* Dirty hack, to make bus_setup_intr to not enable source. */
608 i8254_intsrc->is_handlers++;
609 if ((bus_setup_intr(dev, sc->intr_res,
610 INTR_MPSAFE | INTR_TYPE_CLK,
611 (driver_filter_t *)clkintr, NULL,
612 sc, &sc->intr_handler))) {
613 device_printf(dev, "Can't setup interrupt.\n");
614 i8254_intsrc->is_handlers--;
615 return (0);
616 }
617 i8254_intsrc->is_handlers--;
618 i8254_intsrc->is_pic->pic_enable_intr(i8254_intsrc);
619 sc->et.et_name = "i8254";
620 sc->et.et_flags = ET_FLAGS_PERIODIC;
621 if (!i8254_timecounter)
622 sc->et.et_flags |= ET_FLAGS_ONESHOT;
623 sc->et.et_quality = 100;
624 sc->et.et_frequency = i8254_freq;
625 sc->et.et_min_period = (0x0002LLU << 32) / i8254_freq;
626 sc->et.et_max_period = (0xfffeLLU << 32) / i8254_freq;
627 sc->et.et_start = attimer_start;
628 sc->et.et_stop = attimer_stop;
629 sc->et.et_priv = dev;
630 et_register(&sc->et);
631 }
632 return(0);
633 }
634
635 static int
attimer_resume(device_t dev)636 attimer_resume(device_t dev)
637 {
638
639 i8254_restore();
640 return (0);
641 }
642
643 static device_method_t attimer_methods[] = {
644 /* Device interface */
645 DEVMETHOD(device_probe, attimer_probe),
646 DEVMETHOD(device_attach, attimer_attach),
647 DEVMETHOD(device_resume, attimer_resume),
648 { 0, 0 }
649 };
650
651 static driver_t attimer_driver = {
652 "attimer",
653 attimer_methods,
654 sizeof(struct attimer_softc),
655 };
656
657 static devclass_t attimer_devclass;
658
659 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
660 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
661 ISA_PNP_INFO(attimer_ids);
662
663 #endif /* DEV_ISA */
664