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