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