pcrtc.c revision 162958
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 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 *	from: @(#)clock.c	7.2 (Berkeley) 5/12/91
33 * $FreeBSD: head/sys/pc98/cbus/pcrtc.c 162958 2006-10-02 15:42:02Z phk $
34 */
35
36/*
37 * Routines to handle clock hardware.
38 */
39
40/*
41 * inittodr, settodr and support routines written
42 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
43 *
44 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
45 */
46
47/*
48 * modified for PC98 by Kakefuda
49 */
50
51#include "opt_apic.h"
52#include "opt_clock.h"
53#include "opt_isa.h"
54#include "opt_mca.h"
55
56#include <sys/param.h>
57#include <sys/systm.h>
58#include <sys/bus.h>
59#include <sys/clock.h>
60#include <sys/lock.h>
61#include <sys/kdb.h>
62#include <sys/mutex.h>
63#include <sys/proc.h>
64#include <sys/time.h>
65#include <sys/timetc.h>
66#include <sys/kernel.h>
67#include <sys/limits.h>
68#include <sys/module.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/cpu.h>
75#include <machine/cputypes.h>
76#include <machine/frame.h>
77#include <machine/intr_machdep.h>
78#include <machine/md_var.h>
79#include <machine/psl.h>
80#ifdef DEV_APIC
81#include <machine/apicvar.h>
82#endif
83#include <machine/specialreg.h>
84#include <machine/ppireg.h>
85#include <machine/timerreg.h>
86
87#include <i386/isa/icu.h>
88#include <pc98/cbus/cbus.h>
89#include <pc98/pc98/pc98_machdep.h>
90#ifdef DEV_ISA
91#include <isa/isavar.h>
92#endif
93
94/*
95 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
96 * can use a simple formula for leap years.
97 */
98#define	LEAPYEAR(y) (((u_int)(y) % 4 == 0) ? 1 : 0)
99#define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
100
101#define	TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
102
103int	clkintr_pending;
104int	pscnt = 1;
105int	psdiv = 1;
106int	statclock_disable;
107#ifndef TIMER_FREQ
108#define TIMER_FREQ   2457600
109#endif
110u_int	timer_freq = TIMER_FREQ;
111int	timer0_max_count;
112int	timer0_real_max_count;
113struct mtx clock_lock;
114
115static	int	beeping = 0;
116static	const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
117static	struct intsrc *i8254_intsrc;
118static	u_int32_t i8254_lastcount;
119static	u_int32_t i8254_offset;
120static	int	(*i8254_pending)(struct intsrc *);
121static	int	i8254_ticked;
122static	int	using_lapic_timer;
123
124/* Values for timerX_state: */
125#define	RELEASED	0
126#define	RELEASE_PENDING	1
127#define	ACQUIRED	2
128#define	ACQUIRE_PENDING	3
129
130static 	u_char	timer1_state;
131static	u_char	timer2_state;
132static void rtc_serialcombit(int);
133static void rtc_serialcom(int);
134static int rtc_inb(void);
135static void rtc_outb(int);
136
137static	unsigned i8254_get_timecount(struct timecounter *tc);
138static	unsigned i8254_simple_get_timecount(struct timecounter *tc);
139static	void	set_timer_freq(u_int freq, int intr_freq);
140
141static struct timecounter i8254_timecounter = {
142	i8254_get_timecount,	/* get_timecount */
143	0,			/* no poll_pps */
144	~0u,			/* counter_mask */
145	0,			/* frequency */
146	"i8254",		/* name */
147	0			/* quality */
148};
149
150static void
151clkintr(struct trapframe *frame)
152{
153
154	if (timecounter->tc_get_timecount == i8254_get_timecount) {
155		mtx_lock_spin(&clock_lock);
156		if (i8254_ticked)
157			i8254_ticked = 0;
158		else {
159			i8254_offset += timer0_max_count;
160			i8254_lastcount = 0;
161		}
162		clkintr_pending = 0;
163		mtx_unlock_spin(&clock_lock);
164	}
165	KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
166	hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
167}
168
169int
170acquire_timer1(int mode)
171{
172
173	if (timer1_state != RELEASED)
174		return (-1);
175	timer1_state = ACQUIRED;
176
177	/*
178	 * This access to the timer registers is as atomic as possible
179	 * because it is a single instruction.  We could do better if we
180	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
181	 * and this is probably good enough for timer2, so we aren't as
182	 * careful with it as with timer0.
183	 */
184	outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
185
186	return (0);
187}
188
189int
190acquire_timer2(int mode)
191{
192
193	if (timer2_state != RELEASED)
194		return (-1);
195	timer2_state = ACQUIRED;
196
197	/*
198	 * This access to the timer registers is as atomic as possible
199	 * because it is a single instruction.  We could do better if we
200	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
201	 * and this is probably good enough for timer2, so we aren't as
202	 * careful with it as with timer0.
203	 */
204	outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
205
206	return (0);
207}
208
209int
210release_timer1()
211{
212
213	if (timer1_state != ACQUIRED)
214		return (-1);
215	timer1_state = RELEASED;
216	outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
217	return (0);
218}
219
220int
221release_timer2()
222{
223
224	if (timer2_state != ACQUIRED)
225		return (-1);
226	timer2_state = RELEASED;
227	outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
228	return (0);
229}
230
231
232static int
233getit(void)
234{
235	int high, low;
236
237	mtx_lock_spin(&clock_lock);
238
239	/* Select timer0 and latch counter value. */
240	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
241
242	low = inb(TIMER_CNTR0);
243	high = inb(TIMER_CNTR0);
244
245	mtx_unlock_spin(&clock_lock);
246	return ((high << 8) | low);
247}
248
249/*
250 * Wait "n" microseconds.
251 * Relies on timer 1 counting down from (timer_freq / hz)
252 * Note: timer had better have been programmed before this is first used!
253 */
254void
255DELAY(int n)
256{
257	int delta, prev_tick, tick, ticks_left;
258
259#ifdef DELAYDEBUG
260	int getit_calls = 1;
261	int n1;
262	static int state = 0;
263
264	if (state == 0) {
265		state = 1;
266		for (n1 = 1; n1 <= 10000000; n1 *= 10)
267			DELAY(n1);
268		state = 2;
269	}
270	if (state == 1)
271		printf("DELAY(%d)...", n);
272#endif
273	/*
274	 * Guard against the timer being uninitialized if we are called
275	 * early for console i/o.
276	 */
277	if (timer0_max_count == 0)
278		set_timer_freq(timer_freq, hz);
279
280	/*
281	 * Read the counter first, so that the rest of the setup overhead is
282	 * counted.  Guess the initial overhead is 20 usec (on most systems it
283	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
284	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
285	 * multiplications and divisions to scale the count take a while).
286	 *
287	 * However, if ddb is active then use a fake counter since reading
288	 * the i8254 counter involves acquiring a lock.  ddb must not do
289	 * locking for many reasons, but it calls here for at least atkbd
290	 * input.
291	 */
292#ifdef KDB
293	if (kdb_active)
294		prev_tick = 1;
295	else
296#endif
297		prev_tick = getit();
298	n -= 0;			/* XXX actually guess no initial overhead */
299	/*
300	 * Calculate (n * (timer_freq / 1e6)) without using floating point
301	 * and without any avoidable overflows.
302	 */
303	if (n <= 0)
304		ticks_left = 0;
305	else if (n < 256)
306		/*
307		 * Use fixed point to avoid a slow division by 1000000.
308		 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
309		 * 2^15 is the first power of 2 that gives exact results
310		 * for n between 0 and 256.
311		 */
312		ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
313	else
314		/*
315		 * Don't bother using fixed point, although gcc-2.7.2
316		 * generates particularly poor code for the long long
317		 * division, since even the slow way will complete long
318		 * before the delay is up (unless we're interrupted).
319		 */
320		ticks_left = ((u_int)n * (long long)timer_freq + 999999)
321			     / 1000000;
322
323	while (ticks_left > 0) {
324#ifdef KDB
325		if (kdb_active) {
326			outb(0x5f, 0);
327			tick = prev_tick - 1;
328			if (tick <= 0)
329				tick = timer0_max_count;
330		} else
331#endif
332			tick = getit();
333#ifdef DELAYDEBUG
334		++getit_calls;
335#endif
336		delta = prev_tick - tick;
337		prev_tick = tick;
338		if (delta < 0) {
339			delta += timer0_max_count;
340			/*
341			 * Guard against timer0_max_count being wrong.
342			 * This shouldn't happen in normal operation,
343			 * but it may happen if set_timer_freq() is
344			 * traced.
345			 */
346			if (delta < 0)
347				delta = 0;
348		}
349		ticks_left -= delta;
350	}
351#ifdef DELAYDEBUG
352	if (state == 1)
353		printf(" %d calls to getit() at %d usec each\n",
354		       getit_calls, (n + 5) / getit_calls);
355#endif
356}
357
358static void
359sysbeepstop(void *chan)
360{
361	ppi_spkr_off();		/* disable counter1 output to speaker */
362	timer_spkr_release();
363	beeping = 0;
364}
365
366int
367sysbeep(int pitch, int period)
368{
369	int x = splclock();
370
371	if (timer_spkr_acquire())
372		if (!beeping) {
373			/* Something else owns it. */
374			splx(x);
375			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
376		}
377	disable_intr();
378	spkr_set_pitch(pitch);
379	enable_intr();
380	if (!beeping) {
381		/* enable counter1 output to speaker */
382		ppi_spkr_on();
383		beeping = period;
384		timeout(sysbeepstop, (void *)NULL, period);
385	}
386	splx(x);
387	return (0);
388}
389
390
391unsigned int delaycount;
392#define FIRST_GUESS	0x2000
393static void findcpuspeed(void)
394{
395	int i;
396	int remainder;
397
398	/* Put counter in count down mode */
399	outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
400	outb(TIMER_CNTR0, 0xff);
401	outb(TIMER_CNTR0, 0xff);
402	for (i = FIRST_GUESS; i; i--)
403		;
404	remainder = getit();
405	delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
406}
407
408static u_int
409calibrate_clocks(void)
410{
411	int	timeout;
412	u_int	count, prev_count, tot_count;
413	u_short	sec, start_sec;
414
415	if (bootverbose)
416	        printf("Calibrating clock(s) ... ");
417	/* Check ARTIC. */
418	if (!(PC98_SYSTEM_PARAMETER(0x458) & 0x80) &&
419	    !(PC98_SYSTEM_PARAMETER(0x45b) & 0x04))
420		goto fail;
421	timeout = 100000000;
422
423	/* Read the ARTIC. */
424	sec = inw(0x5e);
425
426	/* Wait for the ARTIC to changes. */
427	start_sec = sec;
428	for (;;) {
429		sec = inw(0x5e);
430		if (sec != start_sec)
431			break;
432		if (--timeout == 0)
433			goto fail;
434	}
435	prev_count = getit();
436	if (prev_count == 0 || prev_count > timer0_max_count)
437		goto fail;
438	tot_count = 0;
439
440	start_sec = sec;
441	for (;;) {
442		sec = inw(0x5e);
443		count = getit();
444		if (count == 0 || count > timer0_max_count)
445			goto fail;
446		if (count > prev_count)
447			tot_count += prev_count - (count - timer0_max_count);
448		else
449			tot_count += prev_count - count;
450		prev_count = count;
451		if ((sec == start_sec + 1200) || /* 1200 = 307.2KHz >> 8 */
452		    (sec < start_sec &&
453		        (u_int)sec + 0x10000 == (u_int)start_sec + 1200))
454			break;
455		if (--timeout == 0)
456			goto fail;
457	}
458
459	if (bootverbose) {
460	        printf("i8254 clock: %u Hz\n", tot_count);
461	}
462	return (tot_count);
463
464fail:
465	if (bootverbose)
466	        printf("failed, using default i8254 clock of %u Hz\n",
467		       timer_freq);
468	return (timer_freq);
469}
470
471static void
472set_timer_freq(u_int freq, int intr_freq)
473{
474	int new_timer0_real_max_count;
475
476	i8254_timecounter.tc_frequency = freq;
477	mtx_lock_spin(&clock_lock);
478	timer_freq = freq;
479	if (using_lapic_timer)
480		new_timer0_real_max_count = 0x10000;
481	else
482		new_timer0_real_max_count = TIMER_DIV(intr_freq);
483	if (new_timer0_real_max_count != timer0_real_max_count) {
484		timer0_real_max_count = new_timer0_real_max_count;
485		if (timer0_real_max_count == 0x10000)
486			timer0_max_count = 0xffff;
487		else
488			timer0_max_count = timer0_real_max_count;
489		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
490		outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
491		outb(TIMER_CNTR0, timer0_real_max_count >> 8);
492	}
493	mtx_unlock_spin(&clock_lock);
494}
495
496static void
497i8254_restore(void)
498{
499
500	mtx_lock_spin(&clock_lock);
501	outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
502	outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
503	outb(TIMER_CNTR0, timer0_real_max_count >> 8);
504	mtx_unlock_spin(&clock_lock);
505}
506
507
508/*
509 * Restore all the timers non-atomically (XXX: should be atomically).
510 *
511 * This function is called from pmtimer_resume() to restore all the timers.
512 * This should not be necessary, but there are broken laptops that do not
513 * restore all the timers on resume.
514 */
515void
516timer_restore(void)
517{
518
519	i8254_restore();		/* restore timer_freq and hz */
520}
521
522/*
523 * Initialize 8254 timer 0 early so that it can be used in DELAY().
524 * XXX initialization of other timers is unintentionally left blank.
525 */
526void
527startrtclock()
528{
529	u_int delta, freq;
530
531	findcpuspeed();
532	if (pc98_machine_type & M_8M)
533		timer_freq = 1996800L; /* 1.9968 MHz */
534	else
535		timer_freq = 2457600L; /* 2.4576 MHz */
536
537	set_timer_freq(timer_freq, hz);
538	freq = calibrate_clocks();
539#ifdef CLK_CALIBRATION_LOOP
540	if (bootverbose) {
541		printf(
542		"Press a key on the console to abort clock calibration\n");
543		while (cncheckc() == -1)
544			calibrate_clocks();
545	}
546#endif
547
548	/*
549	 * Use the calibrated i8254 frequency if it seems reasonable.
550	 * Otherwise use the default, and don't use the calibrated i586
551	 * frequency.
552	 */
553	delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
554	if (delta < timer_freq / 100) {
555#ifndef CLK_USE_I8254_CALIBRATION
556		if (bootverbose)
557			printf(
558"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
559		freq = timer_freq;
560#endif
561		timer_freq = freq;
562	} else {
563		if (bootverbose)
564			printf(
565		    "%d Hz differs from default of %d Hz by more than 1%%\n",
566			       freq, timer_freq);
567	}
568
569	set_timer_freq(timer_freq, hz);
570	tc_init(&i8254_timecounter);
571
572	init_TSC();
573}
574
575static void
576rtc_serialcombit(int i)
577{
578	outb(IO_RTC, ((i&0x01)<<5)|0x07);
579	DELAY(1);
580	outb(IO_RTC, ((i&0x01)<<5)|0x17);
581	DELAY(1);
582	outb(IO_RTC, ((i&0x01)<<5)|0x07);
583	DELAY(1);
584}
585
586static void
587rtc_serialcom(int i)
588{
589	rtc_serialcombit(i&0x01);
590	rtc_serialcombit((i&0x02)>>1);
591	rtc_serialcombit((i&0x04)>>2);
592	rtc_serialcombit((i&0x08)>>3);
593	outb(IO_RTC, 0x07);
594	DELAY(1);
595	outb(IO_RTC, 0x0f);
596	DELAY(1);
597	outb(IO_RTC, 0x07);
598 	DELAY(1);
599}
600
601static void
602rtc_outb(int val)
603{
604	int s;
605	int sa = 0;
606
607	for (s=0;s<8;s++) {
608	    sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
609	    outb(IO_RTC, sa);		/* set DI & CLK 0 */
610	    DELAY(1);
611	    outb(IO_RTC, sa | 0x10);	/* CLK 1 */
612	    DELAY(1);
613	}
614	outb(IO_RTC, sa & 0xef);	/* CLK 0 */
615}
616
617static int
618rtc_inb(void)
619{
620	int s;
621	int sa = 0;
622
623	for (s=0;s<8;s++) {
624	    sa |= ((inb(0x33) & 0x01) << s);
625	    outb(IO_RTC, 0x17);	/* CLK 1 */
626	    DELAY(1);
627	    outb(IO_RTC, 0x07);	/* CLK 0 */
628	    DELAY(2);
629	}
630	return sa;
631}
632
633/*
634 * Initialize the time of day register, based on the time base which is, e.g.
635 * from a filesystem.
636 */
637void
638inittodr(time_t base)
639{
640	unsigned long	sec, days;
641	int		year, month;
642	int		y, m, s;
643	struct timespec ts;
644	int		second, min, hour;
645
646	if (base) {
647		s = splclock();
648		ts.tv_sec = base;
649		ts.tv_nsec = 0;
650		tc_setclock(&ts);
651		splx(s);
652	}
653
654	rtc_serialcom(0x03);	/* Time Read */
655	rtc_serialcom(0x01);	/* Register shift command. */
656	DELAY(20);
657
658	second = bcd2bin(rtc_inb() & 0xff);	/* sec */
659	min = bcd2bin(rtc_inb() & 0xff);	/* min */
660	hour = bcd2bin(rtc_inb() & 0xff);	/* hour */
661	days = bcd2bin(rtc_inb() & 0xff) - 1;	/* date */
662
663	month = (rtc_inb() >> 4) & 0x0f;	/* month */
664	for (m = 1; m <	month; m++)
665		days +=	daysinmonth[m-1];
666	year = bcd2bin(rtc_inb() & 0xff) + 1900;	/* year */
667	/* 2000 year problem */
668	if (year < 1995)
669		year += 100;
670	if (year < 1970)
671		goto wrong_time;
672	for (y = 1970; y < year; y++)
673		days +=	DAYSPERYEAR + LEAPYEAR(y);
674	if ((month > 2)	&& LEAPYEAR(year))
675		days ++;
676	sec = ((( days * 24 +
677		  hour) * 60 +
678		  min) * 60 +
679		  second);
680	/* sec now contains the	number of seconds, since Jan 1 1970,
681	   in the local	time zone */
682
683	s = splhigh();
684
685	sec += tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
686
687	y = time_second - sec;
688	if (y <= -2 || y >= 2) {
689		/* badly off, adjust it */
690		ts.tv_sec = sec;
691		ts.tv_nsec = 0;
692		tc_setclock(&ts);
693	}
694	splx(s);
695	return;
696
697wrong_time:
698	printf("Invalid time in real time clock.\n");
699	printf("Check and reset the date immediately!\n");
700}
701
702/*
703 * Write system time back to RTC
704 */
705void
706resettodr()
707{
708	unsigned long	tm;
709	int		y, m, s;
710	int		wd;
711
712	if (disable_rtc_set)
713		return;
714
715	s = splclock();
716	tm = time_second;
717	splx(s);
718
719	rtc_serialcom(0x01);	/* Register shift command. */
720
721	/* Calculate local time	to put in RTC */
722
723	tm -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
724
725	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
726	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
727	rtc_outb(bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
728
729	/* We have now the days	since 01-01-1970 in tm */
730	wd = (tm + 4) % 7 + 1;			/* Write back Weekday */
731	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
732	     tm >= m;
733	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
734	     tm -= m;
735
736	/* Now we have the years in y and the day-of-the-year in tm */
737	for (m = 0; ; m++) {
738		int ml;
739
740		ml = daysinmonth[m];
741		if (m == 1 && LEAPYEAR(y))
742			ml++;
743		if (tm < ml)
744			break;
745		tm -= ml;
746	}
747
748	m++;
749	rtc_outb(bin2bcd(tm+1));		/* Write back Day     */
750	rtc_outb((m << 4) | wd);		/* Write back Month & Weekday  */
751	rtc_outb(bin2bcd(y%100));		/* Write back Year    */
752
753	rtc_serialcom(0x02);	/* Time set & Counter hold command. */
754	rtc_serialcom(0x00);	/* Register hold command. */
755}
756
757
758/*
759 * Start both clocks running.
760 */
761void
762cpu_initclocks()
763{
764
765#ifdef DEV_APIC
766	using_lapic_timer = lapic_setup_clock();
767#endif
768	/*
769	 * If we aren't using the local APIC timer to drive the kernel
770	 * clocks, setup the interrupt handler for the 8254 timer 0 so
771	 * that it can drive hardclock().  Otherwise, change the 8254
772	 * timecounter to user a simpler algorithm.
773	 */
774	if (!using_lapic_timer) {
775		intr_add_handler("clk", 0, (driver_intr_t *)clkintr, NULL,
776		    INTR_TYPE_CLK | INTR_FAST, NULL);
777		i8254_intsrc = intr_lookup_source(0);
778		if (i8254_intsrc != NULL)
779			i8254_pending =
780			    i8254_intsrc->is_pic->pic_source_pending;
781	} else {
782		i8254_timecounter.tc_get_timecount =
783		    i8254_simple_get_timecount;
784		i8254_timecounter.tc_counter_mask = 0xffff;
785		set_timer_freq(timer_freq, hz);
786	}
787
788	init_TSC_tc();
789}
790
791void
792cpu_startprofclock(void)
793{
794}
795
796void
797cpu_stopprofclock(void)
798{
799}
800
801static int
802sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
803{
804	int error;
805	u_int freq;
806
807	/*
808	 * Use `i8254' instead of `timer' in external names because `timer'
809	 * is is too generic.  Should use it everywhere.
810	 */
811	freq = timer_freq;
812	error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
813	if (error == 0 && req->newptr != NULL)
814		set_timer_freq(freq, hz);
815	return (error);
816}
817
818SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
819    0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
820
821static unsigned
822i8254_simple_get_timecount(struct timecounter *tc)
823{
824
825	return (timer0_max_count - getit());
826}
827
828static unsigned
829i8254_get_timecount(struct timecounter *tc)
830{
831	u_int count;
832	u_int high, low;
833	u_int eflags;
834
835	eflags = read_eflags();
836	mtx_lock_spin(&clock_lock);
837
838	/* Select timer0 and latch counter value. */
839	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
840
841	low = inb(TIMER_CNTR0);
842	high = inb(TIMER_CNTR0);
843	count = timer0_max_count - ((high << 8) | low);
844	if (count < i8254_lastcount ||
845	    (!i8254_ticked && (clkintr_pending ||
846	    ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
847	    i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
848		i8254_ticked = 1;
849		i8254_offset += timer0_max_count;
850	}
851	i8254_lastcount = count;
852	count += i8254_offset;
853	mtx_unlock_spin(&clock_lock);
854	return (count);
855}
856
857#ifdef DEV_ISA
858/*
859 * Attach to the ISA PnP descriptors for the timer and realtime clock.
860 */
861static struct isa_pnp_id attimer_ids[] = {
862	{ 0x0001d041 /* PNP0100 */, "AT timer" },
863	{ 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
864	{ 0 }
865};
866
867static int
868attimer_probe(device_t dev)
869{
870	int result;
871
872	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
873		device_quiet(dev);
874	return(result);
875}
876
877static int
878attimer_attach(device_t dev)
879{
880	return(0);
881}
882
883static device_method_t attimer_methods[] = {
884	/* Device interface */
885	DEVMETHOD(device_probe,		attimer_probe),
886	DEVMETHOD(device_attach,	attimer_attach),
887	DEVMETHOD(device_detach,	bus_generic_detach),
888	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
889	DEVMETHOD(device_suspend,	bus_generic_suspend),	/* XXX stop statclock? */
890	DEVMETHOD(device_resume,	bus_generic_resume),	/* XXX restart statclock? */
891	{ 0, 0 }
892};
893
894static driver_t attimer_driver = {
895	"attimer",
896	attimer_methods,
897	1,		/* no softc */
898};
899
900static devclass_t attimer_devclass;
901
902DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
903#endif /* DEV_ISA */
904