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