2 * Copyright (c) 1990 The Regents of the University of California.
3 * Copyright (c) 2008 The DragonFly Project.
6 * This code is derived from software contributed to Berkeley by
7 * William Jolitz and Don Ahn.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * from: @(#)clock.c 7.2 (Berkeley) 5/12/91
38 * $FreeBSD: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki 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
54 #include "opt_clock.h"
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/eventhandler.h>
61 #include <sys/kernel.h>
66 #include <sys/sysctl.h>
68 #include <sys/systimer.h>
69 #include <sys/globaldata.h>
70 #include <sys/thread2.h>
71 #include <sys/systimer.h>
72 #include <sys/machintr.h>
73 #include <sys/interrupt.h>
75 #include <machine/clock.h>
76 #ifdef CLK_CALIBRATION_LOOP
78 #include <machine/cputypes.h>
79 #include <machine/frame.h>
80 #include <machine/ipl.h>
81 #include <machine/limits.h>
82 #include <machine/md_var.h>
83 #include <machine/psl.h>
84 #include <machine/segments.h>
85 #include <machine/smp.h>
86 #include <machine/specialreg.h>
87 #include <machine/intr_machdep.h>
89 #include <machine_base/icu/icu.h>
90 #include <bus/isa/isa.h>
91 #include <bus/isa/rtc.h>
92 #include <machine_base/isa/timerreg.h>
94 #ifdef SMP /* APIC-IO */
95 /* The interrupt triggered by the 8254 (timer) chip */
97 static void setup_8254_mixed_mode (void);
99 static void i8254_restore(void);
100 static void resettodr_on_shutdown(void *arg __unused);
103 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
104 * can use a simple formula for leap years.
106 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
107 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
110 #define TIMER_FREQ 1193182
113 static uint8_t i8254_walltimer_sel;
114 static uint16_t i8254_walltimer_cntr;
116 int adjkerntz; /* local offset from GMT in seconds */
117 int disable_rtc_set; /* disable resettodr() if != 0 */
119 int64_t tsc_frequency;
121 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
123 enum tstate { RELEASED, ACQUIRED };
124 enum tstate timer0_state;
125 enum tstate timer1_state;
126 enum tstate timer2_state;
128 static int beeping = 0;
129 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
130 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
131 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
132 static int rtc_loaded;
134 static int i8254_cputimer_div;
136 static int i8254_nointr;
137 static int i8254_intr_disable = 0;
138 TUNABLE_INT("hw.i8254.intr_disable", &i8254_intr_disable);
140 static struct callout sysbeepstop_ch;
142 static sysclock_t i8254_cputimer_count(void);
143 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
144 static void i8254_cputimer_destruct(struct cputimer *cputimer);
146 static struct cputimer i8254_cputimer = {
147 SLIST_ENTRY_INITIALIZER,
151 i8254_cputimer_count,
152 cputimer_default_fromhz,
153 cputimer_default_fromus,
154 i8254_cputimer_construct,
155 i8254_cputimer_destruct,
160 static void i8254_intr_reload(struct cputimer_intr *, sysclock_t);
161 static void i8254_intr_config(struct cputimer_intr *, const struct cputimer *);
162 static void i8254_intr_initclock(struct cputimer_intr *, boolean_t);
164 static struct cputimer_intr i8254_cputimer_intr = {
166 .reload = i8254_intr_reload,
167 .enable = cputimer_intr_default_enable,
168 .config = i8254_intr_config,
169 .restart = cputimer_intr_default_restart,
170 .pmfixup = cputimer_intr_default_pmfixup,
171 .initclock = i8254_intr_initclock,
172 .next = SLIST_ENTRY_INITIALIZER,
174 .type = CPUTIMER_INTR_8254,
175 .prio = CPUTIMER_INTR_PRIO_8254,
176 .caps = CPUTIMER_INTR_CAP_PS
180 * timer0 clock interrupt. Timer0 is in one-shot mode and has stopped
181 * counting as of this interrupt. We use timer1 in free-running mode (not
182 * generating any interrupts) as our main counter. Each cpu has timeouts
185 * This code is INTR_MPSAFE and may be called without the BGL held.
188 clkintr(void *dummy, void *frame_arg)
190 static sysclock_t sysclock_count; /* NOTE! Must be static */
191 struct globaldata *gd = mycpu;
193 struct globaldata *gscan;
198 * SWSTROBE mode is a one-shot, the timer is no longer running
203 * XXX the dispatcher needs work. right now we call systimer_intr()
204 * directly or via IPI for any cpu with systimers queued, which is
205 * usually *ALL* of them. We need to use the LAPIC timer for this.
207 sysclock_count = sys_cputimer->count();
209 for (n = 0; n < ncpus; ++n) {
210 gscan = globaldata_find(n);
211 if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
214 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr,
217 systimer_intr(&sysclock_count, 0, frame_arg);
221 if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
222 systimer_intr(&sysclock_count, 0, frame_arg);
231 acquire_timer2(int mode)
233 if (timer2_state != RELEASED)
235 timer2_state = ACQUIRED;
238 * This access to the timer registers is as atomic as possible
239 * because it is a single instruction. We could do better if we
242 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
249 if (timer2_state != ACQUIRED)
251 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
252 timer2_state = RELEASED;
260 DB_SHOW_COMMAND(rtc, rtc)
262 kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
263 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
264 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
265 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
270 * Return the current cpu timer count as a 32 bit integer.
274 i8254_cputimer_count(void)
276 static __uint16_t cputimer_last;
281 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
282 count = (__uint8_t)inb(i8254_walltimer_cntr); /* get countdown */
283 count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
284 count = -count; /* -> countup */
285 if (count < cputimer_last) /* rollover */
286 i8254_cputimer.base += 0x00010000;
287 ret = i8254_cputimer.base | count;
288 cputimer_last = count;
294 * This function is called whenever the system timebase changes, allowing
295 * us to calculate what is needed to convert a system timebase tick
296 * into an 8254 tick for the interrupt timer. If we can convert to a
297 * simple shift, multiplication, or division, we do so. Otherwise 64
298 * bit arithmatic is required every time the interrupt timer is reloaded.
301 i8254_intr_config(struct cputimer_intr *cti, const struct cputimer *timer)
307 * Will a simple divide do the trick?
309 div = (timer->freq + (cti->freq / 2)) / cti->freq;
310 freq = cti->freq * div;
312 if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
313 i8254_cputimer_div = div;
315 i8254_cputimer_div = 0;
319 * Reload for the next timeout. It is possible for the reload value
320 * to be 0 or negative, indicating that an immediate timer interrupt
321 * is desired. For now make the minimum 2 ticks.
323 * We may have to convert from the system timebase to the 8254 timebase.
326 i8254_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
330 if (i8254_cputimer_div)
331 reload /= i8254_cputimer_div;
333 reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
339 if (timer0_running) {
340 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); /* count-down timer */
341 count = (__uint8_t)inb(TIMER_CNTR0); /* lsb */
342 count |= ((__uint8_t)inb(TIMER_CNTR0) << 8); /* msb */
343 if (reload < count) {
344 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
345 outb(TIMER_CNTR0, (__uint8_t)reload); /* lsb */
346 outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
351 reload = 0; /* full 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 */
360 * DELAY(usec) - Spin for the specified number of microseconds.
361 * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
362 * but do a thread switch in the loop
364 * Relies on timer 1 counting down from (cputimer_freq / hz)
365 * Note: timer had better have been programmed before this is first used!
368 DODELAY(int n, int doswitch)
370 int delta, prev_tick, tick, ticks_left;
375 static int state = 0;
379 for (n1 = 1; n1 <= 10000000; n1 *= 10)
384 kprintf("DELAY(%d)...", n);
387 * Guard against the timer being uninitialized if we are called
388 * early for console i/o.
390 if (timer0_state == RELEASED)
394 * Read the counter first, so that the rest of the setup overhead is
395 * counted. Then calculate the number of hardware timer ticks
396 * required, rounding up to be sure we delay at least the requested
397 * number of microseconds.
399 prev_tick = sys_cputimer->count();
400 ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
406 while (ticks_left > 0) {
407 tick = sys_cputimer->count();
411 delta = tick - prev_tick;
416 if (doswitch && ticks_left > 0)
422 kprintf(" %d calls to getit() at %d usec each\n",
423 getit_calls, (n + 5) / getit_calls);
428 * DELAY() never switches.
437 * Returns non-zero if the specified time period has elapsed. Call
438 * first with last_clock set to 0.
441 CHECKTIMEOUT(TOTALDELAY *tdd)
446 if (tdd->started == 0) {
447 if (timer0_state == RELEASED)
449 tdd->last_clock = sys_cputimer->count();
453 delta = sys_cputimer->count() - tdd->last_clock;
454 us = (u_int64_t)delta * (u_int64_t)1000000 /
455 (u_int64_t)sys_cputimer->freq;
456 tdd->last_clock += (u_int64_t)us * (u_int64_t)sys_cputimer->freq /
459 return (tdd->us < 0);
464 * DRIVERSLEEP() does not switch if called with a spinlock held or
465 * from a hard interrupt.
468 DRIVERSLEEP(int usec)
470 globaldata_t gd = mycpu;
472 if (gd->gd_intr_nesting_level || gd->gd_spinlocks_wr) {
480 sysbeepstop(void *chan)
482 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
488 sysbeep(int pitch, int period)
490 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
492 if (sysbeep_enable == 0)
495 * Nobody else is using timer2, we do not need the clock lock
497 outb(TIMER_CNTR2, pitch);
498 outb(TIMER_CNTR2, (pitch>>8));
500 /* enable counter2 output to speaker */
501 outb(IO_PPI, inb(IO_PPI) | 3);
503 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
509 * RTC support routines
520 val = inb(IO_RTC + 1);
527 writertc(u_char reg, u_char val)
533 outb(IO_RTC + 1, val);
534 inb(0x84); /* XXX work around wrong order in rtcin() */
541 return(bcd2bin(rtcin(port)));
545 calibrate_clocks(void)
548 u_int count, prev_count, tot_count;
549 int sec, start_sec, timeout;
552 kprintf("Calibrating clock(s) ... ");
553 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
557 /* Read the mc146818A seconds counter. */
559 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
560 sec = rtcin(RTC_SEC);
567 /* Wait for the mC146818A seconds counter to change. */
570 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
571 sec = rtcin(RTC_SEC);
572 if (sec != start_sec)
579 /* Start keeping track of the i8254 counter. */
580 prev_count = sys_cputimer->count();
586 old_tsc = 0; /* shut up gcc */
589 * Wait for the mc146818A seconds counter to change. Read the i8254
590 * counter for each iteration since this is convenient and only
591 * costs a few usec of inaccuracy. The timing of the final reads
592 * of the counters almost matches the timing of the initial reads,
593 * so the main cause of inaccuracy is the varying latency from
594 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
595 * rtcin(RTC_SEC) that returns a changed seconds count. The
596 * maximum inaccuracy from this cause is < 10 usec on 486's.
600 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
601 sec = rtcin(RTC_SEC);
602 count = sys_cputimer->count();
603 tot_count += (int)(count - prev_count);
605 if (sec != start_sec)
612 * Read the cpu cycle counter. The timing considerations are
613 * similar to those for the i8254 clock.
616 tsc_frequency = rdtsc() - old_tsc;
620 kprintf("TSC clock: %llu Hz, ", (long long)tsc_frequency);
621 kprintf("i8254 clock: %u Hz\n", tot_count);
625 kprintf("failed, using default i8254 clock of %u Hz\n",
626 i8254_cputimer.freq);
627 return (i8254_cputimer.freq);
633 timer0_state = ACQUIRED;
638 * Timer0 is our fine-grained variable clock interrupt
640 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
641 outb(TIMER_CNTR0, 2); /* lsb */
642 outb(TIMER_CNTR0, 0); /* msb */
646 cputimer_intr_register(&i8254_cputimer_intr);
647 cputimer_intr_select(&i8254_cputimer_intr, 0);
651 * Timer1 or timer2 is our free-running clock, but only if another
652 * has not been selected.
654 cputimer_register(&i8254_cputimer);
655 cputimer_select(&i8254_cputimer, 0);
659 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
664 * Should we use timer 1 or timer 2 ?
667 TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
668 if (which != 1 && which != 2)
673 timer->name = "i8254_timer1";
674 timer->type = CPUTIMER_8254_SEL1;
675 i8254_walltimer_sel = TIMER_SEL1;
676 i8254_walltimer_cntr = TIMER_CNTR1;
677 timer1_state = ACQUIRED;
680 timer->name = "i8254_timer2";
681 timer->type = CPUTIMER_8254_SEL2;
682 i8254_walltimer_sel = TIMER_SEL2;
683 i8254_walltimer_cntr = TIMER_CNTR2;
684 timer2_state = ACQUIRED;
688 timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
691 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
692 outb(i8254_walltimer_cntr, 0); /* lsb */
693 outb(i8254_walltimer_cntr, 0); /* msb */
694 outb(IO_PPI, inb(IO_PPI) | 1); /* bit 0: enable gate, bit 1: spkr */
699 i8254_cputimer_destruct(struct cputimer *timer)
701 switch(timer->type) {
702 case CPUTIMER_8254_SEL1:
703 timer1_state = RELEASED;
705 case CPUTIMER_8254_SEL2:
706 timer2_state = RELEASED;
717 /* Restore all of the RTC's "status" (actually, control) registers. */
718 writertc(RTC_STATUSB, RTCSB_24HR);
719 writertc(RTC_STATUSA, rtc_statusa);
720 writertc(RTC_STATUSB, rtc_statusb);
724 * Restore all the timers.
726 * This function is called to resynchronize our core timekeeping after a
727 * long halt, e.g. from apm_default_resume() and friends. It is also
728 * called if after a BIOS call we have detected munging of the 8254.
729 * It is necessary because cputimer_count() counter's delta may have grown
730 * too large for nanouptime() and friends to handle, or (in the case of 8254
731 * munging) might cause the SYSTIMER code to prematurely trigger.
737 i8254_restore(); /* restore timer_freq and hz */
738 rtc_restore(); /* reenable RTC interrupts */
743 * Initialize 8254 timer 0 early so that it can be used in DELAY().
751 * Can we use the TSC?
753 if (cpu_feature & CPUID_TSC)
759 * Initial RTC state, don't do anything unexpected
761 writertc(RTC_STATUSA, rtc_statusa);
762 writertc(RTC_STATUSB, RTCSB_24HR);
765 * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to
766 * generate an interrupt, which we will ignore for now.
768 * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
769 * (so it counts a full 2^16 and repeats). We will use this timer
773 freq = calibrate_clocks();
774 #ifdef CLK_CALIBRATION_LOOP
777 "Press a key on the console to abort clock calibration\n");
778 while (cncheckc() == -1)
784 * Use the calibrated i8254 frequency if it seems reasonable.
785 * Otherwise use the default, and don't use the calibrated i586
788 delta = freq > i8254_cputimer.freq ?
789 freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
790 if (delta < i8254_cputimer.freq / 100) {
791 #ifndef CLK_USE_I8254_CALIBRATION
794 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
795 freq = i8254_cputimer.freq;
799 * Interrupt timer's freq must be adjusted
800 * before we change the cuptimer's frequency.
802 i8254_cputimer_intr.freq = freq;
803 cputimer_set_frequency(&i8254_cputimer, freq);
807 "%d Hz differs from default of %d Hz by more than 1%%\n",
808 freq, i8254_cputimer.freq);
812 #ifndef CLK_USE_TSC_CALIBRATION
813 if (tsc_frequency != 0) {
816 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
820 if (tsc_present && tsc_frequency == 0) {
822 * Calibration of the i586 clock relative to the mc146818A
823 * clock failed. Do a less accurate calibration relative
824 * to the i8254 clock.
826 u_int64_t old_tsc = rdtsc();
829 tsc_frequency = rdtsc() - old_tsc;
830 #ifdef CLK_USE_TSC_CALIBRATION
832 kprintf("TSC clock: %llu Hz (Method B)\n",
838 EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
842 * We can not use the TSC in SMP mode, until we figure out a
843 * cheap (impossible), reliable and precise (yeah right!) way
844 * to synchronize the TSCs of all the CPUs.
845 * Curse Intel for leaving the counter out of the I/O APIC.
850 * We can not use the TSC if we support APM. Precise timekeeping
851 * on an APM'ed machine is at best a fools pursuit, since
852 * any and all of the time spent in various SMM code can't
853 * be reliably accounted for. Reading the RTC is your only
854 * source of reliable time info. The i8254 looses too of course
855 * but we need to have some kind of time...
856 * We don't know at this point whether APM is going to be used
857 * or not, nor when it might be activated. Play it safe.
860 #endif /* NAPM > 0 */
862 #endif /* !defined(SMP) */
866 * Sync the time of day back to the RTC on shutdown, but only if
867 * we have already loaded it and have not crashed.
870 resettodr_on_shutdown(void *arg __unused)
872 if (rtc_loaded && panicstr == NULL) {
878 * Initialize the time of day register, based on the time base which is, e.g.
882 inittodr(time_t base)
884 unsigned long sec, days;
895 /* Look if we have a RTC present and the time is valid */
896 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
899 /* wait for time update to complete */
900 /* If RTCSA_TUP is zero, we have at least 244us before next update */
902 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
908 #ifdef USE_RTC_CENTURY
909 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
911 year = readrtc(RTC_YEAR) + 1900;
919 month = readrtc(RTC_MONTH);
920 for (m = 1; m < month; m++)
921 days += daysinmonth[m-1];
922 if ((month > 2) && LEAPYEAR(year))
924 days += readrtc(RTC_DAY) - 1;
925 for (y = 1970; y < year; y++)
926 days += DAYSPERYEAR + LEAPYEAR(y);
927 sec = ((( days * 24 +
928 readrtc(RTC_HRS)) * 60 +
929 readrtc(RTC_MIN)) * 60 +
931 /* sec now contains the number of seconds, since Jan 1 1970,
932 in the local time zone */
934 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
936 y = time_second - sec;
937 if (y <= -2 || y >= 2) {
938 /* badly off, adjust it */
948 kprintf("Invalid time in real time clock.\n");
949 kprintf("Check and reset the date immediately!\n");
953 * Write system time back to RTC
970 /* Disable RTC updates and interrupts. */
971 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
973 /* Calculate local time to put in RTC */
975 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
977 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
978 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
979 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
981 /* We have now the days since 01-01-1970 in tm */
982 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
983 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
985 y++, m = DAYSPERYEAR + LEAPYEAR(y))
988 /* Now we have the years in y and the day-of-the-year in tm */
989 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
990 #ifdef USE_RTC_CENTURY
991 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
997 if (m == 1 && LEAPYEAR(y))
1004 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1005 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1007 /* Reenable RTC updates and interrupts. */
1008 writertc(RTC_STATUSB, rtc_statusb);
1014 * Start both clocks running. DragonFly note: the stat clock is no longer
1015 * used. Instead, 8254 based systimers are used for all major clock
1019 i8254_intr_initclock(struct cputimer_intr *cti, boolean_t selected)
1021 #ifdef SMP /* APIC-IO */
1022 int apic_8254_trial = 0;
1023 void *clkdesc = NULL;
1026 callout_init(&sysbeepstop_ch);
1028 if (!selected && i8254_intr_disable) {
1029 i8254_nointr = 1; /* don't try to register again */
1030 cputimer_intr_deregister(cti);
1035 * The stat interrupt mask is different without the
1036 * statistics clock. Also, don't set the interrupt
1037 * flag which would normally cause the RTC to generate
1040 rtc_statusb = RTCSB_24HR;
1042 /* Finish initializing 8254 timer 0. */
1043 #ifdef SMP /* APIC-IO */
1044 if (apic_io_enable) {
1045 apic_8254_intr = isa_apic_irq(0);
1046 if (apic_8254_intr >= 0 ) {
1047 if (apic_int_type(0, 0) == 3)
1048 apic_8254_trial = 1;
1050 /* look for ExtInt on pin 0 */
1051 if (apic_int_type(0, 0) == 3) {
1052 apic_8254_intr = apic_irq(0, 0);
1053 setup_8254_mixed_mode();
1055 panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1058 clkdesc = register_int(apic_8254_intr, clkintr, NULL, "clk",
1060 INTR_EXCL | INTR_CLOCK |
1061 INTR_NOPOLL | INTR_MPSAFE |
1063 machintr_intren(apic_8254_intr);
1066 register_int(0, clkintr, NULL, "clk", NULL,
1067 INTR_EXCL | INTR_CLOCK |
1068 INTR_NOPOLL | INTR_MPSAFE |
1070 machintr_intren(ICU_IRQ0);
1071 #ifdef SMP /* APIC-IO */
1075 /* Initialize RTC. */
1076 writertc(RTC_STATUSA, rtc_statusa);
1077 writertc(RTC_STATUSB, RTCSB_24HR);
1079 #ifdef SMP /* APIC-IO */
1080 if (apic_io_enable) {
1081 if (apic_8254_trial) {
1086 * Following code assumes the 8254 is the cpu timer,
1087 * so make sure it is.
1089 KKASSERT(sys_cputimer == &i8254_cputimer);
1090 KKASSERT(cti == &i8254_cputimer_intr);
1092 lastcnt = get_interrupt_counter(apic_8254_intr);
1095 * Force an 8254 Timer0 interrupt and wait 1/100s for
1096 * it to happen, then see if we got it.
1098 kprintf("APIC_IO: Testing 8254 interrupt delivery\n");
1099 i8254_intr_reload(cti, 2);
1100 base = sys_cputimer->count();
1101 while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1103 if (get_interrupt_counter(apic_8254_intr) - lastcnt == 0) {
1105 * The MP table is broken.
1106 * The 8254 was not connected to the specified pin
1108 * Workaround: Limited variant of mixed mode.
1110 machintr_intrdis(apic_8254_intr);
1111 unregister_int(clkdesc);
1112 kprintf("APIC_IO: Broken MP table detected: "
1113 "8254 is not connected to "
1114 "IOAPIC #%d intpin %d\n",
1115 int_to_apicintpin[apic_8254_intr].ioapic,
1116 int_to_apicintpin[apic_8254_intr].int_pin);
1118 * Revoke current ISA IRQ 0 assignment and
1119 * configure a fallback interrupt routing from
1120 * the 8254 Timer via the 8259 PIC to the
1121 * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1122 * We reuse the low level interrupt handler number.
1124 if (apic_irq(0, 0) < 0) {
1125 revoke_apic_irq(apic_8254_intr);
1126 assign_apic_irq(0, 0, apic_8254_intr);
1128 apic_8254_intr = apic_irq(0, 0);
1129 setup_8254_mixed_mode();
1130 register_int(apic_8254_intr, clkintr, NULL, "clk",
1132 INTR_EXCL | INTR_CLOCK |
1133 INTR_NOPOLL | INTR_MPSAFE |
1135 machintr_intren(apic_8254_intr);
1138 if (apic_int_type(0, 0) != 3 ||
1139 int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1140 int_to_apicintpin[apic_8254_intr].int_pin != 0) {
1141 kprintf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1142 int_to_apicintpin[apic_8254_intr].ioapic,
1143 int_to_apicintpin[apic_8254_intr].int_pin);
1146 "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1152 #ifdef SMP /* APIC-IO */
1155 setup_8254_mixed_mode(void)
1158 * Allow 8254 timer to INTerrupt 8259:
1159 * re-initialize master 8259:
1160 * reset; prog 4 bytes, single ICU, edge triggered
1162 outb(IO_ICU1, 0x13);
1163 outb(IO_ICU1 + 1, IDT_OFFSET); /* start vector (unused) */
1164 outb(IO_ICU1 + 1, 0x00); /* ignore slave */
1165 outb(IO_ICU1 + 1, 0x03); /* auto EOI, 8086 */
1166 outb(IO_ICU1 + 1, 0xfe); /* unmask INT0 */
1168 /* program IO APIC for type 3 INT on INT0 */
1169 if (ext_int_setup(0, 0) < 0)
1170 panic("8254 redirect via APIC pin0 impossible!");
1175 setstatclockrate(int newhz)
1177 if (newhz == RTC_PROFRATE)
1178 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1180 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1181 writertc(RTC_STATUSA, rtc_statusa);
1186 tsc_get_timecount(struct timecounter *tc)
1192 #ifdef KERN_TIMESTAMP
1193 #define KERN_TIMESTAMP_SIZE 16384
1194 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1195 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1196 sizeof(tsc), "LU", "Kernel timestamps");
1202 tsc[i] = (u_int32_t)rdtsc();
1205 if (i >= KERN_TIMESTAMP_SIZE)
1207 tsc[i] = 0; /* mark last entry */
1209 #endif /* KERN_TIMESTAMP */
1216 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1223 if (sys_cputimer == &i8254_cputimer)
1224 count = sys_cputimer->count();
1232 ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1233 return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1236 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1237 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1239 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1240 0, 0, hw_i8254_timestamp, "A", "");
1242 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1243 &tsc_present, 0, "TSC Available");
1244 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1245 &tsc_frequency, 0, "TSC Frequency");