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