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