pcrtc.c revision 39569
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.60 1998/09/20 10:51:57 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 <sys/interrupt.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[3] = {
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[3] = {
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#ifndef PC98
708static u_int
709calibrate_clocks(void)
710{
711	u_int count, prev_count, tot_count;
712	int sec, start_sec, timeout;
713
714	if (bootverbose)
715	        printf("Calibrating clock(s) ... ");
716	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
717		goto fail;
718	timeout = 100000000;
719
720	/* Read the mc146818A seconds counter. */
721	for (;;) {
722		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
723			sec = rtcin(RTC_SEC);
724			break;
725		}
726		if (--timeout == 0)
727			goto fail;
728	}
729
730	/* Wait for the mC146818A seconds counter to change. */
731	start_sec = sec;
732	for (;;) {
733		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
734			sec = rtcin(RTC_SEC);
735			if (sec != start_sec)
736				break;
737		}
738		if (--timeout == 0)
739			goto fail;
740	}
741
742	/* Start keeping track of the i8254 counter. */
743	prev_count = getit();
744	if (prev_count == 0 || prev_count > timer0_max_count)
745		goto fail;
746	tot_count = 0;
747
748	if (tsc_present)
749		wrmsr(0x10, 0LL);	/* XXX 0x10 is the MSR for the TSC */
750
751	/*
752	 * Wait for the mc146818A seconds counter to change.  Read the i8254
753	 * counter for each iteration since this is convenient and only
754	 * costs a few usec of inaccuracy. The timing of the final reads
755	 * of the counters almost matches the timing of the initial reads,
756	 * so the main cause of inaccuracy is the varying latency from
757	 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
758	 * rtcin(RTC_SEC) that returns a changed seconds count.  The
759	 * maximum inaccuracy from this cause is < 10 usec on 486's.
760	 */
761	start_sec = sec;
762	for (;;) {
763		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
764			sec = rtcin(RTC_SEC);
765		count = getit();
766		if (count == 0 || count > timer0_max_count)
767			goto fail;
768		if (count > prev_count)
769			tot_count += prev_count - (count - timer0_max_count);
770		else
771			tot_count += prev_count - count;
772		prev_count = count;
773		if (sec != start_sec)
774			break;
775		if (--timeout == 0)
776			goto fail;
777	}
778
779	/*
780	 * Read the cpu cycle counter.  The timing considerations are
781	 * similar to those for the i8254 clock.
782	 */
783	if (tsc_present)
784		tsc_freq = rdtsc();
785
786	if (bootverbose) {
787		if (tsc_present)
788		        printf("TSC clock: %u Hz, ", tsc_freq);
789	        printf("i8254 clock: %u Hz\n", tot_count);
790	}
791	return (tot_count);
792
793fail:
794	if (bootverbose)
795	        printf("failed, using default i8254 clock of %u Hz\n",
796		       timer_freq);
797	return (timer_freq);
798}
799#endif	/* !PC98 */
800
801static void
802set_timer_freq(u_int freq, int intr_freq)
803{
804	u_long ef;
805	int new_timer0_max_count;
806
807	ef = read_eflags();
808	disable_intr();
809	timer_freq = freq;
810	new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
811	if (new_timer0_max_count != timer0_max_count) {
812		timer0_max_count = new_timer0_max_count;
813		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
814		outb(TIMER_CNTR0, timer0_max_count & 0xff);
815		outb(TIMER_CNTR0, timer0_max_count >> 8);
816	}
817	CLOCK_UNLOCK();
818	write_eflags(ef);
819}
820
821/*
822 * Initialize 8254 timer 0 early so that it can be used in DELAY().
823 * XXX initialization of other timers is unintentionally left blank.
824 */
825void
826startrtclock()
827{
828	u_int delta, freq;
829
830#ifdef PC98
831	findcpuspeed();
832	if (pc98_machine_type & M_8M)
833		timer_freq = 1996800L; /* 1.9968 MHz */
834	else
835		timer_freq = 2457600L; /* 2.4576 MHz */
836#endif /* PC98 */
837
838	if (cpu_feature & CPUID_TSC)
839		tsc_present = 1;
840	else
841		tsc_present = 0;
842
843#ifndef PC98
844	writertc(RTC_STATUSA, rtc_statusa);
845	writertc(RTC_STATUSB, RTCSB_24HR);
846#endif
847
848#ifndef PC98
849	set_timer_freq(timer_freq, hz);
850	freq = calibrate_clocks();
851#ifdef CLK_CALIBRATION_LOOP
852	if (bootverbose) {
853		printf(
854		"Press a key on the console to abort clock calibration\n");
855		while (cncheckc() == -1)
856			calibrate_clocks();
857	}
858#endif
859
860	/*
861	 * Use the calibrated i8254 frequency if it seems reasonable.
862	 * Otherwise use the default, and don't use the calibrated i586
863	 * frequency.
864	 */
865	delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
866	if (delta < timer_freq / 100) {
867#ifndef CLK_USE_I8254_CALIBRATION
868		if (bootverbose)
869			printf(
870"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
871		freq = timer_freq;
872#endif
873		timer_freq = freq;
874	} else {
875		if (bootverbose)
876			printf(
877		    "%d Hz differs from default of %d Hz by more than 1%%\n",
878			       freq, timer_freq);
879		tsc_freq = 0;
880	}
881#endif
882
883	set_timer_freq(timer_freq, hz);
884	i8254_timecounter[0].tc_frequency = timer_freq;
885	init_timecounter(i8254_timecounter);
886
887#ifndef CLK_USE_TSC_CALIBRATION
888	if (tsc_freq != 0) {
889		if (bootverbose)
890			printf(
891"CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
892		tsc_freq = 0;
893	}
894#endif
895	if (tsc_present && tsc_freq == 0) {
896		/*
897		 * Calibration of the i586 clock relative to the mc146818A
898		 * clock failed.  Do a less accurate calibration relative
899		 * to the i8254 clock.
900		 */
901		wrmsr(0x10, 0LL);	/* XXX */
902		DELAY(1000000);
903		tsc_freq = rdtsc();
904#ifdef CLK_USE_TSC_CALIBRATION
905		if (bootverbose)
906			printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
907#endif
908	}
909
910#if !defined(SMP)
911	/*
912	 * We can not use the TSC in SMP mode, until we figure out a
913	 * cheap (impossible), reliable and precise (yeah right!)  way
914	 * to synchronize the TSCs of all the CPUs.
915	 * Curse Intel for leaving the counter out of the I/O APIC.
916	 */
917
918#if NAPM > 0
919	/*
920	 * We can not use the TSC if we found an APM bios.  Too many
921	 * of them lie about their ability&intention to fiddle the CPU
922	 * clock for us to rely on this.  Precise timekeeping on an
923	 * APM'ed machine is at best a fools pursuit anyway, since
924	 * any and all of the time spent in various SMM code can't
925	 * be reliably accounted for.  Reading the RTC is your only
926	 * source of reliable time info.  The i8254 looses too of course
927	 * but we need to have some kind of time...
928	 */
929	if (apm_version != APMINI_CANTFIND)
930		return;
931#endif /* NAPM > 0 */
932
933	if (tsc_present && tsc_freq != 0) {
934		tsc_timecounter[0].tc_frequency = tsc_freq;
935		init_timecounter(tsc_timecounter);
936	}
937
938#endif /* !defined(SMP) */
939}
940
941#ifdef PC98
942static void
943rtc_serialcombit(int i)
944{
945	outb(IO_RTC, ((i&0x01)<<5)|0x07);
946	DELAY(1);
947	outb(IO_RTC, ((i&0x01)<<5)|0x17);
948	DELAY(1);
949	outb(IO_RTC, ((i&0x01)<<5)|0x07);
950	DELAY(1);
951}
952
953static void
954rtc_serialcom(int i)
955{
956	rtc_serialcombit(i&0x01);
957	rtc_serialcombit((i&0x02)>>1);
958	rtc_serialcombit((i&0x04)>>2);
959	rtc_serialcombit((i&0x08)>>3);
960	outb(IO_RTC, 0x07);
961	DELAY(1);
962	outb(IO_RTC, 0x0f);
963	DELAY(1);
964	outb(IO_RTC, 0x07);
965 	DELAY(1);
966}
967
968static void
969rtc_outb(int val)
970{
971	int s;
972	int sa = 0;
973
974	for (s=0;s<8;s++) {
975	    sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
976	    outb(IO_RTC, sa);		/* set DI & CLK 0 */
977	    DELAY(1);
978	    outb(IO_RTC, sa | 0x10);	/* CLK 1 */
979	    DELAY(1);
980	}
981	outb(IO_RTC, sa & 0xef);	/* CLK 0 */
982}
983
984static int
985rtc_inb(void)
986{
987	int s;
988	int sa = 0;
989
990	for (s=0;s<8;s++) {
991	    sa |= ((inb(0x33) & 0x01) << s);
992	    outb(IO_RTC, 0x17);	/* CLK 1 */
993	    DELAY(1);
994	    outb(IO_RTC, 0x07);	/* CLK 0 */
995	    DELAY(2);
996	}
997	return sa;
998}
999#endif /* PC-98 */
1000
1001/*
1002 * Initialize the time of day register,	based on the time base which is, e.g.
1003 * from	a filesystem.
1004 */
1005void
1006inittodr(time_t base)
1007{
1008	unsigned long	sec, days;
1009	int		yd;
1010	int		year, month;
1011	int		y, m, s;
1012	struct timespec ts;
1013#ifdef PC98
1014	int		second, min, hour;
1015#endif
1016
1017	if (base) {
1018		s = splclock();
1019		ts.tv_sec = base;
1020		ts.tv_nsec = 0;
1021		set_timecounter(&ts);
1022		splx(s);
1023	}
1024
1025#ifdef PC98
1026	rtc_serialcom(0x03);	/* Time Read */
1027	rtc_serialcom(0x01);	/* Register shift command. */
1028	DELAY(20);
1029
1030	second = bcd2bin(rtc_inb() & 0xff);	/* sec */
1031	min = bcd2bin(rtc_inb() & 0xff);	/* min */
1032	hour = bcd2bin(rtc_inb() & 0xff);	/* hour */
1033	days = bcd2bin(rtc_inb() & 0xff) - 1;	/* date */
1034
1035	month = (rtc_inb() >> 4) & 0x0f;	/* month */
1036	for (m = 1; m <	month; m++)
1037		days +=	daysinmonth[m-1];
1038	year = bcd2bin(rtc_inb() & 0xff) + 1900;	/* year */
1039	/* 2000 year problem */
1040	if (year < 1995)
1041		year += 100;
1042	if (year < 1970)
1043		goto wrong_time;
1044	for (y = 1970; y < year; y++)
1045		days +=	DAYSPERYEAR + LEAPYEAR(y);
1046	if ((month > 2)	&& LEAPYEAR(year))
1047		days ++;
1048	sec = ((( days * 24 +
1049		  hour) * 60 +
1050		  min) * 60 +
1051		  second);
1052	/* sec now contains the	number of seconds, since Jan 1 1970,
1053	   in the local	time zone */
1054#else	/* IBM-PC */
1055	/* Look	if we have a RTC present and the time is valid */
1056	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
1057		goto wrong_time;
1058
1059	/* wait	for time update	to complete */
1060	/* If RTCSA_TUP	is zero, we have at least 244us	before next update */
1061	while (rtcin(RTC_STATUSA) & RTCSA_TUP);
1062
1063	days = 0;
1064#ifdef USE_RTC_CENTURY
1065	year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY)	* 100;
1066#else
1067	year = readrtc(RTC_YEAR) + 1900;
1068	if (year < 1970)
1069		year += 100;
1070#endif
1071	if (year < 1970)
1072		goto wrong_time;
1073	month =	readrtc(RTC_MONTH);
1074	for (m = 1; m <	month; m++)
1075		days +=	daysinmonth[m-1];
1076	if ((month > 2)	&& LEAPYEAR(year))
1077		days ++;
1078	days +=	readrtc(RTC_DAY) - 1;
1079	yd = days;
1080	for (y = 1970; y < year; y++)
1081		days +=	DAYSPERYEAR + LEAPYEAR(y);
1082	sec = ((( days * 24 +
1083		  readrtc(RTC_HRS)) * 60 +
1084		  readrtc(RTC_MIN)) * 60 +
1085		  readrtc(RTC_SEC));
1086	/* sec now contains the	number of seconds, since Jan 1 1970,
1087	   in the local	time zone */
1088#endif
1089
1090	sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1091
1092	y = time_second - sec;
1093	if (y <= -2 || y >= 2) {
1094		/* badly off, adjust it */
1095		s = splclock();
1096		ts.tv_sec = sec;
1097		ts.tv_nsec = 0;
1098		set_timecounter(&ts);
1099		splx(s);
1100	}
1101	return;
1102
1103wrong_time:
1104	printf("Invalid	time in	real time clock.\n");
1105	printf("Check and reset	the date immediately!\n");
1106}
1107
1108/*
1109 * Write system	time back to RTC
1110 */
1111void
1112resettodr()
1113{
1114	unsigned long	tm;
1115	int		y, m, s;
1116#ifdef PC98
1117	int		wd;
1118#endif
1119
1120	if (disable_rtc_set)
1121		return;
1122
1123	s = splclock();
1124	tm = time_second;
1125	splx(s);
1126
1127#ifdef PC98
1128	rtc_serialcom(0x01);	/* Register shift command. */
1129
1130	/* Calculate local time	to put in RTC */
1131
1132	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1133
1134	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1135	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1136	rtc_outb(bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1137
1138	/* We have now the days	since 01-01-1970 in tm */
1139	wd = (tm+4)%7;
1140	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1141	     tm >= m;
1142	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1143	     tm -= m;
1144
1145	/* Now we have the years in y and the day-of-the-year in tm */
1146	for (m = 0; ; m++) {
1147		int ml;
1148
1149		ml = daysinmonth[m];
1150		if (m == 1 && LEAPYEAR(y))
1151			ml++;
1152		if (tm < ml)
1153			break;
1154		tm -= ml;
1155	}
1156
1157	m++;
1158	rtc_outb(bin2bcd(tm+1));		/* Write back Day     */
1159	rtc_outb((m << 4) | wd);		/* Write back Month & Weekday  */
1160	rtc_outb(bin2bcd(y%100));		/* Write back Year    */
1161
1162	rtc_serialcom(0x02);	/* Time set & Counter hold command. */
1163	rtc_serialcom(0x00);	/* Register hold command. */
1164#else
1165	/* Disable RTC updates and interrupts. */
1166	writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1167
1168	/* Calculate local time	to put in RTC */
1169
1170	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1171
1172	writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1173	writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1174	writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1175
1176	/* We have now the days	since 01-01-1970 in tm */
1177	writertc(RTC_WDAY, (tm+4)%7);			/* Write back Weekday */
1178	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1179	     tm >= m;
1180	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1181	     tm -= m;
1182
1183	/* Now we have the years in y and the day-of-the-year in tm */
1184	writertc(RTC_YEAR, bin2bcd(y%100));		/* Write back Year    */
1185#ifdef USE_RTC_CENTURY
1186	writertc(RTC_CENTURY, bin2bcd(y/100));		/* ... and Century    */
1187#endif
1188	for (m = 0; ; m++) {
1189		int ml;
1190
1191		ml = daysinmonth[m];
1192		if (m == 1 && LEAPYEAR(y))
1193			ml++;
1194		if (tm < ml)
1195			break;
1196		tm -= ml;
1197	}
1198
1199	writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
1200	writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
1201
1202	/* Reenable RTC updates and interrupts. */
1203	writertc(RTC_STATUSB, rtc_statusb);
1204#endif
1205}
1206
1207
1208/*
1209 * Start both clocks running.
1210 */
1211void
1212cpu_initclocks()
1213{
1214#ifdef APIC_IO
1215	int apic_8254_trial;
1216#endif /* APIC_IO */
1217#ifndef PC98
1218	int diag;
1219
1220	if (statclock_disable) {
1221		/*
1222		 * The stat interrupt mask is different without the
1223		 * statistics clock.  Also, don't set the interrupt
1224		 * flag which would normally cause the RTC to generate
1225		 * interrupts.
1226		 */
1227		stat_imask = HWI_MASK | SWI_MASK;
1228		rtc_statusb = RTCSB_24HR;
1229	} else {
1230	        /* Setting stathz to nonzero early helps avoid races. */
1231		stathz = RTC_NOPROFRATE;
1232		profhz = RTC_PROFRATE;
1233        }
1234#endif
1235
1236	/* Finish initializing 8253 timer 0. */
1237#ifdef APIC_IO
1238
1239	apic_8254_intr = isa_apic_irq(0);
1240	apic_8254_trial = 0;
1241	if (apic_8254_intr >= 0 ) {
1242		if (apic_int_type(0, 0) == 3)
1243			apic_8254_trial = 1;
1244	} else {
1245		/* look for ExtInt on pin 0 */
1246		if (apic_int_type(0, 0) == 3) {
1247			apic_8254_intr = 0;
1248			setup_8254_mixed_mode();
1249		} else
1250			panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1251	}
1252
1253	register_intr(/* irq */ apic_8254_intr, /* XXX id */ 0, /* flags */ 0,
1254		      /* XXX */ (inthand2_t *)clkintr, &clk_imask,
1255		      /* unit */ 0);
1256	INTREN(1 << apic_8254_intr);
1257
1258#else /* APIC_IO */
1259
1260	register_intr(/* irq */ 0, /* XXX id */ 0, /* flags */ 0,
1261		      /* XXX */ (inthand2_t *)clkintr, &clk_imask,
1262		      /* unit */ 0);
1263	INTREN(IRQ0);
1264
1265#endif /* APIC_IO */
1266
1267#ifndef PC98
1268	/* Initialize RTC. */
1269	writertc(RTC_STATUSA, rtc_statusa);
1270	writertc(RTC_STATUSB, RTCSB_24HR);
1271
1272	/* Don't bother enabling the statistics clock. */
1273	if (statclock_disable)
1274		return;
1275	diag = rtcin(RTC_DIAG);
1276	if (diag != 0)
1277		printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1278
1279#ifdef APIC_IO
1280	if (isa_apic_irq(8) != 8)
1281		panic("APIC RTC != 8");
1282#endif /* APIC_IO */
1283
1284	register_intr(/* irq */ 8, /* XXX id */ 1, /* flags */ 0,
1285		      /* XXX */ (inthand2_t *)rtcintr, &stat_imask,
1286		      /* unit */ 0);
1287
1288#ifdef APIC_IO
1289	INTREN(APIC_IRQ8);
1290#else
1291	INTREN(IRQ8);
1292#endif /* APIC_IO */
1293
1294	writertc(RTC_STATUSB, rtc_statusb);
1295#endif /* !PC98 */
1296
1297#ifdef APIC_IO
1298	if (apic_8254_trial) {
1299
1300		printf("APIC_IO: Testing 8254 interrupt delivery\n");
1301		while (read_intr_count(8) < 6)
1302			;	/* nothing */
1303		if (read_intr_count(apic_8254_intr) < 3) {
1304			/*
1305			 * The MP table is broken.
1306			 * The 8254 was not connected to the specified pin
1307			 * on the IO APIC.
1308			 * Workaround: Limited variant of mixed mode.
1309			 */
1310			INTRDIS(1 << apic_8254_intr);
1311			unregister_intr(apic_8254_intr,
1312					/* XXX */ (inthand2_t *) clkintr);
1313			printf("APIC_IO: Broken MP table detected: "
1314			       "8254 is not connected to IO APIC int pin %d\n",
1315			       apic_8254_intr);
1316
1317			apic_8254_intr = 0;
1318			setup_8254_mixed_mode();
1319			register_intr(/* irq */ apic_8254_intr, /* XXX id */ 0, /* flags */ 0,
1320				      /* XXX */ (inthand2_t *)clkintr, &clk_imask,
1321				      /* unit */ 0);
1322			INTREN(1 << apic_8254_intr);
1323		}
1324
1325	}
1326	if (apic_8254_intr)
1327		printf("APIC_IO: routing 8254 via pin %d\n",apic_8254_intr);
1328	else
1329		printf("APIC_IO: routing 8254 via 8259 on pin 0\n");
1330#endif
1331
1332}
1333
1334#ifdef APIC_IO
1335static u_long
1336read_intr_count(int vec)
1337{
1338	u_long *up;
1339	up = intr_countp[vec];
1340	if (up)
1341		return *up;
1342	return 0UL;
1343}
1344
1345static void
1346setup_8254_mixed_mode()
1347{
1348	/*
1349	 * Allow 8254 timer to INTerrupt 8259:
1350	 *  re-initialize master 8259:
1351	 *   reset; prog 4 bytes, single ICU, edge triggered
1352	 */
1353	outb(IO_ICU1, 0x13);
1354#ifdef PC98
1355	outb(IO_ICU1 + 2, NRSVIDT);	/* start vector (unused) */
1356	outb(IO_ICU1 + 2, 0x00);	/* ignore slave */
1357	outb(IO_ICU1 + 2, 0x03);	/* auto EOI, 8086 */
1358	outb(IO_ICU1 + 2, 0xfe);	/* unmask INT0 */
1359#else
1360	outb(IO_ICU1 + 1, NRSVIDT);	/* start vector (unused) */
1361	outb(IO_ICU1 + 1, 0x00);	/* ignore slave */
1362	outb(IO_ICU1 + 1, 0x03);	/* auto EOI, 8086 */
1363	outb(IO_ICU1 + 1, 0xfe);	/* unmask INT0 */
1364#endif
1365	/* program IO APIC for type 3 INT on INT0 */
1366	if (ext_int_setup(0, 0) < 0)
1367		panic("8254 redirect via APIC pin0 impossible!");
1368}
1369#endif
1370
1371void
1372setstatclockrate(int newhz)
1373{
1374#ifndef PC98
1375	if (newhz == RTC_PROFRATE)
1376		rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1377	else
1378		rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1379	writertc(RTC_STATUSA, rtc_statusa);
1380#endif
1381}
1382
1383static int
1384sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
1385{
1386	int error;
1387	u_int freq;
1388
1389	/*
1390	 * Use `i8254' instead of `timer' in external names because `timer'
1391	 * is is too generic.  Should use it everywhere.
1392	 */
1393	freq = timer_freq;
1394	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1395	if (error == 0 && req->newptr != NULL) {
1396		if (timer0_state != RELEASED)
1397			return (EBUSY);	/* too much trouble to handle */
1398		set_timer_freq(freq, hz);
1399		i8254_timecounter[0].tc_frequency = freq;
1400	}
1401	return (error);
1402}
1403
1404SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1405	    0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1406
1407static int
1408sysctl_machdep_tsc_freq SYSCTL_HANDLER_ARGS
1409{
1410	int error;
1411	u_int freq;
1412
1413	if (!tsc_present)
1414		return (EOPNOTSUPP);
1415	freq = tsc_freq;
1416	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1417	if (error == 0 && req->newptr != NULL) {
1418		tsc_freq = freq;
1419		tsc_timecounter[0].tc_frequency = tsc_freq;
1420	}
1421	return (error);
1422}
1423
1424SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1425	    0, sizeof(u_int), sysctl_machdep_tsc_freq, "I", "");
1426
1427static unsigned
1428i8254_get_timecount(struct timecounter *tc)
1429{
1430	u_int count;
1431	u_long ef;
1432	u_int high, low;
1433
1434	ef = read_eflags();
1435	disable_intr();
1436
1437	/* Select timer0 and latch counter value. */
1438	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1439
1440	low = inb(TIMER_CNTR0);
1441	high = inb(TIMER_CNTR0);
1442
1443	count = hardclock_max_count - ((high << 8) | low);
1444	if (count < i8254_lastcount) {
1445		i8254_ticked = 1;
1446		i8254_offset += hardclock_max_count;
1447	}
1448
1449	i8254_lastcount = count;
1450	count += i8254_offset;
1451	CLOCK_UNLOCK();
1452	write_eflags(ef);
1453	return (count);
1454}
1455
1456static unsigned
1457tsc_get_timecount(struct timecounter *tc)
1458{
1459	return (rdtsc());
1460}
1461