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