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