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