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 $
41 * Routines to handle clock hardware.
45 * inittodr, settodr and support routines written
46 * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
48 * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
51 #include "opt_clock.h"
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/eventhandler.h>
57 #include <sys/kernel.h>
59 #include <sys/sysctl.h>
61 #include <sys/systimer.h>
62 #include <sys/globaldata.h>
63 #include <sys/thread2.h>
64 #include <sys/machintr.h>
65 #include <sys/interrupt.h>
67 #include <machine/clock.h>
68 #include <machine/cputypes.h>
69 #include <machine/frame.h>
70 #include <machine/ipl.h>
71 #include <machine/limits.h>
72 #include <machine/md_var.h>
73 #include <machine/psl.h>
74 #include <machine/segments.h>
75 #include <machine/smp.h>
76 #include <machine/specialreg.h>
78 #include <machine_base/apic/ioapic.h>
79 #include <machine_base/apic/ioapic_abi.h>
80 #include <machine_base/icu/icu.h>
81 #include <bus/isa/isa.h>
82 #include <bus/isa/rtc.h>
83 #include <machine_base/isa/timerreg.h>
85 #include <machine/intr_machdep.h>
87 static void i8254_restore(void);
88 static void resettodr_on_shutdown(void *arg __unused);
91 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
92 * can use a simple formula for leap years.
94 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
95 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
98 #define TIMER_FREQ 1193182
101 static uint8_t i8254_walltimer_sel;
102 static uint16_t i8254_walltimer_cntr;
104 int adjkerntz; /* local offset from GMT in seconds */
105 int disable_rtc_set; /* disable resettodr() if != 0 */
109 int64_t tsc_frequency;
111 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
113 enum tstate { RELEASED, ACQUIRED };
114 enum tstate timer0_state;
115 enum tstate timer1_state;
116 enum tstate timer2_state;
118 static int beeping = 0;
119 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
120 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
121 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
122 static int rtc_loaded;
124 static int i8254_cputimer_div;
126 static int i8254_nointr;
127 static int i8254_intr_disable = 1;
128 TUNABLE_INT("hw.i8254.intr_disable", &i8254_intr_disable);
130 static struct callout sysbeepstop_ch;
132 static sysclock_t i8254_cputimer_count(void);
133 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
134 static void i8254_cputimer_destruct(struct cputimer *cputimer);
136 static struct cputimer i8254_cputimer = {
137 SLIST_ENTRY_INITIALIZER,
141 i8254_cputimer_count,
142 cputimer_default_fromhz,
143 cputimer_default_fromus,
144 i8254_cputimer_construct,
145 i8254_cputimer_destruct,
150 static void i8254_intr_reload(struct cputimer_intr *, sysclock_t);
151 static void i8254_intr_config(struct cputimer_intr *, const struct cputimer *);
152 static void i8254_intr_initclock(struct cputimer_intr *, boolean_t);
154 static struct cputimer_intr i8254_cputimer_intr = {
156 .reload = i8254_intr_reload,
157 .enable = cputimer_intr_default_enable,
158 .config = i8254_intr_config,
159 .restart = cputimer_intr_default_restart,
160 .pmfixup = cputimer_intr_default_pmfixup,
161 .initclock = i8254_intr_initclock,
162 .next = SLIST_ENTRY_INITIALIZER,
164 .type = CPUTIMER_INTR_8254,
165 .prio = CPUTIMER_INTR_PRIO_8254,
166 .caps = CPUTIMER_INTR_CAP_PS
170 * timer0 clock interrupt. Timer0 is in one-shot mode and has stopped
171 * counting as of this interrupt. We use timer1 in free-running mode (not
172 * generating any interrupts) as our main counter. Each cpu has timeouts
175 * This code is INTR_MPSAFE and may be called without the BGL held.
178 clkintr(void *dummy, void *frame_arg)
180 static sysclock_t sysclock_count; /* NOTE! Must be static */
181 struct globaldata *gd = mycpu;
182 struct globaldata *gscan;
186 * SWSTROBE mode is a one-shot, the timer is no longer running
191 * XXX the dispatcher needs work. right now we call systimer_intr()
192 * directly or via IPI for any cpu with systimers queued, which is
193 * usually *ALL* of them. We need to use the LAPIC timer for this.
195 sysclock_count = sys_cputimer->count();
196 for (n = 0; n < ncpus; ++n) {
197 gscan = globaldata_find(n);
198 if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
201 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr,
204 systimer_intr(&sysclock_count, 0, frame_arg);
214 acquire_timer2(int mode)
216 if (timer2_state != RELEASED)
218 timer2_state = ACQUIRED;
221 * This access to the timer registers is as atomic as possible
222 * because it is a single instruction. We could do better if we
225 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
232 if (timer2_state != ACQUIRED)
234 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
235 timer2_state = RELEASED;
243 DB_SHOW_COMMAND(rtc, rtc)
245 kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
246 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
247 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
248 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
253 * Return the current cpu timer count as a 32 bit integer.
257 i8254_cputimer_count(void)
259 static __uint16_t cputimer_last;
264 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
265 count = (__uint8_t)inb(i8254_walltimer_cntr); /* get countdown */
266 count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
267 count = -count; /* -> countup */
268 if (count < cputimer_last) /* rollover */
269 i8254_cputimer.base += 0x00010000;
270 ret = i8254_cputimer.base | count;
271 cputimer_last = count;
277 * This function is called whenever the system timebase changes, allowing
278 * us to calculate what is needed to convert a system timebase tick
279 * into an 8254 tick for the interrupt timer. If we can convert to a
280 * simple shift, multiplication, or division, we do so. Otherwise 64
281 * bit arithmatic is required every time the interrupt timer is reloaded.
284 i8254_intr_config(struct cputimer_intr *cti, const struct cputimer *timer)
290 * Will a simple divide do the trick?
292 div = (timer->freq + (cti->freq / 2)) / cti->freq;
293 freq = cti->freq * div;
295 if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
296 i8254_cputimer_div = div;
298 i8254_cputimer_div = 0;
302 * Reload for the next timeout. It is possible for the reload value
303 * to be 0 or negative, indicating that an immediate timer interrupt
304 * is desired. For now make the minimum 2 ticks.
306 * We may have to convert from the system timebase to the 8254 timebase.
309 i8254_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
313 if (i8254_cputimer_div)
314 reload /= i8254_cputimer_div;
316 reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
322 if (timer0_running) {
323 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); /* count-down timer */
324 count = (__uint8_t)inb(TIMER_CNTR0); /* lsb */
325 count |= ((__uint8_t)inb(TIMER_CNTR0) << 8); /* msb */
326 if (reload < count) {
327 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
328 outb(TIMER_CNTR0, (__uint8_t)reload); /* lsb */
329 outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
334 reload = 0; /* full count */
335 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
336 outb(TIMER_CNTR0, (__uint8_t)reload); /* lsb */
337 outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
343 * DELAY(usec) - Spin for the specified number of microseconds.
344 * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
345 * but do a thread switch in the loop
347 * Relies on timer 1 counting down from (cputimer_freq / hz)
348 * Note: timer had better have been programmed before this is first used!
351 DODELAY(int n, int doswitch)
353 ssysclock_t delta, ticks_left;
354 sysclock_t prev_tick, tick;
359 static int state = 0;
363 for (n1 = 1; n1 <= 10000000; n1 *= 10)
368 kprintf("DELAY(%d)...", n);
371 * Guard against the timer being uninitialized if we are called
372 * early for console i/o.
374 if (timer0_state == RELEASED)
378 * Read the counter first, so that the rest of the setup overhead is
379 * counted. Then calculate the number of hardware timer ticks
380 * required, rounding up to be sure we delay at least the requested
381 * number of microseconds.
383 prev_tick = sys_cputimer->count();
384 ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
390 while (ticks_left > 0) {
391 tick = sys_cputimer->count();
395 delta = tick - prev_tick;
400 if (doswitch && ticks_left > 0)
406 kprintf(" %d calls to getit() at %d usec each\n",
407 getit_calls, (n + 5) / getit_calls);
412 * DELAY() never switches
421 CHECKTIMEOUT(TOTALDELAY *tdd)
426 if (tdd->started == 0) {
427 if (timer0_state == RELEASED)
429 tdd->last_clock = sys_cputimer->count();
433 delta = sys_cputimer->count() - tdd->last_clock;
434 us = (u_int64_t)delta * (u_int64_t)1000000 /
435 (u_int64_t)sys_cputimer->freq;
436 tdd->last_clock += (u_int64_t)us * (u_int64_t)sys_cputimer->freq /
439 return (tdd->us < 0);
443 * DRIVERSLEEP() does not switch if called with a spinlock held or
444 * from a hard interrupt.
447 DRIVERSLEEP(int usec)
449 globaldata_t gd = mycpu;
451 if (gd->gd_intr_nesting_level || gd->gd_spinlocks) {
459 sysbeepstop(void *chan)
461 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
467 sysbeep(int pitch, int period)
469 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
471 if (sysbeep_enable == 0)
474 * Nobody else is using timer2, we do not need the clock lock
476 outb(TIMER_CNTR2, pitch);
477 outb(TIMER_CNTR2, (pitch>>8));
479 /* enable counter2 output to speaker */
480 outb(IO_PPI, inb(IO_PPI) | 3);
482 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
488 * RTC support routines
499 val = inb(IO_RTC + 1);
506 writertc(u_char reg, u_char val)
512 outb(IO_RTC + 1, val);
513 inb(0x84); /* XXX work around wrong order in rtcin() */
520 return(bcd2bin(rtcin(port)));
524 calibrate_clocks(void)
528 sysclock_t count, prev_count;
529 int sec, start_sec, timeout;
532 kprintf("Calibrating clock(s) ...\n");
533 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
537 /* Read the mc146818A seconds counter. */
539 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
540 sec = rtcin(RTC_SEC);
547 /* Wait for the mC146818A seconds counter to change. */
550 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
551 sec = rtcin(RTC_SEC);
552 if (sec != start_sec)
559 /* Start keeping track of the i8254 counter. */
560 prev_count = sys_cputimer->count();
566 old_tsc = 0; /* shut up gcc */
569 * Wait for the mc146818A seconds counter to change. Read the i8254
570 * counter for each iteration since this is convenient and only
571 * costs a few usec of inaccuracy. The timing of the final reads
572 * of the counters almost matches the timing of the initial reads,
573 * so the main cause of inaccuracy is the varying latency from
574 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
575 * rtcin(RTC_SEC) that returns a changed seconds count. The
576 * maximum inaccuracy from this cause is < 10 usec on 486's.
580 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
581 sec = rtcin(RTC_SEC);
582 count = sys_cputimer->count();
583 tot_count += (int)(count - prev_count);
585 if (sec != start_sec)
592 * Read the cpu cycle counter. The timing considerations are
593 * similar to those for the i8254 clock.
596 tsc_frequency = rdtsc() - old_tsc;
600 kprintf("TSC%s clock: %llu Hz, ",
601 tsc_invariant ? " invariant" : "",
602 (long long)tsc_frequency);
604 kprintf("i8254 clock: %u Hz\n", tot_count);
608 kprintf("failed, using default i8254 clock of %u Hz\n",
609 i8254_cputimer.freq);
610 return (i8254_cputimer.freq);
616 timer0_state = ACQUIRED;
621 * Timer0 is our fine-grained variable clock interrupt
623 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
624 outb(TIMER_CNTR0, 2); /* lsb */
625 outb(TIMER_CNTR0, 0); /* msb */
629 cputimer_intr_register(&i8254_cputimer_intr);
630 cputimer_intr_select(&i8254_cputimer_intr, 0);
634 * Timer1 or timer2 is our free-running clock, but only if another
635 * has not been selected.
637 cputimer_register(&i8254_cputimer);
638 cputimer_select(&i8254_cputimer, 0);
642 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
647 * Should we use timer 1 or timer 2 ?
650 TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
651 if (which != 1 && which != 2)
656 timer->name = "i8254_timer1";
657 timer->type = CPUTIMER_8254_SEL1;
658 i8254_walltimer_sel = TIMER_SEL1;
659 i8254_walltimer_cntr = TIMER_CNTR1;
660 timer1_state = ACQUIRED;
663 timer->name = "i8254_timer2";
664 timer->type = CPUTIMER_8254_SEL2;
665 i8254_walltimer_sel = TIMER_SEL2;
666 i8254_walltimer_cntr = TIMER_CNTR2;
667 timer2_state = ACQUIRED;
671 timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
674 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
675 outb(i8254_walltimer_cntr, 0); /* lsb */
676 outb(i8254_walltimer_cntr, 0); /* msb */
677 outb(IO_PPI, inb(IO_PPI) | 1); /* bit 0: enable gate, bit 1: spkr */
682 i8254_cputimer_destruct(struct cputimer *timer)
684 switch(timer->type) {
685 case CPUTIMER_8254_SEL1:
686 timer1_state = RELEASED;
688 case CPUTIMER_8254_SEL2:
689 timer2_state = RELEASED;
700 /* Restore all of the RTC's "status" (actually, control) registers. */
701 writertc(RTC_STATUSB, RTCSB_24HR);
702 writertc(RTC_STATUSA, rtc_statusa);
703 writertc(RTC_STATUSB, rtc_statusb);
707 * Restore all the timers.
709 * This function is called to resynchronize our core timekeeping after a
710 * long halt, e.g. from apm_default_resume() and friends. It is also
711 * called if after a BIOS call we have detected munging of the 8254.
712 * It is necessary because cputimer_count() counter's delta may have grown
713 * too large for nanouptime() and friends to handle, or (in the case of 8254
714 * munging) might cause the SYSTIMER code to prematurely trigger.
720 i8254_restore(); /* restore timer_freq and hz */
721 rtc_restore(); /* reenable RTC interrupts */
726 * Initialize 8254 timer 0 early so that it can be used in DELAY().
734 * Can we use the TSC?
736 if (cpu_feature & CPUID_TSC) {
738 if ((cpu_vendor_id == CPU_VENDOR_INTEL ||
739 cpu_vendor_id == CPU_VENDOR_AMD) &&
740 cpu_exthigh >= 0x80000007) {
743 do_cpuid(0x80000007, regs);
752 * Initial RTC state, don't do anything unexpected
754 writertc(RTC_STATUSA, rtc_statusa);
755 writertc(RTC_STATUSB, RTCSB_24HR);
758 * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to
759 * generate an interrupt, which we will ignore for now.
761 * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
762 * (so it counts a full 2^16 and repeats). We will use this timer
766 freq = calibrate_clocks();
767 #ifdef CLK_CALIBRATION_LOOP
770 "Press a key on the console to abort clock calibration\n");
771 while (cncheckc() == -1)
777 * Use the calibrated i8254 frequency if it seems reasonable.
778 * Otherwise use the default, and don't use the calibrated i586
781 delta = freq > i8254_cputimer.freq ?
782 freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
783 if (delta < i8254_cputimer.freq / 100) {
784 #ifndef CLK_USE_I8254_CALIBRATION
787 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
788 freq = i8254_cputimer.freq;
792 * Interrupt timer's freq must be adjusted
793 * before we change the cuptimer's frequency.
795 i8254_cputimer_intr.freq = freq;
796 cputimer_set_frequency(&i8254_cputimer, freq);
800 "%d Hz differs from default of %d Hz by more than 1%%\n",
801 freq, i8254_cputimer.freq);
805 #ifndef CLK_USE_TSC_CALIBRATION
806 if (tsc_frequency != 0) {
809 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
813 if (tsc_present && tsc_frequency == 0) {
815 * Calibration of the i586 clock relative to the mc146818A
816 * clock failed. Do a less accurate calibration relative
817 * to the i8254 clock.
819 u_int64_t old_tsc = rdtsc();
822 tsc_frequency = rdtsc() - old_tsc;
823 #ifdef CLK_USE_TSC_CALIBRATION
825 kprintf("TSC clock: %llu Hz (Method B)\n",
831 EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
835 * Sync the time of day back to the RTC on shutdown, but only if
836 * we have already loaded it and have not crashed.
839 resettodr_on_shutdown(void *arg __unused)
841 if (rtc_loaded && panicstr == NULL) {
847 * Initialize the time of day register, based on the time base which is, e.g.
851 inittodr(time_t base)
853 unsigned long sec, days;
864 /* Look if we have a RTC present and the time is valid */
865 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
868 /* wait for time update to complete */
869 /* If RTCSA_TUP is zero, we have at least 244us before next update */
871 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
877 #ifdef USE_RTC_CENTURY
878 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
880 year = readrtc(RTC_YEAR) + 1900;
888 month = readrtc(RTC_MONTH);
889 for (m = 1; m < month; m++)
890 days += daysinmonth[m-1];
891 if ((month > 2) && LEAPYEAR(year))
893 days += readrtc(RTC_DAY) - 1;
894 for (y = 1970; y < year; y++)
895 days += DAYSPERYEAR + LEAPYEAR(y);
896 sec = ((( days * 24 +
897 readrtc(RTC_HRS)) * 60 +
898 readrtc(RTC_MIN)) * 60 +
900 /* sec now contains the number of seconds, since Jan 1 1970,
901 in the local time zone */
903 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
905 y = time_second - sec;
906 if (y <= -2 || y >= 2) {
907 /* badly off, adjust it */
917 kprintf("Invalid time in real time clock.\n");
918 kprintf("Check and reset the date immediately!\n");
922 * Write system time back to RTC
939 /* Disable RTC updates and interrupts. */
940 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
942 /* Calculate local time to put in RTC */
944 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
946 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
947 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
948 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
950 /* We have now the days since 01-01-1970 in tm */
951 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
952 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
954 y++, m = DAYSPERYEAR + LEAPYEAR(y))
957 /* Now we have the years in y and the day-of-the-year in tm */
958 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
959 #ifdef USE_RTC_CENTURY
960 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
966 if (m == 1 && LEAPYEAR(y))
973 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
974 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
976 /* Reenable RTC updates and interrupts. */
977 writertc(RTC_STATUSB, rtc_statusb);
982 i8254_ioapic_trial(int irq, struct cputimer_intr *cti)
988 * Following code assumes the 8254 is the cpu timer,
989 * so make sure it is.
991 KKASSERT(sys_cputimer == &i8254_cputimer);
992 KKASSERT(cti == &i8254_cputimer_intr);
994 lastcnt = get_interrupt_counter(irq, mycpuid);
997 * Force an 8254 Timer0 interrupt and wait 1/100s for
998 * it to happen, then see if we got it.
1000 kprintf("IOAPIC: testing 8254 interrupt delivery\n");
1002 i8254_intr_reload(cti, 2);
1003 base = sys_cputimer->count();
1004 while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1007 if (get_interrupt_counter(irq, mycpuid) - lastcnt == 0)
1013 * Start both clocks running. DragonFly note: the stat clock is no longer
1014 * used. Instead, 8254 based systimers are used for all major clock
1018 i8254_intr_initclock(struct cputimer_intr *cti, boolean_t selected)
1020 void *clkdesc = NULL;
1021 int irq = 0, mixed_mode = 0, error;
1023 KKASSERT(mycpuid == 0);
1024 callout_init(&sysbeepstop_ch);
1026 if (!selected && i8254_intr_disable)
1030 * The stat interrupt mask is different without the
1031 * statistics clock. Also, don't set the interrupt
1032 * flag which would normally cause the RTC to generate
1035 rtc_statusb = RTCSB_24HR;
1037 /* Finish initializing 8253 timer 0. */
1038 if (ioapic_enable) {
1039 irq = machintr_legacy_intr_find(0, INTR_TRIGGER_EDGE,
1040 INTR_POLARITY_HIGH);
1043 error = ioapic_conf_legacy_extint(0);
1045 irq = machintr_legacy_intr_find(0,
1046 INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
1053 kprintf("IOAPIC: setup mixed mode for "
1054 "irq 0 failed: %d\n", error);
1057 panic("IOAPIC: setup mixed mode for "
1058 "irq 0 failed: %d\n", error);
1063 clkdesc = register_int(irq, clkintr, NULL, "clk",
1065 INTR_EXCL | INTR_CLOCK |
1066 INTR_NOPOLL | INTR_MPSAFE |
1069 register_int(0, clkintr, NULL, "clk", NULL,
1070 INTR_EXCL | INTR_CLOCK |
1071 INTR_NOPOLL | INTR_MPSAFE |
1075 /* Initialize RTC. */
1076 writertc(RTC_STATUSA, rtc_statusa);
1077 writertc(RTC_STATUSB, RTCSB_24HR);
1079 if (ioapic_enable) {
1080 error = i8254_ioapic_trial(irq, cti);
1084 kprintf("IOAPIC: mixed mode for irq %d "
1085 "trial failed: %d\n",
1089 panic("IOAPIC: mixed mode for irq %d "
1090 "trial failed: %d\n", irq, error);
1093 kprintf("IOAPIC: warning 8254 is not connected "
1094 "to the correct pin, try mixed mode\n");
1095 unregister_int(clkdesc, 0);
1096 goto mixed_mode_setup;
1103 i8254_nointr = 1; /* don't try to register again */
1104 cputimer_intr_deregister(cti);
1108 setstatclockrate(int newhz)
1110 if (newhz == RTC_PROFRATE)
1111 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1113 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1114 writertc(RTC_STATUSA, rtc_statusa);
1119 tsc_get_timecount(struct timecounter *tc)
1125 #ifdef KERN_TIMESTAMP
1126 #define KERN_TIMESTAMP_SIZE 16384
1127 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1128 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1129 sizeof(tsc), "LU", "Kernel timestamps");
1135 tsc[i] = (u_int32_t)rdtsc();
1138 if (i >= KERN_TIMESTAMP_SIZE)
1140 tsc[i] = 0; /* mark last entry */
1142 #endif /* KERN_TIMESTAMP */
1149 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1156 if (sys_cputimer == &i8254_cputimer)
1157 count = sys_cputimer->count();
1165 ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1166 return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1169 static uint64_t tsc_mpsync_target;
1172 tsc_mpsync_test_remote(void *arg __unused)
1177 if (tsc < tsc_mpsync_target)
1182 tsc_mpsync_test(void)
1184 struct globaldata *gd = mycpu;
1185 uint64_t test_end, test_begin;
1188 if (!tsc_invariant) {
1189 /* Not even invariant TSC */
1199 if (cpu_vendor_id != CPU_VENDOR_INTEL) {
1200 /* XXX only Intel works */
1204 kprintf("TSC testing MP synchronization ...\n");
1207 /* Run test for 100ms */
1208 test_begin = rdtsc();
1209 test_end = test_begin + (tsc_frequency / 10);
1211 #define TSC_TEST_TRYMAX 1000000 /* Make sure we could stop */
1213 for (i = 0; i < TSC_TEST_TRYMAX; ++i) {
1214 struct lwkt_cpusync cs;
1217 lwkt_cpusync_init(&cs, gd->gd_other_cpus,
1218 tsc_mpsync_test_remote, NULL);
1219 lwkt_cpusync_interlock(&cs);
1220 tsc_mpsync_target = rdtsc();
1222 lwkt_cpusync_deinterlock(&cs);
1226 kprintf("TSC is not MP synchronized @%u\n", i);
1229 if (tsc_mpsync_target > test_end)
1233 #undef TSC_TEST_TRYMAX
1236 if (tsc_mpsync_target == test_begin) {
1237 kprintf("TSC does not tick?!");
1238 /* XXX disable TSC? */
1244 kprintf("TSC is MP synchronized");
1246 kprintf(", after %u tries", i);
1250 SYSINIT(tsc_mpsync, SI_BOOT2_FINISH_SMP, SI_ORDER_ANY, tsc_mpsync_test, NULL);
1252 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1253 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1255 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1256 0, 0, hw_i8254_timestamp, "A", "");
1258 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1259 &tsc_present, 0, "TSC Available");
1260 SYSCTL_INT(_hw, OID_AUTO, tsc_invariant, CTLFLAG_RD,
1261 &tsc_invariant, 0, "Invariant TSC");
1262 SYSCTL_INT(_hw, OID_AUTO, tsc_mpsync, CTLFLAG_RD,
1263 &tsc_mpsync, 0, "TSC is synchronized across CPUs");
1264 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1265 &tsc_frequency, 0, "TSC Frequency");