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