FreeBSD/Linux Kernel Cross Reference
sys/i386/isa/clock.c
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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
33 */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD: releng/6.2/sys/i386/isa/clock.c 161534 2006-08-22 16:52:42Z rink $");
37
38 /*
39 * Routines to handle clock hardware.
40 */
41
42 /*
43 * inittodr, settodr and support routines written
44 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
45 *
46 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
47 */
48
49 #include "opt_apic.h"
50 #include "opt_clock.h"
51 #include "opt_isa.h"
52 #include "opt_mca.h"
53 #include "opt_xbox.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/bus.h>
58 #include <sys/lock.h>
59 #include <sys/kdb.h>
60 #include <sys/mutex.h>
61 #include <sys/proc.h>
62 #include <sys/time.h>
63 #include <sys/timetc.h>
64 #include <sys/kernel.h>
65 #include <sys/limits.h>
66 #include <sys/module.h>
67 #include <sys/sysctl.h>
68 #include <sys/cons.h>
69 #include <sys/power.h>
70
71 #include <machine/clock.h>
72 #include <machine/cputypes.h>
73 #include <machine/frame.h>
74 #include <machine/intr_machdep.h>
75 #include <machine/md_var.h>
76 #include <machine/psl.h>
77 #ifdef DEV_APIC
78 #include <machine/apicvar.h>
79 #endif
80 #include <machine/specialreg.h>
81 #include <machine/ppireg.h>
82 #include <machine/timerreg.h>
83
84 #include <isa/rtc.h>
85 #ifdef DEV_ISA
86 #include <isa/isareg.h>
87 #include <isa/isavar.h>
88 #endif
89
90 #ifdef DEV_MCA
91 #include <i386/bios/mca_machdep.h>
92 #endif
93
94 #ifdef XBOX
95 #include <machine/xbox.h>
96 #endif
97
98 /*
99 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
100 * can use a simple formula for leap years.
101 */
102 #define LEAPYEAR(y) (((u_int)(y) % 4 == 0) ? 1 : 0)
103 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
104
105 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
106
107 int adjkerntz; /* local offset from GMT in seconds */
108 int clkintr_pending;
109 int disable_rtc_set; /* disable resettodr() if != 0 */
110 int pscnt = 1;
111 int psdiv = 1;
112 int statclock_disable;
113 #ifndef TIMER_FREQ
114 #define TIMER_FREQ 1193182
115 #endif
116 u_int timer_freq = TIMER_FREQ;
117 int timer0_max_count;
118 int timer0_real_max_count;
119 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
120 struct mtx clock_lock;
121 #define RTC_LOCK mtx_lock_spin(&clock_lock)
122 #define RTC_UNLOCK mtx_unlock_spin(&clock_lock)
123
124 static int beeping = 0;
125 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
126 static struct intsrc *i8254_intsrc;
127 static u_int32_t i8254_lastcount;
128 static u_int32_t i8254_offset;
129 static int (*i8254_pending)(struct intsrc *);
130 static int i8254_ticked;
131 static int using_lapic_timer;
132 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
133 static u_char rtc_statusb = RTCSB_24HR;
134
135 /* Values for timerX_state: */
136 #define RELEASED 0
137 #define RELEASE_PENDING 1
138 #define ACQUIRED 2
139 #define ACQUIRE_PENDING 3
140
141 static u_char timer2_state;
142
143 static unsigned i8254_get_timecount(struct timecounter *tc);
144 static unsigned i8254_simple_get_timecount(struct timecounter *tc);
145 static void set_timer_freq(u_int freq, int intr_freq);
146
147 static struct timecounter i8254_timecounter = {
148 i8254_get_timecount, /* get_timecount */
149 0, /* no poll_pps */
150 ~0u, /* counter_mask */
151 0, /* frequency */
152 "i8254", /* name */
153 0 /* quality */
154 };
155
156 static void
157 clkintr(struct clockframe *frame)
158 {
159
160 if (timecounter->tc_get_timecount == i8254_get_timecount) {
161 mtx_lock_spin(&clock_lock);
162 if (i8254_ticked)
163 i8254_ticked = 0;
164 else {
165 i8254_offset += timer0_max_count;
166 i8254_lastcount = 0;
167 }
168 clkintr_pending = 0;
169 mtx_unlock_spin(&clock_lock);
170 }
171 if (!using_lapic_timer)
172 hardclock(frame);
173 #ifdef DEV_MCA
174 /* Reset clock interrupt by asserting bit 7 of port 0x61 */
175 if (MCA_system)
176 outb(0x61, inb(0x61) | 0x80);
177 #endif
178 }
179
180 int
181 acquire_timer2(int mode)
182 {
183
184 if (timer2_state != RELEASED)
185 return (-1);
186 timer2_state = ACQUIRED;
187
188 /*
189 * This access to the timer registers is as atomic as possible
190 * because it is a single instruction. We could do better if we
191 * knew the rate. Use of splclock() limits glitches to 10-100us,
192 * and this is probably good enough for timer2, so we aren't as
193 * careful with it as with timer0.
194 */
195 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
196
197 return (0);
198 }
199
200 int
201 release_timer2()
202 {
203
204 if (timer2_state != ACQUIRED)
205 return (-1);
206 timer2_state = RELEASED;
207 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
208 return (0);
209 }
210
211 /*
212 * This routine receives statistical clock interrupts from the RTC.
213 * As explained above, these occur at 128 interrupts per second.
214 * When profiling, we receive interrupts at a rate of 1024 Hz.
215 *
216 * This does not actually add as much overhead as it sounds, because
217 * when the statistical clock is active, the hardclock driver no longer
218 * needs to keep (inaccurate) statistics on its own. This decouples
219 * statistics gathering from scheduling interrupts.
220 *
221 * The RTC chip requires that we read status register C (RTC_INTR)
222 * to acknowledge an interrupt, before it will generate the next one.
223 * Under high interrupt load, rtcintr() can be indefinitely delayed and
224 * the clock can tick immediately after the read from RTC_INTR. In this
225 * case, the mc146818A interrupt signal will not drop for long enough
226 * to register with the 8259 PIC. If an interrupt is missed, the stat
227 * clock will halt, considerably degrading system performance. This is
228 * why we use 'while' rather than a more straightforward 'if' below.
229 * Stat clock ticks can still be lost, causing minor loss of accuracy
230 * in the statistics, but the stat clock will no longer stop.
231 */
232 static void
233 rtcintr(struct clockframe *frame)
234 {
235
236 while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
237 if (profprocs != 0) {
238 if (--pscnt == 0)
239 pscnt = psdiv;
240 profclock(frame);
241 }
242 if (pscnt == psdiv)
243 statclock(frame);
244 }
245 }
246
247 #include "opt_ddb.h"
248 #ifdef DDB
249 #include <ddb/ddb.h>
250
251 DB_SHOW_COMMAND(rtc, rtc)
252 {
253 printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
254 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
255 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
256 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
257 }
258 #endif /* DDB */
259
260 static int
261 getit(void)
262 {
263 int high, low;
264
265 mtx_lock_spin(&clock_lock);
266
267 /* Select timer0 and latch counter value. */
268 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
269
270 low = inb(TIMER_CNTR0);
271 high = inb(TIMER_CNTR0);
272
273 mtx_unlock_spin(&clock_lock);
274 return ((high << 8) | low);
275 }
276
277 /*
278 * Wait "n" microseconds.
279 * Relies on timer 1 counting down from (timer_freq / hz)
280 * Note: timer had better have been programmed before this is first used!
281 */
282 void
283 DELAY(int n)
284 {
285 int delta, prev_tick, tick, ticks_left;
286
287 #ifdef DELAYDEBUG
288 int getit_calls = 1;
289 int n1;
290 static int state = 0;
291
292 if (state == 0) {
293 state = 1;
294 for (n1 = 1; n1 <= 10000000; n1 *= 10)
295 DELAY(n1);
296 state = 2;
297 }
298 if (state == 1)
299 printf("DELAY(%d)...", n);
300 #endif
301 /*
302 * Guard against the timer being uninitialized if we are called
303 * early for console i/o.
304 */
305 if (timer0_max_count == 0)
306 set_timer_freq(timer_freq, hz);
307
308 /*
309 * Read the counter first, so that the rest of the setup overhead is
310 * counted. Guess the initial overhead is 20 usec (on most systems it
311 * takes about 1.5 usec for each of the i/o's in getit(). The loop
312 * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The
313 * multiplications and divisions to scale the count take a while).
314 *
315 * However, if ddb is active then use a fake counter since reading
316 * the i8254 counter involves acquiring a lock. ddb must not do
317 * locking for many reasons, but it calls here for at least atkbd
318 * input.
319 */
320 #ifdef KDB
321 if (kdb_active)
322 prev_tick = 1;
323 else
324 #endif
325 prev_tick = getit();
326 n -= 0; /* XXX actually guess no initial overhead */
327 /*
328 * Calculate (n * (timer_freq / 1e6)) without using floating point
329 * and without any avoidable overflows.
330 */
331 if (n <= 0)
332 ticks_left = 0;
333 else if (n < 256)
334 /*
335 * Use fixed point to avoid a slow division by 1000000.
336 * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
337 * 2^15 is the first power of 2 that gives exact results
338 * for n between 0 and 256.
339 */
340 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
341 else
342 /*
343 * Don't bother using fixed point, although gcc-2.7.2
344 * generates particularly poor code for the long long
345 * division, since even the slow way will complete long
346 * before the delay is up (unless we're interrupted).
347 */
348 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
349 / 1000000;
350
351 while (ticks_left > 0) {
352 #ifdef KDB
353 if (kdb_active) {
354 inb(0x84);
355 tick = prev_tick - 1;
356 if (tick <= 0)
357 tick = timer0_max_count;
358 } else
359 #endif
360 tick = getit();
361 #ifdef DELAYDEBUG
362 ++getit_calls;
363 #endif
364 delta = prev_tick - tick;
365 prev_tick = tick;
366 if (delta < 0) {
367 delta += timer0_max_count;
368 /*
369 * Guard against timer0_max_count being wrong.
370 * This shouldn't happen in normal operation,
371 * but it may happen if set_timer_freq() is
372 * traced.
373 */
374 if (delta < 0)
375 delta = 0;
376 }
377 ticks_left -= delta;
378 }
379 #ifdef DELAYDEBUG
380 if (state == 1)
381 printf(" %d calls to getit() at %d usec each\n",
382 getit_calls, (n + 5) / getit_calls);
383 #endif
384 }
385
386 static void
387 sysbeepstop(void *chan)
388 {
389 ppi_spkr_off(); /* disable counter2 output to speaker */
390 timer_spkr_release();
391 beeping = 0;
392 }
393
394 int
395 sysbeep(int pitch, int period)
396 {
397 int x = splclock();
398
399 if (timer_spkr_acquire())
400 if (!beeping) {
401 /* Something else owns it. */
402 splx(x);
403 return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
404 }
405 mtx_lock_spin(&clock_lock);
406 spkr_set_pitch(pitch);
407 mtx_unlock_spin(&clock_lock);
408 if (!beeping) {
409 /* enable counter2 output to speaker */
410 ppi_spkr_on();
411 beeping = period;
412 timeout(sysbeepstop, (void *)NULL, period);
413 }
414 splx(x);
415 return (0);
416 }
417
418 /*
419 * RTC support routines
420 */
421
422 int
423 rtcin(reg)
424 int reg;
425 {
426 u_char val;
427
428 RTC_LOCK;
429 outb(IO_RTC, reg);
430 inb(0x84);
431 val = inb(IO_RTC + 1);
432 inb(0x84);
433 RTC_UNLOCK;
434 return (val);
435 }
436
437 static __inline void
438 writertc(u_char reg, u_char val)
439 {
440
441 RTC_LOCK;
442 inb(0x84);
443 outb(IO_RTC, reg);
444 inb(0x84);
445 outb(IO_RTC + 1, val);
446 inb(0x84); /* XXX work around wrong order in rtcin() */
447 RTC_UNLOCK;
448 }
449
450 static __inline int
451 readrtc(int port)
452 {
453 return(bcd2bin(rtcin(port)));
454 }
455
456 static u_int
457 calibrate_clocks(void)
458 {
459 u_int count, prev_count, tot_count;
460 int sec, start_sec, timeout;
461
462 if (bootverbose)
463 printf("Calibrating clock(s) ... ");
464 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
465 goto fail;
466 timeout = 100000000;
467
468 /* Read the mc146818A seconds counter. */
469 for (;;) {
470 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
471 sec = rtcin(RTC_SEC);
472 break;
473 }
474 if (--timeout == 0)
475 goto fail;
476 }
477
478 /* Wait for the mC146818A seconds counter to change. */
479 start_sec = sec;
480 for (;;) {
481 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
482 sec = rtcin(RTC_SEC);
483 if (sec != start_sec)
484 break;
485 }
486 if (--timeout == 0)
487 goto fail;
488 }
489
490 /* Start keeping track of the i8254 counter. */
491 prev_count = getit();
492 if (prev_count == 0 || prev_count > timer0_max_count)
493 goto fail;
494 tot_count = 0;
495
496 /*
497 * Wait for the mc146818A seconds counter to change. Read the i8254
498 * counter for each iteration since this is convenient and only
499 * costs a few usec of inaccuracy. The timing of the final reads
500 * of the counters almost matches the timing of the initial reads,
501 * so the main cause of inaccuracy is the varying latency from
502 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
503 * rtcin(RTC_SEC) that returns a changed seconds count. The
504 * maximum inaccuracy from this cause is < 10 usec on 486's.
505 */
506 start_sec = sec;
507 for (;;) {
508 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
509 sec = rtcin(RTC_SEC);
510 count = getit();
511 if (count == 0 || count > timer0_max_count)
512 goto fail;
513 if (count > prev_count)
514 tot_count += prev_count - (count - timer0_max_count);
515 else
516 tot_count += prev_count - count;
517 prev_count = count;
518 if (sec != start_sec)
519 break;
520 if (--timeout == 0)
521 goto fail;
522 }
523
524 if (bootverbose) {
525 printf("i8254 clock: %u Hz\n", tot_count);
526 }
527 return (tot_count);
528
529 fail:
530 #ifdef XBOX
531 if (arch_i386_is_xbox)
532 timer_freq = 1125000; /* gives ~733.34MHz CPU clock */
533 #endif
534
535 if (bootverbose)
536 printf("failed, using default i8254 clock of %u Hz\n",
537 timer_freq);
538 return (timer_freq);
539 }
540
541 static void
542 set_timer_freq(u_int freq, int intr_freq)
543 {
544 int new_timer0_real_max_count;
545
546 i8254_timecounter.tc_frequency = freq;
547 mtx_lock_spin(&clock_lock);
548 timer_freq = freq;
549 if (using_lapic_timer)
550 new_timer0_real_max_count = 0x10000;
551 else
552 new_timer0_real_max_count = TIMER_DIV(intr_freq);
553 if (new_timer0_real_max_count != timer0_real_max_count) {
554 timer0_real_max_count = new_timer0_real_max_count;
555 if (timer0_real_max_count == 0x10000)
556 timer0_max_count = 0xffff;
557 else
558 timer0_max_count = timer0_real_max_count;
559 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
560 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
561 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
562 }
563 mtx_unlock_spin(&clock_lock);
564 }
565
566 static void
567 i8254_restore(void)
568 {
569
570 mtx_lock_spin(&clock_lock);
571 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
572 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
573 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
574 mtx_unlock_spin(&clock_lock);
575 }
576
577 static void
578 rtc_restore(void)
579 {
580
581 /* Restore all of the RTC's "status" (actually, control) registers. */
582 /* XXX locking is needed for RTC access. */
583 writertc(RTC_STATUSB, RTCSB_24HR);
584 writertc(RTC_STATUSA, rtc_statusa);
585 writertc(RTC_STATUSB, rtc_statusb);
586 rtcin(RTC_INTR);
587 }
588
589 /*
590 * Restore all the timers non-atomically (XXX: should be atomically).
591 *
592 * This function is called from pmtimer_resume() to restore all the timers.
593 * This should not be necessary, but there are broken laptops that do not
594 * restore all the timers on resume.
595 */
596 void
597 timer_restore(void)
598 {
599
600 i8254_restore(); /* restore timer_freq and hz */
601 rtc_restore(); /* reenable RTC interrupts */
602 }
603
604 /*
605 * Initialize 8254 timer 0 early so that it can be used in DELAY().
606 * XXX initialization of other timers is unintentionally left blank.
607 */
608 void
609 startrtclock()
610 {
611 u_int delta, freq;
612
613 writertc(RTC_STATUSA, rtc_statusa);
614 writertc(RTC_STATUSB, RTCSB_24HR);
615
616 set_timer_freq(timer_freq, hz);
617 freq = calibrate_clocks();
618 #ifdef CLK_CALIBRATION_LOOP
619 if (bootverbose) {
620 printf(
621 "Press a key on the console to abort clock calibration\n");
622 while (cncheckc() == -1)
623 calibrate_clocks();
624 }
625 #endif
626
627 /*
628 * Use the calibrated i8254 frequency if it seems reasonable.
629 * Otherwise use the default, and don't use the calibrated i586
630 * frequency.
631 */
632 delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
633 if (delta < timer_freq / 100) {
634 #ifndef CLK_USE_I8254_CALIBRATION
635 if (bootverbose)
636 printf(
637 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
638 freq = timer_freq;
639 #endif
640 timer_freq = freq;
641 } else {
642 if (bootverbose)
643 printf(
644 "%d Hz differs from default of %d Hz by more than 1%%\n",
645 freq, timer_freq);
646 }
647
648 set_timer_freq(timer_freq, hz);
649 tc_init(&i8254_timecounter);
650
651 init_TSC();
652 }
653
654 /*
655 * Initialize the time of day register, based on the time base which is, e.g.
656 * from a filesystem.
657 */
658 void
659 inittodr(time_t base)
660 {
661 unsigned long sec, days;
662 int year, month;
663 int y, m, s;
664 struct timespec ts;
665
666 if (base) {
667 s = splclock();
668 ts.tv_sec = base;
669 ts.tv_nsec = 0;
670 tc_setclock(&ts);
671 splx(s);
672 }
673
674 /* Look if we have a RTC present and the time is valid */
675 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
676 goto wrong_time;
677
678 /* wait for time update to complete */
679 /* If RTCSA_TUP is zero, we have at least 244us before next update */
680 s = splhigh();
681 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
682 splx(s);
683 s = splhigh();
684 }
685
686 days = 0;
687 #ifdef USE_RTC_CENTURY
688 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
689 #else
690 year = readrtc(RTC_YEAR) + 1900;
691 if (year < 1970)
692 year += 100;
693 #endif
694 if (year < 1970) {
695 splx(s);
696 goto wrong_time;
697 }
698 month = readrtc(RTC_MONTH);
699 for (m = 1; m < month; m++)
700 days += daysinmonth[m-1];
701 if ((month > 2) && LEAPYEAR(year))
702 days ++;
703 days += readrtc(RTC_DAY) - 1;
704 for (y = 1970; y < year; y++)
705 days += DAYSPERYEAR + LEAPYEAR(y);
706 sec = ((( days * 24 +
707 readrtc(RTC_HRS)) * 60 +
708 readrtc(RTC_MIN)) * 60 +
709 readrtc(RTC_SEC));
710 /* sec now contains the number of seconds, since Jan 1 1970,
711 in the local time zone */
712
713 sec += tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
714
715 y = time_second - sec;
716 if (y <= -2 || y >= 2) {
717 /* badly off, adjust it */
718 ts.tv_sec = sec;
719 ts.tv_nsec = 0;
720 tc_setclock(&ts);
721 }
722 splx(s);
723 return;
724
725 wrong_time:
726 printf("Invalid time in real time clock.\n");
727 printf("Check and reset the date immediately!\n");
728 }
729
730 /*
731 * Write system time back to RTC
732 */
733 void
734 resettodr()
735 {
736 unsigned long tm;
737 int y, m, s;
738
739 if (disable_rtc_set)
740 return;
741
742 s = splclock();
743 tm = time_second;
744 splx(s);
745
746 /* Disable RTC updates and interrupts. */
747 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
748
749 /* Calculate local time to put in RTC */
750
751 tm -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
752
753 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
754 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
755 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
756
757 /* We have now the days since 01-01-1970 in tm */
758 writertc(RTC_WDAY, (tm + 4) % 7 + 1); /* Write back Weekday */
759 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
760 tm >= m;
761 y++, m = DAYSPERYEAR + LEAPYEAR(y))
762 tm -= m;
763
764 /* Now we have the years in y and the day-of-the-year in tm */
765 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
766 #ifdef USE_RTC_CENTURY
767 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
768 #endif
769 for (m = 0; ; m++) {
770 int ml;
771
772 ml = daysinmonth[m];
773 if (m == 1 && LEAPYEAR(y))
774 ml++;
775 if (tm < ml)
776 break;
777 tm -= ml;
778 }
779
780 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
781 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
782
783 /* Reenable RTC updates and interrupts. */
784 writertc(RTC_STATUSB, rtc_statusb);
785 rtcin(RTC_INTR);
786 }
787
788
789 /*
790 * Start both clocks running.
791 */
792 void
793 cpu_initclocks()
794 {
795 int diag;
796
797 #ifdef DEV_APIC
798 using_lapic_timer = lapic_setup_clock();
799 #endif
800 /*
801 * If we aren't using the local APIC timer to drive the kernel
802 * clocks, setup the interrupt handler for the 8254 timer 0 so
803 * that it can drive hardclock(). Otherwise, change the 8254
804 * timecounter to user a simpler algorithm.
805 */
806 if (!using_lapic_timer) {
807 intr_add_handler("clk", 0, (driver_intr_t *)clkintr, NULL,
808 INTR_TYPE_CLK | INTR_FAST, NULL);
809 i8254_intsrc = intr_lookup_source(0);
810 if (i8254_intsrc != NULL)
811 i8254_pending =
812 i8254_intsrc->is_pic->pic_source_pending;
813 } else {
814 i8254_timecounter.tc_get_timecount =
815 i8254_simple_get_timecount;
816 i8254_timecounter.tc_counter_mask = 0xffff;
817 set_timer_freq(timer_freq, hz);
818 }
819
820 /* Initialize RTC. */
821 writertc(RTC_STATUSA, rtc_statusa);
822 writertc(RTC_STATUSB, RTCSB_24HR);
823
824 /*
825 * If the separate statistics clock hasn't been explicility disabled
826 * and we aren't already using the local APIC timer to drive the
827 * kernel clocks, then setup the RTC to periodically interrupt to
828 * drive statclock() and profclock().
829 */
830 if (!statclock_disable && !using_lapic_timer) {
831 diag = rtcin(RTC_DIAG);
832 if (diag != 0)
833 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
834
835 /* Setting stathz to nonzero early helps avoid races. */
836 stathz = RTC_NOPROFRATE;
837 profhz = RTC_PROFRATE;
838
839 /* Enable periodic interrupts from the RTC. */
840 rtc_statusb |= RTCSB_PINTR;
841 intr_add_handler("rtc", 8, (driver_intr_t *)rtcintr, NULL,
842 INTR_TYPE_CLK | INTR_FAST, NULL);
843
844 writertc(RTC_STATUSB, rtc_statusb);
845 rtcin(RTC_INTR);
846 }
847
848 init_TSC_tc();
849 }
850
851 void
852 cpu_startprofclock(void)
853 {
854
855 if (using_lapic_timer)
856 return;
857 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
858 writertc(RTC_STATUSA, rtc_statusa);
859 psdiv = pscnt = psratio;
860 }
861
862 void
863 cpu_stopprofclock(void)
864 {
865
866 if (using_lapic_timer)
867 return;
868 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
869 writertc(RTC_STATUSA, rtc_statusa);
870 psdiv = pscnt = 1;
871 }
872
873 static int
874 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
875 {
876 int error;
877 u_int freq;
878
879 /*
880 * Use `i8254' instead of `timer' in external names because `timer'
881 * is is too generic. Should use it everywhere.
882 */
883 freq = timer_freq;
884 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
885 if (error == 0 && req->newptr != NULL)
886 set_timer_freq(freq, hz);
887 return (error);
888 }
889
890 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
891 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
892
893 static unsigned
894 i8254_simple_get_timecount(struct timecounter *tc)
895 {
896
897 return (timer0_max_count - getit());
898 }
899
900 static unsigned
901 i8254_get_timecount(struct timecounter *tc)
902 {
903 u_int count;
904 u_int high, low;
905 u_int eflags;
906
907 eflags = read_eflags();
908 mtx_lock_spin(&clock_lock);
909
910 /* Select timer0 and latch counter value. */
911 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
912
913 low = inb(TIMER_CNTR0);
914 high = inb(TIMER_CNTR0);
915 count = timer0_max_count - ((high << 8) | low);
916 if (count < i8254_lastcount ||
917 (!i8254_ticked && (clkintr_pending ||
918 ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
919 i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
920 i8254_ticked = 1;
921 i8254_offset += timer0_max_count;
922 }
923 i8254_lastcount = count;
924 count += i8254_offset;
925 mtx_unlock_spin(&clock_lock);
926 return (count);
927 }
928
929 #ifdef DEV_ISA
930 /*
931 * Attach to the ISA PnP descriptors for the timer and realtime clock.
932 */
933 static struct isa_pnp_id attimer_ids[] = {
934 { 0x0001d041 /* PNP0100 */, "AT timer" },
935 { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
936 { 0 }
937 };
938
939 static int
940 attimer_probe(device_t dev)
941 {
942 int result;
943
944 if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
945 device_quiet(dev);
946 return(result);
947 }
948
949 static int
950 attimer_attach(device_t dev)
951 {
952 return(0);
953 }
954
955 static device_method_t attimer_methods[] = {
956 /* Device interface */
957 DEVMETHOD(device_probe, attimer_probe),
958 DEVMETHOD(device_attach, attimer_attach),
959 DEVMETHOD(device_detach, bus_generic_detach),
960 DEVMETHOD(device_shutdown, bus_generic_shutdown),
961 DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */
962 DEVMETHOD(device_resume, bus_generic_resume), /* XXX restart statclock? */
963 { 0, 0 }
964 };
965
966 static driver_t attimer_driver = {
967 "attimer",
968 attimer_methods,
969 1, /* no softc */
970 };
971
972 static devclass_t attimer_devclass;
973
974 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
975 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
976 #endif /* DEV_ISA */
Cache object: 9e2a93442a7de15381cfab8dc7bb3aa3
|