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