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