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