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