FreeBSD/Linux Kernel Cross Reference
sys/i386/isa/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.1/sys/i386/isa/clock.c 114216 2003-04-29 13:36:06Z kan $
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 #include "opt_clock.h"
52 #include "opt_isa.h"
53 #include "opt_mca.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/bus.h>
58 #include <sys/lock.h>
59 #include <sys/mutex.h>
60 #include <sys/proc.h>
61 #include <sys/time.h>
62 #include <sys/timetc.h>
63 #include <sys/kernel.h>
64 #include <sys/limits.h>
65 #include <sys/sysctl.h>
66 #include <sys/cons.h>
67 #include <sys/power.h>
68
69 #include <machine/clock.h>
70 #include <machine/cputypes.h>
71 #include <machine/frame.h>
72 #include <machine/md_var.h>
73 #include <machine/psl.h>
74 #ifdef APIC_IO
75 #include <machine/segments.h>
76 #endif
77 #if defined(SMP) || defined(APIC_IO)
78 #include <machine/smp.h>
79 #endif /* SMP || APIC_IO */
80 #include <machine/specialreg.h>
81
82 #include <i386/isa/icu.h>
83 #include <i386/isa/isa.h>
84 #include <isa/rtc.h>
85 #ifdef DEV_ISA
86 #include <isa/isavar.h>
87 #endif
88 #include <i386/isa/timerreg.h>
89
90 #include <i386/isa/intr_machdep.h>
91
92 #ifdef DEV_MCA
93 #include <i386/bios/mca_machdep.h>
94 #endif
95
96 #ifdef APIC_IO
97 #include <i386/isa/intr_machdep.h>
98 /* The interrupt triggered by the 8254 (timer) chip */
99 int apic_8254_intr;
100 static u_long read_intr_count(int vec);
101 static void setup_8254_mixed_mode(void);
102 #endif
103
104 /*
105 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
106 * can use a simple formula for leap years.
107 */
108 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
109 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
110
111 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
112
113 /*
114 * Time in timer cycles that it takes for microtime() to disable interrupts
115 * and latch the count. microtime() currently uses "cli; outb ..." so it
116 * normally takes less than 2 timer cycles. Add a few for cache misses.
117 * Add a few more to allow for latency in bogus calls to microtime() with
118 * interrupts already disabled.
119 */
120 #define TIMER0_LATCH_COUNT 20
121
122 /*
123 * Maximum frequency that we are willing to allow for timer0. Must be
124 * low enough to guarantee that the timer interrupt handler returns
125 * before the next timer interrupt.
126 */
127 #define TIMER0_MAX_FREQ 20000
128
129 int adjkerntz; /* local offset from GMT in seconds */
130 int clkintr_pending;
131 int disable_rtc_set; /* disable resettodr() if != 0 */
132 int pscnt = 1;
133 int psdiv = 1;
134 int statclock_disable;
135 #ifndef TIMER_FREQ
136 #define TIMER_FREQ 1193182
137 #endif
138 u_int timer_freq = TIMER_FREQ;
139 int timer0_max_count;
140 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
141 struct mtx clock_lock;
142
143 static int beeping = 0;
144 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
145 static u_int hardclock_max_count;
146 static u_int32_t i8254_lastcount;
147 static u_int32_t i8254_offset;
148 static int i8254_ticked;
149 /*
150 * XXX new_function and timer_func should not handle clockframes, but
151 * timer_func currently needs to hold hardclock to handle the
152 * timer0_state == 0 case. We should use inthand_add()/inthand_remove()
153 * to switch between clkintr() and a slightly different timerintr().
154 */
155 static void (*new_function)(struct clockframe *frame);
156 static u_int new_rate;
157 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
158 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
159 static u_int timer0_prescaler_count;
160
161 /* Values for timerX_state: */
162 #define RELEASED 0
163 #define RELEASE_PENDING 1
164 #define ACQUIRED 2
165 #define ACQUIRE_PENDING 3
166
167 static u_char timer0_state;
168 static u_char timer2_state;
169 static void (*timer_func)(struct clockframe *frame) = hardclock;
170
171 static unsigned i8254_get_timecount(struct timecounter *tc);
172 static void set_timer_freq(u_int freq, int intr_freq);
173
174 static struct timecounter i8254_timecounter = {
175 i8254_get_timecount, /* get_timecount */
176 0, /* no poll_pps */
177 ~0u, /* counter_mask */
178 0, /* frequency */
179 "i8254" /* name */
180 };
181
182 static void
183 clkintr(struct clockframe frame)
184 {
185
186 if (timecounter->tc_get_timecount == i8254_get_timecount) {
187 mtx_lock_spin(&clock_lock);
188 if (i8254_ticked)
189 i8254_ticked = 0;
190 else {
191 i8254_offset += timer0_max_count;
192 i8254_lastcount = 0;
193 }
194 clkintr_pending = 0;
195 mtx_unlock_spin(&clock_lock);
196 }
197 timer_func(&frame);
198 #ifdef SMP
199 if (timer_func == hardclock)
200 forward_hardclock();
201 #endif
202 switch (timer0_state) {
203
204 case RELEASED:
205 break;
206
207 case ACQUIRED:
208 if ((timer0_prescaler_count += timer0_max_count)
209 >= hardclock_max_count) {
210 timer0_prescaler_count -= hardclock_max_count;
211 hardclock(&frame);
212 #ifdef SMP
213 forward_hardclock();
214 #endif
215 }
216 break;
217
218 case ACQUIRE_PENDING:
219 mtx_lock_spin(&clock_lock);
220 i8254_offset = i8254_get_timecount(NULL);
221 i8254_lastcount = 0;
222 timer0_max_count = TIMER_DIV(new_rate);
223 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
224 outb(TIMER_CNTR0, timer0_max_count & 0xff);
225 outb(TIMER_CNTR0, timer0_max_count >> 8);
226 mtx_unlock_spin(&clock_lock);
227 timer_func = new_function;
228 timer0_state = ACQUIRED;
229 break;
230
231 case RELEASE_PENDING:
232 if ((timer0_prescaler_count += timer0_max_count)
233 >= hardclock_max_count) {
234 mtx_lock_spin(&clock_lock);
235 i8254_offset = i8254_get_timecount(NULL);
236 i8254_lastcount = 0;
237 timer0_max_count = hardclock_max_count;
238 outb(TIMER_MODE,
239 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
240 outb(TIMER_CNTR0, timer0_max_count & 0xff);
241 outb(TIMER_CNTR0, timer0_max_count >> 8);
242 mtx_unlock_spin(&clock_lock);
243 timer0_prescaler_count = 0;
244 timer_func = hardclock;
245 timer0_state = RELEASED;
246 hardclock(&frame);
247 #ifdef SMP
248 forward_hardclock();
249 #endif
250 }
251 break;
252 }
253 #ifdef DEV_MCA
254 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
255 if (MCA_system)
256 outb(0x61, inb(0x61) | 0x80);
257 #endif
258 }
259
260 /*
261 * The acquire and release functions must be called at ipl >= splclock().
262 */
263 int
264 acquire_timer0(int rate, void (*function)(struct clockframe *frame))
265 {
266 static int old_rate;
267
268 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
269 return (-1);
270 switch (timer0_state) {
271
272 case RELEASED:
273 timer0_state = ACQUIRE_PENDING;
274 break;
275
276 case RELEASE_PENDING:
277 if (rate != old_rate)
278 return (-1);
279 /*
280 * The timer has been released recently, but is being
281 * re-acquired before the release completed. In this
282 * case, we simply reclaim it as if it had not been
283 * released at all.
284 */
285 timer0_state = ACQUIRED;
286 break;
287
288 default:
289 return (-1); /* busy */
290 }
291 new_function = function;
292 old_rate = new_rate = rate;
293 return (0);
294 }
295
296 int
297 acquire_timer2(int mode)
298 {
299
300 if (timer2_state != RELEASED)
301 return (-1);
302 timer2_state = ACQUIRED;
303
304 /*
305 * This access to the timer registers is as atomic as possible
306 * because it is a single instruction. We could do better if we
307 * knew the rate. Use of splclock() limits glitches to 10-100us,
308 * and this is probably good enough for timer2, so we aren't as
309 * careful with it as with timer0.
310 */
311 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
312
313 return (0);
314 }
315
316 int
317 release_timer0()
318 {
319 switch (timer0_state) {
320
321 case ACQUIRED:
322 timer0_state = RELEASE_PENDING;
323 break;
324
325 case ACQUIRE_PENDING:
326 /* Nothing happened yet, release quickly. */
327 timer0_state = RELEASED;
328 break;
329
330 default:
331 return (-1);
332 }
333 return (0);
334 }
335
336 int
337 release_timer2()
338 {
339
340 if (timer2_state != ACQUIRED)
341 return (-1);
342 timer2_state = RELEASED;
343 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
344 return (0);
345 }
346
347 /*
348 * This routine receives statistical clock interrupts from the RTC.
349 * As explained above, these occur at 128 interrupts per second.
350 * When profiling, we receive interrupts at a rate of 1024 Hz.
351 *
352 * This does not actually add as much overhead as it sounds, because
353 * when the statistical clock is active, the hardclock driver no longer
354 * needs to keep (inaccurate) statistics on its own. This decouples
355 * statistics gathering from scheduling interrupts.
356 *
357 * The RTC chip requires that we read status register C (RTC_INTR)
358 * to acknowledge an interrupt, before it will generate the next one.
359 * Under high interrupt load, rtcintr() can be indefinitely delayed and
360 * the clock can tick immediately after the read from RTC_INTR. In this
361 * case, the mc146818A interrupt signal will not drop for long enough
362 * to register with the 8259 PIC. If an interrupt is missed, the stat
363 * clock will halt, considerably degrading system performance. This is
364 * why we use 'while' rather than a more straightforward 'if' below.
365 * Stat clock ticks can still be lost, causing minor loss of accuracy
366 * in the statistics, but the stat clock will no longer stop.
367 */
368 static void
369 rtcintr(struct clockframe frame)
370 {
371 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
372 if (profprocs != 0) {
373 if (--pscnt == 0)
374 pscnt = psdiv;
375 profclock(&frame);
376 }
377 if (pscnt == psdiv)
378 statclock(&frame);
379 #ifdef SMP
380 forward_statclock();
381 #endif
382 }
383 }
384
385 #include "opt_ddb.h"
386 #ifdef DDB
387 #include <ddb/ddb.h>
388
389 DB_SHOW_COMMAND(rtc, rtc)
390 {
391 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
392 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
393 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
394 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
395 }
396 #endif /* DDB */
397
398 static int
399 getit(void)
400 {
401 int high, low;
402
403 mtx_lock_spin(&clock_lock);
404
405 /* Select timer0 and latch counter value. */
406 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
407
408 low = inb(TIMER_CNTR0);
409 high = inb(TIMER_CNTR0);
410
411 mtx_unlock_spin(&clock_lock);
412 return ((high << 8) | low);
413 }
414
415 /*
416 * Wait "n" microseconds.
417 * Relies on timer 1 counting down from (timer_freq / hz)
418 * Note: timer had better have been programmed before this is first used!
419 */
420 void
421 DELAY(int n)
422 {
423 int delta, prev_tick, tick, ticks_left;
424
425 #ifdef DELAYDEBUG
426 int getit_calls = 1;
427 int n1;
428 static int state = 0;
429
430 if (state == 0) {
431 state = 1;
432 for (n1 = 1; n1 <= 10000000; n1 *= 10)
433 DELAY(n1);
434 state = 2;
435 }
436 if (state == 1)
437 printf("DELAY(%d)...", n);
438 #endif
439 /*
440 * Guard against the timer being uninitialized if we are called
441 * early for console i/o.
442 */
443 if (timer0_max_count == 0)
444 set_timer_freq(timer_freq, hz);
445
446 /*
447 * Read the counter first, so that the rest of the setup overhead is
448 * counted. Guess the initial overhead is 20 usec (on most systems it
449 * takes about 1.5 usec for each of the i/o's in getit(). The loop
450 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
451 * multiplications and divisions to scale the count take a while).
452 */
453 prev_tick = getit();
454 n -= 0; /* XXX actually guess no initial overhead */
455 /*
456 * Calculate (n * (timer_freq / 1e6)) without using floating point
457 * and without any avoidable overflows.
458 */
459 if (n <= 0)
460 ticks_left = 0;
461 else if (n < 256)
462 /*
463 * Use fixed point to avoid a slow division by 1000000.
464 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
465 * 2^15 is the first power of 2 that gives exact results
466 * for n between 0 and 256.
467 */
468 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
469 else
470 /*
471 * Don't bother using fixed point, although gcc-2.7.2
472 * generates particularly poor code for the long long
473 * division, since even the slow way will complete long
474 * before the delay is up (unless we're interrupted).
475 */
476 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
477 / 1000000;
478
479 while (ticks_left > 0) {
480 tick = getit();
481 #ifdef DELAYDEBUG
482 ++getit_calls;
483 #endif
484 delta = prev_tick - tick;
485 prev_tick = tick;
486 if (delta < 0) {
487 delta += timer0_max_count;
488 /*
489 * Guard against timer0_max_count being wrong.
490 * This shouldn't happen in normal operation,
491 * but it may happen if set_timer_freq() is
492 * traced.
493 */
494 if (delta < 0)
495 delta = 0;
496 }
497 ticks_left -= delta;
498 }
499 #ifdef DELAYDEBUG
500 if (state == 1)
501 printf(" %d calls to getit() at %d usec each\n",
502 getit_calls, (n + 5) / getit_calls);
503 #endif
504 }
505
506 static void
507 sysbeepstop(void *chan)
508 {
509 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
510 release_timer2();
511 beeping = 0;
512 }
513
514 int
515 sysbeep(int pitch, int period)
516 {
517 int x = splclock();
518
519 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
520 if (!beeping) {
521 /* Something else owns it. */
522 splx(x);
523 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
524 }
525 mtx_lock_spin(&clock_lock);
526 outb(TIMER_CNTR2, pitch);
527 outb(TIMER_CNTR2, (pitch>>8));
528 mtx_unlock_spin(&clock_lock);
529 if (!beeping) {
530 /* enable counter2 output to speaker */
531 outb(IO_PPI, inb(IO_PPI) | 3);
532 beeping = period;
533 timeout(sysbeepstop, (void *)NULL, period);
534 }
535 splx(x);
536 return (0);
537 }
538
539 /*
540 * RTC support routines
541 */
542
543 int
544 rtcin(reg)
545 int reg;
546 {
547 int s;
548 u_char val;
549
550 s = splhigh();
551 outb(IO_RTC, reg);
552 inb(0x84);
553 val = inb(IO_RTC + 1);
554 inb(0x84);
555 splx(s);
556 return (val);
557 }
558
559 static __inline void
560 writertc(u_char reg, u_char val)
561 {
562 int s;
563
564 s = splhigh();
565 inb(0x84);
566 outb(IO_RTC, reg);
567 inb(0x84);
568 outb(IO_RTC + 1, val);
569 inb(0x84); /* XXX work around wrong order in rtcin() */
570 splx(s);
571 }
572
573 static __inline int
574 readrtc(int port)
575 {
576 return(bcd2bin(rtcin(port)));
577 }
578
579 static u_int
580 calibrate_clocks(void)
581 {
582 u_int count, prev_count, tot_count;
583 int sec, start_sec, timeout;
584
585 if (bootverbose)
586 printf("Calibrating clock(s) ... ");
587 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
588 goto fail;
589 timeout = 100000000;
590
591 /* Read the mc146818A seconds counter. */
592 for (;;) {
593 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
594 sec = rtcin(RTC_SEC);
595 break;
596 }
597 if (--timeout == 0)
598 goto fail;
599 }
600
601 /* Wait for the mC146818A seconds counter to change. */
602 start_sec = sec;
603 for (;;) {
604 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
605 sec = rtcin(RTC_SEC);
606 if (sec != start_sec)
607 break;
608 }
609 if (--timeout == 0)
610 goto fail;
611 }
612
613 /* Start keeping track of the i8254 counter. */
614 prev_count = getit();
615 if (prev_count == 0 || prev_count > timer0_max_count)
616 goto fail;
617 tot_count = 0;
618
619 /*
620 * Wait for the mc146818A seconds counter to change. Read the i8254
621 * counter for each iteration since this is convenient and only
622 * costs a few usec of inaccuracy. The timing of the final reads
623 * of the counters almost matches the timing of the initial reads,
624 * so the main cause of inaccuracy is the varying latency from
625 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
626 * rtcin(RTC_SEC) that returns a changed seconds count. The
627 * maximum inaccuracy from this cause is < 10 usec on 486's.
628 */
629 start_sec = sec;
630 for (;;) {
631 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
632 sec = rtcin(RTC_SEC);
633 count = getit();
634 if (count == 0 || count > timer0_max_count)
635 goto fail;
636 if (count > prev_count)
637 tot_count += prev_count - (count - timer0_max_count);
638 else
639 tot_count += prev_count - count;
640 prev_count = count;
641 if (sec != start_sec)
642 break;
643 if (--timeout == 0)
644 goto fail;
645 }
646
647 if (bootverbose) {
648 printf("i8254 clock: %u Hz\n", tot_count);
649 }
650 return (tot_count);
651
652 fail:
653 if (bootverbose)
654 printf("failed, using default i8254 clock of %u Hz\n",
655 timer_freq);
656 return (timer_freq);
657 }
658
659 static void
660 set_timer_freq(u_int freq, int intr_freq)
661 {
662 int new_timer0_max_count;
663
664 mtx_lock_spin(&clock_lock);
665 timer_freq = freq;
666 new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
667 if (new_timer0_max_count != timer0_max_count) {
668 timer0_max_count = new_timer0_max_count;
669 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
670 outb(TIMER_CNTR0, timer0_max_count & 0xff);
671 outb(TIMER_CNTR0, timer0_max_count >> 8);
672 }
673 mtx_unlock_spin(&clock_lock);
674 }
675
676 static void
677 i8254_restore(void)
678 {
679
680 mtx_lock_spin(&clock_lock);
681 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
682 outb(TIMER_CNTR0, timer0_max_count & 0xff);
683 outb(TIMER_CNTR0, timer0_max_count >> 8);
684 mtx_unlock_spin(&clock_lock);
685 }
686
687 static void
688 rtc_restore(void)
689 {
690
691 /* Restore all of the RTC's "status" (actually, control) registers. */
692 /* XXX locking is needed for RTC access. */
693 writertc(RTC_STATUSB, RTCSB_24HR);
694 writertc(RTC_STATUSA, rtc_statusa);
695 writertc(RTC_STATUSB, rtc_statusb);
696 }
697
698 /*
699 * Restore all the timers non-atomically (XXX: should be atomically).
700 *
701 * This function is called from pmtimer_resume() to restore all the timers.
702 * This should not be necessary, but there are broken laptops that do not
703 * restore all the timers on resume.
704 */
705 void
706 timer_restore(void)
707 {
708
709 i8254_restore(); /* restore timer_freq and hz */
710 rtc_restore(); /* reenable RTC interrupts */
711 }
712
713 /*
714 * Initialize 8254 timer 0 early so that it can be used in DELAY().
715 * XXX initialization of other timers is unintentionally left blank.
716 */
717 void
718 startrtclock()
719 {
720 u_int delta, freq;
721
722 writertc(RTC_STATUSA, rtc_statusa);
723 writertc(RTC_STATUSB, RTCSB_24HR);
724
725 set_timer_freq(timer_freq, hz);
726 freq = calibrate_clocks();
727 #ifdef CLK_CALIBRATION_LOOP
728 if (bootverbose) {
729 printf(
730 "Press a key on the console to abort clock calibration\n");
731 while (cncheckc() == -1)
732 calibrate_clocks();
733 }
734 #endif
735
736 /*
737 * Use the calibrated i8254 frequency if it seems reasonable.
738 * Otherwise use the default, and don't use the calibrated i586
739 * frequency.
740 */
741 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
742 if (delta < timer_freq / 100) {
743 #ifndef CLK_USE_I8254_CALIBRATION
744 if (bootverbose)
745 printf(
746 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
747 freq = timer_freq;
748 #endif
749 timer_freq = freq;
750 } else {
751 if (bootverbose)
752 printf(
753 "%d Hz differs from default of %d Hz by more than 1%%\n",
754 freq, timer_freq);
755 }
756
757 set_timer_freq(timer_freq, hz);
758 i8254_timecounter.tc_frequency = timer_freq;
759 tc_init(&i8254_timecounter);
760
761 init_TSC();
762 }
763
764 /*
765 * Initialize the time of day register, based on the time base which is, e.g.
766 * from a filesystem.
767 */
768 void
769 inittodr(time_t base)
770 {
771 unsigned long sec, days;
772 int year, month;
773 int y, m, s;
774 struct timespec ts;
775
776 if (base) {
777 s = splclock();
778 ts.tv_sec = base;
779 ts.tv_nsec = 0;
780 tc_setclock(&ts);
781 splx(s);
782 }
783
784 /* Look if we have a RTC present and the time is valid */
785 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
786 goto wrong_time;
787
788 /* wait for time update to complete */
789 /* If RTCSA_TUP is zero, we have at least 244us before next update */
790 s = splhigh();
791 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
792 splx(s);
793 s = splhigh();
794 }
795
796 days = 0;
797 #ifdef USE_RTC_CENTURY
798 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
799 #else
800 year = readrtc(RTC_YEAR) + 1900;
801 if (year < 1970)
802 year += 100;
803 #endif
804 if (year < 1970) {
805 splx(s);
806 goto wrong_time;
807 }
808 month = readrtc(RTC_MONTH);
809 for (m = 1; m < month; m++)
810 days += daysinmonth[m-1];
811 if ((month > 2) && LEAPYEAR(year))
812 days ++;
813 days += readrtc(RTC_DAY) - 1;
814 for (y = 1970; y < year; y++)
815 days += DAYSPERYEAR + LEAPYEAR(y);
816 sec = ((( days * 24 +
817 readrtc(RTC_HRS)) * 60 +
818 readrtc(RTC_MIN)) * 60 +
819 readrtc(RTC_SEC));
820 /* sec now contains the number of seconds, since Jan 1 1970,
821 in the local time zone */
822
823 sec += tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
824
825 y = time_second - sec;
826 if (y <= -2 || y >= 2) {
827 /* badly off, adjust it */
828 ts.tv_sec = sec;
829 ts.tv_nsec = 0;
830 tc_setclock(&ts);
831 }
832 splx(s);
833 return;
834
835 wrong_time:
836 printf("Invalid time in real time clock.\n");
837 printf("Check and reset the date immediately!\n");
838 }
839
840 /*
841 * Write system time back to RTC
842 */
843 void
844 resettodr()
845 {
846 unsigned long tm;
847 int y, m, s;
848
849 if (disable_rtc_set)
850 return;
851
852 s = splclock();
853 tm = time_second;
854 splx(s);
855
856 /* Disable RTC updates and interrupts. */
857 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
858
859 /* Calculate local time to put in RTC */
860
861 tm -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
862
863 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
864 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
865 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
866
867 /* We have now the days since 01-01-1970 in tm */
868 writertc(RTC_WDAY, (tm + 4) % 7 + 1); /* Write back Weekday */
869 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
870 tm >= m;
871 y++, m = DAYSPERYEAR + LEAPYEAR(y))
872 tm -= m;
873
874 /* Now we have the years in y and the day-of-the-year in tm */
875 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
876 #ifdef USE_RTC_CENTURY
877 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
878 #endif
879 for (m = 0; ; m++) {
880 int ml;
881
882 ml = daysinmonth[m];
883 if (m == 1 && LEAPYEAR(y))
884 ml++;
885 if (tm < ml)
886 break;
887 tm -= ml;
888 }
889
890 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
891 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
892
893 /* Reenable RTC updates and interrupts. */
894 writertc(RTC_STATUSB, rtc_statusb);
895 }
896
897
898 /*
899 * Start both clocks running.
900 */
901 void
902 cpu_initclocks()
903 {
904 int diag;
905 #ifdef APIC_IO
906 int apic_8254_trial;
907 void *clkdesc;
908 #endif /* APIC_IO */
909 register_t crit;
910
911 if (statclock_disable) {
912 /*
913 * The stat interrupt mask is different without the
914 * statistics clock. Also, don't set the interrupt
915 * flag which would normally cause the RTC to generate
916 * interrupts.
917 */
918 rtc_statusb = RTCSB_24HR;
919 } else {
920 /* Setting stathz to nonzero early helps avoid races. */
921 stathz = RTC_NOPROFRATE;
922 profhz = RTC_PROFRATE;
923 }
924
925 /* Finish initializing 8253 timer 0. */
926 #ifdef APIC_IO
927
928 apic_8254_intr = isa_apic_irq(0);
929 apic_8254_trial = 0;
930 if (apic_8254_intr >= 0 ) {
931 if (apic_int_type(0, 0) == 3)
932 apic_8254_trial = 1;
933 } else {
934 /* look for ExtInt on pin 0 */
935 if (apic_int_type(0, 0) == 3) {
936 apic_8254_intr = apic_irq(0, 0);
937 setup_8254_mixed_mode();
938 } else
939 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
940 }
941
942 inthand_add("clk", apic_8254_intr, (driver_intr_t *)clkintr, NULL,
943 INTR_TYPE_CLK | INTR_FAST, &clkdesc);
944 crit = intr_disable();
945 mtx_lock_spin(&icu_lock);
946 INTREN(1 << apic_8254_intr);
947 mtx_unlock_spin(&icu_lock);
948 intr_restore(crit);
949
950 #else /* APIC_IO */
951
952 /*
953 * XXX Check the priority of this interrupt handler. I
954 * couldn't find anything suitable in the BSD/OS code (grog,
955 * 19 July 2000).
956 */
957 inthand_add("clk", 0, (driver_intr_t *)clkintr, NULL,
958 INTR_TYPE_CLK | INTR_FAST, NULL);
959 crit = intr_disable();
960 mtx_lock_spin(&icu_lock);
961 INTREN(IRQ0);
962 mtx_unlock_spin(&icu_lock);
963 intr_restore(crit);
964
965 #endif /* APIC_IO */
966
967 /* Initialize RTC. */
968 writertc(RTC_STATUSA, rtc_statusa);
969 writertc(RTC_STATUSB, RTCSB_24HR);
970
971 /* Don't bother enabling the statistics clock. */
972 if (statclock_disable)
973 return;
974 diag = rtcin(RTC_DIAG);
975 if (diag != 0)
976 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
977
978 #ifdef APIC_IO
979 if (isa_apic_irq(8) != 8)
980 panic("APIC RTC != 8");
981 #endif /* APIC_IO */
982
983 inthand_add("rtc", 8, (driver_intr_t *)rtcintr, NULL,
984 INTR_TYPE_CLK | INTR_FAST, NULL);
985
986 crit = intr_disable();
987 mtx_lock_spin(&icu_lock);
988 #ifdef APIC_IO
989 INTREN(APIC_IRQ8);
990 #else
991 INTREN(IRQ8);
992 #endif /* APIC_IO */
993 mtx_unlock_spin(&icu_lock);
994 intr_restore(crit);
995
996 writertc(RTC_STATUSB, rtc_statusb);
997
998 #ifdef APIC_IO
999 if (apic_8254_trial) {
1000
1001 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1002 while (read_intr_count(8) < 6)
1003 ; /* nothing */
1004 if (read_intr_count(apic_8254_intr) < 3) {
1005 /*
1006 * The MP table is broken.
1007 * The 8254 was not connected to the specified pin
1008 * on the IO APIC.
1009 * Workaround: Limited variant of mixed mode.
1010 */
1011
1012 crit = intr_disable();
1013 mtx_lock_spin(&icu_lock);
1014 INTRDIS(1 << apic_8254_intr);
1015 mtx_unlock_spin(&icu_lock);
1016 intr_restore(crit);
1017 inthand_remove(clkdesc);
1018 printf("APIC_IO: Broken MP table detected: "
1019 "8254 is not connected to "
1020 "IOAPIC #%d intpin %d\n",
1021 int_to_apicintpin[apic_8254_intr].ioapic,
1022 int_to_apicintpin[apic_8254_intr].int_pin);
1023 /*
1024 * Revoke current ISA IRQ 0 assignment and
1025 * configure a fallback interrupt routing from
1026 * the 8254 Timer via the 8259 PIC to the
1027 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1028 * We reuse the low level interrupt handler number.
1029 */
1030 if (apic_irq(0, 0) < 0) {
1031 revoke_apic_irq(apic_8254_intr);
1032 assign_apic_irq(0, 0, apic_8254_intr);
1033 }
1034 apic_8254_intr = apic_irq(0, 0);
1035 setup_8254_mixed_mode();
1036 inthand_add("clk", apic_8254_intr,
1037 (driver_intr_t *)clkintr, NULL,
1038 INTR_TYPE_CLK | INTR_FAST, NULL);
1039 crit = intr_disable();
1040 mtx_lock_spin(&icu_lock);
1041 INTREN(1 << apic_8254_intr);
1042 mtx_unlock_spin(&icu_lock);
1043 intr_restore(crit);
1044 }
1045
1046 }
1047 if (apic_int_type(0, 0) != 3 ||
1048 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1049 int_to_apicintpin[apic_8254_intr].int_pin != 0)
1050 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1051 int_to_apicintpin[apic_8254_intr].ioapic,
1052 int_to_apicintpin[apic_8254_intr].int_pin);
1053 else
1054 printf("APIC_IO: "
1055 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1056 #endif
1057
1058 }
1059
1060 #ifdef APIC_IO
1061 static u_long
1062 read_intr_count(int vec)
1063 {
1064 u_long *up;
1065 up = intr_countp[vec];
1066 if (up)
1067 return *up;
1068 return 0UL;
1069 }
1070
1071 static void
1072 setup_8254_mixed_mode()
1073 {
1074 /*
1075 * Allow 8254 timer to INTerrupt 8259:
1076 * re-initialize master 8259:
1077 * reset; prog 4 bytes, single ICU, edge triggered
1078 */
1079 outb(IO_ICU1, 0x13);
1080 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
1081 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1082 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1083 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1084
1085 /* program IO APIC for type 3 INT on INT0 */
1086 if (ext_int_setup(0, 0) < 0)
1087 panic("8254 redirect via APIC pin0 impossible!");
1088 }
1089 #endif
1090
1091 void
1092 cpu_startprofclock(void)
1093 {
1094
1095 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1096 writertc(RTC_STATUSA, rtc_statusa);
1097 psdiv = pscnt = psratio;
1098 }
1099
1100 void
1101 cpu_stopprofclock(void)
1102 {
1103
1104 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1105 writertc(RTC_STATUSA, rtc_statusa);
1106 psdiv = pscnt = 1;
1107 }
1108
1109 static int
1110 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1111 {
1112 int error;
1113 u_int freq;
1114
1115 /*
1116 * Use `i8254' instead of `timer' in external names because `timer'
1117 * is is too generic. Should use it everywhere.
1118 */
1119 freq = timer_freq;
1120 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1121 if (error == 0 && req->newptr != NULL) {
1122 if (timer0_state != RELEASED)
1123 return (EBUSY); /* too much trouble to handle */
1124 set_timer_freq(freq, hz);
1125 i8254_timecounter.tc_frequency = freq;
1126 }
1127 return (error);
1128 }
1129
1130 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1131 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
1132
1133 static unsigned
1134 i8254_get_timecount(struct timecounter *tc)
1135 {
1136 u_int count;
1137 u_int high, low;
1138 u_int eflags;
1139
1140 eflags = read_eflags();
1141 mtx_lock_spin(&clock_lock);
1142
1143 /* Select timer0 and latch counter value. */
1144 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1145
1146 low = inb(TIMER_CNTR0);
1147 high = inb(TIMER_CNTR0);
1148 count = timer0_max_count - ((high << 8) | low);
1149 if (count < i8254_lastcount ||
1150 (!i8254_ticked && (clkintr_pending ||
1151 ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
1152 #ifdef APIC_IO
1153 #define lapic_irr1 ((volatile u_int *)&lapic)[0x210 / 4] /* XXX XXX */
1154 /* XXX this assumes that apic_8254_intr is < 24. */
1155 (lapic_irr1 & (1 << apic_8254_intr))))
1156 #else
1157 (inb(IO_ICU1) & 1)))
1158 #endif
1159 )) {
1160 i8254_ticked = 1;
1161 i8254_offset += timer0_max_count;
1162 }
1163 i8254_lastcount = count;
1164 count += i8254_offset;
1165 mtx_unlock_spin(&clock_lock);
1166 return (count);
1167 }
1168
1169 #ifdef DEV_ISA
1170 /*
1171 * Attach to the ISA PnP descriptors for the timer and realtime clock.
1172 */
1173 static struct isa_pnp_id attimer_ids[] = {
1174 { 0x0001d041 /* PNP0100 */, "AT timer" },
1175 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
1176 { 0 }
1177 };
1178
1179 static int
1180 attimer_probe(device_t dev)
1181 {
1182 int result;
1183
1184 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
1185 device_quiet(dev);
1186 return(result);
1187 }
1188
1189 static int
1190 attimer_attach(device_t dev)
1191 {
1192 return(0);
1193 }
1194
1195 static device_method_t attimer_methods[] = {
1196 /* Device interface */
1197 DEVMETHOD(device_probe, attimer_probe),
1198 DEVMETHOD(device_attach, attimer_attach),
1199 DEVMETHOD(device_detach, bus_generic_detach),
1200 DEVMETHOD(device_shutdown, bus_generic_shutdown),
1201 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
1202 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
1203 { 0, 0 }
1204 };
1205
1206 static driver_t attimer_driver = {
1207 "attimer",
1208 attimer_methods,
1209 1, /* no softc */
1210 };
1211
1212 static devclass_t attimer_devclass;
1213
1214 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1215 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
1216 #endif /* DEV_ISA */
Cache object: 5e34099b5672eec4ca94961e0a1d2b0f
|