Home | History | Annotate | Line # | Download | only in isa
clock.c revision 1.10
      1 /*	$NetBSD: clock.c,v 1.10 2007/09/26 19:48:42 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * William Jolitz and Don Ahn.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  *
     34  *	@(#)clock.c	7.2 (Berkeley) 5/12/91
     35  */
     36 /*-
     37  * Copyright (c) 1993, 1994 Charles M. Hannum.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * William Jolitz and Don Ahn.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)clock.c	7.2 (Berkeley) 5/12/91
     71  */
     72 /*
     73  * Mach Operating System
     74  * Copyright (c) 1991,1990,1989 Carnegie Mellon University
     75  * All Rights Reserved.
     76  *
     77  * Permission to use, copy, modify and distribute this software and its
     78  * documentation is hereby granted, provided that both the copyright
     79  * notice and this permission notice appear in all copies of the
     80  * software, derivative works or modified versions, and any portions
     81  * thereof, and that both notices appear in supporting documentation.
     82  *
     83  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     84  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
     85  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     86  *
     87  * Carnegie Mellon requests users of this software to return to
     88  *
     89  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     90  *  School of Computer Science
     91  *  Carnegie Mellon University
     92  *  Pittsburgh PA 15213-3890
     93  *
     94  * any improvements or extensions that they make and grant Carnegie Mellon
     95  * the rights to redistribute these changes.
     96  */
     97 /*
     98   Copyright 1988, 1989 by Intel Corporation, Santa Clara, California.
     99 
    100 		All Rights Reserved
    101 
    102 Permission to use, copy, modify, and distribute this software and
    103 its documentation for any purpose and without fee is hereby
    104 granted, provided that the above copyright notice appears in all
    105 copies and that both the copyright notice and this permission notice
    106 appear in supporting documentation, and that the name of Intel
    107 not be used in advertising or publicity pertaining to distribution
    108 of the software without specific, written prior permission.
    109 
    110 INTEL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
    111 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
    112 IN NO EVENT SHALL INTEL BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
    113 CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    114 LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
    115 NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
    116 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    117 */
    118 
    119 /*
    120  * Primitive clock interrupt routines.
    121  */
    122 
    123 #include <sys/cdefs.h>
    124 __KERNEL_RCSID(0, "$NetBSD: clock.c,v 1.10 2007/09/26 19:48:42 ad Exp $");
    125 
    126 /* #define CLOCKDEBUG */
    127 /* #define CLOCK_PARANOIA */
    128 
    129 #include "opt_multiprocessor.h"
    130 #include "opt_ntp.h"
    131 
    132 #include <sys/param.h>
    133 #include <sys/systm.h>
    134 #include <sys/time.h>
    135 #include <sys/timetc.h>
    136 #include <sys/kernel.h>
    137 #include <sys/device.h>
    138 #include <sys/mutex.h>
    139 
    140 #include <machine/cpu.h>
    141 #include <machine/intr.h>
    142 #include <machine/pio.h>
    143 #include <machine/cpufunc.h>
    144 
    145 #include <dev/isa/isareg.h>
    146 #include <dev/isa/isavar.h>
    147 #include <dev/ic/mc146818reg.h>
    148 #include <dev/ic/i8253reg.h>
    149 #include <i386/isa/nvram.h>
    150 #include <x86/x86/tsc.h>
    151 #include <dev/clock_subr.h>
    152 #include <machine/specialreg.h>
    153 
    154 #include "config_time.h"		/* for CONFIG_TIME */
    155 
    156 #ifndef __x86_64__
    157 #include "mca.h"
    158 #endif
    159 #if NMCA > 0
    160 #include <machine/mca_machdep.h>	/* for MCA_system */
    161 #endif
    162 
    163 #include "pcppi.h"
    164 #if (NPCPPI > 0)
    165 #include <dev/isa/pcppivar.h>
    166 
    167 int sysbeepmatch(struct device *, struct cfdata *, void *);
    168 void sysbeepattach(struct device *, struct device *, void *);
    169 
    170 CFATTACH_DECL(sysbeep, sizeof(struct device),
    171     sysbeepmatch, sysbeepattach, NULL, NULL);
    172 
    173 static int ppi_attached;
    174 static pcppi_tag_t ppicookie;
    175 #endif /* PCPPI */
    176 
    177 #ifdef CLOCKDEBUG
    178 int clock_debug = 0;
    179 #define DPRINTF(arg) if (clock_debug) printf arg
    180 #else
    181 #define DPRINTF(arg)
    182 #endif
    183 
    184 int		gettick(void);
    185 void		sysbeep(int, int);
    186 static void     tickle_tc(void);
    187 
    188 static int	clockintr(void *, struct intrframe *);
    189 static void	rtcinit(void);
    190 static int	rtcget(mc_todregs *);
    191 static void	rtcput(mc_todregs *);
    192 
    193 static int	cmoscheck(void);
    194 
    195 static int	clock_expandyear(int);
    196 
    197 static inline int gettick_broken_latch(void);
    198 
    199 static volatile uint32_t i8254_lastcount;
    200 static volatile uint32_t i8254_offset;
    201 static volatile int i8254_ticked;
    202 
    203 /* to protect TC timer variables */
    204 static __cpu_simple_lock_t tmr_lock = __SIMPLELOCK_UNLOCKED;
    205 
    206 inline u_int mc146818_read(void *, u_int);
    207 inline void mc146818_write(void *, u_int, u_int);
    208 
    209 u_int i8254_get_timecount(struct timecounter *);
    210 static void rtc_register(void);
    211 
    212 static struct timecounter i8254_timecounter = {
    213 	i8254_get_timecount,	/* get_timecount */
    214 	0,			/* no poll_pps */
    215 	~0u,			/* counter_mask */
    216 	TIMER_FREQ,		/* frequency */
    217 	"i8254",		/* name */
    218 	100,			/* quality */
    219 	NULL,			/* prev */
    220 	NULL,			/* next */
    221 };
    222 
    223 /* XXX use sc? */
    224 inline u_int
    225 mc146818_read(void *sc, u_int reg)
    226 {
    227 
    228 	outb(IO_RTC, reg);
    229 	return (inb(IO_RTC+1));
    230 }
    231 
    232 /* XXX use sc? */
    233 inline void
    234 mc146818_write(void *sc, u_int reg, u_int datum)
    235 {
    236 
    237 	outb(IO_RTC, reg);
    238 	outb(IO_RTC+1, datum);
    239 }
    240 
    241 u_long rtclock_tval;		/* i8254 reload value for countdown */
    242 int    rtclock_init = 0;
    243 
    244 int clock_broken_latch = 0;
    245 
    246 #ifdef CLOCK_PARANOIA
    247 static int ticks[6];
    248 #endif
    249 /*
    250  * i8254 latch check routine:
    251  *     National Geode (formerly Cyrix MediaGX) has a serious bug in
    252  *     its built-in i8254-compatible clock module.
    253  *     machdep sets the variable 'clock_broken_latch' to indicate it.
    254  */
    255 
    256 int
    257 gettick_broken_latch(void)
    258 {
    259 	u_long flags;
    260 	int v1, v2, v3;
    261 	int w1, w2, w3;
    262 
    263 	/* Don't want someone screwing with the counter while we're here. */
    264 	flags = x86_read_psl();
    265 	x86_disable_intr();
    266 
    267 	v1 = inb(IO_TIMER1+TIMER_CNTR0);
    268 	v1 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
    269 	v2 = inb(IO_TIMER1+TIMER_CNTR0);
    270 	v2 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
    271 	v3 = inb(IO_TIMER1+TIMER_CNTR0);
    272 	v3 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
    273 
    274 	x86_write_psl(flags);
    275 
    276 #ifdef CLOCK_PARANOIA
    277 	if (clock_debug) {
    278 		ticks[0] = ticks[3];
    279 		ticks[1] = ticks[4];
    280 		ticks[2] = ticks[5];
    281 		ticks[3] = v1;
    282 		ticks[4] = v2;
    283 		ticks[5] = v3;
    284 	}
    285 #endif
    286 
    287 	if (v1 >= v2 && v2 >= v3 && v1 - v3 < 0x200)
    288 		return (v2);
    289 
    290 #define _swap_val(a, b) do { \
    291 	int c = a; \
    292 	a = b; \
    293 	b = c; \
    294 } while (0)
    295 
    296 	/*
    297 	 * sort v1 v2 v3
    298 	 */
    299 	if (v1 < v2)
    300 		_swap_val(v1, v2);
    301 	if (v2 < v3)
    302 		_swap_val(v2, v3);
    303 	if (v1 < v2)
    304 		_swap_val(v1, v2);
    305 
    306 	/*
    307 	 * compute the middle value
    308 	 */
    309 
    310 	if (v1 - v3 < 0x200)
    311 		return (v2);
    312 
    313 	w1 = v2 - v3;
    314 	w2 = v3 - v1 + rtclock_tval;
    315 	w3 = v1 - v2;
    316 	if (w1 >= w2) {
    317 		if (w1 >= w3)
    318 		        return (v1);
    319 	} else {
    320 		if (w2 >= w3)
    321 			return (v2);
    322 	}
    323 	return (v3);
    324 }
    325 
    326 /* minimal initialization, enough for delay() */
    327 void
    328 initrtclock(u_long freq)
    329 {
    330 	u_long tval;
    331 
    332 	/*
    333 	 * Compute timer_count, the count-down count the timer will be
    334 	 * set to.  Also, correctly round
    335 	 * this by carrying an extra bit through the division.
    336 	 */
    337 	tval = (freq * 2) / (u_long) hz;
    338 	tval = (tval / 2) + (tval & 0x1);
    339 
    340 	/* initialize 8254 clock */
    341 	outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0|TIMER_RATEGEN|TIMER_16BIT);
    342 
    343 	/* Correct rounding will buy us a better precision in timekeeping */
    344 	outb(IO_TIMER1+TIMER_CNTR0, tval % 256);
    345 	outb(IO_TIMER1+TIMER_CNTR0, tval / 256);
    346 
    347 	rtclock_tval = tval ? tval : 0xFFFF;
    348 	rtclock_init = 1;
    349 }
    350 
    351 void
    352 startrtclock(void)
    353 {
    354 	int s;
    355 
    356 	if (!rtclock_init)
    357 		initrtclock(TIMER_FREQ);
    358 
    359 	/* Check diagnostic status */
    360 	if ((s = mc146818_read(NULL, NVRAM_DIAG)) != 0) { /* XXX softc */
    361 		char bits[128];
    362 		printf("RTC BIOS diagnostic error %s\n",
    363 		    bitmask_snprintf(s, NVRAM_DIAG_BITS, bits, sizeof(bits)));
    364 	}
    365 
    366 	tc_init(&i8254_timecounter);
    367 
    368 #if defined(I586_CPU) || defined(I686_CPU) || defined(__x86_64__)
    369 	init_TSC();
    370 #endif
    371 
    372 	rtc_register();
    373 }
    374 
    375 /*
    376  * Must be called at splclock().
    377  */
    378 static void
    379 tickle_tc(void)
    380 {
    381 #if defined(MULTIPROCESSOR)
    382 	struct cpu_info *ci = curcpu();
    383 	/*
    384 	 * If we are not the primary CPU, we're not allowed to do
    385 	 * any more work.
    386 	 */
    387 	if (CPU_IS_PRIMARY(ci) == 0)
    388 		return;
    389 #endif
    390 	if (rtclock_tval && timecounter->tc_get_timecount == i8254_get_timecount) {
    391 		__cpu_simple_lock(&tmr_lock);
    392 		if (i8254_ticked)
    393 			i8254_ticked    = 0;
    394 		else {
    395 			i8254_offset   += rtclock_tval;
    396 			i8254_lastcount = 0;
    397 		}
    398 		__cpu_simple_unlock(&tmr_lock);
    399 	}
    400 
    401 }
    402 
    403 static int
    404 clockintr(void *arg, struct intrframe *frame)
    405 {
    406 	tickle_tc();
    407 
    408 	hardclock((struct clockframe *)frame);
    409 
    410 #if NMCA > 0
    411 	if (MCA_system) {
    412 		/* Reset PS/2 clock interrupt by asserting bit 7 of port 0x61 */
    413 		outb(0x61, inb(0x61) | 0x80);
    414 	}
    415 #endif
    416 	return -1;
    417 }
    418 
    419 u_int
    420 i8254_get_timecount(struct timecounter *tc)
    421 {
    422 	u_int count;
    423 	u_char high, low;
    424 	u_long flags;
    425 
    426 	/* Don't want someone screwing with the counter while we're here. */
    427 	flags = x86_read_psl();
    428 	x86_disable_intr();
    429 	__cpu_simple_lock(&tmr_lock);
    430 
    431 	/* Select timer0 and latch counter value. */
    432 	outb(IO_TIMER1 + TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
    433 
    434 	low = inb(IO_TIMER1 + TIMER_CNTR0);
    435 	high = inb(IO_TIMER1 + TIMER_CNTR0);
    436 	count = rtclock_tval - ((high << 8) | low);
    437 
    438 	if (rtclock_tval && (count < i8254_lastcount || !i8254_ticked)) {
    439 		i8254_ticked = 1;
    440 		i8254_offset += rtclock_tval;
    441 	}
    442 
    443 	i8254_lastcount = count;
    444 	count += i8254_offset;
    445 
    446 	__cpu_simple_unlock(&tmr_lock);
    447 	x86_write_psl(flags);
    448 
    449 	return (count);
    450 }
    451 
    452 int
    453 gettick(void)
    454 {
    455 	u_long flags;
    456 	u_char lo, hi;
    457 
    458 	if (clock_broken_latch)
    459 		return (gettick_broken_latch());
    460 
    461 	/* Don't want someone screwing with the counter while we're here. */
    462 	flags = x86_read_psl();
    463 	x86_disable_intr();
    464 	/* Select counter 0 and latch it. */
    465 	outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
    466 	lo = inb(IO_TIMER1+TIMER_CNTR0);
    467 	hi = inb(IO_TIMER1+TIMER_CNTR0);
    468 	x86_write_psl(flags);
    469 	return ((hi << 8) | lo);
    470 }
    471 
    472 /*
    473  * Wait approximately `n' microseconds.
    474  * Relies on timer 1 counting down from (TIMER_FREQ / hz) at TIMER_FREQ Hz.
    475  * Note: timer had better have been programmed before this is first used!
    476  * (Note that we use `rate generator' mode, which counts at 1:1; `square
    477  * wave' mode counts at 2:1).
    478  * Don't rely on this being particularly accurate.
    479  */
    480 void
    481 i8254_delay(int n)
    482 {
    483 	int delay_tick, odelay_tick;
    484 	static const int delaytab[26] = {
    485 		 0,  2,  3,  4,  5,  6,  7,  9, 10, 11,
    486 		12, 13, 15, 16, 17, 18, 19, 21, 22, 23,
    487 		24, 25, 27, 28, 29, 30,
    488 	};
    489 
    490 	/* allow DELAY() to be used before startrtclock() */
    491 	if (!rtclock_init)
    492 		initrtclock(TIMER_FREQ);
    493 
    494 	/*
    495 	 * Read the counter first, so that the rest of the setup overhead is
    496 	 * counted.
    497 	 */
    498 	odelay_tick = gettick();
    499 
    500 	if (n <= 25)
    501 		n = delaytab[n];
    502 	else {
    503 #ifdef __GNUC__
    504 		/*
    505 		 * Calculate ((n * TIMER_FREQ) / 1e6) using explicit assembler
    506 		 * code so we can take advantage of the intermediate 64-bit
    507 		 * quantity to prevent loss of significance.
    508 		 */
    509 		int m;
    510 		__asm volatile("mul %3"
    511 				 : "=a" (n), "=d" (m)
    512 				 : "0" (n), "r" (TIMER_FREQ));
    513 		__asm volatile("div %4"
    514 				 : "=a" (n), "=d" (m)
    515 				 : "0" (n), "1" (m), "r" (1000000));
    516 #else
    517 		/*
    518 		 * Calculate ((n * TIMER_FREQ) / 1e6) without using floating
    519 		 * point and without any avoidable overflows.
    520 		 */
    521 		int sec = n / 1000000,
    522 		    usec = n % 1000000;
    523 		n = sec * TIMER_FREQ +
    524 		    usec * (TIMER_FREQ / 1000000) +
    525 		    usec * ((TIMER_FREQ % 1000000) / 1000) / 1000 +
    526 		    usec * (TIMER_FREQ % 1000) / 1000000;
    527 #endif
    528 	}
    529 
    530 	while (n > 0) {
    531 #ifdef CLOCK_PARANOIA
    532 		int delta;
    533 		delay_tick = gettick();
    534 		if (delay_tick > odelay_tick)
    535 			delta = rtclock_tval - (delay_tick - odelay_tick);
    536 		else
    537 			delta = odelay_tick - delay_tick;
    538 		if (delta < 0 || delta >= rtclock_tval / 2) {
    539 			DPRINTF(("delay: ignore ticks %.4x-%.4x",
    540 				 odelay_tick, delay_tick));
    541 			if (clock_broken_latch) {
    542 				DPRINTF(("  (%.4x %.4x %.4x %.4x %.4x %.4x)\n",
    543 				         ticks[0], ticks[1], ticks[2],
    544 				         ticks[3], ticks[4], ticks[5]));
    545 			} else {
    546 				DPRINTF(("\n"));
    547 			}
    548 		} else
    549 			n -= delta;
    550 #else
    551 		delay_tick = gettick();
    552 		if (delay_tick > odelay_tick)
    553 			n -= rtclock_tval - (delay_tick - odelay_tick);
    554 		else
    555 			n -= odelay_tick - delay_tick;
    556 #endif
    557 		odelay_tick = delay_tick;
    558 	}
    559 }
    560 
    561 #if (NPCPPI > 0)
    562 int
    563 sysbeepmatch(struct device *parent, struct cfdata *match,
    564     void *aux)
    565 {
    566 	return (!ppi_attached);
    567 }
    568 
    569 void
    570 sysbeepattach(struct device *parent, struct device *self,
    571     void *aux)
    572 {
    573 	aprint_naive("\n");
    574 	aprint_normal("\n");
    575 
    576 	ppicookie = ((struct pcppi_attach_args *)aux)->pa_cookie;
    577 	ppi_attached = 1;
    578 }
    579 #endif
    580 
    581 void
    582 sysbeep(int pitch, int period)
    583 {
    584 #if (NPCPPI > 0)
    585 	if (ppi_attached)
    586 		pcppi_bell(ppicookie, pitch, period, 0);
    587 #endif
    588 }
    589 
    590 void
    591 i8254_initclocks(void)
    592 {
    593 
    594 	/*
    595 	 * XXX If you're doing strange things with multiple clocks, you might
    596 	 * want to keep track of clock handlers.
    597 	 */
    598 	(void)isa_intr_establish(NULL, 0, IST_PULSE, IPL_CLOCK,
    599 	    (int (*)(void *))clockintr, 0);
    600 }
    601 
    602 static void
    603 rtcinit(void)
    604 {
    605 	static int first_rtcopen_ever = 1;
    606 
    607 	if (!first_rtcopen_ever)
    608 		return;
    609 	first_rtcopen_ever = 0;
    610 
    611 	mc146818_write(NULL, MC_REGA,			/* XXX softc */
    612 	    MC_BASE_32_KHz | MC_RATE_1024_Hz);
    613 	mc146818_write(NULL, MC_REGB, MC_REGB_24HR);	/* XXX softc */
    614 }
    615 
    616 static int
    617 rtcget(mc_todregs *regs)
    618 {
    619 
    620 	rtcinit();
    621 	if ((mc146818_read(NULL, MC_REGD) & MC_REGD_VRT) == 0) /* XXX softc */
    622 		return (-1);
    623 	MC146818_GETTOD(NULL, regs);			/* XXX softc */
    624 	return (0);
    625 }
    626 
    627 static void
    628 rtcput(mc_todregs *regs)
    629 {
    630 
    631 	rtcinit();
    632 	MC146818_PUTTOD(NULL, regs);			/* XXX softc */
    633 }
    634 
    635 /*
    636  * check whether the CMOS layout is "standard"-like (ie, not PS/2-like),
    637  * to be called at splclock()
    638  */
    639 static int
    640 cmoscheck(void)
    641 {
    642 	int i;
    643 	unsigned short cksum = 0;
    644 
    645 	for (i = 0x10; i <= 0x2d; i++)
    646 		cksum += mc146818_read(NULL, i); /* XXX softc */
    647 
    648 	return (cksum == (mc146818_read(NULL, 0x2e) << 8)
    649 			  + mc146818_read(NULL, 0x2f));
    650 }
    651 
    652 #if NMCA > 0
    653 /*
    654  * Check whether the CMOS layout is PS/2 like, to be called at splclock().
    655  */
    656 static int cmoscheckps2(void);
    657 static int
    658 cmoscheckps2(void)
    659 {
    660 #if 0
    661 	/* Disabled until I find out the CRC checksum algorithm IBM uses */
    662 	int i;
    663 	unsigned short cksum = 0;
    664 
    665 	for (i = 0x10; i <= 0x31; i++)
    666 		cksum += mc146818_read(NULL, i); /* XXX softc */
    667 
    668 	return (cksum == (mc146818_read(NULL, 0x32) << 8)
    669 			  + mc146818_read(NULL, 0x33));
    670 #else
    671 	/* Check 'incorrect checksum' bit of IBM PS/2 Diagnostic Status Byte */
    672 	return ((mc146818_read(NULL, NVRAM_DIAG) & (1<<6)) == 0);
    673 #endif
    674 }
    675 #endif /* NMCA > 0 */
    676 
    677 /*
    678  * patchable to control century byte handling:
    679  * 1: always update
    680  * -1: never touch
    681  * 0: try to figure out itself
    682  */
    683 int rtc_update_century = 0;
    684 
    685 /*
    686  * Expand a two-digit year as read from the clock chip
    687  * into full width.
    688  * Being here, deal with the CMOS century byte.
    689  */
    690 static int centb = NVRAM_CENTURY;
    691 static int
    692 clock_expandyear(int clockyear)
    693 {
    694 	int s, clockcentury, cmoscentury;
    695 
    696 	clockcentury = (clockyear < 70) ? 20 : 19;
    697 	clockyear += 100 * clockcentury;
    698 
    699 	if (rtc_update_century < 0)
    700 		return (clockyear);
    701 
    702 	s = splclock();
    703 	if (cmoscheck())
    704 		cmoscentury = mc146818_read(NULL, NVRAM_CENTURY);
    705 #if NMCA > 0
    706 	else if (MCA_system && cmoscheckps2())
    707 		cmoscentury = mc146818_read(NULL, (centb = 0x37));
    708 #endif
    709 	else
    710 		cmoscentury = 0;
    711 	splx(s);
    712 	if (!cmoscentury) {
    713 #ifdef DIAGNOSTIC
    714 		printf("clock: unknown CMOS layout\n");
    715 #endif
    716 		return (clockyear);
    717 	}
    718 	cmoscentury = bcdtobin(cmoscentury);
    719 
    720 	if (cmoscentury != clockcentury) {
    721 		/* XXX note: saying "century is 20" might confuse the naive. */
    722 		printf("WARNING: NVRAM century is %d but RTC year is %d\n",
    723 		       cmoscentury, clockyear);
    724 
    725 		/* Kludge to roll over century. */
    726 		if ((rtc_update_century > 0) ||
    727 		    ((cmoscentury == 19) && (clockcentury == 20) &&
    728 		     (clockyear == 2000))) {
    729 			printf("WARNING: Setting NVRAM century to %d\n",
    730 			       clockcentury);
    731 			s = splclock();
    732 			mc146818_write(NULL, centb, bintobcd(clockcentury));
    733 			splx(s);
    734 		}
    735 	} else if (cmoscentury == 19 && rtc_update_century == 0)
    736 		rtc_update_century = 1; /* will update later in resettodr() */
    737 
    738 	return (clockyear);
    739 }
    740 
    741 static int
    742 rtc_get_ymdhms(todr_chip_handle_t tch, struct clock_ymdhms *dt)
    743 {
    744 	int s;
    745 	mc_todregs rtclk;
    746 
    747 	s = splclock();
    748 	if (rtcget(&rtclk)) {
    749 		splx(s);
    750 		return -1;
    751 	}
    752 	splx(s);
    753 
    754 	dt->dt_sec = bcdtobin(rtclk[MC_SEC]);
    755 	dt->dt_min = bcdtobin(rtclk[MC_MIN]);
    756 	dt->dt_hour = bcdtobin(rtclk[MC_HOUR]);
    757 	dt->dt_day = bcdtobin(rtclk[MC_DOM]);
    758 	dt->dt_mon = bcdtobin(rtclk[MC_MONTH]);
    759 	dt->dt_year = clock_expandyear(bcdtobin(rtclk[MC_YEAR]));
    760 
    761 	return 0;
    762 }
    763 
    764 static int
    765 rtc_set_ymdhms(todr_chip_handle_t tch, struct clock_ymdhms *dt)
    766 {
    767 	mc_todregs rtclk;
    768 	int century;
    769 	int s;
    770 
    771 	s = splclock();
    772 	if (rtcget(&rtclk))
    773 		memset(&rtclk, 0, sizeof(rtclk));
    774 	splx(s);
    775 
    776 	rtclk[MC_SEC] = bintobcd(dt->dt_sec);
    777 	rtclk[MC_MIN] = bintobcd(dt->dt_min);
    778 	rtclk[MC_HOUR] = bintobcd(dt->dt_hour);
    779 	rtclk[MC_DOW] = dt->dt_wday + 1;
    780 	rtclk[MC_YEAR] = bintobcd(dt->dt_year % 100);
    781 	rtclk[MC_MONTH] = bintobcd(dt->dt_mon);
    782 	rtclk[MC_DOM] = bintobcd(dt->dt_day);
    783 
    784 #ifdef DEBUG_CLOCK
    785 	printf("setclock: %x/%x/%x %x:%x:%x\n", rtclk[MC_YEAR], rtclk[MC_MONTH],
    786 	   rtclk[MC_DOM], rtclk[MC_HOUR], rtclk[MC_MIN], rtclk[MC_SEC]);
    787 #endif
    788 	s = splclock();
    789 	rtcput(&rtclk);
    790 	if (rtc_update_century > 0) {
    791 		century = bintobcd(dt->dt_year / 100);
    792 		mc146818_write(NULL, centb, century); /* XXX softc */
    793 	}
    794 	splx(s);
    795 	return 0;
    796 
    797 }
    798 
    799 static void
    800 rtc_register(void)
    801 {
    802 	static struct todr_chip_handle	tch;
    803 	tch.todr_gettime_ymdhms = rtc_get_ymdhms;
    804 	tch.todr_settime_ymdhms = rtc_set_ymdhms;
    805 	tch.todr_setwen = NULL;
    806 
    807 	todr_attach(&tch);
    808 }
    809 
    810 void
    811 setstatclockrate(int arg)
    812 {
    813 }
    814