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