pcrtc.c revision 119987
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/pc98/cbus/pcrtc.c 119987 2003-09-11 14:05:06Z nyan $
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/*
52 * modified for PC98 by Kakefuda
53 */
54
55#include "opt_clock.h"
56#include "opt_isa.h"
57#include "opt_mca.h"
58
59#include <sys/param.h>
60#include <sys/systm.h>
61#include <sys/bus.h>
62#include <sys/limits.h>
63#include <sys/lock.h>
64#include <sys/mutex.h>
65#include <sys/proc.h>
66#include <sys/time.h>
67#include <sys/timetc.h>
68#include <sys/kernel.h>
69#include <sys/sysctl.h>
70#include <sys/cons.h>
71#include <sys/power.h>
72
73#include <machine/clock.h>
74#include <machine/cputypes.h>
75#include <machine/frame.h>
76#include <machine/md_var.h>
77#include <machine/psl.h>
78#ifdef APIC_IO
79#include <machine/segments.h>
80#endif
81#if defined(SMP) || defined(APIC_IO)
82#include <machine/smp.h>
83#endif /* SMP || APIC_IO */
84#include <machine/specialreg.h>
85
86#include <i386/isa/icu.h>
87#include <pc98/pc98/pc98.h>
88#include <pc98/pc98/pc98_machdep.h>
89#include <i386/isa/isa_device.h>
90#ifdef DEV_ISA
91#include <isa/isavar.h>
92#endif
93#include <i386/isa/timerreg.h>
94
95#include <i386/isa/intr_machdep.h>
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(int vec);
102static void setup_8254_mixed_mode(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) ? 1 : 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
115int	adjkerntz;		/* local offset from GMT in seconds */
116int	clkintr_pending;
117int	disable_rtc_set;	/* disable resettodr() if != 0 */
118int	pscnt = 1;
119int	psdiv = 1;
120int	statclock_disable;
121#ifndef TIMER_FREQ
122#define TIMER_FREQ   2457600
123#endif
124u_int	timer_freq = TIMER_FREQ;
125int	timer0_max_count;
126int	wall_cmos_clock;	/* wall CMOS clock assumed if != 0 */
127struct mtx clock_lock;
128
129static	int	beeping = 0;
130static	const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
131static	u_int	hardclock_max_count;
132static	u_int32_t i8254_lastcount;
133static	u_int32_t i8254_offset;
134static	int	i8254_ticked;
135
136
137/* Values for timerX_state: */
138#define	RELEASED	0
139#define	RELEASE_PENDING	1
140#define	ACQUIRED	2
141#define	ACQUIRE_PENDING	3
142
143static 	u_char	timer1_state;
144static	u_char	timer2_state;
145static	void	(*timer_func)(struct clockframe *frame) = hardclock;
146static void rtc_serialcombit(int);
147static void rtc_serialcom(int);
148static int rtc_inb(void);
149static void rtc_outb(int);
150
151static	unsigned i8254_get_timecount(struct timecounter *tc);
152static	void	set_timer_freq(u_int freq, int intr_freq);
153
154static struct timecounter i8254_timecounter = {
155	i8254_get_timecount,	/* get_timecount */
156	0,			/* no poll_pps */
157	~0u,			/* counter_mask */
158	0,			/* frequency */
159	"i8254",		/* name */
160	0			/* quality */
161};
162
163static void
164clkintr(struct clockframe frame)
165{
166
167	if (timecounter->tc_get_timecount == i8254_get_timecount) {
168		mtx_lock_spin(&clock_lock);
169		if (i8254_ticked)
170			i8254_ticked = 0;
171		else {
172			i8254_offset += timer0_max_count;
173			i8254_lastcount = 0;
174		}
175		clkintr_pending = 0;
176		mtx_unlock_spin(&clock_lock);
177	}
178	timer_func(&frame);
179#ifdef SMP
180	if (timer_func == hardclock)
181		forward_hardclock();
182#endif
183}
184
185int
186acquire_timer1(int mode)
187{
188
189	if (timer1_state != RELEASED)
190		return (-1);
191	timer1_state = ACQUIRED;
192
193	/*
194	 * This access to the timer registers is as atomic as possible
195	 * because it is a single instruction.  We could do better if we
196	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
197	 * and this is probably good enough for timer2, so we aren't as
198	 * careful with it as with timer0.
199	 */
200	outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
201
202	return (0);
203}
204
205int
206acquire_timer2(int mode)
207{
208
209	if (timer2_state != RELEASED)
210		return (-1);
211	timer2_state = ACQUIRED;
212
213	/*
214	 * This access to the timer registers is as atomic as possible
215	 * because it is a single instruction.  We could do better if we
216	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
217	 * and this is probably good enough for timer2, so we aren't as
218	 * careful with it as with timer0.
219	 */
220	outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
221
222	return (0);
223}
224
225int
226release_timer1()
227{
228
229	if (timer1_state != ACQUIRED)
230		return (-1);
231	timer1_state = RELEASED;
232	outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
233	return (0);
234}
235
236int
237release_timer2()
238{
239
240	if (timer2_state != ACQUIRED)
241		return (-1);
242	timer2_state = RELEASED;
243	outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
244	return (0);
245}
246
247
248static int
249getit(void)
250{
251	int high, low;
252
253	mtx_lock_spin(&clock_lock);
254
255	/* Select timer0 and latch counter value. */
256	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
257
258	low = inb(TIMER_CNTR0);
259	high = inb(TIMER_CNTR0);
260
261	mtx_unlock_spin(&clock_lock);
262	return ((high << 8) | low);
263}
264
265/*
266 * Wait "n" microseconds.
267 * Relies on timer 1 counting down from (timer_freq / hz)
268 * Note: timer had better have been programmed before this is first used!
269 */
270void
271DELAY(int n)
272{
273	int delta, prev_tick, tick, ticks_left;
274
275#ifdef DELAYDEBUG
276	int getit_calls = 1;
277	int n1;
278	static int state = 0;
279
280	if (state == 0) {
281		state = 1;
282		for (n1 = 1; n1 <= 10000000; n1 *= 10)
283			DELAY(n1);
284		state = 2;
285	}
286	if (state == 1)
287		printf("DELAY(%d)...", n);
288#endif
289	/*
290	 * Guard against the timer being uninitialized if we are called
291	 * early for console i/o.
292	 */
293	if (timer0_max_count == 0)
294		set_timer_freq(timer_freq, hz);
295
296	/*
297	 * Read the counter first, so that the rest of the setup overhead is
298	 * counted.  Guess the initial overhead is 20 usec (on most systems it
299	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
300	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
301	 * multiplications and divisions to scale the count take a while).
302	 *
303	 * However, if ddb is active then use a fake counter since reading
304	 * the i8254 counter involves acquiring a lock.  ddb must not go
305	 * locking for many reasons, but it calls here for at least atkbd
306	 * input.
307	 */
308#ifdef DDB
309	if (db_active)
310		prev_tick = 0;
311	else
312#endif
313		prev_tick = getit();
314	n -= 0;			/* XXX actually guess no initial overhead */
315	/*
316	 * Calculate (n * (timer_freq / 1e6)) without using floating point
317	 * and without any avoidable overflows.
318	 */
319	if (n <= 0)
320		ticks_left = 0;
321	else if (n < 256)
322		/*
323		 * Use fixed point to avoid a slow division by 1000000.
324		 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
325		 * 2^15 is the first power of 2 that gives exact results
326		 * for n between 0 and 256.
327		 */
328		ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
329	else
330		/*
331		 * Don't bother using fixed point, although gcc-2.7.2
332		 * generates particularly poor code for the long long
333		 * division, since even the slow way will complete long
334		 * before the delay is up (unless we're interrupted).
335		 */
336		ticks_left = ((u_int)n * (long long)timer_freq + 999999)
337			     / 1000000;
338
339	while (ticks_left > 0) {
340#ifdef DDB
341		if (db_active) {
342			outb(0x5f, 0);
343			tick = prev_tick + 1;
344		} else
345#endif
346			tick = getit();
347#ifdef DELAYDEBUG
348		++getit_calls;
349#endif
350		delta = prev_tick - tick;
351		prev_tick = tick;
352		if (delta < 0) {
353			delta += timer0_max_count;
354			/*
355			 * Guard against timer0_max_count being wrong.
356			 * This shouldn't happen in normal operation,
357			 * but it may happen if set_timer_freq() is
358			 * traced.
359			 */
360			if (delta < 0)
361				delta = 0;
362		}
363		ticks_left -= delta;
364	}
365#ifdef DELAYDEBUG
366	if (state == 1)
367		printf(" %d calls to getit() at %d usec each\n",
368		       getit_calls, (n + 5) / getit_calls);
369#endif
370}
371
372static void
373sysbeepstop(void *chan)
374{
375	outb(IO_PPI, inb(IO_PPI)|0x08);	/* disable counter1 output to speaker */
376	release_timer1();
377	beeping = 0;
378}
379
380int
381sysbeep(int pitch, int period)
382{
383	int x = splclock();
384
385	if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
386		if (!beeping) {
387			/* Something else owns it. */
388			splx(x);
389			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
390		}
391	disable_intr();
392	outb(0x3fdb, pitch);
393	outb(0x3fdb, (pitch>>8));
394	enable_intr();
395	if (!beeping) {
396		/* enable counter1 output to speaker */
397		outb(IO_PPI, (inb(IO_PPI) & 0xf7));
398		beeping = period;
399		timeout(sysbeepstop, (void *)NULL, period);
400	}
401	splx(x);
402	return (0);
403}
404
405
406unsigned int delaycount;
407#define FIRST_GUESS	0x2000
408static void findcpuspeed(void)
409{
410	int i;
411	int remainder;
412
413	/* Put counter in count down mode */
414	outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
415	outb(TIMER_CNTR0, 0xff);
416	outb(TIMER_CNTR0, 0xff);
417	for (i = FIRST_GUESS; i; i--)
418		;
419	remainder = getit();
420	delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
421}
422
423static u_int
424calibrate_clocks(void)
425{
426	int	timeout;
427	u_int	count, prev_count, tot_count;
428	u_short	sec, start_sec;
429
430	if (bootverbose)
431	        printf("Calibrating clock(s) ... ");
432	/* Check ARTIC. */
433	if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
434	    !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
435		goto fail;
436	timeout = 100000000;
437
438	/* Read the ARTIC. */
439	sec = inw(0x5e);
440
441	/* Wait for the ARTIC to changes. */
442	start_sec = sec;
443	for (;;) {
444		sec = inw(0x5e);
445		if (sec != start_sec)
446			break;
447		if (--timeout == 0)
448			goto fail;
449	}
450	prev_count = getit();
451	if (prev_count == 0 || prev_count > timer0_max_count)
452		goto fail;
453	tot_count = 0;
454
455	start_sec = sec;
456	for (;;) {
457		sec = inw(0x5e);
458		count = getit();
459		if (count == 0 || count > timer0_max_count)
460			goto fail;
461		if (count > prev_count)
462			tot_count += prev_count - (count - timer0_max_count);
463		else
464			tot_count += prev_count - count;
465		prev_count = count;
466		if ((sec == start_sec + 1200) ||
467		    (sec < start_sec &&
468		        (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
469			break;
470		if (--timeout == 0)
471			goto fail;
472	}
473
474	if (bootverbose) {
475	        printf("i8254 clock: %u Hz\n", tot_count);
476	}
477	return (tot_count);
478
479fail:
480	if (bootverbose)
481	        printf("failed, using default i8254 clock of %u Hz\n",
482		       timer_freq);
483	return (timer_freq);
484}
485
486static void
487set_timer_freq(u_int freq, int intr_freq)
488{
489	int new_timer0_max_count;
490
491	mtx_lock_spin(&clock_lock);
492	timer_freq = freq;
493	new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
494	if (new_timer0_max_count != timer0_max_count) {
495		timer0_max_count = new_timer0_max_count;
496		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
497		outb(TIMER_CNTR0, timer0_max_count & 0xff);
498		outb(TIMER_CNTR0, timer0_max_count >> 8);
499	}
500	mtx_unlock_spin(&clock_lock);
501}
502
503static void
504i8254_restore(void)
505{
506
507	mtx_lock_spin(&clock_lock);
508	outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
509	outb(TIMER_CNTR0, timer0_max_count & 0xff);
510	outb(TIMER_CNTR0, timer0_max_count >> 8);
511	mtx_unlock_spin(&clock_lock);
512}
513
514
515/*
516 * Restore all the timers non-atomically (XXX: should be atomically).
517 *
518 * This function is called from pmtimer_resume() to restore all the timers.
519 * This should not be necessary, but there are broken laptops that do not
520 * restore all the timers on resume.
521 */
522void
523timer_restore(void)
524{
525
526	i8254_restore();		/* restore timer_freq and hz */
527}
528
529/*
530 * Initialize 8254 timer 0 early so that it can be used in DELAY().
531 * XXX initialization of other timers is unintentionally left blank.
532 */
533void
534startrtclock()
535{
536	u_int delta, freq;
537
538	findcpuspeed();
539	if (pc98_machine_type & M_8M)
540		timer_freq = 1996800L; /* 1.9968 MHz */
541	else
542		timer_freq = 2457600L; /* 2.4576 MHz */
543
544	set_timer_freq(timer_freq, hz);
545	freq = calibrate_clocks();
546#ifdef CLK_CALIBRATION_LOOP
547	if (bootverbose) {
548		printf(
549		"Press a key on the console to abort clock calibration\n");
550		while (cncheckc() == -1)
551			calibrate_clocks();
552	}
553#endif
554
555	/*
556	 * Use the calibrated i8254 frequency if it seems reasonable.
557	 * Otherwise use the default, and don't use the calibrated i586
558	 * frequency.
559	 */
560	delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
561	if (delta < timer_freq / 100) {
562#ifndef CLK_USE_I8254_CALIBRATION
563		if (bootverbose)
564			printf(
565"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
566		freq = timer_freq;
567#endif
568		timer_freq = freq;
569	} else {
570		if (bootverbose)
571			printf(
572		    "%d Hz differs from default of %d Hz by more than 1%%\n",
573			       freq, timer_freq);
574	}
575
576	set_timer_freq(timer_freq, hz);
577	i8254_timecounter.tc_frequency = timer_freq;
578	tc_init(&i8254_timecounter);
579
580	init_TSC();
581}
582
583static void
584rtc_serialcombit(int i)
585{
586	outb(IO_RTC, ((i&0x01)<<5)|0x07);
587	DELAY(1);
588	outb(IO_RTC, ((i&0x01)<<5)|0x17);
589	DELAY(1);
590	outb(IO_RTC, ((i&0x01)<<5)|0x07);
591	DELAY(1);
592}
593
594static void
595rtc_serialcom(int i)
596{
597	rtc_serialcombit(i&0x01);
598	rtc_serialcombit((i&0x02)>>1);
599	rtc_serialcombit((i&0x04)>>2);
600	rtc_serialcombit((i&0x08)>>3);
601	outb(IO_RTC, 0x07);
602	DELAY(1);
603	outb(IO_RTC, 0x0f);
604	DELAY(1);
605	outb(IO_RTC, 0x07);
606 	DELAY(1);
607}
608
609static void
610rtc_outb(int val)
611{
612	int s;
613	int sa = 0;
614
615	for (s=0;s<8;s++) {
616	    sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
617	    outb(IO_RTC, sa);		/* set DI & CLK 0 */
618	    DELAY(1);
619	    outb(IO_RTC, sa | 0x10);	/* CLK 1 */
620	    DELAY(1);
621	}
622	outb(IO_RTC, sa & 0xef);	/* CLK 0 */
623}
624
625static int
626rtc_inb(void)
627{
628	int s;
629	int sa = 0;
630
631	for (s=0;s<8;s++) {
632	    sa |= ((inb(0x33) & 0x01) << s);
633	    outb(IO_RTC, 0x17);	/* CLK 1 */
634	    DELAY(1);
635	    outb(IO_RTC, 0x07);	/* CLK 0 */
636	    DELAY(2);
637	}
638	return sa;
639}
640
641/*
642 * Initialize the time of day register, based on the time base which is, e.g.
643 * from a filesystem.
644 */
645void
646inittodr(time_t base)
647{
648	unsigned long	sec, days;
649	int		year, month;
650	int		y, m, s;
651	struct timespec ts;
652	int		second, min, hour;
653
654	if (base) {
655		s = splclock();
656		ts.tv_sec = base;
657		ts.tv_nsec = 0;
658		tc_setclock(&ts);
659		splx(s);
660	}
661
662	rtc_serialcom(0x03);	/* Time Read */
663	rtc_serialcom(0x01);	/* Register shift command. */
664	DELAY(20);
665
666	second = bcd2bin(rtc_inb() & 0xff);	/* sec */
667	min = bcd2bin(rtc_inb() & 0xff);	/* min */
668	hour = bcd2bin(rtc_inb() & 0xff);	/* hour */
669	days = bcd2bin(rtc_inb() & 0xff) - 1;	/* date */
670
671	month = (rtc_inb() >> 4) & 0x0f;	/* month */
672	for (m = 1; m <	month; m++)
673		days +=	daysinmonth[m-1];
674	year = bcd2bin(rtc_inb() & 0xff) + 1900;	/* year */
675	/* 2000 year problem */
676	if (year < 1995)
677		year += 100;
678	if (year < 1970)
679		goto wrong_time;
680	for (y = 1970; y < year; y++)
681		days +=	DAYSPERYEAR + LEAPYEAR(y);
682	if ((month > 2)	&& LEAPYEAR(year))
683		days ++;
684	sec = ((( days * 24 +
685		  hour) * 60 +
686		  min) * 60 +
687		  second);
688	/* sec now contains the	number of seconds, since Jan 1 1970,
689	   in the local	time zone */
690
691	s = splhigh();
692
693	sec += tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
694
695	y = time_second - sec;
696	if (y <= -2 || y >= 2) {
697		/* badly off, adjust it */
698		ts.tv_sec = sec;
699		ts.tv_nsec = 0;
700		tc_setclock(&ts);
701	}
702	splx(s);
703	return;
704
705wrong_time:
706	printf("Invalid time in real time clock.\n");
707	printf("Check and reset the date immediately!\n");
708}
709
710/*
711 * Write system time back to RTC
712 */
713void
714resettodr()
715{
716	unsigned long	tm;
717	int		y, m, s;
718	int		wd;
719
720	if (disable_rtc_set)
721		return;
722
723	s = splclock();
724	tm = time_second;
725	splx(s);
726
727	rtc_serialcom(0x01);	/* Register shift command. */
728
729	/* Calculate local time	to put in RTC */
730
731	tm -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
732
733	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
734	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
735	rtc_outb(bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
736
737	/* We have now the days	since 01-01-1970 in tm */
738	wd = (tm + 4) % 7 + 1;			/* Write back Weekday */
739	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
740	     tm >= m;
741	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
742	     tm -= m;
743
744	/* Now we have the years in y and the day-of-the-year in tm */
745	for (m = 0; ; m++) {
746		int ml;
747
748		ml = daysinmonth[m];
749		if (m == 1 && LEAPYEAR(y))
750			ml++;
751		if (tm < ml)
752			break;
753		tm -= ml;
754	}
755
756	m++;
757	rtc_outb(bin2bcd(tm+1));		/* Write back Day     */
758	rtc_outb((m << 4) | wd);		/* Write back Month & Weekday  */
759	rtc_outb(bin2bcd(y%100));		/* Write back Year    */
760
761	rtc_serialcom(0x02);	/* Time set & Counter hold command. */
762	rtc_serialcom(0x00);	/* Register hold command. */
763}
764
765
766/*
767 * Start both clocks running.
768 */
769void
770cpu_initclocks()
771{
772#ifdef APIC_IO
773	int apic_8254_trial;
774	void *clkdesc;
775#endif /* APIC_IO */
776	register_t crit;
777
778
779	/* Finish initializing 8253 timer 0. */
780#ifdef APIC_IO
781
782	apic_8254_intr = isa_apic_irq(0);
783	apic_8254_trial = 0;
784	if (apic_8254_intr >= 0 ) {
785		if (apic_int_type(0, 0) == 3)
786			apic_8254_trial = 1;
787	} else {
788		/* look for ExtInt on pin 0 */
789		if (apic_int_type(0, 0) == 3) {
790			apic_8254_intr = apic_irq(0, 0);
791			setup_8254_mixed_mode();
792		} else
793			panic("APIC_IO: Cannot route 8254 interrupt to CPU");
794	}
795
796	inthand_add("clk", apic_8254_intr, (driver_intr_t *)clkintr, NULL,
797	    INTR_TYPE_CLK | INTR_FAST, &clkdesc);
798	crit = intr_disable();
799	mtx_lock_spin(&icu_lock);
800	INTREN(1 << apic_8254_intr);
801	mtx_unlock_spin(&icu_lock);
802	intr_restore(crit);
803
804#else /* APIC_IO */
805
806	/*
807	 * XXX Check the priority of this interrupt handler.  I
808	 * couldn't find anything suitable in the BSD/OS code (grog,
809	 * 19 July 2000).
810	 */
811	inthand_add("clk", 0, (driver_intr_t *)clkintr, NULL,
812	    INTR_TYPE_CLK | INTR_FAST, NULL);
813	crit = intr_disable();
814	mtx_lock_spin(&icu_lock);
815	INTREN(IRQ0);
816	mtx_unlock_spin(&icu_lock);
817	intr_restore(crit);
818
819#endif /* APIC_IO */
820
821
822
823#ifdef APIC_IO
824	if (apic_8254_trial) {
825
826		printf("APIC_IO: Testing 8254 interrupt delivery\n");
827		while (read_intr_count(8) < 6)
828			;	/* nothing */
829		if (read_intr_count(apic_8254_intr) < 3) {
830			/*
831			 * The MP table is broken.
832			 * The 8254 was not connected to the specified pin
833			 * on the IO APIC.
834			 * Workaround: Limited variant of mixed mode.
835			 */
836
837			crit = intr_disable();
838			mtx_lock_spin(&icu_lock);
839			INTRDIS(1 << apic_8254_intr);
840			mtx_unlock_spin(&icu_lock);
841			intr_restore(crit);
842			inthand_remove(clkdesc);
843			printf("APIC_IO: Broken MP table detected: "
844			       "8254 is not connected to "
845			       "IOAPIC #%d intpin %d\n",
846			       int_to_apicintpin[apic_8254_intr].ioapic,
847			       int_to_apicintpin[apic_8254_intr].int_pin);
848			/*
849			 * Revoke current ISA IRQ 0 assignment and
850			 * configure a fallback interrupt routing from
851			 * the 8254 Timer via the 8259 PIC to the
852			 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
853			 * We reuse the low level interrupt handler number.
854			 */
855			if (apic_irq(0, 0) < 0) {
856				revoke_apic_irq(apic_8254_intr);
857				assign_apic_irq(0, 0, apic_8254_intr);
858			}
859			apic_8254_intr = apic_irq(0, 0);
860			setup_8254_mixed_mode();
861			inthand_add("clk", apic_8254_intr,
862				    (driver_intr_t *)clkintr, NULL,
863				    INTR_TYPE_CLK | INTR_FAST, NULL);
864			crit = intr_disable();
865			mtx_lock_spin(&icu_lock);
866			INTREN(1 << apic_8254_intr);
867			mtx_unlock_spin(&icu_lock);
868			intr_restore(crit);
869		}
870
871	}
872	if (apic_int_type(0, 0) != 3 ||
873	    int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
874	    int_to_apicintpin[apic_8254_intr].int_pin != 0)
875		printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
876		       int_to_apicintpin[apic_8254_intr].ioapic,
877		       int_to_apicintpin[apic_8254_intr].int_pin);
878	else
879		printf("APIC_IO: "
880		       "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
881#endif
882
883	init_TSC_tc();
884}
885
886#ifdef APIC_IO
887static u_long
888read_intr_count(int vec)
889{
890	u_long *up;
891	up = intr_countp[vec];
892	if (up)
893		return *up;
894	return 0UL;
895}
896
897static void
898setup_8254_mixed_mode()
899{
900	/*
901	 * Allow 8254 timer to INTerrupt 8259:
902	 *  re-initialize master 8259:
903	 *   reset; prog 4 bytes, single ICU, edge triggered
904	 */
905	outb(IO_ICU1, 0x13);
906	outb(IO_ICU1 + 2, NRSVIDT);	/* start vector (unused) */
907	outb(IO_ICU1 + 2, 0x00);	/* ignore slave */
908	outb(IO_ICU1 + 2, 0x03);	/* auto EOI, 8086 */
909	outb(IO_ICU1 + 2, 0xfe);	/* unmask INT0 */
910
911	/* program IO APIC for type 3 INT on INT0 */
912	if (ext_int_setup(0, 0) < 0)
913		panic("8254 redirect via APIC pin0 impossible!");
914}
915#endif
916
917void
918cpu_startprofclock(void)
919{
920}
921
922void
923cpu_stopprofclock(void)
924{
925}
926
927static int
928sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
929{
930	int error;
931	u_int freq;
932
933	/*
934	 * Use `i8254' instead of `timer' in external names because `timer'
935	 * is is too generic.  Should use it everywhere.
936	 */
937	freq = timer_freq;
938	error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
939	if (error == 0 && req->newptr != NULL) {
940		set_timer_freq(freq, hz);
941		i8254_timecounter.tc_frequency = freq;
942	}
943	return (error);
944}
945
946SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
947    0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
948
949static unsigned
950i8254_get_timecount(struct timecounter *tc)
951{
952	u_int count;
953	u_int high, low;
954	u_int eflags;
955
956	eflags = read_eflags();
957	mtx_lock_spin(&clock_lock);
958
959	/* Select timer0 and latch counter value. */
960	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
961
962	low = inb(TIMER_CNTR0);
963	high = inb(TIMER_CNTR0);
964	count = timer0_max_count - ((high << 8) | low);
965	if (count < i8254_lastcount ||
966	    (!i8254_ticked && (clkintr_pending ||
967	    ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
968#ifdef APIC_IO
969#define	lapic_irr1	((volatile u_int *)&lapic)[0x210 / 4]	/* XXX XXX */
970	    /* XXX this assumes that apic_8254_intr is < 24. */
971	    (lapic_irr1 & (1 << apic_8254_intr))))
972#else
973	    (inb(IO_ICU1) & 1)))
974#endif
975	    )) {
976		i8254_ticked = 1;
977		i8254_offset += timer0_max_count;
978	}
979	i8254_lastcount = count;
980	count += i8254_offset;
981	mtx_unlock_spin(&clock_lock);
982	return (count);
983}
984
985#ifdef DEV_ISA
986/*
987 * Attach to the ISA PnP descriptors for the timer and realtime clock.
988 */
989static struct isa_pnp_id attimer_ids[] = {
990	{ 0x0001d041 /* PNP0100 */, "AT timer" },
991	{ 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
992	{ 0 }
993};
994
995static int
996attimer_probe(device_t dev)
997{
998	int result;
999
1000	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
1001		device_quiet(dev);
1002	return(result);
1003}
1004
1005static int
1006attimer_attach(device_t dev)
1007{
1008	return(0);
1009}
1010
1011static device_method_t attimer_methods[] = {
1012	/* Device interface */
1013	DEVMETHOD(device_probe,		attimer_probe),
1014	DEVMETHOD(device_attach,	attimer_attach),
1015	DEVMETHOD(device_detach,	bus_generic_detach),
1016	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1017	DEVMETHOD(device_suspend,	bus_generic_suspend),	/* XXX stop statclock? */
1018	DEVMETHOD(device_resume,	bus_generic_resume),	/* XXX restart statclock? */
1019	{ 0, 0 }
1020};
1021
1022static driver_t attimer_driver = {
1023	"attimer",
1024	attimer_methods,
1025	1,		/* no softc */
1026};
1027
1028static devclass_t attimer_devclass;
1029
1030DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1031#endif /* DEV_ISA */
1032