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