pcrtc.c revision 21268
1251738Sadrian/*-
2251738Sadrian * Copyright (c) 1990 The Regents of the University of California.
3251738Sadrian * All rights reserved.
4251738Sadrian *
5251738Sadrian * This code is derived from software contributed to Berkeley by
6264400Simp * William Jolitz and Don Ahn.
7251738Sadrian *
8251738Sadrian * Redistribution and use in source and binary forms, with or without
9251738Sadrian * modification, are permitted provided that the following conditions
10251738Sadrian * are met:
11251738Sadrian * 1. Redistributions of source code must retain the above copyright
12251738Sadrian *    notice, this list of conditions and the following disclaimer.
13251738Sadrian * 2. Redistributions in binary form must reproduce the above copyright
14251738Sadrian *    notice, this list of conditions and the following disclaimer in the
15251738Sadrian *    documentation and/or other materials provided with the distribution.
16251738Sadrian * 3. All advertising materials mentioning features or use of this software
17251738Sadrian *    must display the following acknowledgement:
18251738Sadrian *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *	from: @(#)clock.c	7.2 (Berkeley) 5/12/91
37 *	$Id: clock.c,v 1.10 1996/10/30 22:39:48 asami Exp $
38 */
39
40/*
41 * Routines to handle clock hardware.
42 */
43
44/*
45 * inittodr, settodr and support routines written
46 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
47 *
48 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
49 */
50
51/*
52 * modified for PC98 by Kakefuda
53 */
54
55#include "opt_clock.h"
56#include "opt_cpu.h"
57
58#include <sys/param.h>
59#include <sys/systm.h>
60#include <sys/time.h>
61#include <sys/kernel.h>
62#include <sys/sysctl.h>
63
64#include <machine/clock.h>
65#ifdef CLK_CALIBRATION_LOOP
66#include <machine/cons.h>
67#endif
68#include <machine/cpu.h>
69#include <machine/frame.h>
70
71#include <i386/isa/icu.h>
72#ifdef PC98
73#include <pc98/pc98/pc98.h>
74#include <i386/isa/isa_device.h>
75#else
76#include <i386/isa/isa.h>
77#include <i386/isa/isa_device.h>
78#include <i386/isa/rtc.h>
79#endif
80#include <i386/isa/timerreg.h>
81
82/*
83 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
84 * can use a simple formula for leap years.
85 */
86#define	LEAPYEAR(y) ((u_int)(y) % 4 == 0)
87#define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
88
89#define	TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
90
91/*
92 * Time in timer cycles that it takes for microtime() to disable interrupts
93 * and latch the count.  microtime() currently uses "cli; outb ..." so it
94 * normally takes less than 2 timer cycles.  Add a few for cache misses.
95 * Add a few more to allow for latency in bogus calls to microtime() with
96 * interrupts already disabled.
97 */
98#define	TIMER0_LATCH_COUNT	20
99
100/*
101 * Maximum frequency that we are willing to allow for timer0.  Must be
102 * low enough to guarantee that the timer interrupt handler returns
103 * before the next timer interrupt.  Must result in a lower TIMER_DIV
104 * value than TIMER0_LATCH_COUNT so that we don't have to worry about
105 * underflow in the calculation of timer0_overflow_threshold.
106 */
107#define	TIMER0_MAX_FREQ		20000
108
109int	adjkerntz;		/* local offset	from GMT in seconds */
110int	disable_rtc_set;	/* disable resettodr() if != 0 */
111u_int	idelayed;
112#if defined(I586_CPU) || defined(I686_CPU)
113u_int	i586_ctr_bias;
114u_int	i586_ctr_comultiplier;
115u_int	i586_ctr_freq;
116u_int	i586_ctr_multiplier;
117#endif
118int	statclock_disable;
119u_int	stat_imask = SWI_CLOCK_MASK;
120#ifdef TIMER_FREQ
121u_int	timer_freq = TIMER_FREQ;
122#else
123#ifdef PC98
124#ifndef AUTO_CLOCK
125#ifndef PC98_8M
126u_int	timer_freq = 2457600;
127#else	/* !PC98_8M */
128u_int	timer_freq = 1996800;
129#endif	/* PC98_8M */
130#else	/* AUTO_CLOCK */
131u_int	timer_freq = 2457600;
132#endif	/* AUTO_CLOCK */
133#else /* IBM-PC */
134u_int	timer_freq = 1193182;
135#endif /* PC98 */
136#endif
137int	timer0_max_count;
138u_int	timer0_overflow_threshold;
139u_int	timer0_prescaler_count;
140int	wall_cmos_clock;	/* wall	CMOS clock assumed if != 0 */
141
142static	int	beeping = 0;
143static	u_int	clk_imask = HWI_MASK | SWI_MASK;
144static	const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
145static	u_int	hardclock_max_count;
146/*
147 * XXX new_function and timer_func should not handle clockframes, but
148 * timer_func currently needs to hold hardclock to handle the
149 * timer0_state == 0 case.  We should use register_intr()/unregister_intr()
150 * to switch between clkintr() and a slightly different timerintr().
151 */
152static	void	(*new_function) __P((struct clockframe *frame));
153static	u_int	new_rate;
154#ifndef PC98
155static	u_char	rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
156static	u_char	rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
157#endif
158
159/* Values for timerX_state: */
160#define	RELEASED	0
161#define	RELEASE_PENDING	1
162#define	ACQUIRED	2
163#define	ACQUIRE_PENDING	3
164
165static 	u_char	timer0_state;
166#ifdef	PC98
167static 	u_char	timer1_state;
168#endif
169static	u_char	timer2_state;
170static	void	(*timer_func) __P((struct clockframe *frame)) = hardclock;
171#ifdef PC98
172int rtc_inb __P((void));
173void rtc_outb __P((int));
174#endif
175
176#if defined(I586_CPU) || defined(I686_CPU)
177static	void	set_i586_ctr_freq(u_int i586_freq, u_int i8254_freq);
178#endif
179
180static void
181clkintr(struct clockframe frame)
182{
183	timer_func(&frame);
184	switch (timer0_state) {
185
186	case RELEASED:
187		setdelayed();
188		break;
189
190	case ACQUIRED:
191		if ((timer0_prescaler_count += timer0_max_count)
192		    >= hardclock_max_count) {
193			hardclock(&frame);
194			setdelayed();
195			timer0_prescaler_count -= hardclock_max_count;
196		}
197		break;
198
199	case ACQUIRE_PENDING:
200		setdelayed();
201		timer0_max_count = TIMER_DIV(new_rate);
202		timer0_overflow_threshold =
203			timer0_max_count - TIMER0_LATCH_COUNT;
204		disable_intr();
205		outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
206		outb(TIMER_CNTR0, timer0_max_count & 0xff);
207		outb(TIMER_CNTR0, timer0_max_count >> 8);
208		enable_intr();
209		timer0_prescaler_count = 0;
210		timer_func = new_function;
211		timer0_state = ACQUIRED;
212		break;
213
214	case RELEASE_PENDING:
215		if ((timer0_prescaler_count += timer0_max_count)
216		    >= hardclock_max_count) {
217			hardclock(&frame);
218			setdelayed();
219			timer0_max_count = hardclock_max_count;
220			timer0_overflow_threshold =
221				timer0_max_count - TIMER0_LATCH_COUNT;
222			disable_intr();
223			outb(TIMER_MODE,
224			     TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
225			outb(TIMER_CNTR0, timer0_max_count & 0xff);
226			outb(TIMER_CNTR0, timer0_max_count >> 8);
227			enable_intr();
228			/*
229			 * See microtime.s for this magic.
230			 */
231#ifdef PC98
232#ifndef AUTO_CLOCK
233#ifndef PC98_8M
234			time.tv_usec += (6667 *
235				(timer0_prescaler_count - hardclock_max_count))
236				>> 14;
237#else /* PC98_8M */
238			time.tv_usec += (16411 *
239				(timer0_prescaler_count - hardclock_max_count))
240				>> 15;
241#endif /* PC98_8M */
242#else /* AUTO_CLOCK */
243			if (pc98_machine_type & M_8M) {
244				/* PC98_8M */
245				time.tv_usec += (16411 *
246					(timer0_prescaler_count -
247					 hardclock_max_count)) >> 15;
248			} else {
249				time.tv_usec += (6667 *
250					(timer0_prescaler_count -
251					 hardclock_max_count)) >> 14;
252			}
253#endif /* AUTO_CLOCK */
254#else /* IBM-PC */
255			time.tv_usec += (27465 *
256				(timer0_prescaler_count - hardclock_max_count))
257				>> 15;
258#endif /* PC98 */
259			if (time.tv_usec >= 1000000)
260				time.tv_usec -= 1000000;
261			timer0_prescaler_count = 0;
262			timer_func = hardclock;
263			timer0_state = RELEASED;
264		}
265		break;
266	}
267}
268
269/*
270 * The acquire and release functions must be called at ipl >= splclock().
271 */
272int
273acquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
274{
275	static int old_rate;
276
277	if (rate <= 0 || rate > TIMER0_MAX_FREQ)
278		return (-1);
279	switch (timer0_state) {
280
281	case RELEASED:
282		timer0_state = ACQUIRE_PENDING;
283		break;
284
285	case RELEASE_PENDING:
286		if (rate != old_rate)
287			return (-1);
288		/*
289		 * The timer has been released recently, but is being
290		 * re-acquired before the release completed.  In this
291		 * case, we simply reclaim it as if it had not been
292		 * released at all.
293		 */
294		timer0_state = ACQUIRED;
295		break;
296
297	default:
298		return (-1);	/* busy */
299	}
300	new_function = function;
301	old_rate = new_rate = rate;
302	return (0);
303}
304
305#ifdef PC98
306int
307acquire_timer1(int mode)
308{
309
310	if (timer1_state != RELEASED)
311		return (-1);
312	timer1_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_SEL1 | (mode & 0x3f));
322
323	return (0);
324}
325#endif
326
327int
328acquire_timer2(int mode)
329{
330
331	if (timer2_state != RELEASED)
332		return (-1);
333	timer2_state = ACQUIRED;
334
335	/*
336	 * This access to the timer registers is as atomic as possible
337	 * because it is a single instruction.  We could do better if we
338	 * knew the rate.  Use of splclock() limits glitches to 10-100us,
339	 * and this is probably good enough for timer2, so we aren't as
340	 * careful with it as with timer0.
341	 */
342	outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
343
344	return (0);
345}
346
347int
348release_timer0()
349{
350	switch (timer0_state) {
351
352	case ACQUIRED:
353		timer0_state = RELEASE_PENDING;
354		break;
355
356	case ACQUIRE_PENDING:
357		/* Nothing happened yet, release quickly. */
358		timer0_state = RELEASED;
359		break;
360
361	default:
362		return (-1);
363	}
364	return (0);
365}
366
367#ifdef PC98
368int
369release_timer1()
370{
371
372	if (timer1_state != ACQUIRED)
373		return (-1);
374	timer1_state = RELEASED;
375	outb(TIMER_MODE, TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT);
376	return (0);
377}
378#endif
379
380int
381release_timer2()
382{
383
384	if (timer2_state != ACQUIRED)
385		return (-1);
386	timer2_state = RELEASED;
387	outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
388	return (0);
389}
390
391#ifndef PC98
392/*
393 * This routine receives statistical clock interrupts from the RTC.
394 * As explained above, these occur at 128 interrupts per second.
395 * When profiling, we receive interrupts at a rate of 1024 Hz.
396 *
397 * This does not actually add as much overhead as it sounds, because
398 * when the statistical clock is active, the hardclock driver no longer
399 * needs to keep (inaccurate) statistics on its own.  This decouples
400 * statistics gathering from scheduling interrupts.
401 *
402 * The RTC chip requires that we read status register C (RTC_INTR)
403 * to acknowledge an interrupt, before it will generate the next one.
404 */
405static void
406rtcintr(struct clockframe frame)
407{
408	u_char stat;
409	stat = rtcin(RTC_INTR);
410	if(stat & RTCIR_PERIOD) {
411		statclock(&frame);
412	}
413}
414
415#include "opt_ddb.h"
416#ifdef DDB
417#include <ddb/ddb.h>
418
419DB_SHOW_COMMAND(rtc, rtc)
420{
421	printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
422	       rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
423	       rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
424	       rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
425}
426#endif /* DDB */
427#endif /* for PC98 */
428
429static int
430getit(void)
431{
432	u_long ef;
433	int high, low;
434
435	ef = read_eflags();
436	disable_intr();
437
438	/* Select timer0 and latch counter value. */
439	outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
440
441	low = inb(TIMER_CNTR0);
442	high = inb(TIMER_CNTR0);
443
444	write_eflags(ef);
445	return ((high << 8) | low);
446}
447
448/*
449 * Wait "n" microseconds.
450 * Relies on timer 1 counting down from (timer_freq / hz)
451 * Note: timer had better have been programmed before this is first used!
452 */
453void
454DELAY(int n)
455{
456	int prev_tick, tick, ticks_left, sec, usec;
457
458#ifdef DELAYDEBUG
459	int getit_calls = 1;
460	int n1;
461	static int state = 0;
462
463	if (state == 0) {
464		state = 1;
465		for (n1 = 1; n1 <= 10000000; n1 *= 10)
466			DELAY(n1);
467		state = 2;
468	}
469	if (state == 1)
470		printf("DELAY(%d)...", n);
471#endif
472	/*
473	 * Read the counter first, so that the rest of the setup overhead is
474	 * counted.  Guess the initial overhead is 20 usec (on most systems it
475	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
476	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
477	 * multiplications and divisions to scale the count take a while).
478	 */
479	prev_tick = getit();
480	n -= 20;
481	/*
482	 * Calculate (n * (timer_freq / 1e6)) without using floating point
483	 * and without any avoidable overflows.
484	 */
485	sec = n / 1000000;
486	usec = n - sec * 1000000;
487	ticks_left = sec * timer_freq
488		     + usec * (timer_freq / 1000000)
489		     + usec * ((timer_freq % 1000000) / 1000) / 1000
490		     + usec * (timer_freq % 1000) / 1000000;
491	if (n < 0)
492		ticks_left = 0;	/* XXX timer_freq is unsigned */
493
494	while (ticks_left > 0) {
495		tick = getit();
496#ifdef DELAYDEBUG
497		++getit_calls;
498#endif
499		if (tick > prev_tick)
500			ticks_left -= prev_tick - (tick - timer0_max_count);
501		else
502			ticks_left -= prev_tick - tick;
503		prev_tick = tick;
504	}
505#ifdef DELAYDEBUG
506	if (state == 1)
507		printf(" %d calls to getit() at %d usec each\n",
508		       getit_calls, (n + 5) / getit_calls);
509#endif
510}
511
512static void
513sysbeepstop(void *chan)
514{
515#ifdef PC98	/* PC98 */
516	outb(IO_PPI, inb(IO_PPI)|0x08);	/* disable counter1 output to speaker */
517	release_timer1();
518#else
519	outb(IO_PPI, inb(IO_PPI)&0xFC);	/* disable counter2 output to speaker */
520	release_timer2();
521#endif
522	beeping = 0;
523}
524
525int
526sysbeep(int pitch, int period)
527{
528	int x = splclock();
529
530#ifdef PC98
531	if (acquire_timer1(TIMER_SQWAVE|TIMER_16BIT))
532		if (!beeping) {
533			/* Something else owns it. */
534			splx(x);
535			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
536		}
537	disable_intr();
538	outb(0x3fdb, pitch);
539	outb(0x3fdb, (pitch>>8));
540	enable_intr();
541	if (!beeping) {
542		/* enable counter1 output to speaker */
543		outb(IO_PPI, (inb(IO_PPI) & 0xf7));
544		beeping = period;
545		timeout(sysbeepstop, (void *)NULL, period);
546	}
547#else
548	if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
549		if (!beeping) {
550			/* Something else owns it. */
551			splx(x);
552			return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
553		}
554	disable_intr();
555	outb(TIMER_CNTR2, pitch);
556	outb(TIMER_CNTR2, (pitch>>8));
557	enable_intr();
558	if (!beeping) {
559		/* enable counter2 output to speaker */
560		outb(IO_PPI, inb(IO_PPI) | 3);
561		beeping = period;
562		timeout(sysbeepstop, (void *)NULL, period);
563	}
564#endif
565	splx(x);
566	return (0);
567}
568
569#ifndef PC98
570/*
571 * RTC support routines
572 */
573
574int
575rtcin(reg)
576	int reg;
577{
578	u_char val;
579
580	outb(IO_RTC, reg);
581	inb(0x84);
582	val = inb(IO_RTC + 1);
583	inb(0x84);
584	return (val);
585}
586
587static __inline void
588writertc(u_char reg, u_char val)
589{
590	outb(IO_RTC, reg);
591	outb(IO_RTC + 1, val);
592}
593
594static __inline int
595readrtc(int port)
596{
597	return(bcd2bin(rtcin(port)));
598}
599#endif
600
601#ifdef PC98
602unsigned int delaycount;
603#define FIRST_GUESS	0x2000
604static void findcpuspeed(void)
605{
606	int i;
607	int remainder;
608
609	/* Put counter in count down mode */
610	outb(TIMER_MODE, TIMER_SEL0 | TIMER_16BIT | TIMER_RATEGEN);
611	outb(TIMER_CNTR0, 0xff);
612	outb(TIMER_CNTR0, 0xff);
613	for (i = FIRST_GUESS; i; i--)
614		;
615	remainder = getit();
616	delaycount = (FIRST_GUESS * TIMER_DIV(1000)) / (0xffff - remainder);
617}
618#endif
619
620#ifndef PC98
621static u_int
622calibrate_clocks(void)
623{
624	u_int count, prev_count, tot_count;
625	int sec, start_sec, timeout;
626
627	printf("Calibrating clock(s) relative to mc146818A clock ... ");
628	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
629		goto fail;
630	timeout = 100000000;
631
632	/* Read the mc146818A seconds counter. */
633	for (;;) {
634		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
635			sec = rtcin(RTC_SEC);
636			break;
637		}
638		if (--timeout == 0)
639			goto fail;
640	}
641
642	/* Wait for the mC146818A seconds counter to change. */
643	start_sec = sec;
644	for (;;) {
645		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
646			sec = rtcin(RTC_SEC);
647			if (sec != start_sec)
648				break;
649		}
650		if (--timeout == 0)
651			goto fail;
652	}
653
654	/* Start keeping track of the i8254 counter. */
655	prev_count = getit();
656	if (prev_count == 0 || prev_count > timer0_max_count)
657		goto fail;
658	tot_count = 0;
659
660#if defined(I586_CPU) || defined(I686_CPU)
661	if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)
662		wrmsr(0x10, 0LL);	/* XXX 0x10 is the MSR for the TSC */
663#endif
664
665	/*
666	 * Wait for the mc146818A seconds counter to change.  Read the i8254
667	 * counter for each iteration since this is convenient and only
668	 * costs a few usec of inaccuracy. The timing of the final reads
669	 * of the counters almost matches the timing of the initial reads,
670	 * so the main cause of inaccuracy is the varying latency from
671	 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
672	 * rtcin(RTC_SEC) that returns a changed seconds count.  The
673	 * maximum inaccuracy from this cause is < 10 usec on 486's.
674	 */
675	start_sec = sec;
676	for (;;) {
677		if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
678			sec = rtcin(RTC_SEC);
679		count = getit();
680		if (count == 0 || count > timer0_max_count)
681			goto fail;
682		if (count > prev_count)
683			tot_count += prev_count - (count - timer0_max_count);
684		else
685			tot_count += prev_count - count;
686		prev_count = count;
687		if (sec != start_sec)
688			break;
689		if (--timeout == 0)
690			goto fail;
691	}
692
693#if defined(I586_CPU) || defined(I686_CPU)
694	/*
695	 * Read the cpu cycle counter.  The timing considerations are
696	 * similar to those for the i8254 clock.
697	 */
698	if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686) {
699		set_i586_ctr_freq((u_int)rdtsc(), tot_count);
700		printf("i586 clock: %u Hz, ", i586_ctr_freq);
701	}
702#endif
703
704	printf("i8254 clock: %u Hz\n", tot_count);
705	return (tot_count);
706
707fail:
708	printf("failed, using default i8254 clock of %u Hz\n", timer_freq);
709	return (timer_freq);
710}
711#endif	/* !PC98 */
712
713static void
714set_timer_freq(u_int freq, int intr_freq)
715{
716	u_long ef;
717
718	ef = read_eflags();
719	disable_intr();
720	timer_freq = freq;
721	timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
722	timer0_overflow_threshold = timer0_max_count - TIMER0_LATCH_COUNT;
723	outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
724	outb(TIMER_CNTR0, timer0_max_count & 0xff);
725	outb(TIMER_CNTR0, timer0_max_count >> 8);
726	write_eflags(ef);
727}
728
729/*
730 * Initialize 8253 timer 0 early so that it can be used in DELAY().
731 * XXX initialization of other timers is unintentionally left blank.
732 */
733void
734startrtclock()
735{
736	u_int delta, freq;
737
738#ifdef PC98
739	findcpuspeed();
740#ifndef AUTO_CLOCK
741	if (pc98_machine_type & M_8M) {
742#ifndef	PC98_8M
743		printf("you must reconfig a kernel with \"PC98_8M\" option.\n");
744#endif
745	} else {
746#ifdef	PC98_8M
747		printf("You must reconfig a kernel without \"PC98_8M\" option.\n");
748#endif
749	}
750#else /* AUTO_CLOCK */
751	if (pc98_machine_type & M_8M)
752		timer_freq = 1996800L; /* 1.9968 MHz */
753	else
754		timer_freq = 2457600L; /* 2.4576 MHz */
755#endif /* AUTO_CLOCK */
756#endif /* PC98 */
757
758#ifndef PC98
759	writertc(RTC_STATUSA, rtc_statusa);
760	writertc(RTC_STATUSB, RTCSB_24HR);
761#endif
762
763#ifndef PC98
764	set_timer_freq(timer_freq, hz);
765	freq = calibrate_clocks();
766#ifdef CLK_CALIBRATION_LOOP
767	if (bootverbose) {
768		printf(
769		"Press a key on the console to abort clock calibration\n");
770		while (cncheckc() == -1)
771			calibrate_clocks();
772	}
773#endif
774
775	/*
776	 * Use the calibrated i8254 frequency if it seems reasonable.
777	 * Otherwise use the default, and don't use the calibrated i586
778	 * frequency.
779	 */
780	delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
781	if (delta < timer_freq / 100) {
782#ifndef CLK_USE_I8254_CALIBRATION
783		if (bootverbose)
784			printf(
785"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
786		freq = timer_freq;
787#endif
788		timer_freq = freq;
789	} else {
790		printf("%d Hz differs from default of %d Hz by more than 1%%\n",
791		       freq, timer_freq);
792#if defined(I586_CPU) || defined(I686_CPU)
793		i586_ctr_freq = 0;
794#endif
795	}
796#endif
797
798	set_timer_freq(timer_freq, hz);
799
800#if defined(I586_CPU) || defined(I686_CPU)
801#ifndef CLK_USE_I586_CALIBRATION
802	if (i586_ctr_freq != 0) {
803		if (bootverbose)
804			printf(
805"CLK_USE_I586_CALIBRATION not specified - using old calibration method\n");
806		i586_ctr_freq = 0;
807	}
808#endif
809	if (i586_ctr_freq == 0 &&
810	    (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)) {
811		/*
812		 * Calibration of the i586 clock relative to the mc146818A
813		 * clock failed.  Do a less accurate calibration relative
814		 * to the i8254 clock.
815		 */
816		wrmsr(0x10, 0LL);	/* XXX */
817		DELAY(1000000);
818		set_i586_ctr_freq((u_int)rdtsc(), timer_freq);
819#ifdef CLK_USE_I586_CALIBRATION
820		printf("i586 clock: %u Hz\n", i586_ctr_freq);
821#endif
822	}
823#endif
824}
825
826#ifdef PC98
827void
828rtc_serialcombit(int i)
829{
830	outb(IO_RTC, ((i&0x01)<<5)|0x07);
831	DELAY(1);
832	outb(IO_RTC, ((i&0x01)<<5)|0x17);
833	DELAY(1);
834	outb(IO_RTC, ((i&0x01)<<5)|0x07);
835	DELAY(1);
836}
837
838void
839rtc_serialcom(int i)
840{
841	rtc_serialcombit(i&0x01);
842	rtc_serialcombit((i&0x02)>>1);
843	rtc_serialcombit((i&0x04)>>2);
844	rtc_serialcombit((i&0x08)>>3);
845	outb(IO_RTC, 0x07);
846	DELAY(1);
847	outb(IO_RTC, 0x0f);
848	DELAY(1);
849	outb(IO_RTC, 0x07);
850 	DELAY(1);
851}
852
853void
854rtc_outb(int val)
855{
856	int s;
857	int sa = 0;
858
859	for (s=0;s<8;s++) {
860	    sa = ((val >> s) & 0x01) ? 0x27 : 0x07;
861	    outb(IO_RTC, sa);		/* set DI & CLK 0 */
862	    DELAY(1);
863	    outb(IO_RTC, sa | 0x10);	/* CLK 1 */
864	    DELAY(1);
865	}
866	outb(IO_RTC, sa & 0xef);	/* CLK 0 */
867}
868
869int
870rtc_inb(void)
871{
872	int s;
873	int sa = 0;
874
875	for (s=0;s<8;s++) {
876	    sa |= ((inb(0x33) & 0x01) << s);
877	    outb(IO_RTC, 0x17);	/* CLK 1 */
878	    DELAY(1);
879	    outb(IO_RTC, 0x07);	/* CLK 0 */
880	    DELAY(2);
881	}
882	return sa;
883}
884#endif /* PC-98 */
885
886/*
887 * Initialize the time of day register,	based on the time base which is, e.g.
888 * from	a filesystem.
889 */
890void
891inittodr(time_t base)
892{
893	unsigned long	sec, days;
894	int		yd;
895	int		year, month;
896	int		y, m, s;
897#ifdef PC98
898	int		second, min, hour;
899#endif
900
901	s = splclock();
902	time.tv_sec  = base;
903	time.tv_usec = 0;
904	splx(s);
905
906#ifdef PC98
907	rtc_serialcom(0x03);	/* Time Read */
908	rtc_serialcom(0x01);	/* Register shift command. */
909	DELAY(20);
910
911	second = bcd2bin(rtc_inb() & 0xff);	/* sec */
912	min = bcd2bin(rtc_inb() & 0xff);	/* min */
913	hour = bcd2bin(rtc_inb() & 0xff);	/* hour */
914	days = bcd2bin(rtc_inb() & 0xff) - 1;	/* date */
915
916	month = (rtc_inb() >> 4) & 0x0f;	/* month */
917	for (m = 1; m <	month; m++)
918		days +=	daysinmonth[m-1];
919	year = bcd2bin(rtc_inb() & 0xff) + 1900;	/* year */
920	/* 2000 year problem */
921	if (year < 1995)
922		year += 100;
923	if (year < 1970)
924		goto wrong_time;
925	for (y = 1970; y < year; y++)
926		days +=	DAYSPERYEAR + LEAPYEAR(y);
927	if ((month > 2)	&& LEAPYEAR(year))
928		days ++;
929	sec = ((( days * 24 +
930		  hour) * 60 +
931		  min) * 60 +
932		  second);
933	/* sec now contains the	number of seconds, since Jan 1 1970,
934	   in the local	time zone */
935#else	/* IBM-PC */
936	/* Look	if we have a RTC present and the time is valid */
937	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
938		goto wrong_time;
939
940	/* wait	for time update	to complete */
941	/* If RTCSA_TUP	is zero, we have at least 244us	before next update */
942	while (rtcin(RTC_STATUSA) & RTCSA_TUP);
943
944	days = 0;
945#ifdef USE_RTC_CENTURY
946	year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY)	* 100;
947#else
948	year = readrtc(RTC_YEAR) + 1900;
949	if (year < 1970)
950		year += 100;
951#endif
952	if (year < 1970)
953		goto wrong_time;
954	month =	readrtc(RTC_MONTH);
955	for (m = 1; m <	month; m++)
956		days +=	daysinmonth[m-1];
957	if ((month > 2)	&& LEAPYEAR(year))
958		days ++;
959	days +=	readrtc(RTC_DAY) - 1;
960	yd = days;
961	for (y = 1970; y < year; y++)
962		days +=	DAYSPERYEAR + LEAPYEAR(y);
963	sec = ((( days * 24 +
964		  readrtc(RTC_HRS)) * 60 +
965		  readrtc(RTC_MIN)) * 60 +
966		  readrtc(RTC_SEC));
967	/* sec now contains the	number of seconds, since Jan 1 1970,
968	   in the local	time zone */
969#endif
970
971	sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
972
973	s = splclock();
974	time.tv_sec = sec;
975	splx(s);
976	return;
977
978wrong_time:
979	printf("Invalid	time in	real time clock.\n");
980	printf("Check and reset	the date immediately!\n");
981}
982
983/*
984 * Write system	time back to RTC
985 */
986void
987resettodr()
988{
989	unsigned long	tm;
990	int		y, m, s;
991#ifdef PC98
992	int		wd;
993#endif
994
995	if (disable_rtc_set)
996		return;
997
998	s = splclock();
999	tm = time.tv_sec;
1000	splx(s);
1001
1002#ifdef PC98
1003	rtc_serialcom(0x01);	/* Register shift command. */
1004
1005	/* Calculate local time	to put in RTC */
1006
1007	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1008
1009	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1010	rtc_outb(bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1011	rtc_outb(bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1012
1013	/* We have now the days	since 01-01-1970 in tm */
1014	wd = (tm+4)%7;
1015	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1016	     tm >= m;
1017	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1018	     tm -= m;
1019
1020	/* Now we have the years in y and the day-of-the-year in tm */
1021	for (m = 0; ; m++) {
1022		int ml;
1023
1024		ml = daysinmonth[m];
1025		if (m == 1 && LEAPYEAR(y))
1026			ml++;
1027		if (tm < ml)
1028			break;
1029		tm -= ml;
1030	}
1031
1032	m++;
1033	rtc_outb(bin2bcd(tm+1));		/* Write back Day     */
1034	rtc_outb((m << 4) | wd);		/* Write back Month & Weekday  */
1035	rtc_outb(bin2bcd(y%100));		/* Write back Year    */
1036
1037	rtc_serialcom(0x02);	/* Time set & Counter hold command. */
1038	rtc_serialcom(0x00);	/* Register hold command. */
1039#else
1040	/* Disable RTC updates and interrupts. */
1041	writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1042
1043	/* Calculate local time	to put in RTC */
1044
1045	tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1046
1047	writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;	/* Write back Seconds */
1048	writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;	/* Write back Minutes */
1049	writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;	/* Write back Hours   */
1050
1051	/* We have now the days	since 01-01-1970 in tm */
1052	writertc(RTC_WDAY, (tm+4)%7);			/* Write back Weekday */
1053	for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1054	     tm >= m;
1055	     y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1056	     tm -= m;
1057
1058	/* Now we have the years in y and the day-of-the-year in tm */
1059	writertc(RTC_YEAR, bin2bcd(y%100));		/* Write back Year    */
1060#ifdef USE_RTC_CENTURY
1061	writertc(RTC_CENTURY, bin2bcd(y/100));		/* ... and Century    */
1062#endif
1063	for (m = 0; ; m++) {
1064		int ml;
1065
1066		ml = daysinmonth[m];
1067		if (m == 1 && LEAPYEAR(y))
1068			ml++;
1069		if (tm < ml)
1070			break;
1071		tm -= ml;
1072	}
1073
1074	writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
1075	writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
1076
1077	/* Reenable RTC updates and interrupts. */
1078	writertc(RTC_STATUSB, rtc_statusb);
1079#endif
1080}
1081
1082/*
1083 * Start both clocks running.
1084 */
1085void
1086cpu_initclocks()
1087{
1088#ifndef PC98
1089	int diag;
1090
1091	if (statclock_disable) {
1092		/*
1093		 * The stat interrupt mask is different without the
1094		 * statistics clock.  Also, don't set the interrupt
1095		 * flag which would normally cause the RTC to generate
1096		 * interrupts.
1097		 */
1098		stat_imask = HWI_MASK | SWI_MASK;
1099		rtc_statusb = RTCSB_24HR;
1100	} else {
1101	        /* Setting stathz to nonzero early helps avoid races. */
1102		stathz = RTC_NOPROFRATE;
1103		profhz = RTC_PROFRATE;
1104        }
1105#endif
1106
1107	/* Finish initializing 8253 timer 0. */
1108	register_intr(/* irq */ 0, /* XXX id */ 0, /* flags */ 0,
1109		      /* XXX */ (inthand2_t *)clkintr, &clk_imask,
1110		      /* unit */ 0);
1111	INTREN(IRQ0);
1112#if defined(I586_CPU) || defined(I686_CPU)
1113	/*
1114	 * Finish setting up anti-jitter measures.
1115	 */
1116	if (i586_ctr_freq != 0)
1117		i586_ctr_bias = rdtsc();
1118#endif
1119
1120#ifndef PC98
1121	/* Initialize RTC. */
1122	writertc(RTC_STATUSA, rtc_statusa);
1123	writertc(RTC_STATUSB, RTCSB_24HR);
1124
1125	/* Don't bother enabling the statistics clock. */
1126	if (statclock_disable)
1127		return;
1128	diag = rtcin(RTC_DIAG);
1129	if (diag != 0)
1130		printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1131	register_intr(/* irq */ 8, /* XXX id */ 1, /* flags */ 0,
1132		      /* XXX */ (inthand2_t *)rtcintr, &stat_imask,
1133		      /* unit */ 0);
1134	INTREN(IRQ8);
1135	writertc(RTC_STATUSB, rtc_statusb);
1136#endif
1137}
1138
1139void
1140setstatclockrate(int newhz)
1141{
1142#ifndef PC98
1143	if (newhz == RTC_PROFRATE)
1144		rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1145	else
1146		rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1147	writertc(RTC_STATUSA, rtc_statusa);
1148#endif
1149}
1150
1151static int
1152sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
1153{
1154	int error;
1155	u_int freq;
1156
1157	/*
1158	 * Use `i8254' instead of `timer' in external names because `timer'
1159	 * is is too generic.  Should use it everywhere.
1160	 */
1161	freq = timer_freq;
1162	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1163	if (error == 0 && req->newptr != NULL) {
1164		if (timer0_state != 0)
1165			return (EBUSY);	/* too much trouble to handle */
1166		set_timer_freq(freq, hz);
1167#if defined(I586_CPU) || defined(I686_CPU)
1168		set_i586_ctr_freq(i586_ctr_freq, timer_freq);
1169#endif
1170	}
1171	return (error);
1172}
1173
1174SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1175	    0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1176
1177#if defined(I586_CPU) || defined(I686_CPU)
1178static void
1179set_i586_ctr_freq(u_int i586_freq, u_int i8254_freq)
1180{
1181	u_int comultiplier, multiplier;
1182	u_long ef;
1183
1184	if (i586_freq == 0) {
1185		i586_ctr_freq = i586_freq;
1186		return;
1187	}
1188	comultiplier = ((unsigned long long)i586_freq
1189			<< I586_CTR_COMULTIPLIER_SHIFT) / i8254_freq;
1190	multiplier = (1000000LL << I586_CTR_MULTIPLIER_SHIFT) / i586_freq;
1191	ef = read_eflags();
1192	disable_intr();
1193	i586_ctr_freq = i586_freq;
1194	i586_ctr_comultiplier = comultiplier;
1195	i586_ctr_multiplier = multiplier;
1196	write_eflags(ef);
1197}
1198
1199static int
1200sysctl_machdep_i586_freq SYSCTL_HANDLER_ARGS
1201{
1202	int error;
1203	u_int freq;
1204
1205	if (cpu_class != CPUCLASS_586 && cpu_class != CPUCLASS_686)
1206		return (EOPNOTSUPP);
1207	freq = i586_ctr_freq;
1208	error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1209	if (error == 0 && req->newptr != NULL)
1210		set_i586_ctr_freq(freq, timer_freq);
1211	return (error);
1212}
1213
1214SYSCTL_PROC(_machdep, OID_AUTO, i586_freq, CTLTYPE_INT | CTLFLAG_RW,
1215	    0, sizeof(u_int), sysctl_machdep_i586_freq, "I", "");
1216#endif /* defined(I586_CPU) || defined(I686_CPU) */
1217