Deleted Added
sdiff udiff text old ( 29000 ) new ( 30805 )
full compact
1/*-
2 * Copyright (c) 1990 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz and Don Ahn.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * 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.12 1997/09/01 07:37:01 smp Exp smp $
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#include "opt_clock.h"
52#include "opt_cpu.h"
53
54#include <sys/param.h>
55#include <sys/systm.h>
56#include <sys/time.h>
57#include <sys/kernel.h>
58#include <sys/sysctl.h>
59
60#include <machine/clock.h>
61#ifdef CLK_CALIBRATION_LOOP
62#include <machine/cons.h>
63#endif
64#include
65#include <machine/frame.h>
66#include <machine/ipl.h>
67#include <machine/limits.h>
68#if defined(SMP) || defined(APIC_IO)
69#include <machine/smp.h>
70#endif /* SMP || APIC_IO */
71
72#include <i386/isa/icu.h>
73#include <i386/isa/isa.h>
74#include <i386/isa/rtc.h>
75#include <i386/isa/timerreg.h>
76
77#include <i386/isa/intr_machdep.h>
78#include <sys/interrupt.h>
79
80#ifdef SMP
81#define disable_intr() CLOCK_DISABLE_INTR()
82#define enable_intr() CLOCK_ENABLE_INTR()
83#endif /* SMP */
84
85/*
86 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
87 * can use a simple formula for leap years.
88 */
89#define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
90#define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
91
92#define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
93
94/*
95 * Time in timer cycles that it takes for microtime() to disable interrupts
96 * and latch the count. microtime() currently uses "cli; outb ..." so it
97 * normally takes less than 2 timer cycles. Add a few for cache misses.
98 * Add a few more to allow for latency in bogus calls to microtime() with
99 * interrupts already disabled.
100 */
101#define TIMER0_LATCH_COUNT 20
102
103/*
104 * Maximum frequency that we are willing to allow for timer0. Must be
105 * low enough to guarantee that the timer interrupt handler returns
106 * before the next timer interrupt. Must result in a lower TIMER_DIV
107 * value than TIMER0_LATCH_COUNT so that we don't have to worry about
108 * underflow in the calculation of timer0_overflow_threshold.
109 */
110#define TIMER0_MAX_FREQ 20000
111
112int adjkerntz; /* local offset from GMT in seconds */
113int disable_rtc_set; /* disable resettodr() if != 0 */
114u_int idelayed;
115#if defined(I586_CPU) || defined(I686_CPU)
116#ifndef SMP
117u_int i586_ctr_bias;
118u_int i586_ctr_comultiplier;
119#endif
120u_int i586_ctr_freq;
121#ifndef SMP
122u_int i586_ctr_multiplier;
123#endif
124#endif
125int statclock_disable;
126u_int stat_imask = SWI_CLOCK_MASK;
127#ifdef TIMER_FREQ
128u_int timer_freq = TIMER_FREQ;
129#else
130u_int timer_freq = 1193182;
131#endif
132int timer0_max_count;
133u_int timer0_overflow_threshold;
134u_int timer0_prescaler_count;
135int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
136
137static int beeping = 0;
138static u_int clk_imask = HWI_MASK | SWI_MASK;
139static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
140static u_int hardclock_max_count;
141/*
142 * XXX new_function and timer_func should not handle clockframes, but
143 * timer_func currently needs to hold hardclock to handle the
144 * timer0_state == 0 case. We should use register_intr()/unregister_intr()
145 * to switch between clkintr() and a slightly different timerintr().
146 */
147static void (*new_function) __P((struct clockframe *frame));
148static u_int new_rate;
149static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
150static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
151
152/* Values for timerX_state: */
153#define RELEASED 0
154#define RELEASE_PENDING 1
155#define ACQUIRED 2
156#define ACQUIRE_PENDING 3
157
158static u_char timer0_state;
159static u_char timer2_state;
160static void (*timer_func) __P((struct clockframe *frame)) = hardclock;
161
162#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
163static void set_i586_ctr_freq(u_int i586_freq, u_int i8254_freq);
164#endif
165static void set_timer_freq(u_int freq, int intr_freq);
166
167static void
168clkintr(struct clockframe frame)
169{
170 timer_func(&frame);
171 switch (timer0_state) {
172
173 case RELEASED:
174 setdelayed();
175 break;
176
177 case ACQUIRED:
178 if ((timer0_prescaler_count += timer0_max_count)
179 >= hardclock_max_count) {
180 hardclock(&frame);
181 setdelayed();
182 timer0_prescaler_count -= hardclock_max_count;
183 }
184 break;
185
186 case ACQUIRE_PENDING:
187 setdelayed();
188 timer0_max_count = TIMER_DIV(new_rate);
189 timer0_overflow_threshold =
190 timer0_max_count - TIMER0_LATCH_COUNT;
191 disable_intr();
192 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
193 outb(TIMER_CNTR0, timer0_max_count & 0xff);
194 outb(TIMER_CNTR0, timer0_max_count >> 8);
195 enable_intr();
196 timer0_prescaler_count = 0;
197 timer_func = new_function;
198 timer0_state = ACQUIRED;
199 break;
200
201 case RELEASE_PENDING:
202 if ((timer0_prescaler_count += timer0_max_count)
203 >= hardclock_max_count) {
204 hardclock(&frame);
205 setdelayed();
206 timer0_max_count = hardclock_max_count;
207 timer0_overflow_threshold =
208 timer0_max_count - TIMER0_LATCH_COUNT;
209 disable_intr();
210 outb(TIMER_MODE,
211 TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
212 outb(TIMER_CNTR0, timer0_max_count & 0xff);
213 outb(TIMER_CNTR0, timer0_max_count >> 8);
214 enable_intr();
215 /*
216 * See microtime.s for this magic.
217 */
218 time.tv_usec += (27465 *
219 (timer0_prescaler_count - hardclock_max_count))
220 >> 15;
221 if (time.tv_usec >= 1000000)
222 time.tv_usec -= 1000000;
223 timer0_prescaler_count = 0;
224 timer_func = hardclock;
225 timer0_state = RELEASED;
226 }
227 break;
228 }
229}
230
231/*
232 * The acquire and release functions must be called at ipl >= splclock().
233 */
234int
235acquire_timer0(int rate, void (*function) __P((struct clockframe *frame)))
236{
237 static int old_rate;
238
239 if (rate <= 0 || rate > TIMER0_MAX_FREQ)
240 return (-1);
241 switch (timer0_state) {
242
243 case RELEASED:
244 timer0_state = ACQUIRE_PENDING;
245 break;
246
247 case RELEASE_PENDING:
248 if (rate != old_rate)
249 return (-1);
250 /*
251 * The timer has been released recently, but is being
252 * re-acquired before the release completed. In this
253 * case, we simply reclaim it as if it had not been
254 * released at all.
255 */
256 timer0_state = ACQUIRED;
257 break;
258
259 default:
260 return (-1); /* busy */
261 }
262 new_function = function;
263 old_rate = new_rate = rate;
264 return (0);
265}
266
267int
268acquire_timer2(int mode)
269{
270
271 if (timer2_state != RELEASED)
272 return (-1);
273 timer2_state = ACQUIRED;
274
275 /*
276 * This access to the timer registers is as atomic as possible
277 * because it is a single instruction. We could do better if we
278 * knew the rate. Use of splclock() limits glitches to 10-100us,
279 * and this is probably good enough for timer2, so we aren't as
280 * careful with it as with timer0.
281 */
282 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
283
284 return (0);
285}
286
287int
288release_timer0()
289{
290 switch (timer0_state) {
291
292 case ACQUIRED:
293 timer0_state = RELEASE_PENDING;
294 break;
295
296 case ACQUIRE_PENDING:
297 /* Nothing happened yet, release quickly. */
298 timer0_state = RELEASED;
299 break;
300
301 default:
302 return (-1);
303 }
304 return (0);
305}
306
307int
308release_timer2()
309{
310
311 if (timer2_state != ACQUIRED)
312 return (-1);
313 timer2_state = RELEASED;
314 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
315 return (0);
316}
317
318/*
319 * This routine receives statistical clock interrupts from the RTC.
320 * As explained above, these occur at 128 interrupts per second.
321 * When profiling, we receive interrupts at a rate of 1024 Hz.
322 *
323 * This does not actually add as much overhead as it sounds, because
324 * when the statistical clock is active, the hardclock driver no longer
325 * needs to keep (inaccurate) statistics on its own. This decouples
326 * statistics gathering from scheduling interrupts.
327 *
328 * The RTC chip requires that we read status register C (RTC_INTR)
329 * to acknowledge an interrupt, before it will generate the next one.
330 * Under high interrupt load, rtcintr() can be indefinitely delayed and
331 * the clock can tick immediately after the read from RTC_INTR. In this
332 * case, the mc146818A interrupt signal will not drop for long enough
333 * to register with the 8259 PIC. If an interrupt is missed, the stat
334 * clock will halt, considerably degrading system performance. This is
335 * why we use 'while' rather than a more straightforward 'if' below.
336 * Stat clock ticks can still be lost, causing minor loss of accuracy
337 * in the statistics, but the stat clock will no longer stop.
338 */
339static void
340rtcintr(struct clockframe frame)
341{
342 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
343 statclock(&frame);
344}
345
346#include "opt_ddb.h"
347#ifdef DDB
348#include <ddb/ddb.h>
349
350DB_SHOW_COMMAND(rtc, rtc)
351{
352 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
353 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
354 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
355 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
356}
357#endif /* DDB */
358
359static int
360getit(void)
361{
362 u_long ef;
363 int high, low;
364
365 ef = read_eflags();
366 disable_intr();
367
368 /* Select timer0 and latch counter value. */
369 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
370
371 low = inb(TIMER_CNTR0);
372 high = inb(TIMER_CNTR0);
373
374 CLOCK_UNLOCK();
375 write_eflags(ef);
376 return ((high << 8) | low);
377}
378
379/*
380 * Wait "n" microseconds.
381 * Relies on timer 1 counting down from (timer_freq / hz)
382 * Note: timer had better have been programmed before this is first used!
383 */
384void
385DELAY(int n)
386{
387 int delta, prev_tick, tick, ticks_left;
388
389#ifdef DELAYDEBUG
390 int getit_calls = 1;
391 int n1;
392 static int state = 0;
393
394 if (state == 0) {
395 state = 1;
396 for (n1 = 1; n1 <= 10000000; n1 *= 10)
397 DELAY(n1);
398 state = 2;
399 }
400 if (state == 1)
401 printf("DELAY(%d)...", n);
402#endif
403 /*
404 * Guard against the timer being uninitialized if we are called
405 * early for console i/o.
406 */
407 if (timer0_max_count == 0)
408 set_timer_freq(timer_freq, hz);
409
410 /*
411 * Read the counter first, so that the rest of the setup overhead is
412 * counted. Guess the initial overhead is 20 usec (on most systems it
413 * takes about 1.5 usec for each of the i/o's in getit(). The loop
414 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
415 * multiplications and divisions to scale the count take a while).
416 */
417 prev_tick = getit();
418 n -= 0; /* XXX actually guess no initial overhead */
419 /*
420 * Calculate (n * (timer_freq / 1e6)) without using floating point
421 * and without any avoidable overflows.
422 */
423 if (n <= 0)
424 ticks_left = 0;
425 else if (n < 256)
426 /*
427 * Use fixed point to avoid a slow division by 1000000.
428 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
429 * 2^15 is the first power of 2 that gives exact results
430 * for n between 0 and 256.
431 */
432 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
433 else
434 /*
435 * Don't bother using fixed point, although gcc-2.7.2
436 * generates particularly poor code for the long long
437 * division, since even the slow way will complete long
438 * before the delay is up (unless we're interrupted).
439 */
440 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
441 / 1000000;
442
443 while (ticks_left > 0) {
444 tick = getit();
445#ifdef DELAYDEBUG
446 ++getit_calls;
447#endif
448 delta = prev_tick - tick;
449 prev_tick = tick;
450 if (delta < 0) {
451 delta += timer0_max_count;
452 /*
453 * Guard against timer0_max_count being wrong.
454 * This shouldn't happen in normal operation,
455 * but it may happen if set_timer_freq() is
456 * traced.
457 */
458 if (delta < 0)
459 delta = 0;
460 }
461 ticks_left -= delta;
462 }
463#ifdef DELAYDEBUG
464 if (state == 1)
465 printf(" %d calls to getit() at %d usec each\n",
466 getit_calls, (n + 5) / getit_calls);
467#endif
468}
469
470static void
471sysbeepstop(void *chan)
472{
473 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
474 release_timer2();
475 beeping = 0;
476}
477
478int
479sysbeep(int pitch, int period)
480{
481 int x = splclock();
482
483 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
484 if (!beeping) {
485 /* Something else owns it. */
486 splx(x);
487 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
488 }
489 disable_intr();
490 outb(TIMER_CNTR2, pitch);
491 outb(TIMER_CNTR2, (pitch>>8));
492 enable_intr();
493 if (!beeping) {
494 /* enable counter2 output to speaker */
495 outb(IO_PPI, inb(IO_PPI) | 3);
496 beeping = period;
497 timeout(sysbeepstop, (void *)NULL, period);
498 }
499 splx(x);
500 return (0);
501}
502
503/*
504 * RTC support routines
505 */
506
507int
508rtcin(reg)
509 int reg;
510{
511 u_char val;
512
513 outb(IO_RTC, reg);
514 inb(0x84);
515 val = inb(IO_RTC + 1);
516 inb(0x84);
517 return (val);
518}
519
520static __inline void
521writertc(u_char reg, u_char val)
522{
523 outb(IO_RTC, reg);
524 outb(IO_RTC + 1, val);
525}
526
527static __inline int
528readrtc(int port)
529{
530 return(bcd2bin(rtcin(port)));
531}
532
533static u_int
534calibrate_clocks(void)
535{
536 u_int count, prev_count, tot_count;
537 int sec, start_sec, timeout;
538
539 if (bootverbose)
540 printf("Calibrating clock(s) ... ");
541 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
542 goto fail;
543 timeout = 100000000;
544
545 /* Read the mc146818A seconds counter. */
546 for (;;) {
547 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
548 sec = rtcin(RTC_SEC);
549 break;
550 }
551 if (--timeout == 0)
552 goto fail;
553 }
554
555 /* Wait for the mC146818A seconds counter to change. */
556 start_sec = sec;
557 for (;;) {
558 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
559 sec = rtcin(RTC_SEC);
560 if (sec != start_sec)
561 break;
562 }
563 if (--timeout == 0)
564 goto fail;
565 }
566
567 /* Start keeping track of the i8254 counter. */
568 prev_count = getit();
569 if (prev_count == 0 || prev_count > timer0_max_count)
570 goto fail;
571 tot_count = 0;
572
573#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
574 if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)
575 wrmsr(0x10, 0LL); /* XXX 0x10 is the MSR for the TSC */
576#endif
577
578 /*
579 * Wait for the mc146818A seconds counter to change. Read the i8254
580 * counter for each iteration since this is convenient and only
581 * costs a few usec of inaccuracy. The timing of the final reads
582 * of the counters almost matches the timing of the initial reads,
583 * so the main cause of inaccuracy is the varying latency from
584 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
585 * rtcin(RTC_SEC) that returns a changed seconds count. The
586 * maximum inaccuracy from this cause is < 10 usec on 486's.
587 */
588 start_sec = sec;
589 for (;;) {
590 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
591 sec = rtcin(RTC_SEC);
592 count = getit();
593 if (count == 0 || count > timer0_max_count)
594 goto fail;
595 if (count > prev_count)
596 tot_count += prev_count - (count - timer0_max_count);
597 else
598 tot_count += prev_count - count;
599 prev_count = count;
600 if (sec != start_sec)
601 break;
602 if (--timeout == 0)
603 goto fail;
604 }
605
606#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
607 /*
608 * Read the cpu cycle counter. The timing considerations are
609 * similar to those for the i8254 clock.
610 */
611 if (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686) {
612 set_i586_ctr_freq((u_int)rdtsc(), tot_count);
613 if (bootverbose)
614 printf("i586 clock: %u Hz, ", i586_ctr_freq);
615 }
616#endif
617
618 if (bootverbose)
619 printf("i8254 clock: %u Hz\n", tot_count);
620 return (tot_count);
621
622fail:
623 if (bootverbose)
624 printf("failed, using default i8254 clock of %u Hz\n",
625 timer_freq);
626 return (timer_freq);
627}
628
629static void
630set_timer_freq(u_int freq, int intr_freq)
631{
632 u_long ef;
633
634 ef = read_eflags();
635 disable_intr();
636 timer_freq = freq;
637 timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
638 timer0_overflow_threshold = timer0_max_count - TIMER0_LATCH_COUNT;
639 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
640 outb(TIMER_CNTR0, timer0_max_count & 0xff);
641 outb(TIMER_CNTR0, timer0_max_count >> 8);
642 CLOCK_UNLOCK();
643 write_eflags(ef);
644}
645
646/*
647 * Initialize 8253 timer 0 early so that it can be used in DELAY().
648 * XXX initialization of other timers is unintentionally left blank.
649 */
650void
651startrtclock()
652{
653 u_int delta, freq;
654
655 writertc(RTC_STATUSA, rtc_statusa);
656 writertc(RTC_STATUSB, RTCSB_24HR);
657
658 set_timer_freq(timer_freq, hz);
659 freq = calibrate_clocks();
660#ifdef CLK_CALIBRATION_LOOP
661 if (bootverbose) {
662 printf(
663 "Press a key on the console to abort clock calibration\n");
664 while (cncheckc() == -1)
665 calibrate_clocks();
666 }
667#endif
668
669 /*
670 * Use the calibrated i8254 frequency if it seems reasonable.
671 * Otherwise use the default, and don't use the calibrated i586
672 * frequency.
673 */
674 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
675 if (delta < timer_freq / 100) {
676#ifndef CLK_USE_I8254_CALIBRATION
677 if (bootverbose)
678 printf(
679"CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
680 freq = timer_freq;
681#endif
682 timer_freq = freq;
683 } else {
684 if (bootverbose)
685 printf(
686 "%d Hz differs from default of %d Hz by more than 1%%\n",
687 freq, timer_freq);
688#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
689 i586_ctr_freq = 0;
690#endif
691 }
692
693 set_timer_freq(timer_freq, hz);
694
695#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
696#ifndef CLK_USE_I586_CALIBRATION
697 if (i586_ctr_freq != 0) {
698 if (bootverbose)
699 printf(
700"CLK_USE_I586_CALIBRATION not specified - using old calibration method\n");
701 i586_ctr_freq = 0;
702 }
703#endif
704 if (i586_ctr_freq == 0 &&
705 (cpu_class == CPUCLASS_586 || cpu_class == CPUCLASS_686)) {
706 /*
707 * Calibration of the i586 clock relative to the mc146818A
708 * clock failed. Do a less accurate calibration relative
709 * to the i8254 clock.
710 */
711 wrmsr(0x10, 0LL); /* XXX */
712 DELAY(1000000);
713 set_i586_ctr_freq((u_int)rdtsc(), timer_freq);
714#ifdef CLK_USE_I586_CALIBRATION
715 if (bootverbose)
716 printf("i586 clock: %u Hz\n", i586_ctr_freq);
717#endif
718 }
719#endif
720}
721
722/*
723 * Initialize the time of day register, based on the time base which is, e.g.
724 * from a filesystem.
725 */
726void
727inittodr(time_t base)
728{
729 unsigned long sec, days;
730 int yd;
731 int year, month;
732 int y, m, s;
733
734 s = splclock();
735 time.tv_sec = base;
736 time.tv_usec = 0;
737 splx(s);
738
739 /* Look if we have a RTC present and the time is valid */
740 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
741 goto wrong_time;
742
743 /* wait for time update to complete */
744 /* If RTCSA_TUP is zero, we have at least 244us before next update */
745 while (rtcin(RTC_STATUSA) & RTCSA_TUP);
746
747 days = 0;
748#ifdef USE_RTC_CENTURY
749 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
750#else
751 year = readrtc(RTC_YEAR) + 1900;
752 if (year < 1970)
753 year += 100;
754#endif
755 if (year < 1970)
756 goto wrong_time;
757 month = readrtc(RTC_MONTH);
758 for (m = 1; m < month; m++)
759 days += daysinmonth[m-1];
760 if ((month > 2) && LEAPYEAR(year))
761 days ++;
762 days += readrtc(RTC_DAY) - 1;
763 yd = days;
764 for (y = 1970; y < year; y++)
765 days += DAYSPERYEAR + LEAPYEAR(y);
766 sec = ((( days * 24 +
767 readrtc(RTC_HRS)) * 60 +
768 readrtc(RTC_MIN)) * 60 +
769 readrtc(RTC_SEC));
770 /* sec now contains the number of seconds, since Jan 1 1970,
771 in the local time zone */
772
773 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
774
775 s = splclock();
776 time.tv_sec = sec;
777 splx(s);
778 return;
779
780wrong_time:
781 printf("Invalid time in real time clock.\n");
782 printf("Check and reset the date immediately!\n");
783}
784
785/*
786 * Write system time back to RTC
787 */
788void
789resettodr()
790{
791 unsigned long tm;
792 int y, m, s;
793
794 if (disable_rtc_set)
795 return;
796
797 s = splclock();
798 tm = time.tv_sec;
799 splx(s);
800
801 /* Disable RTC updates and interrupts. */
802 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
803
804 /* Calculate local time to put in RTC */
805
806 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
807
808 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
809 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
810 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
811
812 /* We have now the days since 01-01-1970 in tm */
813 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
814 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
815 tm >= m;
816 y++, m = DAYSPERYEAR + LEAPYEAR(y))
817 tm -= m;
818
819 /* Now we have the years in y and the day-of-the-year in tm */
820 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
821#ifdef USE_RTC_CENTURY
822 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
823#endif
824 for (m = 0; ; m++) {
825 int ml;
826
827 ml = daysinmonth[m];
828 if (m == 1 && LEAPYEAR(y))
829 ml++;
830 if (tm < ml)
831 break;
832 tm -= ml;
833 }
834
835 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
836 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
837
838 /* Reenable RTC updates and interrupts. */
839 writertc(RTC_STATUSB, rtc_statusb);
840}
841
842
843/*
844 * Start both clocks running.
845 */
846void
847cpu_initclocks()
848{
849 int diag;
850#ifdef APIC_IO
851 int x;
852#endif /* APIC_IO */
853
854 if (statclock_disable) {
855 /*
856 * The stat interrupt mask is different without the
857 * statistics clock. Also, don't set the interrupt
858 * flag which would normally cause the RTC to generate
859 * interrupts.
860 */
861 stat_imask = HWI_MASK | SWI_MASK;
862 rtc_statusb = RTCSB_24HR;
863 } else {
864 /* Setting stathz to nonzero early helps avoid races. */
865 stathz = RTC_NOPROFRATE;
866 profhz = RTC_PROFRATE;
867 }
868
869 /* Finish initializing 8253 timer 0. */
870#ifdef APIC_IO
871
872 /* 1st look for ExtInt on pin 0 */
873 if (apic_int_type(0, 0) == 3) {
874 /*
875 * Allow 8254 timer to INTerrupt 8259:
876 * re-initialize master 8259:
877 * reset; prog 4 bytes, single ICU, edge triggered
878 */
879 outb(IO_ICU1, 0x13);
880 outb(IO_ICU1 + 1, NRSVIDT); /* start vector (unused) */
881 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
882 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
883 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
884
885 /* program IO APIC for type 3 INT on INT0 */
886 if (ext_int_setup(0, 0) < 0)
887 panic("8254 redirect via APIC pin0 impossible!");
888
889 x = 0;
890 /* XXX if (bootverbose) */
891 printf("APIC_IO: routing 8254 via 8259 on pin 0\n");
892 }
893
894 /* failing that, look for 8254 on pin 2 */
895 else if (isa_apic_pin(0) == 2) {
896 x = 2;
897 /* XXX if (bootverbose) */
898 printf("APIC_IO: routing 8254 via pin 2\n");
899 }
900
901 /* better write that 8254 INT discover code... */
902 else
903 panic("neither pin 0 or pin 2 works for 8254");
904
905 /* setup the vectors */
906 vec[x] = (u_int)vec8254;
907 Xintr8254 = (u_int)ivectors[x];
908 mask8254 = (1 << x);
909
910 register_intr(/* irq */ x, /* XXX id */ 0, /* flags */ 0,
911 /* XXX */ (inthand2_t *)clkintr, &clk_imask,
912 /* unit */ 0);
913 INTREN(mask8254);
914
915#else /* APIC_IO */
916
917 register_intr(/* irq */ 0, /* XXX id */ 0, /* flags */ 0,
918 /* XXX */ (inthand2_t *)clkintr, &clk_imask,
919 /* unit */ 0);
920 INTREN(IRQ0);
921
922#endif /* APIC_IO */
923
924#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
925 /*
926 * Finish setting up anti-jitter measures.
927 */
928 if (i586_ctr_freq != 0)
929 i586_ctr_bias = rdtsc();
930#endif
931
932 /* Initialize RTC. */
933 writertc(RTC_STATUSA, rtc_statusa);
934 writertc(RTC_STATUSB, RTCSB_24HR);
935
936 /* Don't bother enabling the statistics clock. */
937 if (statclock_disable)
938 return;
939 diag = rtcin(RTC_DIAG);
940 if (diag != 0)
941 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
942
943#ifdef APIC_IO
944 if (isa_apic_pin(8) != 8)
945 panic("APIC RTC != 8");
946#endif /* APIC_IO */
947
948 register_intr(/* irq */ 8, /* XXX id */ 1, /* flags */ 0,
949 /* XXX */ (inthand2_t *)rtcintr, &stat_imask,
950 /* unit */ 0);
951
952#ifdef APIC_IO
953 INTREN(APIC_IRQ8);
954#else
955 INTREN(IRQ8);
956#endif /* APIC_IO */
957
958 writertc(RTC_STATUSB, rtc_statusb);
959}
960
961void
962setstatclockrate(int newhz)
963{
964 if (newhz == RTC_PROFRATE)
965 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
966 else
967 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
968 writertc(RTC_STATUSA, rtc_statusa);
969}
970
971static int
972sysctl_machdep_i8254_freq SYSCTL_HANDLER_ARGS
973{
974 int error;
975 u_int freq;
976
977 /*
978 * Use `i8254' instead of `timer' in external names because `timer'
979 * is is too generic. Should use it everywhere.
980 */
981 freq = timer_freq;
982 error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
983 if (error == 0 && req->newptr != NULL) {
984 if (timer0_state != 0)
985 return (EBUSY); /* too much trouble to handle */
986 set_timer_freq(freq, hz);
987#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
988 set_i586_ctr_freq(i586_ctr_freq, timer_freq);
989#endif
990 }
991 return (error);
992}
993
994SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
995 0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
996
997#if (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP)
998static void
999set_i586_ctr_freq(u_int i586_freq, u_int i8254_freq)
1000{
1001 u_int comultiplier, multiplier;
1002 u_long ef;
1003
1004 if (i586_freq == 0) {
1005 i586_ctr_freq = i586_freq;
1006 return;
1007 }
1008 comultiplier = ((unsigned long long)i586_freq
1009 << I586_CTR_COMULTIPLIER_SHIFT) / i8254_freq;
1010 multiplier = (1000000LL << I586_CTR_MULTIPLIER_SHIFT) / i586_freq;
1011 ef = read_eflags();
1012 disable_intr();
1013 i586_ctr_freq = i586_freq;
1014 i586_ctr_comultiplier = comultiplier;
1015 i586_ctr_multiplier = multiplier;
1016 CLOCK_UNLOCK();
1017 write_eflags(ef);
1018}
1019
1020static int
1021sysctl_machdep_i586_freq SYSCTL_HANDLER_ARGS
1022{
1023 int error;
1024 u_int freq;
1025
1026 if (cpu_class != CPUCLASS_586 && cpu_class != CPUCLASS_686)
1027 return (EOPNOTSUPP);
1028 freq = i586_ctr_freq;
1029 error = sysctl_handle_opaque(oidp, &freq, sizeof freq, req);
1030 if (error == 0 && req->newptr != NULL)
1031 set_i586_ctr_freq(freq, timer_freq);
1032 return (error);
1033}
1034
1035SYSCTL_PROC(_machdep, OID_AUTO, i586_freq, CTLTYPE_INT | CTLFLAG_RW,
1036 0, sizeof(u_int), sysctl_machdep_i586_freq, "I", "");
1037#endif /* (defined(I586_CPU) || defined(I686_CPU)) && !defined(SMP) */