pcrtc.c revision 17256
1219820Sjeff/*-
2219820Sjeff * Copyright (c) 1990 The Regents of the University of California.
3219820Sjeff * All rights reserved.
4219820Sjeff *
5219820Sjeff * This code is derived from software contributed to Berkeley by
6219820Sjeff * William Jolitz and Don Ahn.
7219820Sjeff *
8219820Sjeff * Redistribution and use in source and binary forms, with or without
9219820Sjeff * modification, are permitted provided that the following conditions
10219820Sjeff * are met:
11219820Sjeff * 1. Redistributions of source code must retain the above copyright
12219820Sjeff *    notice, this list of conditions and the following disclaimer.
13219820Sjeff * 2. Redistributions in binary form must reproduce the above copyright
14219820Sjeff *    notice, this list of conditions and the following disclaimer in the
15219820Sjeff *    documentation and/or other materials provided with the distribution.
16219820Sjeff * 3. All advertising materials mentioning features or use of this software
17219820Sjeff *    must display the following acknowledgement:
18219820Sjeff *	This product includes software developed by the University of
19219820Sjeff *	California, Berkeley and its contributors.
20219820Sjeff * 4. Neither the name of the University nor the names of its contributors
21219820Sjeff *    may be used to endorse or promote products derived from this software
22219820Sjeff *    without specific prior written permission.
23219820Sjeff *
24219820Sjeff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25219820Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26219820Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27219820Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28219820Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29219820Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30219820Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31219820Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32219820Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33219820Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34219820Sjeff * SUCH DAMAGE.
35219820Sjeff *
36219820Sjeff *	from: @(#)clock.c	7.2 (Berkeley) 5/12/91
37219820Sjeff *	$Id: clock.c,v 1.1.1.1 1996/06/14 10:04:42 asami Exp $
38219820Sjeff */
39219820Sjeff
40219820Sjeff/*
41219820Sjeff * inittodr, settodr and support routines written
42219820Sjeff * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
43219820Sjeff *
44219820Sjeff * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
45219820Sjeff */
46219820Sjeff
47219820Sjeff/*
48219820Sjeff * modified for PC98
49219820Sjeff *	$Id: clock.c,v 1.1.1.1 1996/06/14 10:04:42 asami Exp $
50219820Sjeff */
51219820Sjeff
52219820Sjeff/*
53219820Sjeff * Primitive clock interrupt routines.
54219820Sjeff */
55219820Sjeff#include "opt_ddb.h"
56219820Sjeff#include "opt_clock.h"
57219820Sjeff
58219820Sjeff#include <sys/param.h>
59219820Sjeff#include <sys/systm.h>
60219820Sjeff#include <sys/time.h>
61219820Sjeff#include <sys/kernel.h>
62219820Sjeff#include <sys/sysctl.h>
63219820Sjeff
64219820Sjeff#include <machine/clock.h>
65219820Sjeff#ifdef CLK_CALIBRATION_LOOP
66219820Sjeff#include <machine/cons.h>
67219820Sjeff#endif
68219820Sjeff#include <machine/cpu.h>
69219820Sjeff#include <machine/frame.h>
70219820Sjeff
71219820Sjeff#ifdef PC98
72219820Sjeff#include <sys/syslog.h>
73219820Sjeff#include <pc98/pc98/icu.h>
74219820Sjeff#include <pc98/pc98/pc98.h>
75219820Sjeff#include <pc98/pc98/pc98_device.h>
76219820Sjeff#include <pc98/pc98/timerreg.h>
77219820Sjeff#else
78219820Sjeff#include <i386/isa/icu.h>
79219820Sjeff#include <i386/isa/isa.h>
80219820Sjeff#include <i386/isa/isa_device.h>
81219820Sjeff#include <i386/isa/rtc.h>
82219820Sjeff#include <i386/isa/timerreg.h>
83219820Sjeff#endif
84219820Sjeff
85219820Sjeff/*
86219820Sjeff * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
87219820Sjeff * can use a simple formula for leap years.
88219820Sjeff */
89219820Sjeff#define	LEAPYEAR(y) ((u_int)(y) % 4 == 0)
90219820Sjeff#define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
91219820Sjeff
92219820Sjeff#define	TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
93219820Sjeff
94219820Sjeff/*
95219820Sjeff * Time in timer cycles that it takes for microtime() to disable interrupts
96219820Sjeff * and latch the count.  microtime() currently uses "cli; outb ..." so it
97219820Sjeff * normally takes less than 2 timer cycles.  Add a few for cache misses.
98219820Sjeff * Add a few more to allow for latency in bogus calls to microtime() with
99219820Sjeff * interrupts already disabled.
100219820Sjeff */
101219820Sjeff#define	TIMER0_LATCH_COUNT	20
102219820Sjeff
103219820Sjeff/*
104219820Sjeff * Maximum frequency that we are willing to allow for timer0.  Must be
105219820Sjeff * low enough to guarantee that the timer interrupt handler returns
106219820Sjeff * before the next timer interrupt.  Must result in a lower TIMER_DIV
107219820Sjeff * value than TIMER0_LATCH_COUNT so that we don't have to worry about
108219820Sjeff * underflow in the calculation of timer0_overflow_threshold.
109219820Sjeff */
110219820Sjeff#define	TIMER0_MAX_FREQ		20000
111219820Sjeff
112219820Sjeffint	adjkerntz;		/* local offset	from GMT in seconds */
113219820Sjeffint	disable_rtc_set;	/* disable resettodr() if != 0 */
114219820Sjeffint	wall_cmos_clock;	/* wall	CMOS clock assumed if != 0 */
115219820Sjeff
116219820Sjeffu_int	idelayed;
117219820Sjeff#if defined(I586_CPU) || defined(I686_CPU)
118219820Sjeffunsigned	i586_ctr_freq;
119219820Sjeffunsigned	i586_ctr_rate;
120219820Sjefflong long	i586_ctr_bias;
121219820Sjefflong long	i586_last_tick;
122219820Sjeffunsigned long	i586_avg_tick;
123219820Sjeff#endif
124219820Sjeffint	statclock_disable;
125219820Sjeffu_int	stat_imask = SWI_CLOCK_MASK;
126219820Sjeff#ifdef TIMER_FREQ
127219820Sjeffstatic	u_int	timer_freq = TIMER_FREQ;
128219820Sjeff#else
129219820Sjeff#ifdef PC98
130219820Sjeff#ifndef AUTO_CLOCK
131219820Sjeff#ifndef PC98_8M
132219820Sjeffstatic	u_int	timer_freq = 2457600;
133219820Sjeff#else	/* !PC98_8M */
134219820Sjeffstatic	u_int	timer_freq = 1996800;
135219820Sjeff#endif	/* PC98_8M */
136219820Sjeff#else	/* AUTO_CLOCK */
137219820Sjeffstatic	u_int	timer_freq = 2457600;
138219820Sjeff#endif	/* AUTO_CLOCK */
139219820Sjeff#else /* IBM-PC */
140219820Sjeffstatic	u_int	timer_freq = 1193182;
141219820Sjeff#endif /* PC98 */
142219820Sjeff#endif
143219820Sjeffint 	timer0_max_count;
144219820Sjeffu_int 	timer0_overflow_threshold;
145219820Sjeffu_int 	timer0_prescaler_count;
146219820Sjeff
147219820Sjeffstatic	int	beeping = 0;
148219820Sjeffstatic	u_int	clk_imask = HWI_MASK | SWI_MASK;
149219820Sjeffstatic	const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
150219820Sjeffstatic 	u_int	hardclock_max_count;
151219820Sjeff/*
152219820Sjeff * XXX new_function and timer_func should not handle clockframes, but
153219820Sjeff * timer_func currently needs to hold hardclock to handle the
154219820Sjeff * timer0_state == 0 case.  We should use register_intr()/unregister_intr()
155219820Sjeff * to switch between clkintr() and a slightly different timerintr().
156219820Sjeff */
157219820Sjeffstatic 	void	(*new_function) __P((struct clockframe *frame));
158219820Sjeffstatic 	u_int	new_rate;
159219820Sjeff#ifndef PC98
160219820Sjeffstatic	u_char	rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
161219820Sjeffstatic	u_char	rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
162219820Sjeff#endif
163219820Sjeff
164219820Sjeff/* Values for timerX_state: */
165219820Sjeff#define	RELEASED	0
166219820Sjeff#define	RELEASE_PENDING	1
167219820Sjeff#define	ACQUIRED	2
168219820Sjeff#define	ACQUIRE_PENDING	3
169219820Sjeff
170219820Sjeffstatic 	u_char	timer0_state;
171219820Sjeff#ifdef	PC98
172219820Sjeffstatic 	u_char	timer1_state;
173219820Sjeff#endif
174219820Sjeffstatic	u_char	timer2_state;
175219820Sjeffstatic 	void	(*timer_func) __P((struct clockframe *frame)) = hardclock;
176219820Sjeffint		rtc_inb __P((void));
177219820Sjeff
178219820Sjeffstatic void
179219820Sjeffclkintr(struct clockframe frame)
180219820Sjeff{
181219820Sjeff	timer_func(&frame);
182219820Sjeff	switch (timer0_state) {
183219820Sjeff
184219820Sjeff	case RELEASED:
185219820Sjeff		setdelayed();
186219820Sjeff		break;
187219820Sjeff
188219820Sjeff	case ACQUIRED:
189219820Sjeff		if ((timer0_prescaler_count += timer0_max_count)
190219820Sjeff		    >= hardclock_max_count) {
191219820Sjeff			hardclock(&frame);
192219820Sjeff			setdelayed();
193219820Sjeff			timer0_prescaler_count -= hardclock_max_count;
194219820Sjeff		}
195219820Sjeff		break;
196219820Sjeff
197219820Sjeff	case ACQUIRE_PENDING:
198219820Sjeff		setdelayed();
199219820Sjeff		timer0_max_count = TIMER_DIV(new_rate);
200219820Sjeff		timer0_overflow_threshold =
201219820Sjeff			timer0_max_count - TIMER0_LATCH_COUNT;
202219820Sjeff		disable_intr();
203219820Sjeff		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
204219820Sjeff		outb(TIMER_CNTR0, timer0_max_count & 0xff);
205219820Sjeff		outb(TIMER_CNTR0, timer0_max_count >> 8);
206219820Sjeff		enable_intr();
207219820Sjeff		timer0_prescaler_count = 0;
208219820Sjeff		timer_func = new_function;
209219820Sjeff		timer0_state = ACQUIRED;
210219820Sjeff		break;
211219820Sjeff
212219820Sjeff	case RELEASE_PENDING:
213219820Sjeff		if ((timer0_prescaler_count += timer0_max_count)
214219820Sjeff		    >= hardclock_max_count) {
215219820Sjeff			hardclock(&frame);
216219820Sjeff			setdelayed();
217219820Sjeff			timer0_max_count = hardclock_max_count;
218219820Sjeff			timer0_overflow_threshold =
219219820Sjeff				timer0_max_count - TIMER0_LATCH_COUNT;
220219820Sjeff			disable_intr();
221219820Sjeff			outb(TIMER_MODE,
222219820Sjeff			     TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
223219820Sjeff			outb(TIMER_CNTR0, timer0_max_count & 0xff);
224219820Sjeff			outb(TIMER_CNTR0, timer0_max_count >> 8);
225219820Sjeff			enable_intr();
226219820Sjeff			/*
227219820Sjeff			 * See microtime.s for this magic.
228219820Sjeff			 */
229219820Sjeff#ifdef PC98
230219820Sjeff#ifndef AUTO_CLOCK
231219820Sjeff#ifndef PC98_8M
232219820Sjeff			time.tv_usec += (6667 *
233219820Sjeff				(timer0_prescaler_count - hardclock_max_count))
234219820Sjeff				>> 14;
235219820Sjeff#else /* PC98_8M */
236219820Sjeff			time.tv_usec += (16411 *
237219820Sjeff				(timer0_prescaler_count - hardclock_max_count))
238219820Sjeff				>> 15;
239219820Sjeff#endif /* PC98_8M */
240219820Sjeff#else /* AUTO_CLOCK */
241219820Sjeff			if (pc98_machine_type & M_8M) {
242219820Sjeff				/* PC98_8M */
243219820Sjeff				time.tv_usec += (16411 *
244219820Sjeff					(timer0_prescaler_count -
245219820Sjeff					 hardclock_max_count)) >> 15;
246219820Sjeff			} else {
247219820Sjeff				time.tv_usec += (6667 *
248219820Sjeff					(timer0_prescaler_count -
249219820Sjeff					 hardclock_max_count)) >> 14;
250219820Sjeff			}
251219820Sjeff#endif /* AUTO_CLOCK */
252219820Sjeff#else /* IBM-PC */
253219820Sjeff			time.tv_usec += (27465 *
254219820Sjeff				(timer0_prescaler_count - hardclock_max_count))
255219820Sjeff				>> 15;
256219820Sjeff#endif /* PC98 */
257219820Sjeff			if (time.tv_usec >= 1000000)
258219820Sjeff				time.tv_usec -= 1000000;
259219820Sjeff			timer0_prescaler_count = 0;
260219820Sjeff			timer_func = hardclock;
261219820Sjeff			timer0_state = RELEASED;
262219820Sjeff		}
263219820Sjeff		break;
264219820Sjeff	}
265219820Sjeff}
266219820Sjeff
267219820Sjeff/*
268219820Sjeff * The acquire and release functions must be called at ipl >= splclock().
269219820Sjeff */
270219820Sjeffint
271219820Sjeffacquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
272219820Sjeff{
273219820Sjeff	static int old_rate;
274219820Sjeff
275219820Sjeff	if (rate <= 0 || rate > TIMER0_MAX_FREQ)
276219820Sjeff		return (-1);
277219820Sjeff	switch (timer0_state) {
278219820Sjeff
279219820Sjeff	case RELEASED:
280219820Sjeff		timer0_state = ACQUIRE_PENDING;
281		break;
282
283	case RELEASE_PENDING:
284		if (rate != old_rate)
285			return (-1);
286		/*
287		 * The timer has been released recently, but is being
288		 * re-acquired before the release completed.  In this
289		 * case, we simply reclaim it as if it had not been
290		 * released at all.
291		 */
292		timer0_state = ACQUIRED;
293		break;
294
295	default:
296		return (-1);	/* busy */
297	}
298	new_function = function;
299	old_rate = new_rate = rate;
300	return (0);
301}
302
303#ifdef PC98
304int
305acquire_timer1(int mode)
306{
307
308	if (timer1_state != RELEASED)
309		return (-1);
310	timer1_state = ACQUIRED;
311
312	/*
313	 * This access to the timer registers is as atomic as possible
314	 * because it is a single instruction.  We could do better if we
315	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
316	 * and this is probably good enough for timer2, so we aren't as
317	 * careful with it as with timer0.
318	 */
319	outb(TIMER_MODE, TIMER_SEL1 | (mode & 0x3f));
320
321	return (0);
322}
323#endif
324
325int
326acquire_timer2(int mode)
327{
328
329	if (timer2_state != RELEASED)
330		return (-1);
331	timer2_state = ACQUIRED;
332
333	/*
334	 * This access to the timer registers is as atomic as possible
335	 * because it is a single instruction.  We could do better if we
336	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
337	 * and this is probably good enough for timer2, so we aren't as
338	 * careful with it as with timer0.
339	 */
340	outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
341
342	return (0);
343}
344
345int
346release_timer0()
347{
348	switch (timer0_state) {
349
350	case ACQUIRED:
351		timer0_state = RELEASE_PENDING;
352		break;
353
354	case ACQUIRE_PENDING:
355		/* Nothing happened yet, release quickly. */
356		timer0_state = RELEASED;
357		break;
358
359	default:
360		return (-1);
361	}
362	return (0);
363}
364
365#ifdef PC98
366int
367release_timer1()
368{
369
370	if (timer1_state != ACQUIRED)
371		return (-1);
372	timer1_state = RELEASED;
373	outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
374	return (0);
375}
376#endif
377
378int
379release_timer2()
380{
381
382	if (timer2_state != ACQUIRED)
383		return (-1);
384	timer2_state = RELEASED;
385	outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
386	return (0);
387}
388
389#ifndef PC98
390/*
391 * This routine receives statistical clock interrupts from the RTC.
392 * As explained above, these occur at 128 interrupts per second.
393 * When profiling, we receive interrupts at a rate of 1024 Hz.
394 *
395 * This does not actually add as much overhead as it sounds, because
396 * when the statistical clock is active, the hardclock driver no longer
397 * needs to keep (inaccurate) statistics on its own.  This decouples
398 * statistics gathering from scheduling interrupts.
399 *
400 * The RTC chip requires that we read status register C (RTC_INTR)
401 * to acknowledge an interrupt, before it will generate the next one.
402 */
403static void
404rtcintr(struct clockframe frame)
405{
406	u_char stat;
407	stat = rtcin(RTC_INTR);
408	if(stat & RTCIR_PERIOD) {
409		statclock(&frame);
410	}
411}
412
413#ifdef DDB
414static void
415DDB_printrtc(void)
416{
417	printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
418	       rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
419	       rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
420	       rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
421}
422#endif
423#endif /* for PC98 */
424
425static int
426getit(void)
427{
428	u_long ef;
429	int high, low;
430
431	ef = read_eflags();
432	disable_intr();
433
434	/* Select timer0 and latch counter value. */
435	outb(TIMER_MODE, TIMER_SEL0);
436
437	low = inb(TIMER_CNTR0);
438	high = inb(TIMER_CNTR0);
439
440	write_eflags(ef);
441	return ((high << 8) | low);
442}
443
444/*
445 * Wait "n" microseconds.
446 * Relies on timer 1 counting down from (timer_freq / hz)
447 * Note: timer had better have been programmed before this is first used!
448 */
449void
450DELAY(int n)
451{
452	int prev_tick, tick, ticks_left, sec, usec;
453
454#ifdef DELAYDEBUG
455	int getit_calls = 1;
456	int n1;
457	static int state = 0;
458
459	if (state == 0) {
460		state = 1;
461		for (n1 = 1; n1 <= 10000000; n1 *= 10)
462			DELAY(n1);
463		state = 2;
464	}
465	if (state == 1)
466		printf("DELAY(%d)...", n);
467#endif
468	/*
469	 * Read the counter first, so that the rest of the setup overhead is
470	 * counted.  Guess the initial overhead is 20 usec (on most systems it
471	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
472	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
473	 * multiplications and divisions to scale the count take a while).
474	 */
475	prev_tick = getit();
476	n -= 20;
477	/*
478	 * Calculate (n * (timer_freq / 1e6)) without using floating point
479	 * Calculate (n * (TIMER_FREQ / 1e6)) without using floating point
480	 * and without any avoidable overflows.
481	 */
482	sec = n / 1000000;
483	usec = n - sec * 1000000;
484	ticks_left = sec * timer_freq
485		     + usec * (timer_freq / 1000000)
486		     + usec * ((timer_freq % 1000000) / 1000) / 1000
487		     + usec * (timer_freq % 1000) / 1000000;
488	if (n < 0)
489		ticks_left = 0;	/* XXX timer_freq is unsigned */
490
491	while (ticks_left > 0) {
492		tick = getit();
493#ifdef DELAYDEBUG
494		++getit_calls;
495#endif
496		if (tick > prev_tick)
497			ticks_left -= prev_tick - (tick - timer0_max_count);
498		else
499			ticks_left -= prev_tick - tick;
500		prev_tick = tick;
501	}
502#ifdef DELAYDEBUG
503	if (state == 1)
504		printf(" %d calls to getit() at %d usec each\n",
505		       getit_calls, (n + 5) / getit_calls);
506#endif
507}
508
509static void
510sysbeepstop(void *chan)
511{
512#ifdef PC98	/* PC98 */
513	outb(IO_PPI, inb(IO_PPI)|0x08);	/* disable counter1 output to speaker */
514	release_timer1();
515#else
516	outb(IO_PPI, inb(IO_PPI)&0xFC);	/* disable counter2 output to speaker */
517	release_timer2();
518#endif
519	beeping = 0;
520}
521
522int
523sysbeep(int pitch, int period)
524{
525	int x = splclock();
526
527#ifdef PC98
528	if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
529		if (!beeping) {
530			/* Something else owns it. */
531			splx(x);
532			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
533		}
534	disable_intr();
535	outb(0x3fdb, pitch);
536	outb(0x3fdb, (pitch>>8));
537	enable_intr();
538	if (!beeping) {
539		/* enable counter1 output to speaker */
540		outb(IO_PPI, (inb(IO_PPI) & 0xf7));
541		beeping = period;
542		timeout(sysbeepstop, (void *)NULL, period);
543	}
544#else
545	if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
546		if (!beeping) {
547			/* Something else owns it. */
548			splx(x);
549			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
550		}
551	disable_intr();
552	outb(TIMER_CNTR2, pitch);
553	outb(TIMER_CNTR2, (pitch>>8));
554	enable_intr();
555	if (!beeping) {
556		/* enable counter2 output to speaker */
557		outb(IO_PPI, inb(IO_PPI) | 3);
558		beeping = period;
559		timeout(sysbeepstop, (void *)NULL, period);
560	}
561#endif
562	splx(x);
563	return (0);
564}
565
566#ifndef PC98
567/*
568 * RTC support routines
569 */
570
571int
572rtcin(reg)
573	int reg;
574{
575	u_char val;
576
577	outb(IO_RTC, reg);
578	inb(0x84);
579	val = inb(IO_RTC + 1);
580	inb(0x84);
581	return (val);
582}
583
584static __inline void
585writertc(u_char reg, u_char val)
586{
587	outb(IO_RTC, reg);
588	outb(IO_RTC + 1, val);
589}
590
591static __inline int
592readrtc(int port)
593{
594	return(bcd2bin(rtcin(port)));
595}
596#endif
597
598#ifdef PC98
599unsigned int delaycount;
600#define FIRST_GUESS	0x2000
601static void findcpuspeed(void)
602{
603	int i;
604	int remainder;
605
606	/* Put counter in count down mode */
607	outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
608	outb(TIMER_CNTR0, 0xff);
609	outb(TIMER_CNTR0, 0xff);
610	for (i = FIRST_GUESS; i; i--)
611		;
612	remainder = getit();
613	delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
614}
615#endif
616
617#ifndef PC98
618static u_int
619calibrate_clocks(void)
620{
621	u_int count, prev_count, tot_count;
622	int sec, start_sec, timeout;
623
624	printf("Calibrating clock(s) relative to mc146818A clock...\n");
625	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
626		goto fail;
627	timeout = 100000000;
628
629	/* Read the mc146818A seconds counter. */
630	for (;;) {
631		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
632			sec = rtcin(RTC_SEC);
633			break;
634		}
635		if (--timeout == 0)
636			goto fail;
637	}
638
639	/* Wait for the mC146818A seconds counter to change. */
640	start_sec = sec;
641	for (;;) {
642		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
643			sec = rtcin(RTC_SEC);
644			if (sec != start_sec)
645				break;
646		}
647		if (--timeout == 0)
648			goto fail;
649	}
650
651	/* Start keeping track of the i8254 counter. */
652	prev_count = getit();
653	if (prev_count == 0 || prev_count > timer0_max_count)
654		goto fail;
655	tot_count = 0;
656
657#if defined(I586_CPU) || defined(I686_CPU)
658	if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)
659		wrmsr(0x10, 0LL);	/* XXX 0x10 is the MSR for the TSC */
660#endif
661
662	/*
663	 * Wait for the mc146818A seconds counter to change.  Read the i8254
664	 * counter for each iteration since this is convenient and only
665	 * costs a few usec of inaccuracy. The timing of the final reads
666	 * of the counters almost matches the timing of the initial reads,
667	 * so the main cause of inaccuracy is the varying latency from
668	 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
669	 * rtcin(RTC_SEC) that returns a changed seconds count.  The
670	 * maximum inaccuracy from this cause is < 10 usec on 486's.
671	 */
672	start_sec = sec;
673	for (;;) {
674		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
675			sec = rtcin(RTC_SEC);
676		count = getit();
677		if (count == 0 || count > timer0_max_count)
678			goto fail;
679		if (count > prev_count)
680			tot_count += prev_count - (count - timer0_max_count);
681		else
682			tot_count += prev_count - count;
683		prev_count = count;
684		if (sec != start_sec)
685			break;
686		if (--timeout == 0)
687			goto fail;
688	}
689
690#if defined(I586_CPU) || defined(I686_CPU)
691	/*
692	 * Read the cpu cycle counter.  The timing considerations are
693	 * similar to those for the i8254 clock.
694	 */
695	if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686) {
696		unsigned long long i586_count;
697
698		i586_count = rdtsc();
699		i586_ctr_freq = i586_count;
700		i586_ctr_rate = (i586_count << I586_CTR_RATE_SHIFT) / 1000000;
701		printf("i586 clock: %u Hz, ", i586_ctr_freq);
702	}
703#endif
704
705	printf("i8254 clock: %u Hz\n", tot_count);
706	return (tot_count);
707
708fail:
709	printf("failed, using default i8254 clock of %u Hz\n", timer_freq);
710	return (timer_freq);
711}
712#endif	/* !PC98 */
713
714static void
715set_timer_freq(u_int freq, int intr_freq)
716{
717	u_long ef;
718
719	ef = read_eflags();
720	disable_intr();
721	timer_freq = freq;
722	timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
723	timer0_overflow_threshold = timer0_max_count - TIMER0_LATCH_COUNT;
724	outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
725	outb(TIMER_CNTR0, timer0_max_count & 0xff);
726	outb(TIMER_CNTR0, timer0_max_count >> 8);
727	write_eflags(ef);
728}
729
730/*
731 * Initialize 8253 timer 0 early so that it can be used in DELAY().
732 * XXX initialization of other timers is unintentionally left blank.
733 */
734void
735startrtclock()
736{
737	u_int delta, freq;
738
739#ifdef PC98
740	findcpuspeed();
741#ifndef AUTO_CLOCK
742	if (pc98_machine_type & M_8M) {
743#ifndef	PC98_8M
744		log(LOG_EMERG,
745		    "you must reconfig a kernel with \"PC98_8M\" option.\n");
746#endif
747	} else {
748#ifdef	PC98_8M
749		log(LOG_EMERG,
750		    "You must reconfig a kernel without \"PC98_8M\" option.\n");
751#endif
752	}
753#else /* AUTO_CLOCK */
754	if (pc98_machine_type & M_8M)
755		timer_freq = 1996800L; /* 1.9968 MHz */
756	else
757		timer_freq = 2457600L; /* 2.4576 MHz */
758#endif /* AUTO_CLOCK */
759#endif /* PC98 */
760
761#ifndef PC98
762	writertc(RTC_STATUSA, rtc_statusa);
763	writertc(RTC_STATUSB, RTCSB_24HR);
764#endif
765
766#ifndef PC98
767	set_timer_freq(timer_freq, hz);
768	freq = calibrate_clocks();
769#ifdef CLK_CALIBRATION_LOOP
770	if (bootverbose) {
771		printf(
772		"Press a key on the console to abort clock calibration\n");
773		while (!cncheckc())
774			calibrate_clocks();
775	}
776#endif
777
778	/*
779	 * Use the calibrated i8254 frequency if it seems reasonable.
780	 * Otherwise use the default, and don't use the calibrated i586
781	 * frequency.
782	 */
783	delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
784	if (delta < timer_freq / 100) {
785#ifndef CLK_USE_I8254_CALIBRATION
786		if (bootverbose)
787		    printf(
788"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
789		freq = timer_freq;
790#endif
791		timer_freq = freq;
792	} else {
793		printf("%d Hz differs from default of %d Hz by more than 1%%\n",
794		       freq, timer_freq);
795#if defined(I586_CPU) || defined(I686_CPU)
796		i586_ctr_freq = 0;
797		i586_ctr_rate = 0;
798#endif
799	}
800#endif
801
802	set_timer_freq(timer_freq, hz);
803
804#if defined(I586_CPU) || defined(I686_CPU)
805#ifndef CLK_USE_I586_CALIBRATION
806	if (i586_ctr_rate != 0) {
807		if (bootverbose)
808		    printf(
809"CLK_USE_I586_CALIBRATION not specified - using old calibration method\n");
810		i586_ctr_freq = 0;
811		i586_ctr_rate = 0;
812	}
813#endif
814	if (i586_ctr_rate == 0 &&
815	    (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)) {
816		/*
817		 * Calibration of the i586 clock relative to the mc146818A
818		 * clock failed.  Do a less accurate calibration relative
819		 * to the i8254 clock.
820		 */
821		unsigned long long i586_count;
822
823		wrmsr(0x10, 0LL);	/* XXX */
824		DELAY(1000000);
825		i586_count = rdtsc();
826		i586_ctr_rate = (i586_count << I586_CTR_RATE_SHIFT) / 1000000;
827#ifdef CLK_USE_I586_CALIBRATION
828		printf("i586 clock: %u Hz\n", i586_ctr_freq);
829#endif
830	}
831#endif
832}
833
834#ifdef PC98
835void
836rtc_serialcombit(int i)
837{
838	outb(IO_RTC, ((i&0x01)<<5)|0x07);
839	DELAY(1);
840	outb(IO_RTC, ((i&0x01)<<5)|0x17);
841	DELAY(1);
842	outb(IO_RTC, ((i&0x01)<<5)|0x07);
843	DELAY(1);
844}
845
846void
847rtc_serialcom(int i)
848{
849	rtc_serialcombit(i&0x01);
850	rtc_serialcombit((i&0x02)>>1);
851	rtc_serialcombit((i&0x04)>>2);
852	rtc_serialcombit((i&0x08)>>3);
853	outb(IO_RTC, 0x07);
854	DELAY(1);
855	outb(IO_RTC, 0x0f);
856	DELAY(1);
857	outb(IO_RTC, 0x07);
858 	DELAY(1);
859}
860
861void
862rtc_outb(int val)
863{
864	int s;
865	int sa = 0;
866
867	for (s=0;s<8;s++) {
868	    sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
869	    outb(IO_RTC, sa);		/* set DI & CLK 0 */
870	    DELAY(1);
871	    outb(IO_RTC, sa | 0x10);	/* CLK 1 */
872	    DELAY(1);
873	}
874	outb(IO_RTC, sa & 0xef);	/* CLK 0 */
875}
876
877int
878rtc_inb(void)
879{
880	int s;
881	int sa = 0;
882
883	for (s=0;s<8;s++) {
884	    sa |= ((inb(0x33) & 0x01) << s);
885	    outb(IO_RTC, 0x17);	/* CLK 1 */
886	    DELAY(1);
887	    outb(IO_RTC, 0x07);	/* CLK 0 */
888	    DELAY(2);
889	}
890	return sa;
891}
892#endif /* PC-98 */
893
894/*
895 * Initialize the time of day register,	based on the time base which is, e.g.
896 * from	a filesystem.
897 */
898void
899inittodr(time_t base)
900{
901	unsigned long	sec, days;
902	int		yd;
903	int		year, month;
904	int		y, m, s;
905#ifdef PC98
906	int		second, min, hour;
907#endif
908
909	s = splclock();
910	time.tv_sec  = base;
911	time.tv_usec = 0;
912	splx(s);
913
914#ifdef PC98
915	rtc_serialcom(0x03);	/* Time Read */
916	rtc_serialcom(0x01);	/* Register shift command. */
917	DELAY(20);
918
919	second = bcd2bin(rtc_inb() & 0xff);	/* sec */
920	min = bcd2bin(rtc_inb() & 0xff);	/* min */
921	hour = bcd2bin(rtc_inb() & 0xff);	/* hour */
922	days = bcd2bin(rtc_inb() & 0xff) - 1;	/* date */
923
924	month = (rtc_inb() >> 4) & 0x0f;	/* month */
925	for (m = 1; m <	month; m++)
926		days +=	daysinmonth[m-1];
927	year = bcd2bin(rtc_inb() & 0xff) + 1900;	/* year */
928	/* 2000 year problem */
929	if (year < 1995)
930		year += 100;
931	if (year < 1970)
932		goto wrong_time;
933	for (y = 1970; y < year; y++)
934		days +=	DAYSPERYEAR + LEAPYEAR(y);
935	if ((month > 2)	&& LEAPYEAR(year))
936		days ++;
937	sec = ((( days * 24 +
938		  hour) * 60 +
939		  min) * 60 +
940		  second);
941	/* sec now contains the	number of seconds, since Jan 1 1970,
942	   in the local	time zone */
943#else	/* IBM-PC */
944	/* Look	if we have a RTC present and the time is valid */
945	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
946		goto wrong_time;
947
948	/* wait	for time update	to complete */
949	/* If RTCSA_TUP	is zero, we have at least 244us	before next update */
950	while (rtcin(RTC_STATUSA) & RTCSA_TUP);
951
952	days = 0;
953#ifdef USE_RTC_CENTURY
954	year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY)	* 100;
955#else
956	year = readrtc(RTC_YEAR) + 1900;
957	if (year < 1970)
958		year += 100;
959#endif
960	if (year < 1970)
961		goto wrong_time;
962	month =	readrtc(RTC_MONTH);
963	for (m = 1; m <	month; m++)
964		days +=	daysinmonth[m-1];
965	if ((month > 2)	&& LEAPYEAR(year))
966		days ++;
967	days +=	readrtc(RTC_DAY) - 1;
968	yd = days;
969	for (y = 1970; y < year; y++)
970		days +=	DAYSPERYEAR + LEAPYEAR(y);
971	sec = ((( days * 24 +
972		  readrtc(RTC_HRS)) * 60 +
973		  readrtc(RTC_MIN)) * 60 +
974		  readrtc(RTC_SEC));
975	/* sec now contains the	number of seconds, since Jan 1 1970,
976	   in the local	time zone */
977#endif
978
979	sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
980
981	s = splclock();
982	time.tv_sec = sec;
983	splx(s);
984	return;
985
986wrong_time:
987	printf("Invalid	time in	real time clock.\n");
988	printf("Check and reset	the date immediately!\n");
989}
990
991/*
992 * Write system	time back to RTC
993 */
994void
995resettodr()
996{
997	unsigned long	tm;
998	int		y, m, s;
999#ifdef PC98
1000	int		wd;
1001#endif
1002
1003	if (disable_rtc_set)
1004		return;
1005
1006	s = splclock();
1007	tm = time.tv_sec;
1008	splx(s);
1009
1010#ifdef PC98
1011	rtc_serialcom(0x01);	/* Register shift command. */
1012
1013	/* Calculate local time	to put in RTC */
1014
1015	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1016
1017	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1018	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1019	rtc_outb(bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1020
1021	/* We have now the days	since 01-01-1970 in tm */
1022	wd = (tm+4)%7;
1023	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1024	     tm >= m;
1025	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1026	     tm -= m;
1027
1028	/* Now we have the years in y and the day-of-the-year in tm */
1029	for (m = 0; ; m++) {
1030		int ml;
1031
1032		ml = daysinmonth[m];
1033		if (m == 1 && LEAPYEAR(y))
1034			ml++;
1035		if (tm < ml)
1036			break;
1037		tm -= ml;
1038	}
1039
1040	m++;
1041	rtc_outb(bin2bcd(tm+1));		/* Write back Day     */
1042	rtc_outb((m << 4) | wd);		/* Write back Month & Weekday  */
1043	rtc_outb(bin2bcd(y%100));		/* Write back Year    */
1044
1045	rtc_serialcom(0x02);	/* Time set & Counter hold command. */
1046	rtc_serialcom(0x00);	/* Register hold command. */
1047#else
1048	/* Disable RTC updates and interrupts. */
1049	writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1050
1051	/* Calculate local time	to put in RTC */
1052
1053	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1054
1055	writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1056	writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1057	writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1058
1059	/* We have now the days	since 01-01-1970 in tm */
1060	writertc(RTC_WDAY, (tm+4)%7);			/* Write back Weekday */
1061	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1062	     tm >= m;
1063	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1064	     tm -= m;
1065
1066	/* Now we have the years in y and the day-of-the-year in tm */
1067	writertc(RTC_YEAR, bin2bcd(y%100));		/* Write back Year    */
1068#ifdef USE_RTC_CENTURY
1069	writertc(RTC_CENTURY, bin2bcd(y/100));		/* ... and Century    */
1070#endif
1071	for (m = 0; ; m++) {
1072		int ml;
1073
1074		ml = daysinmonth[m];
1075		if (m == 1 && LEAPYEAR(y))
1076			ml++;
1077		if (tm < ml)
1078			break;
1079		tm -= ml;
1080	}
1081
1082	writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
1083	writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
1084
1085	/* Reenable RTC updates and interrupts. */
1086	writertc(RTC_STATUSB, rtc_statusb);
1087#endif
1088}
1089
1090/*
1091 * Start both clocks running.
1092 */
1093void
1094cpu_initclocks()
1095{
1096#ifndef PC98
1097	int diag;
1098
1099	if (statclock_disable) {
1100		/*
1101		 * The stat interrupt mask is different without the
1102		 * statistics clock.  Also, don't set the interrupt
1103		 * flag which would normally cause the RTC to generate
1104		 * interrupts.
1105		 */
1106		stat_imask = HWI_MASK | SWI_MASK;
1107		rtc_statusb = RTCSB_24HR;
1108	} else {
1109	        /* Setting stathz to nonzero early helps avoid races. */
1110		stathz = RTC_NOPROFRATE;
1111		profhz = RTC_PROFRATE;
1112        }
1113#endif
1114
1115	/* Finish initializing 8253 timer 0. */
1116	register_intr(/* irq */ 0, /* XXX id */ 0, /* flags */ 0,
1117		      /* XXX */ (inthand2_t *)clkintr, &clk_imask,
1118		      /* unit */ 0);
1119	INTREN(IRQ0);
1120#if defined(I586_CPU) || defined(I686_CPU)
1121	/*
1122	 * Finish setting up anti-jitter measures.
1123	 */
1124	if (i586_ctr_rate) {
1125		i586_last_tick = rdtsc();
1126		i586_ctr_bias = i586_last_tick;
1127	}
1128#endif
1129
1130#ifndef PC98
1131	/* Initialize RTC. */
1132	writertc(RTC_STATUSA, rtc_statusa);
1133	writertc(RTC_STATUSB, RTCSB_24HR);
1134
1135static int
1136sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
1137{
1138	int error;
1139	u_int freq;
1140
1141	/*
1142	 * Use `i8254' instead of `timer' in external names because `timer'
1143	 * is is too generic.  Should use it everywhere.
1144	 */
1145	freq = timer_freq;
1146	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1147	if (error == 0 && freq != timer_freq) {
1148		if (timer0_state != 0)
1149			return (EBUSY);	/* too much trouble to handle */
1150		set_timer_freq(freq, hz);
1151	}
1152	return (error);
1153}
1154
1155SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1156	    0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1157
1158#if defined(I586_CPU) || defined(I686_CPU)
1159static int
1160sysctl_machdep_i586_freq SYSCTL_HANDLER_ARGS
1161{
1162	int error;
1163	u_int freq;
1164
1165	if (i586_ctr_rate == 0)
1166		return (EOPNOTSUPP);
1167	freq = i586_ctr_freq;
1168	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1169	if (error == 0 && freq != i586_ctr_freq) {
1170		i586_ctr_freq = freq;
1171		i586_ctr_rate = ((unsigned long long)freq <<
1172				 I586_CTR_RATE_SHIFT) / 1000000;
1173	}
1174	return (error);
1175}
1176
1177SYSCTL_PROC(_machdep, OID_AUTO, i586_freq, CTLTYPE_INT | CTLFLAG_RW,
1178	    0, sizeof(u_int), sysctl_machdep_i586_freq, "I", "");
1179#endif /* defined(I586_CPU) || defined(I686_CPU) */
1180
1181	/* Don't bother enabling the statistics clock. */
1182	if (statclock_disable)
1183		return;
1184	diag = rtcin(RTC_DIAG);
1185	if (diag != 0)
1186		printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1187	register_intr(/* irq */ 8, /* XXX id */ 1, /* flags */ 0,
1188		      /* XXX */ (inthand2_t *)rtcintr, &stat_imask,
1189		      /* unit */ 0);
1190	INTREN(IRQ8);
1191	writertc(RTC_STATUSB, rtc_statusb);
1192#endif
1193}
1194
1195void
1196setstatclockrate(int newhz)
1197{
1198#ifndef PC98
1199	if (newhz == RTC_PROFRATE)
1200		rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1201	else
1202		rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1203	writertc(RTC_STATUSA, rtc_statusa);
1204#endif
1205}
1206