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