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