pcrtc.c revision 131977
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 131977 2004-07-11 13:46:10Z nyan $
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_clock.h"
52#include "opt_isa.h"
53#include "opt_mca.h"
54
55#include <sys/param.h>
56#include <sys/systm.h>
57#include <sys/bus.h>
58#include <sys/limits.h>
59#include <sys/lock.h>
60#include <sys/kdb.h>
61#include <sys/module.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/sysctl.h>
68#include <sys/cons.h>
69#include <sys/power.h>
70
71#include <machine/clock.h>
72#include <machine/cputypes.h>
73#include <machine/frame.h>
74#include <machine/intr_machdep.h>
75#include <machine/md_var.h>
76#include <machine/psl.h>
77
78#if defined(SMP)
79#include <machine/smp.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	struct intsrc *i8254_intsrc;
139#ifndef BURN_BRIDGES
140/*
141 * XXX new_function and timer_func should not handle clockframes, but
142 * timer_func currently needs to hold hardclock to handle the
143 * timer0_state == 0 case.  We should use inthand_add()/inthand_remove()
144 * to switch between clkintr() and a slightly different timerintr().
145 */
146static	void	(*new_function)(struct clockframe *frame);
147static	u_int	new_rate;
148static	u_int	timer0_prescaler_count;
149static	u_char	timer0_state;
150#endif
151
152/* Values for timerX_state: */
153#define	RELEASED	0
154#define	RELEASE_PENDING	1
155#define	ACQUIRED	2
156#define	ACQUIRE_PENDING	3
157
158static 	u_char	timer1_state;
159static	u_char	timer2_state;
160static	void	(*timer_func)(struct clockframe *frame) = hardclock;
161static void rtc_serialcombit(int);
162static void rtc_serialcom(int);
163static int rtc_inb(void);
164static void rtc_outb(int);
165
166static	unsigned i8254_get_timecount(struct timecounter *tc);
167static	void	set_timer_freq(u_int freq, int intr_freq);
168
169static struct timecounter i8254_timecounter = {
170	i8254_get_timecount,	/* get_timecount */
171	0,			/* no poll_pps */
172	~0u,			/* counter_mask */
173	0,			/* frequency */
174	"i8254",		/* name */
175	0			/* quality */
176};
177
178static void
179clkintr(struct clockframe *frame)
180{
181
182	if (timecounter->tc_get_timecount == i8254_get_timecount) {
183		mtx_lock_spin(&clock_lock);
184		if (i8254_ticked)
185			i8254_ticked = 0;
186		else {
187			i8254_offset += timer0_max_count;
188			i8254_lastcount = 0;
189		}
190		clkintr_pending = 0;
191		mtx_unlock_spin(&clock_lock);
192	}
193	timer_func(frame);
194#ifdef SMP
195	if (timer_func == hardclock)
196		forward_hardclock();
197#endif
198#ifndef BURN_BRIDGES
199	switch (timer0_state) {
200
201	case RELEASED:
202		break;
203
204	case ACQUIRED:
205		if ((timer0_prescaler_count += timer0_max_count)
206		    >= hardclock_max_count) {
207			timer0_prescaler_count -= hardclock_max_count;
208			hardclock(frame);
209#ifdef SMP
210			forward_hardclock();
211#endif
212		}
213		break;
214
215	case ACQUIRE_PENDING:
216		mtx_lock_spin(&clock_lock);
217		i8254_offset = i8254_get_timecount(NULL);
218		i8254_lastcount = 0;
219		timer0_max_count = TIMER_DIV(new_rate);
220		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
221		outb(TIMER_CNTR0, timer0_max_count & 0xff);
222		outb(TIMER_CNTR0, timer0_max_count >> 8);
223		mtx_unlock_spin(&clock_lock);
224		timer_func = new_function;
225		timer0_state = ACQUIRED;
226		break;
227
228	case RELEASE_PENDING:
229		if ((timer0_prescaler_count += timer0_max_count)
230		    >= hardclock_max_count) {
231			mtx_lock_spin(&clock_lock);
232			i8254_offset = i8254_get_timecount(NULL);
233			i8254_lastcount = 0;
234			timer0_max_count = hardclock_max_count;
235			outb(TIMER_MODE,
236			     TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
237			outb(TIMER_CNTR0, timer0_max_count & 0xff);
238			outb(TIMER_CNTR0, timer0_max_count >> 8);
239			mtx_unlock_spin(&clock_lock);
240			timer0_prescaler_count = 0;
241			timer_func = hardclock;
242			timer0_state = RELEASED;
243			hardclock(frame);
244#ifdef SMP
245			forward_hardclock();
246#endif
247		}
248		break;
249	}
250#endif
251}
252
253#ifndef BURN_BRIDGES
254/*
255 * The acquire and release functions must be called at ipl >= splclock().
256 */
257int
258acquire_timer0(int rate, void (*function)(struct clockframe *frame))
259{
260	static int old_rate;
261
262	if (rate <= 0 || rate > TIMER0_MAX_FREQ)
263		return (-1);
264	switch (timer0_state) {
265
266	case RELEASED:
267		timer0_state = ACQUIRE_PENDING;
268		break;
269
270	case RELEASE_PENDING:
271		if (rate != old_rate)
272			return (-1);
273		/*
274		 * The timer has been released recently, but is being
275		 * re-acquired before the release completed.  In this
276		 * case, we simply reclaim it as if it had not been
277		 * released at all.
278		 */
279		timer0_state = ACQUIRED;
280		break;
281
282	default:
283		return (-1);	/* busy */
284	}
285	new_function = function;
286	old_rate = new_rate = rate;
287	return (0);
288}
289#endif
290
291int
292acquire_timer1(int mode)
293{
294
295	if (timer1_state != RELEASED)
296		return (-1);
297	timer1_state = ACQUIRED;
298
299	/*
300	 * This access to the timer registers is as atomic as possible
301	 * because it is a single instruction.  We could do better if we
302	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
303	 * and this is probably good enough for timer2, so we aren't as
304	 * careful with it as with timer0.
305	 */
306	outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
307
308	return (0);
309}
310
311int
312acquire_timer2(int mode)
313{
314
315	if (timer2_state != RELEASED)
316		return (-1);
317	timer2_state = ACQUIRED;
318
319	/*
320	 * This access to the timer registers is as atomic as possible
321	 * because it is a single instruction.  We could do better if we
322	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
323	 * and this is probably good enough for timer2, so we aren't as
324	 * careful with it as with timer0.
325	 */
326	outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
327
328	return (0);
329}
330
331#ifndef BURN_BRIDGES
332int
333release_timer0()
334{
335	switch (timer0_state) {
336
337	case ACQUIRED:
338		timer0_state = RELEASE_PENDING;
339		break;
340
341	case ACQUIRE_PENDING:
342		/* Nothing happened yet, release quickly. */
343		timer0_state = RELEASED;
344		break;
345
346	default:
347		return (-1);
348	}
349	return (0);
350}
351#endif
352
353int
354release_timer1()
355{
356
357	if (timer1_state != ACQUIRED)
358		return (-1);
359	timer1_state = RELEASED;
360	outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
361	return (0);
362}
363
364int
365release_timer2()
366{
367
368	if (timer2_state != ACQUIRED)
369		return (-1);
370	timer2_state = RELEASED;
371	outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
372	return (0);
373}
374
375
376static int
377getit(void)
378{
379	int high, low;
380
381#ifdef KDB
382	if (!kdb_active)
383#endif
384		mtx_lock_spin(&clock_lock);
385
386	/* Select timer0 and latch counter value. */
387	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
388
389	low = inb(TIMER_CNTR0);
390	high = inb(TIMER_CNTR0);
391
392#ifdef KDB
393	if (!kdb_active)
394#endif
395		mtx_unlock_spin(&clock_lock);
396
397	return ((high << 8) | low);
398}
399
400/*
401 * Wait "n" microseconds.
402 * Relies on timer 1 counting down from (timer_freq / hz)
403 * Note: timer had better have been programmed before this is first used!
404 */
405void
406DELAY(int n)
407{
408	int delta, prev_tick, tick, ticks_left;
409
410#ifdef DELAYDEBUG
411	int getit_calls = 1;
412	int n1;
413	static int state = 0;
414
415	if (state == 0) {
416		state = 1;
417		for (n1 = 1; n1 <= 10000000; n1 *= 10)
418			DELAY(n1);
419		state = 2;
420	}
421	if (state == 1)
422		printf("DELAY(%d)...", n);
423#endif
424	/*
425	 * Guard against the timer being uninitialized if we are called
426	 * early for console i/o.
427	 */
428	if (timer0_max_count == 0)
429		set_timer_freq(timer_freq, hz);
430
431	/*
432	 * Read the counter first, so that the rest of the setup overhead is
433	 * counted.  Guess the initial overhead is 20 usec (on most systems it
434	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
435	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
436	 * multiplications and divisions to scale the count take a while).
437	 */
438	prev_tick = getit();
439	n -= 0;			/* XXX actually guess no initial overhead */
440	/*
441	 * Calculate (n * (timer_freq / 1e6)) without using floating point
442	 * and without any avoidable overflows.
443	 */
444	if (n <= 0)
445		ticks_left = 0;
446	else if (n < 256)
447		/*
448		 * Use fixed point to avoid a slow division by 1000000.
449		 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
450		 * 2^15 is the first power of 2 that gives exact results
451		 * for n between 0 and 256.
452		 */
453		ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
454	else
455		/*
456		 * Don't bother using fixed point, although gcc-2.7.2
457		 * generates particularly poor code for the long long
458		 * division, since even the slow way will complete long
459		 * before the delay is up (unless we're interrupted).
460		 */
461		ticks_left = ((u_int)n * (long long)timer_freq + 999999)
462			     / 1000000;
463
464	while (ticks_left > 0) {
465#ifdef DDB
466		if (db_active) {
467			outb(0x5f, 0);
468			tick = prev_tick + 1;
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	/* Finish initializing 8254 timer 0. */
899	intr_add_handler("clk", 0, (driver_intr_t *)clkintr, NULL,
900	    INTR_TYPE_CLK | INTR_FAST, NULL);
901
902	init_TSC_tc();
903}
904
905void
906cpu_startprofclock(void)
907{
908}
909
910void
911cpu_stopprofclock(void)
912{
913}
914
915static int
916sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
917{
918	int error;
919	u_int freq;
920
921	/*
922	 * Use `i8254' instead of `timer' in external names because `timer'
923	 * is is too generic.  Should use it everywhere.
924	 */
925	freq = timer_freq;
926	error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
927	if (error == 0 && req->newptr != NULL) {
928#ifndef BURN_BRIDGES
929		if (timer0_state != RELEASED)
930			return (EBUSY);	/* too much trouble to handle */
931#endif
932		set_timer_freq(freq, hz);
933		i8254_timecounter.tc_frequency = freq;
934	}
935	return (error);
936}
937
938SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
939    0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
940
941static unsigned
942i8254_get_timecount(struct timecounter *tc)
943{
944	u_int count;
945	u_int high, low;
946	u_int eflags;
947
948	eflags = read_eflags();
949	mtx_lock_spin(&clock_lock);
950
951	/* Select timer0 and latch counter value. */
952	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
953
954	low = inb(TIMER_CNTR0);
955	high = inb(TIMER_CNTR0);
956	count = timer0_max_count - ((high << 8) | low);
957	if (count < i8254_lastcount ||
958	    (!i8254_ticked && (clkintr_pending ||
959	    ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
960	    i8254_intsrc != NULL &&
961	    i8254_intsrc->is_pic->pic_source_pending(i8254_intsrc))))) {
962		i8254_ticked = 1;
963		i8254_offset += timer0_max_count;
964	}
965	i8254_lastcount = count;
966	count += i8254_offset;
967	mtx_unlock_spin(&clock_lock);
968	return (count);
969}
970
971#ifdef DEV_ISA
972/*
973 * Attach to the ISA PnP descriptors for the timer and realtime clock.
974 */
975static struct isa_pnp_id attimer_ids[] = {
976	{ 0x0001d041 /* PNP0100 */, "AT timer" },
977	{ 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
978	{ 0 }
979};
980
981static int
982attimer_probe(device_t dev)
983{
984	int result;
985
986	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
987		device_quiet(dev);
988	return(result);
989}
990
991static int
992attimer_attach(device_t dev)
993{
994	return(0);
995}
996
997static device_method_t attimer_methods[] = {
998	/* Device interface */
999	DEVMETHOD(device_probe,		attimer_probe),
1000	DEVMETHOD(device_attach,	attimer_attach),
1001	DEVMETHOD(device_detach,	bus_generic_detach),
1002	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1003	DEVMETHOD(device_suspend,	bus_generic_suspend),	/* XXX stop statclock? */
1004	DEVMETHOD(device_resume,	bus_generic_resume),	/* XXX restart statclock? */
1005	{ 0, 0 }
1006};
1007
1008static driver_t attimer_driver = {
1009	"attimer",
1010	attimer_methods,
1011	1,		/* no softc */
1012};
1013
1014static devclass_t attimer_devclass;
1015
1016DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1017#endif /* DEV_ISA */
1018