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