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