FreeBSD/Linux Kernel Cross Reference
sys/pc98/pc98/clock.c
1 /*-
2 * Copyright (c) 1990 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz and Don Ahn.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
37 * $FreeBSD: releng/5.0/sys/pc98/pc98/clock.c 105710 2002-10-22 15:19:46Z nyan $
38 */
39
40 /*
41 * Routines to handle clock hardware.
42 */
43
44 /*
45 * inittodr, settodr and support routines written
46 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
47 *
48 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
49 */
50
51 /*
52 * modified for PC98 by Kakefuda
53 */
54
55 #include "opt_clock.h"
56 #include "opt_isa.h"
57 #include "opt_mca.h"
58
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bus.h>
62 #include <sys/lock.h>
63 #include <sys/mutex.h>
64 #include <sys/proc.h>
65 #include <sys/time.h>
66 #include <sys/timetc.h>
67 #include <sys/kernel.h>
68 #include <sys/sysctl.h>
69 #include <sys/cons.h>
70 #include <sys/power.h>
71
72 #include <machine/clock.h>
73 #include <machine/cputypes.h>
74 #include <machine/frame.h>
75 #include <machine/limits.h>
76 #include <machine/md_var.h>
77 #include <machine/psl.h>
78 #ifdef APIC_IO
79 #include <machine/segments.h>
80 #endif
81 #if defined(SMP) || defined(APIC_IO)
82 #include <machine/smp.h>
83 #endif /* SMP || APIC_IO */
84 #include <machine/specialreg.h>
85
86 #include <i386/isa/icu.h>
87 #ifdef PC98
88 #include <pc98/pc98/pc98.h>
89 #include <pc98/pc98/pc98_machdep.h>
90 #include <i386/isa/isa_device.h>
91 #else
92 #include <i386/isa/isa.h>
93 #include <isa/rtc.h>
94 #endif
95 #ifdef DEV_ISA
96 #include <isa/isavar.h>
97 #endif
98 #include <i386/isa/timerreg.h>
99
100 #include <i386/isa/intr_machdep.h>
101
102 #ifdef DEV_MCA
103 #include <i386/isa/mca_machdep.h>
104 #endif
105
106 #ifdef APIC_IO
107 #include <i386/isa/intr_machdep.h>
108 /* The interrupt triggered by the 8254 (timer) chip */
109 int apic_8254_intr;
110 static u_long read_intr_count(int vec);
111 static void setup_8254_mixed_mode(void);
112 #endif
113
114 /*
115 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
116 * can use a simple formula for leap years.
117 */
118 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
119 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
120
121 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
122
123 /*
124 * Time in timer cycles that it takes for microtime() to disable interrupts
125 * and latch the count. microtime() currently uses "cli; outb ..." so it
126 * normally takes less than 2 timer cycles. Add a few for cache misses.
127 * Add a few more to allow for latency in bogus calls to microtime() with
128 * interrupts already disabled.
129 */
130 #define TIMER0_LATCH_COUNT 20
131
132 /*
133 * Maximum frequency that we are willing to allow for timer0. Must be
134 * low enough to guarantee that the timer interrupt handler returns
135 * before the next timer interrupt.
136 */
137 #define TIMER0_MAX_FREQ 20000
138
139 int adjkerntz; /* local offset from GMT in seconds */
140 int clkintr_pending;
141 int disable_rtc_set; /* disable resettodr() if != 0 */
142 int statclock_disable;
143 #ifndef TIMER_FREQ
144 #ifdef PC98
145 #define TIMER_FREQ 2457600
146 #else /* IBM-PC */
147 #define TIMER_FREQ 1193182
148 #endif /* PC98 */
149 #endif
150 u_int timer_freq = TIMER_FREQ;
151 int timer0_max_count;
152 u_int tsc_freq;
153 int tsc_is_broken;
154 u_int tsc_present;
155 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
156 struct mtx clock_lock;
157
158 static int beeping = 0;
159 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
160 static u_int hardclock_max_count;
161 static u_int32_t i8254_lastcount;
162 static u_int32_t i8254_offset;
163 static int i8254_ticked;
164 /*
165 * XXX new_function and timer_func should not handle clockframes, but
166 * timer_func currently needs to hold hardclock to handle the
167 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
168 * to switch between clkintr() and a slightly different timerintr().
169 */
170 static void (*new_function)(struct clockframe *frame);
171 static u_int new_rate;
172 #ifndef PC98
173 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
174 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
175 #endif
176 static u_int timer0_prescaler_count;
177
178 /* Values for timerX_state: */
179 #define RELEASED 0
180 #define RELEASE_PENDING 1
181 #define ACQUIRED 2
182 #define ACQUIRE_PENDING 3
183
184 static u_char timer0_state;
185 #ifdef PC98
186 static u_char timer1_state;
187 #endif
188 static u_char timer2_state;
189 static void (*timer_func)(struct clockframe *frame) = hardclock;
190 #ifdef PC98
191 static void rtc_serialcombit(int);
192 static void rtc_serialcom(int);
193 static int rtc_inb(void);
194 static void rtc_outb(int);
195 #endif
196
197 static unsigned i8254_get_timecount(struct timecounter *tc);
198 static unsigned tsc_get_timecount(struct timecounter *tc);
199 static void set_timer_freq(u_int freq, int intr_freq);
200
201 static struct timecounter tsc_timecounter = {
202 tsc_get_timecount, /* get_timecount */
203 0, /* no poll_pps */
204 ~0u, /* counter_mask */
205 0, /* frequency */
206 "TSC" /* name */
207 };
208
209 static struct timecounter i8254_timecounter = {
210 i8254_get_timecount, /* get_timecount */
211 0, /* no poll_pps */
212 ~0u, /* counter_mask */
213 0, /* frequency */
214 "i8254" /* name */
215 };
216
217 static void
218 clkintr(struct clockframe frame)
219 {
220
221 if (timecounter->tc_get_timecount == i8254_get_timecount) {
222 mtx_lock_spin(&clock_lock);
223 if (i8254_ticked)
224 i8254_ticked = 0;
225 else {
226 i8254_offset += timer0_max_count;
227 i8254_lastcount = 0;
228 }
229 clkintr_pending = 0;
230 mtx_unlock_spin(&clock_lock);
231 }
232 timer_func(&frame);
233 #ifdef SMP
234 if (timer_func == hardclock)
235 forward_hardclock();
236 #endif
237 switch (timer0_state) {
238
239 case RELEASED:
240 break;
241
242 case ACQUIRED:
243 if ((timer0_prescaler_count += timer0_max_count)
244 >= hardclock_max_count) {
245 timer0_prescaler_count -= hardclock_max_count;
246 hardclock(&frame);
247 #ifdef SMP
248 forward_hardclock();
249 #endif
250 }
251 break;
252
253 case ACQUIRE_PENDING:
254 mtx_lock_spin(&clock_lock);
255 i8254_offset = i8254_get_timecount(NULL);
256 i8254_lastcount = 0;
257 timer0_max_count = TIMER_DIV(new_rate);
258 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
259 outb(TIMER_CNTR0, timer0_max_count & 0xff);
260 outb(TIMER_CNTR0, timer0_max_count >> 8);
261 mtx_unlock_spin(&clock_lock);
262 timer_func = new_function;
263 timer0_state = ACQUIRED;
264 break;
265
266 case RELEASE_PENDING:
267 if ((timer0_prescaler_count += timer0_max_count)
268 >= hardclock_max_count) {
269 mtx_lock_spin(&clock_lock);
270 i8254_offset = i8254_get_timecount(NULL);
271 i8254_lastcount = 0;
272 timer0_max_count = hardclock_max_count;
273 outb(TIMER_MODE,
274 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
275 outb(TIMER_CNTR0, timer0_max_count & 0xff);
276 outb(TIMER_CNTR0, timer0_max_count >> 8);
277 mtx_unlock_spin(&clock_lock);
278 timer0_prescaler_count = 0;
279 timer_func = hardclock;
280 timer0_state = RELEASED;
281 hardclock(&frame);
282 #ifdef SMP
283 forward_hardclock();
284 #endif
285 }
286 break;
287 }
288 #ifdef DEV_MCA
289 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
290 if (MCA_system)
291 outb(0x61, inb(0x61) | 0x80);
292 #endif
293 }
294
295 /*
296 * The acquire and release functions must be called at ipl >= splclock().
297 */
298 int
299 acquire_timer0(int rate, void (*function)(struct clockframe *frame))
300 {
301 static int old_rate;
302
303 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
304 return (-1);
305 switch (timer0_state) {
306
307 case RELEASED:
308 timer0_state = ACQUIRE_PENDING;
309 break;
310
311 case RELEASE_PENDING:
312 if (rate != old_rate)
313 return (-1);
314 /*
315 * The timer has been released recently, but is being
316 * re-acquired before the release completed. In this
317 * case, we simply reclaim it as if it had not been
318 * released at all.
319 */
320 timer0_state = ACQUIRED;
321 break;
322
323 default:
324 return (-1); /* busy */
325 }
326 new_function = function;
327 old_rate = new_rate = rate;
328 return (0);
329 }
330
331 #ifdef PC98
332 int
333 acquire_timer1(int mode)
334 {
335
336 if (timer1_state != RELEASED)
337 return (-1);
338 timer1_state = ACQUIRED;
339
340 /*
341 * This access to the timer registers is as atomic as possible
342 * because it is a single instruction. We could do better if we
343 * knew the rate. Use of splclock() limits glitches to 10-100us,
344 * and this is probably good enough for timer2, so we aren't as
345 * careful with it as with timer0.
346 */
347 outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
348
349 return (0);
350 }
351 #endif
352
353 int
354 acquire_timer2(int mode)
355 {
356
357 if (timer2_state != RELEASED)
358 return (-1);
359 timer2_state = ACQUIRED;
360
361 /*
362 * This access to the timer registers is as atomic as possible
363 * because it is a single instruction. We could do better if we
364 * knew the rate. Use of splclock() limits glitches to 10-100us,
365 * and this is probably good enough for timer2, so we aren't as
366 * careful with it as with timer0.
367 */
368 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
369
370 return (0);
371 }
372
373 int
374 release_timer0()
375 {
376 switch (timer0_state) {
377
378 case ACQUIRED:
379 timer0_state = RELEASE_PENDING;
380 break;
381
382 case ACQUIRE_PENDING:
383 /* Nothing happened yet, release quickly. */
384 timer0_state = RELEASED;
385 break;
386
387 default:
388 return (-1);
389 }
390 return (0);
391 }
392
393 #ifdef PC98
394 int
395 release_timer1()
396 {
397
398 if (timer1_state != ACQUIRED)
399 return (-1);
400 timer1_state = RELEASED;
401 outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
402 return (0);
403 }
404 #endif
405
406 int
407 release_timer2()
408 {
409
410 if (timer2_state != ACQUIRED)
411 return (-1);
412 timer2_state = RELEASED;
413 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
414 return (0);
415 }
416
417 #ifndef PC98
418 /*
419 * This routine receives statistical clock interrupts from the RTC.
420 * As explained above, these occur at 128 interrupts per second.
421 * When profiling, we receive interrupts at a rate of 1024 Hz.
422 *
423 * This does not actually add as much overhead as it sounds, because
424 * when the statistical clock is active, the hardclock driver no longer
425 * needs to keep (inaccurate) statistics on its own. This decouples
426 * statistics gathering from scheduling interrupts.
427 *
428 * The RTC chip requires that we read status register C (RTC_INTR)
429 * to acknowledge an interrupt, before it will generate the next one.
430 * Under high interrupt load, rtcintr() can be indefinitely delayed and
431 * the clock can tick immediately after the read from RTC_INTR. In this
432 * case, the mc146818A interrupt signal will not drop for long enough
433 * to register with the 8259 PIC. If an interrupt is missed, the stat
434 * clock will halt, considerably degrading system performance. This is
435 * why we use 'while' rather than a more straightforward 'if' below.
436 * Stat clock ticks can still be lost, causing minor loss of accuracy
437 * in the statistics, but the stat clock will no longer stop.
438 */
439 static void
440 rtcintr(struct clockframe frame)
441 {
442 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
443 statclock(&frame);
444 #ifdef SMP
445 forward_statclock();
446 #endif
447 }
448 }
449
450 #include "opt_ddb.h"
451 #ifdef DDB
452 #include <ddb/ddb.h>
453
454 DB_SHOW_COMMAND(rtc, rtc)
455 {
456 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
457 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
458 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
459 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
460 }
461 #endif /* DDB */
462 #endif /* for PC98 */
463
464 static int
465 getit(void)
466 {
467 int high, low;
468
469 mtx_lock_spin(&clock_lock);
470
471 /* Select timer0 and latch counter value. */
472 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
473
474 low = inb(TIMER_CNTR0);
475 high = inb(TIMER_CNTR0);
476
477 mtx_unlock_spin(&clock_lock);
478 return ((high << 8) | low);
479 }
480
481 /*
482 * Wait "n" microseconds.
483 * Relies on timer 1 counting down from (timer_freq / hz)
484 * Note: timer had better have been programmed before this is first used!
485 */
486 void
487 DELAY(int n)
488 {
489 int delta, prev_tick, tick, ticks_left;
490
491 #ifdef DELAYDEBUG
492 int getit_calls = 1;
493 int n1;
494 static int state = 0;
495
496 if (state == 0) {
497 state = 1;
498 for (n1 = 1; n1 <= 10000000; n1 *= 10)
499 DELAY(n1);
500 state = 2;
501 }
502 if (state == 1)
503 printf("DELAY(%d)...", n);
504 #endif
505 /*
506 * Guard against the timer being uninitialized if we are called
507 * early for console i/o.
508 */
509 if (timer0_max_count == 0)
510 set_timer_freq(timer_freq, hz);
511
512 /*
513 * Read the counter first, so that the rest of the setup overhead is
514 * counted. Guess the initial overhead is 20 usec (on most systems it
515 * takes about 1.5 usec for each of the i/o's in getit(). The loop
516 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
517 * multiplications and divisions to scale the count take a while).
518 */
519 prev_tick = getit();
520 n -= 0; /* XXX actually guess no initial overhead */
521 /*
522 * Calculate (n * (timer_freq / 1e6)) without using floating point
523 * and without any avoidable overflows.
524 */
525 if (n <= 0)
526 ticks_left = 0;
527 else if (n < 256)
528 /*
529 * Use fixed point to avoid a slow division by 1000000.
530 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
531 * 2^15 is the first power of 2 that gives exact results
532 * for n between 0 and 256.
533 */
534 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
535 else
536 /*
537 * Don't bother using fixed point, although gcc-2.7.2
538 * generates particularly poor code for the long long
539 * division, since even the slow way will complete long
540 * before the delay is up (unless we're interrupted).
541 */
542 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
543 / 1000000;
544
545 while (ticks_left > 0) {
546 tick = getit();
547 #ifdef DELAYDEBUG
548 ++getit_calls;
549 #endif
550 delta = prev_tick - tick;
551 prev_tick = tick;
552 if (delta < 0) {
553 delta += timer0_max_count;
554 /*
555 * Guard against timer0_max_count being wrong.
556 * This shouldn't happen in normal operation,
557 * but it may happen if set_timer_freq() is
558 * traced.
559 */
560 if (delta < 0)
561 delta = 0;
562 }
563 ticks_left -= delta;
564 }
565 #ifdef DELAYDEBUG
566 if (state == 1)
567 printf(" %d calls to getit() at %d usec each\n",
568 getit_calls, (n + 5) / getit_calls);
569 #endif
570 }
571
572 static void
573 sysbeepstop(void *chan)
574 {
575 #ifdef PC98 /* PC98 */
576 outb(IO_PPI, inb(IO_PPI)|0x08); /* disable counter1 output to speaker */
577 release_timer1();
578 #else
579 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
580 release_timer2();
581 #endif
582 beeping = 0;
583 }
584
585 int
586 sysbeep(int pitch, int period)
587 {
588 int x = splclock();
589
590 #ifdef PC98
591 if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
592 if (!beeping) {
593 /* Something else owns it. */
594 splx(x);
595 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
596 }
597 disable_intr();
598 outb(0x3fdb, pitch);
599 outb(0x3fdb, (pitch>>8));
600 enable_intr();
601 if (!beeping) {
602 /* enable counter1 output to speaker */
603 outb(IO_PPI, (inb(IO_PPI) & 0xf7));
604 beeping = period;
605 timeout(sysbeepstop, (void *)NULL, period);
606 }
607 #else
608 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
609 if (!beeping) {
610 /* Something else owns it. */
611 splx(x);
612 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
613 }
614 mtx_lock_spin(&clock_lock);
615 outb(TIMER_CNTR2, pitch);
616 outb(TIMER_CNTR2, (pitch>>8));
617 mtx_unlock_spin(&clock_lock);
618 if (!beeping) {
619 /* enable counter2 output to speaker */
620 outb(IO_PPI, inb(IO_PPI) | 3);
621 beeping = period;
622 timeout(sysbeepstop, (void *)NULL, period);
623 }
624 #endif
625 splx(x);
626 return (0);
627 }
628
629 #ifndef PC98
630 /*
631 * RTC support routines
632 */
633
634 int
635 rtcin(reg)
636 int reg;
637 {
638 int s;
639 u_char val;
640
641 s = splhigh();
642 outb(IO_RTC, reg);
643 inb(0x84);
644 val = inb(IO_RTC + 1);
645 inb(0x84);
646 splx(s);
647 return (val);
648 }
649
650 static __inline void
651 writertc(u_char reg, u_char val)
652 {
653 int s;
654
655 s = splhigh();
656 inb(0x84);
657 outb(IO_RTC, reg);
658 inb(0x84);
659 outb(IO_RTC + 1, val);
660 inb(0x84); /* XXX work around wrong order in rtcin() */
661 splx(s);
662 }
663
664 static __inline int
665 readrtc(int port)
666 {
667 return(bcd2bin(rtcin(port)));
668 }
669 #endif
670
671 #ifdef PC98
672 unsigned int delaycount;
673 #define FIRST_GUESS 0x2000
674 static void findcpuspeed(void)
675 {
676 int i;
677 int remainder;
678
679 /* Put counter in count down mode */
680 outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
681 outb(TIMER_CNTR0, 0xff);
682 outb(TIMER_CNTR0, 0xff);
683 for (i = FIRST_GUESS; i; i--)
684 ;
685 remainder = getit();
686 delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
687 }
688 #endif
689
690 #ifdef PC98
691 static u_int
692 calibrate_clocks(void)
693 {
694 int timeout;
695 u_int count, prev_count, tot_count;
696 u_short sec, start_sec;
697
698 if (bootverbose)
699 printf("Calibrating clock(s) ... ");
700 /* Check ARTIC. */
701 if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
702 !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
703 goto fail;
704 timeout = 100000000;
705
706 /* Read the ARTIC. */
707 sec = inw(0x5e);
708
709 /* Wait for the ARTIC to changes. */
710 start_sec = sec;
711 for (;;) {
712 sec = inw(0x5e);
713 if (sec != start_sec)
714 break;
715 if (--timeout == 0)
716 goto fail;
717 }
718 prev_count = getit();
719 if (prev_count == 0 || prev_count > timer0_max_count)
720 goto fail;
721 tot_count = 0;
722
723 if (tsc_present)
724 wrmsr(0x10, 0LL); /* XXX 0x10 is the MSR for the TSC */
725 start_sec = sec;
726 for (;;) {
727 sec = inw(0x5e);
728 count = getit();
729 if (count == 0 || count > timer0_max_count)
730 goto fail;
731 if (count > prev_count)
732 tot_count += prev_count - (count - timer0_max_count);
733 else
734 tot_count += prev_count - count;
735 prev_count = count;
736 if ((sec == start_sec + 1200) ||
737 (sec < start_sec &&
738 (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
739 break;
740 if (--timeout == 0)
741 goto fail;
742 }
743 /*
744 * Read the cpu cycle counter. The timing considerations are
745 * similar to those for the i8254 clock.
746 */
747 if (tsc_present)
748 tsc_freq = rdtsc();
749
750 if (bootverbose) {
751 if (tsc_present)
752 printf("TSC clock: %u Hz, ", tsc_freq);
753 printf("i8254 clock: %u Hz\n", tot_count);
754 }
755 return (tot_count);
756
757 fail:
758 if (bootverbose)
759 printf("failed, using default i8254 clock of %u Hz\n",
760 timer_freq);
761 return (timer_freq);
762 }
763 #else
764 static u_int
765 calibrate_clocks(void)
766 {
767 u_int64_t old_tsc;
768 u_int count, prev_count, tot_count;
769 int sec, start_sec, timeout;
770
771 if (bootverbose)
772 printf("Calibrating clock(s) ... ");
773 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
774 goto fail;
775 timeout = 100000000;
776
777 /* Read the mc146818A seconds counter. */
778 for (;;) {
779 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
780 sec = rtcin(RTC_SEC);
781 break;
782 }
783 if (--timeout == 0)
784 goto fail;
785 }
786
787 /* Wait for the mC146818A seconds counter to change. */
788 start_sec = sec;
789 for (;;) {
790 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
791 sec = rtcin(RTC_SEC);
792 if (sec != start_sec)
793 break;
794 }
795 if (--timeout == 0)
796 goto fail;
797 }
798
799 /* Start keeping track of the i8254 counter. */
800 prev_count = getit();
801 if (prev_count == 0 || prev_count > timer0_max_count)
802 goto fail;
803 tot_count = 0;
804
805 if (tsc_present)
806 old_tsc = rdtsc();
807 else
808 old_tsc = 0; /* shut up gcc */
809
810 /*
811 * Wait for the mc146818A seconds counter to change. Read the i8254
812 * counter for each iteration since this is convenient and only
813 * costs a few usec of inaccuracy. The timing of the final reads
814 * of the counters almost matches the timing of the initial reads,
815 * so the main cause of inaccuracy is the varying latency from
816 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
817 * rtcin(RTC_SEC) that returns a changed seconds count. The
818 * maximum inaccuracy from this cause is < 10 usec on 486's.
819 */
820 start_sec = sec;
821 for (;;) {
822 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
823 sec = rtcin(RTC_SEC);
824 count = getit();
825 if (count == 0 || count > timer0_max_count)
826 goto fail;
827 if (count > prev_count)
828 tot_count += prev_count - (count - timer0_max_count);
829 else
830 tot_count += prev_count - count;
831 prev_count = count;
832 if (sec != start_sec)
833 break;
834 if (--timeout == 0)
835 goto fail;
836 }
837
838 /*
839 * Read the cpu cycle counter. The timing considerations are
840 * similar to those for the i8254 clock.
841 */
842 if (tsc_present)
843 tsc_freq = rdtsc() - old_tsc;
844
845 if (bootverbose) {
846 if (tsc_present)
847 printf("TSC clock: %u Hz, ", tsc_freq);
848 printf("i8254 clock: %u Hz\n", tot_count);
849 }
850 return (tot_count);
851
852 fail:
853 if (bootverbose)
854 printf("failed, using default i8254 clock of %u Hz\n",
855 timer_freq);
856 return (timer_freq);
857 }
858 #endif /* !PC98 */
859
860 static void
861 set_timer_freq(u_int freq, int intr_freq)
862 {
863 int new_timer0_max_count;
864
865 mtx_lock_spin(&clock_lock);
866 timer_freq = freq;
867 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
868 if (new_timer0_max_count != timer0_max_count) {
869 timer0_max_count = new_timer0_max_count;
870 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
871 outb(TIMER_CNTR0, timer0_max_count & 0xff);
872 outb(TIMER_CNTR0, timer0_max_count >> 8);
873 }
874 mtx_unlock_spin(&clock_lock);
875 }
876
877 static void
878 i8254_restore(void)
879 {
880
881 mtx_lock_spin(&clock_lock);
882 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
883 outb(TIMER_CNTR0, timer0_max_count & 0xff);
884 outb(TIMER_CNTR0, timer0_max_count >> 8);
885 mtx_unlock_spin(&clock_lock);
886 }
887
888 #ifndef PC98
889 static void
890 rtc_restore(void)
891 {
892
893 /* Restore all of the RTC's "status" (actually, control) registers. */
894 /* XXX locking is needed for RTC access. */
895 writertc(RTC_STATUSB, RTCSB_24HR);
896 writertc(RTC_STATUSA, rtc_statusa);
897 writertc(RTC_STATUSB, rtc_statusb);
898 }
899 #endif
900
901 /*
902 * Restore all the timers non-atomically (XXX: should be atomically).
903 *
904 * This function is called from pmtimer_resume() to restore all the timers.
905 * This should not be necessary, but there are broken laptops that do not
906 * restore all the timers on resume.
907 */
908 void
909 timer_restore(void)
910 {
911
912 i8254_restore(); /* restore timer_freq and hz */
913 #ifndef PC98
914 rtc_restore(); /* reenable RTC interrupts */
915 #endif
916 }
917
918 /*
919 * Initialize 8254 timer 0 early so that it can be used in DELAY().
920 * XXX initialization of other timers is unintentionally left blank.
921 */
922 void
923 startrtclock()
924 {
925 u_int delta, freq;
926
927 #ifdef PC98
928 findcpuspeed();
929 if (pc98_machine_type & M_8M)
930 timer_freq = 1996800L; /* 1.9968 MHz */
931 else
932 timer_freq = 2457600L; /* 2.4576 MHz */
933 #endif /* PC98 */
934
935 if (cpu_feature & CPUID_TSC)
936 tsc_present = 1;
937 else
938 tsc_present = 0;
939
940 #ifndef PC98
941 writertc(RTC_STATUSA, rtc_statusa);
942 writertc(RTC_STATUSB, RTCSB_24HR);
943 #endif
944
945 set_timer_freq(timer_freq, hz);
946 freq = calibrate_clocks();
947 #ifdef CLK_CALIBRATION_LOOP
948 if (bootverbose) {
949 printf(
950 "Press a key on the console to abort clock calibration\n");
951 while (cncheckc() == -1)
952 calibrate_clocks();
953 }
954 #endif
955
956 /*
957 * Use the calibrated i8254 frequency if it seems reasonable.
958 * Otherwise use the default, and don't use the calibrated i586
959 * frequency.
960 */
961 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
962 if (delta < timer_freq / 100) {
963 #ifndef CLK_USE_I8254_CALIBRATION
964 if (bootverbose)
965 printf(
966 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
967 freq = timer_freq;
968 #endif
969 timer_freq = freq;
970 } else {
971 if (bootverbose)
972 printf(
973 "%d Hz differs from default of %d Hz by more than 1%%\n",
974 freq, timer_freq);
975 tsc_freq = 0;
976 }
977
978 set_timer_freq(timer_freq, hz);
979 i8254_timecounter.tc_frequency = timer_freq;
980 tc_init(&i8254_timecounter);
981
982 #ifndef CLK_USE_TSC_CALIBRATION
983 if (tsc_freq != 0) {
984 if (bootverbose)
985 printf(
986 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
987 tsc_freq = 0;
988 }
989 #endif
990 if (tsc_present && tsc_freq == 0) {
991 /*
992 * Calibration of the i586 clock relative to the mc146818A
993 * clock failed. Do a less accurate calibration relative
994 * to the i8254 clock.
995 */
996 u_int64_t old_tsc = rdtsc();
997
998 DELAY(1000000);
999 tsc_freq = rdtsc() - old_tsc;
1000 #ifdef CLK_USE_TSC_CALIBRATION
1001 if (bootverbose)
1002 printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
1003 #endif
1004 }
1005
1006 #if !defined(SMP)
1007 /*
1008 * We can not use the TSC in SMP mode, until we figure out a
1009 * cheap (impossible), reliable and precise (yeah right!) way
1010 * to synchronize the TSCs of all the CPUs.
1011 * Curse Intel for leaving the counter out of the I/O APIC.
1012 */
1013
1014 /*
1015 * We can not use the TSC if we support APM. Precise timekeeping
1016 * on an APM'ed machine is at best a fools pursuit, since
1017 * any and all of the time spent in various SMM code can't
1018 * be reliably accounted for. Reading the RTC is your only
1019 * source of reliable time info. The i8254 looses too of course
1020 * but we need to have some kind of time...
1021 * We don't know at this point whether APM is going to be used
1022 * or not, nor when it might be activated. Play it safe.
1023 */
1024 if (power_pm_get_type() == POWER_PM_TYPE_APM) {
1025 if (bootverbose)
1026 printf("TSC initialization skipped: APM enabled.\n");
1027 return;
1028 }
1029
1030 if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
1031 tsc_timecounter.tc_frequency = tsc_freq;
1032 tc_init(&tsc_timecounter);
1033 }
1034
1035 #endif /* !defined(SMP) */
1036 }
1037
1038 #ifdef PC98
1039 static void
1040 rtc_serialcombit(int i)
1041 {
1042 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1043 DELAY(1);
1044 outb(IO_RTC, ((i&0x01)<<5)|0x17);
1045 DELAY(1);
1046 outb(IO_RTC, ((i&0x01)<<5)|0x07);
1047 DELAY(1);
1048 }
1049
1050 static void
1051 rtc_serialcom(int i)
1052 {
1053 rtc_serialcombit(i&0x01);
1054 rtc_serialcombit((i&0x02)>>1);
1055 rtc_serialcombit((i&0x04)>>2);
1056 rtc_serialcombit((i&0x08)>>3);
1057 outb(IO_RTC, 0x07);
1058 DELAY(1);
1059 outb(IO_RTC, 0x0f);
1060 DELAY(1);
1061 outb(IO_RTC, 0x07);
1062 DELAY(1);
1063 }
1064
1065 static void
1066 rtc_outb(int val)
1067 {
1068 int s;
1069 int sa = 0;
1070
1071 for (s=0;s<8;s++) {
1072 sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
1073 outb(IO_RTC, sa); /* set DI & CLK 0 */
1074 DELAY(1);
1075 outb(IO_RTC, sa | 0x10); /* CLK 1 */
1076 DELAY(1);
1077 }
1078 outb(IO_RTC, sa & 0xef); /* CLK 0 */
1079 }
1080
1081 static int
1082 rtc_inb(void)
1083 {
1084 int s;
1085 int sa = 0;
1086
1087 for (s=0;s<8;s++) {
1088 sa |= ((inb(0x33) & 0x01) << s);
1089 outb(IO_RTC, 0x17); /* CLK 1 */
1090 DELAY(1);
1091 outb(IO_RTC, 0x07); /* CLK 0 */
1092 DELAY(2);
1093 }
1094 return sa;
1095 }
1096 #endif /* PC-98 */
1097
1098 /*
1099 * Initialize the time of day register, based on the time base which is, e.g.
1100 * from a filesystem.
1101 */
1102 void
1103 inittodr(time_t base)
1104 {
1105 unsigned long sec, days;
1106 int year, month;
1107 int y, m, s;
1108 struct timespec ts;
1109 #ifdef PC98
1110 int second, min, hour;
1111 #endif
1112
1113 if (base) {
1114 s = splclock();
1115 ts.tv_sec = base;
1116 ts.tv_nsec = 0;
1117 tc_setclock(&ts);
1118 splx(s);
1119 }
1120
1121 #ifdef PC98
1122 rtc_serialcom(0x03); /* Time Read */
1123 rtc_serialcom(0x01); /* Register shift command. */
1124 DELAY(20);
1125
1126 second = bcd2bin(rtc_inb() & 0xff); /* sec */
1127 min = bcd2bin(rtc_inb() & 0xff); /* min */
1128 hour = bcd2bin(rtc_inb() & 0xff); /* hour */
1129 days = bcd2bin(rtc_inb() & 0xff) - 1; /* date */
1130
1131 month = (rtc_inb() >> 4) & 0x0f; /* month */
1132 for (m = 1; m < month; m++)
1133 days += daysinmonth[m-1];
1134 year = bcd2bin(rtc_inb() & 0xff) + 1900; /* year */
1135 /* 2000 year problem */
1136 if (year < 1995)
1137 year += 100;
1138 if (year < 1970)
1139 goto wrong_time;
1140 for (y = 1970; y < year; y++)
1141 days += DAYSPERYEAR + LEAPYEAR(y);
1142 if ((month > 2) && LEAPYEAR(year))
1143 days ++;
1144 sec = ((( days * 24 +
1145 hour) * 60 +
1146 min) * 60 +
1147 second);
1148 /* sec now contains the number of seconds, since Jan 1 1970,
1149 in the local time zone */
1150
1151 s = splhigh();
1152 #else /* IBM-PC */
1153 /* Look if we have a RTC present and the time is valid */
1154 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
1155 goto wrong_time;
1156
1157 /* wait for time update to complete */
1158 /* If RTCSA_TUP is zero, we have at least 244us before next update */
1159 s = splhigh();
1160 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
1161 splx(s);
1162 s = splhigh();
1163 }
1164
1165 days = 0;
1166 #ifdef USE_RTC_CENTURY
1167 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
1168 #else
1169 year = readrtc(RTC_YEAR) + 1900;
1170 if (year < 1970)
1171 year += 100;
1172 #endif
1173 if (year < 1970) {
1174 splx(s);
1175 goto wrong_time;
1176 }
1177 month = readrtc(RTC_MONTH);
1178 for (m = 1; m < month; m++)
1179 days += daysinmonth[m-1];
1180 if ((month > 2) && LEAPYEAR(year))
1181 days ++;
1182 days += readrtc(RTC_DAY) - 1;
1183 for (y = 1970; y < year; y++)
1184 days += DAYSPERYEAR + LEAPYEAR(y);
1185 sec = ((( days * 24 +
1186 readrtc(RTC_HRS)) * 60 +
1187 readrtc(RTC_MIN)) * 60 +
1188 readrtc(RTC_SEC));
1189 /* sec now contains the number of seconds, since Jan 1 1970,
1190 in the local time zone */
1191 #endif
1192
1193 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1194
1195 y = time_second - sec;
1196 if (y <= -2 || y >= 2) {
1197 /* badly off, adjust it */
1198 ts.tv_sec = sec;
1199 ts.tv_nsec = 0;
1200 tc_setclock(&ts);
1201 }
1202 splx(s);
1203 return;
1204
1205 wrong_time:
1206 printf("Invalid time in real time clock.\n");
1207 printf("Check and reset the date immediately!\n");
1208 }
1209
1210 /*
1211 * Write system time back to RTC
1212 */
1213 void
1214 resettodr()
1215 {
1216 unsigned long tm;
1217 int y, m, s;
1218 #ifdef PC98
1219 int wd;
1220 #endif
1221
1222 if (disable_rtc_set)
1223 return;
1224
1225 s = splclock();
1226 tm = time_second;
1227 splx(s);
1228
1229 #ifdef PC98
1230 rtc_serialcom(0x01); /* Register shift command. */
1231
1232 /* Calculate local time to put in RTC */
1233
1234 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1235
1236 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1237 rtc_outb(bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1238 rtc_outb(bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1239
1240 /* We have now the days since 01-01-1970 in tm */
1241 wd = (tm+4)%7;
1242 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1243 tm >= m;
1244 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1245 tm -= m;
1246
1247 /* Now we have the years in y and the day-of-the-year in tm */
1248 for (m = 0; ; m++) {
1249 int ml;
1250
1251 ml = daysinmonth[m];
1252 if (m == 1 && LEAPYEAR(y))
1253 ml++;
1254 if (tm < ml)
1255 break;
1256 tm -= ml;
1257 }
1258
1259 m++;
1260 rtc_outb(bin2bcd(tm+1)); /* Write back Day */
1261 rtc_outb((m << 4) | wd); /* Write back Month & Weekday */
1262 rtc_outb(bin2bcd(y%100)); /* Write back Year */
1263
1264 rtc_serialcom(0x02); /* Time set & Counter hold command. */
1265 rtc_serialcom(0x00); /* Register hold command. */
1266 #else
1267 /* Disable RTC updates and interrupts. */
1268 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1269
1270 /* Calculate local time to put in RTC */
1271
1272 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1273
1274 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1275 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1276 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1277
1278 /* We have now the days since 01-01-1970 in tm */
1279 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
1280 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1281 tm >= m;
1282 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1283 tm -= m;
1284
1285 /* Now we have the years in y and the day-of-the-year in tm */
1286 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
1287 #ifdef USE_RTC_CENTURY
1288 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1289 #endif
1290 for (m = 0; ; m++) {
1291 int ml;
1292
1293 ml = daysinmonth[m];
1294 if (m == 1 && LEAPYEAR(y))
1295 ml++;
1296 if (tm < ml)
1297 break;
1298 tm -= ml;
1299 }
1300
1301 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1302 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1303
1304 /* Reenable RTC updates and interrupts. */
1305 writertc(RTC_STATUSB, rtc_statusb);
1306 #endif /* PC98 */
1307 }
1308
1309
1310 /*
1311 * Start both clocks running.
1312 */
1313 void
1314 cpu_initclocks()
1315 {
1316 #ifndef PC98
1317 int diag;
1318 #endif
1319 #ifdef APIC_IO
1320 int apic_8254_trial;
1321 void *clkdesc;
1322 #endif /* APIC_IO */
1323 register_t crit;
1324
1325 #ifndef PC98
1326 if (statclock_disable) {
1327 /*
1328 * The stat interrupt mask is different without the
1329 * statistics clock. Also, don't set the interrupt
1330 * flag which would normally cause the RTC to generate
1331 * interrupts.
1332 */
1333 rtc_statusb = RTCSB_24HR;
1334 } else {
1335 /* Setting stathz to nonzero early helps avoid races. */
1336 stathz = RTC_NOPROFRATE;
1337 profhz = RTC_PROFRATE;
1338 }
1339 #endif
1340
1341 /* Finish initializing 8253 timer 0. */
1342 #ifdef APIC_IO
1343
1344 apic_8254_intr = isa_apic_irq(0);
1345 apic_8254_trial = 0;
1346 if (apic_8254_intr >= 0 ) {
1347 if (apic_int_type(0, 0) == 3)
1348 apic_8254_trial = 1;
1349 } else {
1350 /* look for ExtInt on pin 0 */
1351 if (apic_int_type(0, 0) == 3) {
1352 apic_8254_intr = apic_irq(0, 0);
1353 setup_8254_mixed_mode();
1354 } else
1355 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1356 }
1357
1358 inthand_add("clk", apic_8254_intr, (driver_intr_t *)clkintr, NULL,
1359 INTR_TYPE_CLK | INTR_FAST, &clkdesc);
1360 crit = intr_disable();
1361 mtx_lock_spin(&icu_lock);
1362 INTREN(1 << apic_8254_intr);
1363 mtx_unlock_spin(&icu_lock);
1364 intr_restore(crit);
1365
1366 #else /* APIC_IO */
1367
1368 /*
1369 * XXX Check the priority of this interrupt handler. I
1370 * couldn't find anything suitable in the BSD/OS code (grog,
1371 * 19 July 2000).
1372 */
1373 inthand_add("clk", 0, (driver_intr_t *)clkintr, NULL,
1374 INTR_TYPE_CLK | INTR_FAST, NULL);
1375 crit = intr_disable();
1376 mtx_lock_spin(&icu_lock);
1377 INTREN(IRQ0);
1378 mtx_unlock_spin(&icu_lock);
1379 intr_restore(crit);
1380
1381 #endif /* APIC_IO */
1382
1383 #ifndef PC98
1384 /* Initialize RTC. */
1385 writertc(RTC_STATUSA, rtc_statusa);
1386 writertc(RTC_STATUSB, RTCSB_24HR);
1387
1388 /* Don't bother enabling the statistics clock. */
1389 if (statclock_disable)
1390 return;
1391 diag = rtcin(RTC_DIAG);
1392 if (diag != 0)
1393 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1394 #endif /* !PC98 */
1395
1396 #ifndef PC98
1397 #ifdef APIC_IO
1398 if (isa_apic_irq(8) != 8)
1399 panic("APIC RTC != 8");
1400 #endif /* APIC_IO */
1401
1402 inthand_add("rtc", 8, (driver_intr_t *)rtcintr, NULL,
1403 INTR_TYPE_CLK | INTR_FAST, NULL);
1404
1405 crit = intr_disable();
1406 mtx_lock_spin(&icu_lock);
1407 #ifdef APIC_IO
1408 INTREN(APIC_IRQ8);
1409 #else
1410 INTREN(IRQ8);
1411 #endif /* APIC_IO */
1412 mtx_unlock_spin(&icu_lock);
1413 intr_restore(crit);
1414
1415 writertc(RTC_STATUSB, rtc_statusb);
1416 #endif /* PC98 */
1417
1418 #ifdef APIC_IO
1419 if (apic_8254_trial) {
1420
1421 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1422 while (read_intr_count(8) < 6)
1423 ; /* nothing */
1424 if (read_intr_count(apic_8254_intr) < 3) {
1425 /*
1426 * The MP table is broken.
1427 * The 8254 was not connected to the specified pin
1428 * on the IO APIC.
1429 * Workaround: Limited variant of mixed mode.
1430 */
1431
1432 crit = intr_disable();
1433 mtx_lock_spin(&icu_lock);
1434 INTRDIS(1 << apic_8254_intr);
1435 mtx_unlock_spin(&icu_lock);
1436 intr_restore(crit);
1437 inthand_remove(clkdesc);
1438 printf("APIC_IO: Broken MP table detected: "
1439 "8254 is not connected to "
1440 "IOAPIC #%d intpin %d\n",
1441 int_to_apicintpin[apic_8254_intr].ioapic,
1442 int_to_apicintpin[apic_8254_intr].int_pin);
1443 /*
1444 * Revoke current ISA IRQ 0 assignment and
1445 * configure a fallback interrupt routing from
1446 * the 8254 Timer via the 8259 PIC to the
1447 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1448 * We reuse the low level interrupt handler number.
1449 */
1450 if (apic_irq(0, 0) < 0) {
1451 revoke_apic_irq(apic_8254_intr);
1452 assign_apic_irq(0, 0, apic_8254_intr);
1453 }
1454 apic_8254_intr = apic_irq(0, 0);
1455 setup_8254_mixed_mode();
1456 inthand_add("clk", apic_8254_intr,
1457 (driver_intr_t *)clkintr, NULL,
1458 INTR_TYPE_CLK | INTR_FAST, NULL);
1459 crit = intr_disable();
1460 mtx_lock_spin(&icu_lock);
1461 INTREN(1 << apic_8254_intr);
1462 mtx_unlock_spin(&icu_lock);
1463 intr_restore(crit);
1464 }
1465
1466 }
1467 if (apic_int_type(0, 0) != 3 ||
1468 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1469 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1470 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1471 int_to_apicintpin[apic_8254_intr].ioapic,
1472 int_to_apicintpin[apic_8254_intr].int_pin);
1473 else
1474 printf("APIC_IO: "
1475 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1476 #endif
1477
1478 }
1479
1480 #ifdef APIC_IO
1481 static u_long
1482 read_intr_count(int vec)
1483 {
1484 u_long *up;
1485 up = intr_countp[vec];
1486 if (up)
1487 return *up;
1488 return 0UL;
1489 }
1490
1491 static void
1492 setup_8254_mixed_mode()
1493 {
1494 /*
1495 * Allow 8254 timer to INTerrupt 8259:
1496 * re-initialize master 8259:
1497 * reset; prog 4 bytes, single ICU, edge triggered
1498 */
1499 outb(IO_ICU1, 0x13);
1500 #ifdef PC98
1501 outb(IO_ICU1 + 2, NRSVIDT); /* start vector (unused) */
1502 outb(IO_ICU1 + 2, 0x00); /* ignore slave */
1503 outb(IO_ICU1 + 2, 0x03); /* auto EOI, 8086 */
1504 outb(IO_ICU1 + 2, 0xfe); /* unmask INT0 */
1505 #else
1506 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1507 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1508 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1509 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1510 #endif
1511
1512 /* program IO APIC for type 3 INT on INT0 */
1513 if (ext_int_setup(0, 0) < 0)
1514 panic("8254 redirect via APIC pin0 impossible!");
1515 }
1516 #endif
1517
1518 void
1519 setstatclockrate(int newhz)
1520 {
1521 #ifndef PC98
1522 if (newhz == RTC_PROFRATE)
1523 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1524 else
1525 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1526 writertc(RTC_STATUSA, rtc_statusa);
1527 #endif
1528 }
1529
1530 static int
1531 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1532 {
1533 int error;
1534 u_int freq;
1535
1536 /*
1537 * Use `i8254' instead of `timer' in external names because `timer'
1538 * is is too generic. Should use it everywhere.
1539 */
1540 freq = timer_freq;
1541 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1542 if (error == 0 && req->newptr != NULL) {
1543 if (timer0_state != RELEASED)
1544 return (EBUSY); /* too much trouble to handle */
1545 set_timer_freq(freq, hz);
1546 i8254_timecounter.tc_frequency = freq;
1547 }
1548 return (error);
1549 }
1550
1551 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1552 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
1553
1554 static int
1555 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1556 {
1557 int error;
1558 u_int freq;
1559
1560 if (tsc_timecounter.tc_frequency == 0)
1561 return (EOPNOTSUPP);
1562 freq = tsc_freq;
1563 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1564 if (error == 0 && req->newptr != NULL) {
1565 tsc_freq = freq;
1566 tsc_timecounter.tc_frequency = tsc_freq;
1567 }
1568 return (error);
1569 }
1570
1571 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1572 0, sizeof(u_int), sysctl_machdep_tsc_freq, "IU", "");
1573
1574 static unsigned
1575 i8254_get_timecount(struct timecounter *tc)
1576 {
1577 u_int count;
1578 u_int high, low;
1579 u_int eflags;
1580
1581 eflags = read_eflags();
1582 mtx_lock_spin(&clock_lock);
1583
1584 /* Select timer0 and latch counter value. */
1585 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1586
1587 low = inb(TIMER_CNTR0);
1588 high = inb(TIMER_CNTR0);
1589 count = timer0_max_count - ((high << 8) | low);
1590 if (count < i8254_lastcount ||
1591 (!i8254_ticked && (clkintr_pending ||
1592 ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
1593 #ifdef APIC_IO
1594 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1595 /* XXX this assumes that apic_8254_intr is < 24. */
1596 (lapic_irr1 & (1 << apic_8254_intr))))
1597 #else
1598 (inb(IO_ICU1) & 1)))
1599 #endif
1600 )) {
1601 i8254_ticked = 1;
1602 i8254_offset += timer0_max_count;
1603 }
1604 i8254_lastcount = count;
1605 count += i8254_offset;
1606 mtx_unlock_spin(&clock_lock);
1607 return (count);
1608 }
1609
1610 static unsigned
1611 tsc_get_timecount(struct timecounter *tc)
1612 {
1613 return (rdtsc());
1614 }
1615
1616 #ifdef DEV_ISA
1617 /*
1618 * Attach to the ISA PnP descriptors for the timer and realtime clock.
1619 */
1620 static struct isa_pnp_id attimer_ids[] = {
1621 { 0x0001d041 /* PNP0100 */, "AT timer" },
1622 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
1623 { 0 }
1624 };
1625
1626 static int
1627 attimer_probe(device_t dev)
1628 {
1629 int result;
1630
1631 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
1632 device_quiet(dev);
1633 return(result);
1634 }
1635
1636 static int
1637 attimer_attach(device_t dev)
1638 {
1639 return(0);
1640 }
1641
1642 static device_method_t attimer_methods[] = {
1643 /* Device interface */
1644 DEVMETHOD(device_probe, attimer_probe),
1645 DEVMETHOD(device_attach, attimer_attach),
1646 DEVMETHOD(device_detach, bus_generic_detach),
1647 DEVMETHOD(device_shutdown, bus_generic_shutdown),
1648 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
1649 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
1650 { 0, 0 }
1651 };
1652
1653 static driver_t attimer_driver = {
1654 "attimer",
1655 attimer_methods,
1656 1, /* no softc */
1657 };
1658
1659 static devclass_t attimer_devclass;
1660
1661 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1662 #ifndef PC98
1663 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
1664 #endif
1665 #endif /* DEV_ISA */
Cache object: 3929de2ebe3f1f0fe5bca351bc3171c7
|