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