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