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