2 * Copyright (c) 1990 The Regents of the University of California.
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz and Don Ahn.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
36 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
37 * $FreeBSD: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki Exp $
38 * $DragonFly: src/sys/platform/pc32/isa/clock.c,v 1.55 2008/08/02 01:14:43 dillon Exp $
42 * Routines to handle clock hardware.
46 * inittodr, settodr and support routines written
47 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
49 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
53 #include "opt_clock.h"
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/eventhandler.h>
59 #include <sys/kernel.h>
64 #include <sys/sysctl.h>
66 #include <sys/systimer.h>
67 #include <sys/globaldata.h>
68 #include <sys/thread2.h>
69 #include <sys/systimer.h>
70 #include <sys/machintr.h>
72 #include <machine/clock.h>
73 #ifdef CLK_CALIBRATION_LOOP
75 #include <machine/cputypes.h>
76 #include <machine/frame.h>
77 #include <machine/ipl.h>
78 #include <machine/limits.h>
79 #include <machine/md_var.h>
80 #include <machine/psl.h>
81 #include <machine/segments.h>
82 #include <machine/smp.h>
83 #include <machine/specialreg.h>
85 #include <machine_base/icu/icu.h>
86 #include <bus/isa/isa.h>
87 #include <bus/isa/rtc.h>
88 #include <machine_base/isa/timerreg.h>
90 #include <machine_base/isa/intr_machdep.h>
93 /* The interrupt triggered by the 8254 (timer) chip */
95 static void setup_8254_mixed_mode (void);
97 static void i8254_restore(void);
98 static void resettodr_on_shutdown(void *arg __unused);
101 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
102 * can use a simple formula for leap years.
104 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
105 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
108 #define TIMER_FREQ 1193182
111 static uint8_t i8254_walltimer_sel;
112 static uint16_t i8254_walltimer_cntr;
114 int adjkerntz; /* local offset from GMT in seconds */
115 int disable_rtc_set; /* disable resettodr() if != 0 */
116 int statclock_disable = 1; /* we don't use the statclock right now */
118 int64_t tsc_frequency;
120 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
122 enum tstate { RELEASED, ACQUIRED };
123 enum tstate timer0_state;
124 enum tstate timer1_state;
125 enum tstate timer2_state;
127 static void i8254_intr_reload(sysclock_t);
128 void (*cputimer_intr_reload)(sysclock_t) = i8254_intr_reload;
130 static int beeping = 0;
131 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
132 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
133 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
134 static int rtc_loaded;
136 static int i8254_cputimer_div;
138 static struct callout sysbeepstop_ch;
140 static sysclock_t i8254_cputimer_count(void);
141 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
142 static void i8254_cputimer_destruct(struct cputimer *cputimer);
144 static struct cputimer i8254_cputimer = {
145 SLIST_ENTRY_INITIALIZER,
149 i8254_cputimer_count,
150 cputimer_default_fromhz,
151 cputimer_default_fromus,
152 i8254_cputimer_construct,
153 i8254_cputimer_destruct,
159 * timer0 clock interrupt. Timer0 is in one-shot mode and has stopped
160 * counting as of this interrupt. We use timer1 in free-running mode (not
161 * generating any interrupts) as our main counter. Each cpu has timeouts
164 * This code is INTR_MPSAFE and may be called without the BGL held.
167 clkintr(void *dummy, void *frame_arg)
169 static sysclock_t sysclock_count; /* NOTE! Must be static */
170 struct globaldata *gd = mycpu;
172 struct globaldata *gscan;
177 * SWSTROBE mode is a one-shot, the timer is no longer running
182 * XXX the dispatcher needs work. right now we call systimer_intr()
183 * directly or via IPI for any cpu with systimers queued, which is
184 * usually *ALL* of them. We need to use the LAPIC timer for this.
186 sysclock_count = sys_cputimer->count();
188 for (n = 0; n < ncpus; ++n) {
189 gscan = globaldata_find(n);
190 if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
193 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr,
196 systimer_intr(&sysclock_count, 0, frame_arg);
200 if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
201 systimer_intr(&sysclock_count, 0, frame_arg);
210 acquire_timer2(int mode)
212 if (timer2_state != RELEASED)
214 timer2_state = ACQUIRED;
217 * This access to the timer registers is as atomic as possible
218 * because it is a single instruction. We could do better if we
221 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
228 if (timer2_state != ACQUIRED)
230 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
231 timer2_state = RELEASED;
236 * This routine receives statistical clock interrupts from the RTC.
237 * As explained above, these occur at 128 interrupts per second.
238 * When profiling, we receive interrupts at a rate of 1024 Hz.
240 * This does not actually add as much overhead as it sounds, because
241 * when the statistical clock is active, the hardclock driver no longer
242 * needs to keep (inaccurate) statistics on its own. This decouples
243 * statistics gathering from scheduling interrupts.
245 * The RTC chip requires that we read status register C (RTC_INTR)
246 * to acknowledge an interrupt, before it will generate the next one.
247 * Under high interrupt load, rtcintr() can be indefinitely delayed and
248 * the clock can tick immediately after the read from RTC_INTR. In this
249 * case, the mc146818A interrupt signal will not drop for long enough
250 * to register with the 8259 PIC. If an interrupt is missed, the stat
251 * clock will halt, considerably degrading system performance. This is
252 * why we use 'while' rather than a more straightforward 'if' below.
253 * Stat clock ticks can still be lost, causing minor loss of accuracy
254 * in the statistics, but the stat clock will no longer stop.
257 rtcintr(void *dummy, void *frame)
259 while (rtcin(RTC_INTR) & RTCIR_PERIOD)
261 /* statclock(frame); no longer used */
268 DB_SHOW_COMMAND(rtc, rtc)
270 kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
271 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
272 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
273 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
278 * Return the current cpu timer count as a 32 bit integer.
282 i8254_cputimer_count(void)
284 static __uint16_t cputimer_last;
289 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
290 count = (__uint8_t)inb(i8254_walltimer_cntr); /* get countdown */
291 count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
292 count = -count; /* -> countup */
293 if (count < cputimer_last) /* rollover */
294 i8254_cputimer.base += 0x00010000;
295 ret = i8254_cputimer.base | count;
296 cputimer_last = count;
302 * This function is called whenever the system timebase changes, allowing
303 * us to calculate what is needed to convert a system timebase tick
304 * into an 8254 tick for the interrupt timer. If we can convert to a
305 * simple shift, multiplication, or division, we do so. Otherwise 64
306 * bit arithmatic is required every time the interrupt timer is reloaded.
309 cputimer_intr_config(struct cputimer *timer)
315 * Will a simple divide do the trick?
317 div = (timer->freq + (i8254_cputimer.freq / 2)) / i8254_cputimer.freq;
318 freq = i8254_cputimer.freq * div;
320 if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
321 i8254_cputimer_div = div;
323 i8254_cputimer_div = 0;
327 * Reload for the next timeout. It is possible for the reload value
328 * to be 0 or negative, indicating that an immediate timer interrupt
329 * is desired. For now make the minimum 2 ticks.
331 * We may have to convert from the system timebase to the 8254 timebase.
334 i8254_intr_reload(sysclock_t reload)
338 if (i8254_cputimer_div)
339 reload /= i8254_cputimer_div;
341 reload = (int64_t)reload * i8254_cputimer.freq / sys_cputimer->freq;
347 if (timer0_running) {
348 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); /* count-down timer */
349 count = (__uint8_t)inb(TIMER_CNTR0); /* lsb */
350 count |= ((__uint8_t)inb(TIMER_CNTR0) << 8); /* msb */
351 if (reload < count) {
352 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
353 outb(TIMER_CNTR0, (__uint8_t)reload); /* lsb */
354 outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
359 reload = 0; /* full count */
360 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
361 outb(TIMER_CNTR0, (__uint8_t)reload); /* lsb */
362 outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
369 extern int lapic_timer_test;
370 extern int lapic_timer_enable;
371 extern void lapic_timer_oneshot_intr_enable(void);
372 extern void lapic_timer_intr_test(void);
373 extern void lapic_timer_restart(void);
375 /* Piggyback lapic_timer test */
377 i8254_intr_reload_test(sysclock_t reload)
379 i8254_intr_reload(reload);
380 if (__predict_false(lapic_timer_test))
381 lapic_timer_intr_test();
387 cputimer_intr_enable(void)
390 if (lapic_timer_test || lapic_timer_enable) {
391 lapic_timer_oneshot_intr_enable();
392 if (lapic_timer_test) /* XXX */
393 cputimer_intr_reload = i8254_intr_reload_test;
399 cputimer_intr_switch(enum cputimer_intr_type type)
402 if (lapic_timer_enable || lapic_timer_test) {
404 case CPUTIMER_INTRT_C3:
405 cputimer_intr_reload = i8254_intr_reload;
406 /* Force a quick reload */
407 i8254_intr_reload(0);
410 case CPUTIMER_INTRT_FAST:
411 if (lapic_timer_test) /* XXX */
412 cputimer_intr_reload = i8254_intr_reload_test;
413 else if (lapic_timer_enable)
414 lapic_timer_restart();
422 sysctl_cputimer_intr_switch(SYSCTL_HANDLER_ARGS)
424 enum cputimer_intr_type type = CPUTIMER_INTRT_FAST;
427 error = sysctl_handle_int(oidp, &type, 0, req);
428 if (error || req->newptr == NULL)
431 case CPUTIMER_INTRT_C3:
432 case CPUTIMER_INTRT_FAST:
437 cputimer_intr_switch(type);
440 SYSCTL_PROC(_hw, OID_AUTO, cputimer_intr_type, CTLTYPE_INT | CTLFLAG_RW,
441 0, 0, sysctl_cputimer_intr_switch, "I",
442 "cputimer_intr switch [0|1]");
445 * DELAY(usec) - Spin for the specified number of microseconds.
446 * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
447 * but do a thread switch in the loop
449 * Relies on timer 1 counting down from (cputimer_freq / hz)
450 * Note: timer had better have been programmed before this is first used!
453 DODELAY(int n, int doswitch)
455 int delta, prev_tick, tick, ticks_left;
460 static int state = 0;
464 for (n1 = 1; n1 <= 10000000; n1 *= 10)
469 kprintf("DELAY(%d)...", n);
472 * Guard against the timer being uninitialized if we are called
473 * early for console i/o.
475 if (timer0_state == RELEASED)
479 * Read the counter first, so that the rest of the setup overhead is
480 * counted. Then calculate the number of hardware timer ticks
481 * required, rounding up to be sure we delay at least the requested
482 * number of microseconds.
484 prev_tick = sys_cputimer->count();
485 ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
491 while (ticks_left > 0) {
492 tick = sys_cputimer->count();
496 delta = tick - prev_tick;
501 if (doswitch && ticks_left > 0)
506 kprintf(" %d calls to getit() at %d usec each\n",
507 getit_calls, (n + 5) / getit_calls);
518 DRIVERSLEEP(int usec)
520 globaldata_t gd = mycpu;
522 if (gd->gd_intr_nesting_level ||
523 gd->gd_spinlock_rd ||
524 gd->gd_spinlocks_wr) {
532 sysbeepstop(void *chan)
534 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
540 sysbeep(int pitch, int period)
542 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
545 * Nobody else is using timer2, we do not need the clock lock
547 outb(TIMER_CNTR2, pitch);
548 outb(TIMER_CNTR2, (pitch>>8));
550 /* enable counter2 output to speaker */
551 outb(IO_PPI, inb(IO_PPI) | 3);
553 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
559 * RTC support routines
570 val = inb(IO_RTC + 1);
577 writertc(u_char reg, u_char val)
583 outb(IO_RTC + 1, val);
584 inb(0x84); /* XXX work around wrong order in rtcin() */
591 return(bcd2bin(rtcin(port)));
595 calibrate_clocks(void)
598 u_int count, prev_count, tot_count;
599 int sec, start_sec, timeout;
602 kprintf("Calibrating clock(s) ... ");
603 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
607 /* Read the mc146818A seconds counter. */
609 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
610 sec = rtcin(RTC_SEC);
617 /* Wait for the mC146818A seconds counter to change. */
620 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
621 sec = rtcin(RTC_SEC);
622 if (sec != start_sec)
629 /* Start keeping track of the i8254 counter. */
630 prev_count = sys_cputimer->count();
636 old_tsc = 0; /* shut up gcc */
639 * Wait for the mc146818A seconds counter to change. Read the i8254
640 * counter for each iteration since this is convenient and only
641 * costs a few usec of inaccuracy. The timing of the final reads
642 * of the counters almost matches the timing of the initial reads,
643 * so the main cause of inaccuracy is the varying latency from
644 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
645 * rtcin(RTC_SEC) that returns a changed seconds count. The
646 * maximum inaccuracy from this cause is < 10 usec on 486's.
650 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
651 sec = rtcin(RTC_SEC);
652 count = sys_cputimer->count();
653 tot_count += (int)(count - prev_count);
655 if (sec != start_sec)
662 * Read the cpu cycle counter. The timing considerations are
663 * similar to those for the i8254 clock.
666 tsc_frequency = rdtsc() - old_tsc;
670 kprintf("TSC clock: %llu Hz, ", tsc_frequency);
671 kprintf("i8254 clock: %u Hz\n", tot_count);
675 kprintf("failed, using default i8254 clock of %u Hz\n",
676 i8254_cputimer.freq);
677 return (i8254_cputimer.freq);
683 timer0_state = ACQUIRED;
688 * Timer0 is our fine-grained variable clock interrupt
690 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
691 outb(TIMER_CNTR0, 2); /* lsb */
692 outb(TIMER_CNTR0, 0); /* msb */
696 * Timer1 or timer2 is our free-running clock, but only if another
697 * has not been selected.
699 cputimer_register(&i8254_cputimer);
700 cputimer_select(&i8254_cputimer, 0);
704 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
709 * Should we use timer 1 or timer 2 ?
712 TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
713 if (which != 1 && which != 2)
718 timer->name = "i8254_timer1";
719 timer->type = CPUTIMER_8254_SEL1;
720 i8254_walltimer_sel = TIMER_SEL1;
721 i8254_walltimer_cntr = TIMER_CNTR1;
722 timer1_state = ACQUIRED;
725 timer->name = "i8254_timer2";
726 timer->type = CPUTIMER_8254_SEL2;
727 i8254_walltimer_sel = TIMER_SEL2;
728 i8254_walltimer_cntr = TIMER_CNTR2;
729 timer2_state = ACQUIRED;
733 timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
736 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
737 outb(i8254_walltimer_cntr, 0); /* lsb */
738 outb(i8254_walltimer_cntr, 0); /* msb */
739 outb(IO_PPI, inb(IO_PPI) | 1); /* bit 0: enable gate, bit 1: spkr */
744 i8254_cputimer_destruct(struct cputimer *timer)
746 switch(timer->type) {
747 case CPUTIMER_8254_SEL1:
748 timer1_state = RELEASED;
750 case CPUTIMER_8254_SEL2:
751 timer2_state = RELEASED;
762 /* Restore all of the RTC's "status" (actually, control) registers. */
763 writertc(RTC_STATUSB, RTCSB_24HR);
764 writertc(RTC_STATUSA, rtc_statusa);
765 writertc(RTC_STATUSB, rtc_statusb);
769 * Restore all the timers.
771 * This function is called to resynchronize our core timekeeping after a
772 * long halt, e.g. from apm_default_resume() and friends. It is also
773 * called if after a BIOS call we have detected munging of the 8254.
774 * It is necessary because cputimer_count() counter's delta may have grown
775 * too large for nanouptime() and friends to handle, or (in the case of 8254
776 * munging) might cause the SYSTIMER code to prematurely trigger.
782 i8254_restore(); /* restore timer_freq and hz */
783 rtc_restore(); /* reenable RTC interrupts */
788 * Initialize 8254 timer 0 early so that it can be used in DELAY().
796 * Can we use the TSC?
798 if (cpu_feature & CPUID_TSC)
804 * Initial RTC state, don't do anything unexpected
806 writertc(RTC_STATUSA, rtc_statusa);
807 writertc(RTC_STATUSB, RTCSB_24HR);
810 * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to
811 * generate an interrupt, which we will ignore for now.
813 * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
814 * (so it counts a full 2^16 and repeats). We will use this timer
818 freq = calibrate_clocks();
819 #ifdef CLK_CALIBRATION_LOOP
822 "Press a key on the console to abort clock calibration\n");
823 while (cncheckc() == -1)
829 * Use the calibrated i8254 frequency if it seems reasonable.
830 * Otherwise use the default, and don't use the calibrated i586
833 delta = freq > i8254_cputimer.freq ?
834 freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
835 if (delta < i8254_cputimer.freq / 100) {
836 #ifndef CLK_USE_I8254_CALIBRATION
839 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
840 freq = i8254_cputimer.freq;
842 cputimer_set_frequency(&i8254_cputimer, freq);
846 "%d Hz differs from default of %d Hz by more than 1%%\n",
847 freq, i8254_cputimer.freq);
851 #ifndef CLK_USE_TSC_CALIBRATION
852 if (tsc_frequency != 0) {
855 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
859 if (tsc_present && tsc_frequency == 0) {
861 * Calibration of the i586 clock relative to the mc146818A
862 * clock failed. Do a less accurate calibration relative
863 * to the i8254 clock.
865 u_int64_t old_tsc = rdtsc();
868 tsc_frequency = rdtsc() - old_tsc;
869 #ifdef CLK_USE_TSC_CALIBRATION
871 kprintf("TSC clock: %llu Hz (Method B)\n",
877 EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
881 * We can not use the TSC in SMP mode, until we figure out a
882 * cheap (impossible), reliable and precise (yeah right!) way
883 * to synchronize the TSCs of all the CPUs.
884 * Curse Intel for leaving the counter out of the I/O APIC.
889 * We can not use the TSC if we support APM. Precise timekeeping
890 * on an APM'ed machine is at best a fools pursuit, since
891 * any and all of the time spent in various SMM code can't
892 * be reliably accounted for. Reading the RTC is your only
893 * source of reliable time info. The i8254 looses too of course
894 * but we need to have some kind of time...
895 * We don't know at this point whether APM is going to be used
896 * or not, nor when it might be activated. Play it safe.
899 #endif /* NAPM > 0 */
901 #endif /* !defined(SMP) */
905 * Sync the time of day back to the RTC on shutdown, but only if
906 * we have already loaded it and have not crashed.
909 resettodr_on_shutdown(void *arg __unused)
911 if (rtc_loaded && panicstr == NULL) {
917 * Initialize the time of day register, based on the time base which is, e.g.
921 inittodr(time_t base)
923 unsigned long sec, days;
935 /* Look if we have a RTC present and the time is valid */
936 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
939 /* wait for time update to complete */
940 /* If RTCSA_TUP is zero, we have at least 244us before next update */
942 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
948 #ifdef USE_RTC_CENTURY
949 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
951 year = readrtc(RTC_YEAR) + 1900;
959 month = readrtc(RTC_MONTH);
960 for (m = 1; m < month; m++)
961 days += daysinmonth[m-1];
962 if ((month > 2) && LEAPYEAR(year))
964 days += readrtc(RTC_DAY) - 1;
966 for (y = 1970; y < year; y++)
967 days += DAYSPERYEAR + LEAPYEAR(y);
968 sec = ((( days * 24 +
969 readrtc(RTC_HRS)) * 60 +
970 readrtc(RTC_MIN)) * 60 +
972 /* sec now contains the number of seconds, since Jan 1 1970,
973 in the local time zone */
975 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
977 y = time_second - sec;
978 if (y <= -2 || y >= 2) {
979 /* badly off, adjust it */
989 kprintf("Invalid time in real time clock.\n");
990 kprintf("Check and reset the date immediately!\n");
994 * Write system time back to RTC
1004 if (disable_rtc_set)
1011 /* Disable RTC updates and interrupts. */
1012 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1014 /* Calculate local time to put in RTC */
1016 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1018 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
1019 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
1020 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
1022 /* We have now the days since 01-01-1970 in tm */
1023 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
1024 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1026 y++, m = DAYSPERYEAR + LEAPYEAR(y))
1029 /* Now we have the years in y and the day-of-the-year in tm */
1030 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
1031 #ifdef USE_RTC_CENTURY
1032 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1034 for (m = 0; ; m++) {
1037 ml = daysinmonth[m];
1038 if (m == 1 && LEAPYEAR(y))
1045 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1046 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1048 /* Reenable RTC updates and interrupts. */
1049 writertc(RTC_STATUSB, rtc_statusb);
1055 * Start both clocks running. DragonFly note: the stat clock is no longer
1056 * used. Instead, 8254 based systimers are used for all major clock
1057 * interrupts. statclock_disable is set by default.
1060 cpu_initclocks(void *arg __unused)
1064 int apic_8254_trial;
1066 #endif /* APIC_IO */
1068 callout_init(&sysbeepstop_ch);
1070 if (statclock_disable) {
1072 * The stat interrupt mask is different without the
1073 * statistics clock. Also, don't set the interrupt
1074 * flag which would normally cause the RTC to generate
1077 rtc_statusb = RTCSB_24HR;
1079 /* Setting stathz to nonzero early helps avoid races. */
1080 stathz = RTC_NOPROFRATE;
1081 profhz = RTC_PROFRATE;
1084 /* Finish initializing 8253 timer 0. */
1087 apic_8254_intr = isa_apic_irq(0);
1088 apic_8254_trial = 0;
1089 if (apic_8254_intr >= 0 ) {
1090 if (apic_int_type(0, 0) == 3)
1091 apic_8254_trial = 1;
1093 /* look for ExtInt on pin 0 */
1094 if (apic_int_type(0, 0) == 3) {
1095 apic_8254_intr = apic_irq(0, 0);
1096 setup_8254_mixed_mode();
1098 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1101 clkdesc = register_int(apic_8254_intr, clkintr, NULL, "clk",
1103 INTR_EXCL | INTR_FAST |
1104 INTR_NOPOLL | INTR_MPSAFE |
1106 machintr_intren(apic_8254_intr);
1110 register_int(0, clkintr, NULL, "clk", NULL,
1111 INTR_EXCL | INTR_FAST |
1112 INTR_NOPOLL | INTR_MPSAFE |
1114 machintr_intren(ICU_IRQ0);
1116 #endif /* APIC_IO */
1118 /* Initialize RTC. */
1119 writertc(RTC_STATUSA, rtc_statusa);
1120 writertc(RTC_STATUSB, RTCSB_24HR);
1122 if (statclock_disable == 0) {
1123 diag = rtcin(RTC_DIAG);
1125 kprintf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1128 if (isa_apic_irq(8) != 8)
1129 panic("APIC RTC != 8");
1130 #endif /* APIC_IO */
1132 register_int(8, (inthand2_t *)rtcintr, NULL, "rtc", NULL,
1133 INTR_EXCL | INTR_FAST | INTR_NOPOLL |
1137 writertc(RTC_STATUSB, rtc_statusb);
1141 if (apic_8254_trial) {
1146 * Following code assumes the 8254 is the cpu timer,
1147 * so make sure it is.
1149 KKASSERT(sys_cputimer == &i8254_cputimer);
1151 lastcnt = get_interrupt_counter(apic_8254_intr);
1154 * Force an 8254 Timer0 interrupt and wait 1/100s for
1155 * it to happen, then see if we got it.
1157 kprintf("APIC_IO: Testing 8254 interrupt delivery\n");
1158 i8254_intr_reload(2);
1159 base = sys_cputimer->count();
1160 while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1162 if (get_interrupt_counter(apic_8254_intr) - lastcnt == 0) {
1164 * The MP table is broken.
1165 * The 8254 was not connected to the specified pin
1167 * Workaround: Limited variant of mixed mode.
1169 machintr_intrdis(apic_8254_intr);
1170 unregister_int(clkdesc);
1171 kprintf("APIC_IO: Broken MP table detected: "
1172 "8254 is not connected to "
1173 "IOAPIC #%d intpin %d\n",
1174 int_to_apicintpin[apic_8254_intr].ioapic,
1175 int_to_apicintpin[apic_8254_intr].int_pin);
1177 * Revoke current ISA IRQ 0 assignment and
1178 * configure a fallback interrupt routing from
1179 * the 8254 Timer via the 8259 PIC to the
1180 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1181 * We reuse the low level interrupt handler number.
1183 if (apic_irq(0, 0) < 0) {
1184 revoke_apic_irq(apic_8254_intr);
1185 assign_apic_irq(0, 0, apic_8254_intr);
1187 apic_8254_intr = apic_irq(0, 0);
1188 setup_8254_mixed_mode();
1189 register_int(apic_8254_intr, clkintr, NULL, "clk",
1191 INTR_EXCL | INTR_FAST |
1192 INTR_NOPOLL | INTR_MPSAFE |
1194 machintr_intren(apic_8254_intr);
1198 if (apic_int_type(0, 0) != 3 ||
1199 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1200 int_to_apicintpin[apic_8254_intr].int_pin != 0) {
1201 kprintf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1202 int_to_apicintpin[apic_8254_intr].ioapic,
1203 int_to_apicintpin[apic_8254_intr].int_pin);
1206 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1210 SYSINIT(clocks8254, SI_BOOT2_CLOCKREG, SI_ORDER_FIRST, cpu_initclocks, NULL)
1215 setup_8254_mixed_mode(void)
1218 * Allow 8254 timer to INTerrupt 8259:
1219 * re-initialize master 8259:
1220 * reset; prog 4 bytes, single ICU, edge triggered
1222 outb(IO_ICU1, 0x13);
1223 outb(IO_ICU1 + 1, IDT_OFFSET); /* start vector (unused) */
1224 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1225 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1226 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1228 /* program IO APIC for type 3 INT on INT0 */
1229 if (ext_int_setup(0, 0) < 0)
1230 panic("8254 redirect via APIC pin0 impossible!");
1235 setstatclockrate(int newhz)
1237 if (newhz == RTC_PROFRATE)
1238 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1240 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1241 writertc(RTC_STATUSA, rtc_statusa);
1246 tsc_get_timecount(struct timecounter *tc)
1252 #ifdef KERN_TIMESTAMP
1253 #define KERN_TIMESTAMP_SIZE 16384
1254 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1255 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1256 sizeof(tsc), "LU", "Kernel timestamps");
1262 tsc[i] = (u_int32_t)rdtsc();
1265 if (i >= KERN_TIMESTAMP_SIZE)
1267 tsc[i] = 0; /* mark last entry */
1269 #endif /* KERN_TIMESTAMP */
1276 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1283 if (sys_cputimer == &i8254_cputimer)
1284 count = sys_cputimer->count();
1292 ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1293 return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1296 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1297 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1299 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1300 0, 0, hw_i8254_timestamp, "A", "");
1302 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1303 &tsc_present, 0, "TSC Available");
1304 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1305 &tsc_frequency, 0, "TSC Frequency");