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
53 #include "opt_clock.h"
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/eventhandler.h>
60 #include <sys/kernel.h>
62 #include <sys/sysctl.h>
65 #include <sys/systimer.h>
66 #include <sys/globaldata.h>
67 #include <sys/machintr.h>
68 #include <sys/interrupt.h>
70 #include <sys/thread2.h>
72 #include <machine/clock.h>
73 #include <machine/cputypes.h>
74 #include <machine/frame.h>
75 #include <machine/ipl.h>
76 #include <machine/limits.h>
77 #include <machine/md_var.h>
78 #include <machine/psl.h>
79 #include <machine/segments.h>
80 #include <machine/smp.h>
81 #include <machine/specialreg.h>
82 #include <machine/intr_machdep.h>
84 #include <machine_base/apic/ioapic.h>
85 #include <machine_base/apic/ioapic_abi.h>
86 #include <machine_base/icu/icu.h>
87 #include <bus/isa/isa.h>
88 #include <bus/isa/rtc.h>
89 #include <machine_base/isa/timerreg.h>
91 static void i8254_restore(void);
92 static void resettodr_on_shutdown(void *arg __unused);
95 * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
96 * can use a simple formula for leap years.
98 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
99 #define DAYSPERYEAR (31+28+31+30+31+30+31+31+30+31+30+31)
102 #define TIMER_FREQ 1193182
105 static uint8_t i8254_walltimer_sel;
106 static uint16_t i8254_walltimer_cntr;
108 int adjkerntz; /* local offset from GMT in seconds */
109 int disable_rtc_set; /* disable resettodr() if != 0 */
113 int64_t tsc_frequency;
115 int wall_cmos_clock; /* wall CMOS clock assumed if != 0 */
117 enum tstate { RELEASED, ACQUIRED };
118 enum tstate timer0_state;
119 enum tstate timer1_state;
120 enum tstate timer2_state;
122 static int beeping = 0;
123 static const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
124 static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
125 static u_char rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
126 static int rtc_loaded;
128 static int i8254_cputimer_div;
130 static int i8254_nointr;
131 static int i8254_intr_disable = 1;
132 TUNABLE_INT("hw.i8254.intr_disable", &i8254_intr_disable);
134 static struct callout sysbeepstop_ch;
136 static sysclock_t i8254_cputimer_count(void);
137 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
138 static void i8254_cputimer_destruct(struct cputimer *cputimer);
140 static struct cputimer i8254_cputimer = {
141 SLIST_ENTRY_INITIALIZER,
145 i8254_cputimer_count,
146 cputimer_default_fromhz,
147 cputimer_default_fromus,
148 i8254_cputimer_construct,
149 i8254_cputimer_destruct,
154 static sysclock_t tsc_cputimer_count_mfence(void);
155 static sysclock_t tsc_cputimer_count_lfence(void);
156 static void tsc_cputimer_construct(struct cputimer *, sysclock_t);
158 static struct cputimer tsc_cputimer = {
159 SLIST_ENTRY_INITIALIZER,
163 tsc_cputimer_count_mfence, /* safe bet */
164 cputimer_default_fromhz,
165 cputimer_default_fromus,
166 tsc_cputimer_construct,
167 cputimer_default_destruct,
172 static void i8254_intr_reload(struct cputimer_intr *, sysclock_t);
173 static void i8254_intr_config(struct cputimer_intr *, const struct cputimer *);
174 static void i8254_intr_initclock(struct cputimer_intr *, boolean_t);
176 static struct cputimer_intr i8254_cputimer_intr = {
178 .reload = i8254_intr_reload,
179 .enable = cputimer_intr_default_enable,
180 .config = i8254_intr_config,
181 .restart = cputimer_intr_default_restart,
182 .pmfixup = cputimer_intr_default_pmfixup,
183 .initclock = i8254_intr_initclock,
184 .next = SLIST_ENTRY_INITIALIZER,
186 .type = CPUTIMER_INTR_8254,
187 .prio = CPUTIMER_INTR_PRIO_8254,
188 .caps = CPUTIMER_INTR_CAP_PS
192 * timer0 clock interrupt. Timer0 is in one-shot mode and has stopped
193 * counting as of this interrupt. We use timer1 in free-running mode (not
194 * generating any interrupts) as our main counter. Each cpu has timeouts
197 * This code is INTR_MPSAFE and may be called without the BGL held.
200 clkintr(void *dummy, void *frame_arg)
202 static sysclock_t sysclock_count; /* NOTE! Must be static */
203 struct globaldata *gd = mycpu;
204 struct globaldata *gscan;
208 * SWSTROBE mode is a one-shot, the timer is no longer running
213 * XXX the dispatcher needs work. right now we call systimer_intr()
214 * directly or via IPI for any cpu with systimers queued, which is
215 * usually *ALL* of them. We need to use the LAPIC timer for this.
217 sysclock_count = sys_cputimer->count();
218 for (n = 0; n < ncpus; ++n) {
219 gscan = globaldata_find(n);
220 if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
223 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr,
226 systimer_intr(&sysclock_count, 0, frame_arg);
236 acquire_timer2(int mode)
238 if (timer2_state != RELEASED)
240 timer2_state = ACQUIRED;
243 * This access to the timer registers is as atomic as possible
244 * because it is a single instruction. We could do better if we
247 outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
254 if (timer2_state != ACQUIRED)
256 outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
257 timer2_state = RELEASED;
265 DB_SHOW_COMMAND(rtc, rtc)
267 kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
268 rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
269 rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
270 rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
275 * Return the current cpu timer count as a 32 bit integer.
279 i8254_cputimer_count(void)
281 static uint16_t cputimer_last;
286 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
287 count = (uint8_t)inb(i8254_walltimer_cntr); /* get countdown */
288 count |= ((uint8_t)inb(i8254_walltimer_cntr) << 8);
289 count = -count; /* -> countup */
290 if (count < cputimer_last) /* rollover */
291 i8254_cputimer.base += 0x00010000;
292 ret = i8254_cputimer.base | count;
293 cputimer_last = count;
299 * This function is called whenever the system timebase changes, allowing
300 * us to calculate what is needed to convert a system timebase tick
301 * into an 8254 tick for the interrupt timer. If we can convert to a
302 * simple shift, multiplication, or division, we do so. Otherwise 64
303 * bit arithmatic is required every time the interrupt timer is reloaded.
306 i8254_intr_config(struct cputimer_intr *cti, const struct cputimer *timer)
312 * Will a simple divide do the trick?
314 div = (timer->freq + (cti->freq / 2)) / cti->freq;
315 freq = cti->freq * div;
317 if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
318 i8254_cputimer_div = div;
320 i8254_cputimer_div = 0;
324 * Reload for the next timeout. It is possible for the reload value
325 * to be 0 or negative, indicating that an immediate timer interrupt
326 * is desired. For now make the minimum 2 ticks.
328 * We may have to convert from the system timebase to the 8254 timebase.
331 i8254_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
335 if (i8254_cputimer_div)
336 reload /= i8254_cputimer_div;
338 reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
344 if (timer0_running) {
345 outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); /* count-down timer */
346 count = (uint8_t)inb(TIMER_CNTR0); /* lsb */
347 count |= ((uint8_t)inb(TIMER_CNTR0) << 8); /* msb */
348 if (reload < count) {
349 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
350 outb(TIMER_CNTR0, (uint8_t)reload); /* lsb */
351 outb(TIMER_CNTR0, (uint8_t)(reload >> 8)); /* msb */
356 reload = 0; /* full count */
357 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
358 outb(TIMER_CNTR0, (uint8_t)reload); /* lsb */
359 outb(TIMER_CNTR0, (uint8_t)(reload >> 8)); /* msb */
365 * DELAY(usec) - Spin for the specified number of microseconds.
366 * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
367 * but do a thread switch in the loop
369 * Relies on timer 1 counting down from (cputimer_freq / hz)
370 * Note: timer had better have been programmed before this is first used!
373 DODELAY(int n, int doswitch)
375 ssysclock_t delta, ticks_left;
376 sysclock_t prev_tick, tick;
381 static int state = 0;
385 for (n1 = 1; n1 <= 10000000; n1 *= 10)
390 kprintf("DELAY(%d)...", n);
393 * Guard against the timer being uninitialized if we are called
394 * early for console i/o.
396 if (timer0_state == RELEASED)
400 * Read the counter first, so that the rest of the setup overhead is
401 * counted. Then calculate the number of hardware timer ticks
402 * required, rounding up to be sure we delay at least the requested
403 * number of microseconds.
405 prev_tick = sys_cputimer->count();
406 ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
412 while (ticks_left > 0) {
413 tick = sys_cputimer->count();
417 delta = tick - prev_tick;
422 if (doswitch && ticks_left > 0)
428 kprintf(" %d calls to getit() at %d usec each\n",
429 getit_calls, (n + 5) / getit_calls);
434 * DELAY() never switches.
443 * Returns non-zero if the specified time period has elapsed. Call
444 * first with last_clock set to 0.
447 CHECKTIMEOUT(TOTALDELAY *tdd)
452 if (tdd->started == 0) {
453 if (timer0_state == RELEASED)
455 tdd->last_clock = sys_cputimer->count();
459 delta = sys_cputimer->count() - tdd->last_clock;
460 us = (u_int64_t)delta * (u_int64_t)1000000 /
461 (u_int64_t)sys_cputimer->freq;
462 tdd->last_clock += (u_int64_t)us * (u_int64_t)sys_cputimer->freq /
465 return (tdd->us < 0);
470 * DRIVERSLEEP() does not switch if called with a spinlock held or
471 * from a hard interrupt.
474 DRIVERSLEEP(int usec)
476 globaldata_t gd = mycpu;
478 if (gd->gd_intr_nesting_level || gd->gd_spinlocks) {
486 sysbeepstop(void *chan)
488 outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
494 sysbeep(int pitch, int period)
496 if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
498 if (sysbeep_enable == 0)
501 * Nobody else is using timer2, we do not need the clock lock
503 outb(TIMER_CNTR2, pitch);
504 outb(TIMER_CNTR2, (pitch>>8));
506 /* enable counter2 output to speaker */
507 outb(IO_PPI, inb(IO_PPI) | 3);
509 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
515 * RTC support routines
526 val = inb(IO_RTC + 1);
533 writertc(u_char reg, u_char val)
539 outb(IO_RTC + 1, val);
540 inb(0x84); /* XXX work around wrong order in rtcin() */
547 return(bcd2bin(rtcin(port)));
551 calibrate_clocks(void)
555 sysclock_t count, prev_count;
556 int sec, start_sec, timeout;
559 kprintf("Calibrating clock(s) ...\n");
560 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
564 /* Read the mc146818A seconds counter. */
566 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
567 sec = rtcin(RTC_SEC);
574 /* Wait for the mC146818A seconds counter to change. */
577 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
578 sec = rtcin(RTC_SEC);
579 if (sec != start_sec)
586 /* Start keeping track of the i8254 counter. */
587 prev_count = sys_cputimer->count();
593 old_tsc = 0; /* shut up gcc */
596 * Wait for the mc146818A seconds counter to change. Read the i8254
597 * counter for each iteration since this is convenient and only
598 * costs a few usec of inaccuracy. The timing of the final reads
599 * of the counters almost matches the timing of the initial reads,
600 * so the main cause of inaccuracy is the varying latency from
601 * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
602 * rtcin(RTC_SEC) that returns a changed seconds count. The
603 * maximum inaccuracy from this cause is < 10 usec on 486's.
607 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
608 sec = rtcin(RTC_SEC);
609 count = sys_cputimer->count();
610 tot_count += (int)(count - prev_count);
612 if (sec != start_sec)
619 * Read the cpu cycle counter. The timing considerations are
620 * similar to those for the i8254 clock.
623 tsc_frequency = rdtsc() - old_tsc;
627 kprintf("TSC%s clock: %llu Hz, ",
628 tsc_invariant ? " invariant" : "",
629 (long long)tsc_frequency);
631 kprintf("i8254 clock: %u Hz\n", tot_count);
635 kprintf("failed, using default i8254 clock of %u Hz\n",
636 i8254_cputimer.freq);
637 return (i8254_cputimer.freq);
643 timer0_state = ACQUIRED;
648 * Timer0 is our fine-grained variable clock interrupt
650 outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
651 outb(TIMER_CNTR0, 2); /* lsb */
652 outb(TIMER_CNTR0, 0); /* msb */
656 cputimer_intr_register(&i8254_cputimer_intr);
657 cputimer_intr_select(&i8254_cputimer_intr, 0);
661 * Timer1 or timer2 is our free-running clock, but only if another
662 * has not been selected.
664 cputimer_register(&i8254_cputimer);
665 cputimer_select(&i8254_cputimer, 0);
669 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
674 * Should we use timer 1 or timer 2 ?
677 TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
678 if (which != 1 && which != 2)
683 timer->name = "i8254_timer1";
684 timer->type = CPUTIMER_8254_SEL1;
685 i8254_walltimer_sel = TIMER_SEL1;
686 i8254_walltimer_cntr = TIMER_CNTR1;
687 timer1_state = ACQUIRED;
690 timer->name = "i8254_timer2";
691 timer->type = CPUTIMER_8254_SEL2;
692 i8254_walltimer_sel = TIMER_SEL2;
693 i8254_walltimer_cntr = TIMER_CNTR2;
694 timer2_state = ACQUIRED;
698 timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
701 outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
702 outb(i8254_walltimer_cntr, 0); /* lsb */
703 outb(i8254_walltimer_cntr, 0); /* msb */
704 outb(IO_PPI, inb(IO_PPI) | 1); /* bit 0: enable gate, bit 1: spkr */
709 i8254_cputimer_destruct(struct cputimer *timer)
711 switch(timer->type) {
712 case CPUTIMER_8254_SEL1:
713 timer1_state = RELEASED;
715 case CPUTIMER_8254_SEL2:
716 timer2_state = RELEASED;
727 /* Restore all of the RTC's "status" (actually, control) registers. */
728 writertc(RTC_STATUSB, RTCSB_24HR);
729 writertc(RTC_STATUSA, rtc_statusa);
730 writertc(RTC_STATUSB, rtc_statusb);
734 * Restore all the timers.
736 * This function is called to resynchronize our core timekeeping after a
737 * long halt, e.g. from apm_default_resume() and friends. It is also
738 * called if after a BIOS call we have detected munging of the 8254.
739 * It is necessary because cputimer_count() counter's delta may have grown
740 * too large for nanouptime() and friends to handle, or (in the case of 8254
741 * munging) might cause the SYSTIMER code to prematurely trigger.
747 i8254_restore(); /* restore timer_freq and hz */
748 rtc_restore(); /* reenable RTC interrupts */
753 * Initialize 8254 timer 0 early so that it can be used in DELAY().
761 * Can we use the TSC?
763 * NOTE: If running under qemu, probably a good idea to force the
764 * TSC because we are not likely to detect it as being
765 * invariant or mpsyncd if you don't. This will greatly
766 * reduce SMP contention.
768 if (cpu_feature & CPUID_TSC) {
770 TUNABLE_INT_FETCH("hw.tsc_cputimer_force", &tsc_invariant);
772 if ((cpu_vendor_id == CPU_VENDOR_INTEL ||
773 cpu_vendor_id == CPU_VENDOR_AMD) &&
774 cpu_exthigh >= 0x80000007) {
777 do_cpuid(0x80000007, regs);
786 * Initial RTC state, don't do anything unexpected
788 writertc(RTC_STATUSA, rtc_statusa);
789 writertc(RTC_STATUSB, RTCSB_24HR);
792 * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to
793 * generate an interrupt, which we will ignore for now.
795 * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
796 * (so it counts a full 2^16 and repeats). We will use this timer
800 freq = calibrate_clocks();
801 #ifdef CLK_CALIBRATION_LOOP
806 kprintf("Press a key on the console to "
807 "abort clock calibration\n");
808 while ((c = cncheckc()) == -1 || c == NOKEY)
815 * Use the calibrated i8254 frequency if it seems reasonable.
816 * Otherwise use the default, and don't use the calibrated i586
819 delta = freq > i8254_cputimer.freq ?
820 freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
821 if (delta < i8254_cputimer.freq / 100) {
822 #ifndef CLK_USE_I8254_CALIBRATION
825 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
826 freq = i8254_cputimer.freq;
830 * Interrupt timer's freq must be adjusted
831 * before we change the cuptimer's frequency.
833 i8254_cputimer_intr.freq = freq;
834 cputimer_set_frequency(&i8254_cputimer, freq);
838 "%d Hz differs from default of %d Hz by more than 1%%\n",
839 freq, i8254_cputimer.freq);
843 #ifndef CLK_USE_TSC_CALIBRATION
844 if (tsc_frequency != 0) {
847 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
851 if (tsc_present && tsc_frequency == 0) {
853 * Calibration of the i586 clock relative to the mc146818A
854 * clock failed. Do a less accurate calibration relative
855 * to the i8254 clock.
857 u_int64_t old_tsc = rdtsc();
860 tsc_frequency = rdtsc() - old_tsc;
861 #ifdef CLK_USE_TSC_CALIBRATION
863 kprintf("TSC clock: %llu Hz (Method B)\n",
869 EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
873 * Sync the time of day back to the RTC on shutdown, but only if
874 * we have already loaded it and have not crashed.
877 resettodr_on_shutdown(void *arg __unused)
879 if (rtc_loaded && panicstr == NULL) {
885 * Initialize the time of day register, based on the time base which is, e.g.
889 inittodr(time_t base)
891 unsigned long sec, days;
902 /* Look if we have a RTC present and the time is valid */
903 if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
906 /* wait for time update to complete */
907 /* If RTCSA_TUP is zero, we have at least 244us before next update */
909 while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
915 #ifdef USE_RTC_CENTURY
916 year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
918 year = readrtc(RTC_YEAR) + 1900;
926 month = readrtc(RTC_MONTH);
927 for (m = 1; m < month; m++)
928 days += daysinmonth[m-1];
929 if ((month > 2) && LEAPYEAR(year))
931 days += readrtc(RTC_DAY) - 1;
932 for (y = 1970; y < year; y++)
933 days += DAYSPERYEAR + LEAPYEAR(y);
934 sec = ((( days * 24 +
935 readrtc(RTC_HRS)) * 60 +
936 readrtc(RTC_MIN)) * 60 +
938 /* sec now contains the number of seconds, since Jan 1 1970,
939 in the local time zone */
941 sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
943 y = (int)(time_second - sec);
944 if (y <= -2 || y >= 2) {
945 /* badly off, adjust it */
955 kprintf("Invalid time in real time clock.\n");
956 kprintf("Check and reset the date immediately!\n");
960 * Write system time back to RTC
977 /* Disable RTC updates and interrupts. */
978 writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
980 /* Calculate local time to put in RTC */
982 tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
984 writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60; /* Write back Seconds */
985 writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60; /* Write back Minutes */
986 writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24; /* Write back Hours */
988 /* We have now the days since 01-01-1970 in tm */
989 writertc(RTC_WDAY, (tm+4)%7); /* Write back Weekday */
990 for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
992 y++, m = DAYSPERYEAR + LEAPYEAR(y))
995 /* Now we have the years in y and the day-of-the-year in tm */
996 writertc(RTC_YEAR, bin2bcd(y%100)); /* Write back Year */
997 #ifdef USE_RTC_CENTURY
998 writertc(RTC_CENTURY, bin2bcd(y/100)); /* ... and Century */
1000 for (m = 0; ; m++) {
1003 ml = daysinmonth[m];
1004 if (m == 1 && LEAPYEAR(y))
1011 writertc(RTC_MONTH, bin2bcd(m + 1)); /* Write back Month */
1012 writertc(RTC_DAY, bin2bcd(tm + 1)); /* Write back Month Day */
1014 /* Reenable RTC updates and interrupts. */
1015 writertc(RTC_STATUSB, rtc_statusb);
1020 i8254_ioapic_trial(int irq, struct cputimer_intr *cti)
1026 * Following code assumes the 8254 is the cpu timer,
1027 * so make sure it is.
1029 KKASSERT(sys_cputimer == &i8254_cputimer);
1030 KKASSERT(cti == &i8254_cputimer_intr);
1032 lastcnt = get_interrupt_counter(irq, mycpuid);
1035 * Force an 8254 Timer0 interrupt and wait 1/100s for
1036 * it to happen, then see if we got it.
1038 kprintf("IOAPIC: testing 8254 interrupt delivery\n");
1040 i8254_intr_reload(cti, 2);
1041 base = sys_cputimer->count();
1042 while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1045 if (get_interrupt_counter(irq, mycpuid) - lastcnt == 0)
1051 * Start both clocks running. DragonFly note: the stat clock is no longer
1052 * used. Instead, 8254 based systimers are used for all major clock
1056 i8254_intr_initclock(struct cputimer_intr *cti, boolean_t selected)
1058 void *clkdesc = NULL;
1059 int irq = 0, mixed_mode = 0, error;
1061 KKASSERT(mycpuid == 0);
1062 callout_init_mp(&sysbeepstop_ch);
1064 if (!selected && i8254_intr_disable)
1068 * The stat interrupt mask is different without the
1069 * statistics clock. Also, don't set the interrupt
1070 * flag which would normally cause the RTC to generate
1073 rtc_statusb = RTCSB_24HR;
1075 /* Finish initializing 8254 timer 0. */
1076 if (ioapic_enable) {
1077 irq = machintr_legacy_intr_find(0, INTR_TRIGGER_EDGE,
1078 INTR_POLARITY_HIGH);
1081 error = ioapic_conf_legacy_extint(0);
1083 irq = machintr_legacy_intr_find(0,
1084 INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
1091 kprintf("IOAPIC: setup mixed mode for "
1092 "irq 0 failed: %d\n", error);
1095 panic("IOAPIC: setup mixed mode for "
1096 "irq 0 failed: %d\n", error);
1101 clkdesc = register_int(irq, clkintr, NULL, "clk",
1103 INTR_EXCL | INTR_CLOCK |
1104 INTR_NOPOLL | INTR_MPSAFE |
1107 register_int(0, clkintr, NULL, "clk", NULL,
1108 INTR_EXCL | INTR_CLOCK |
1109 INTR_NOPOLL | INTR_MPSAFE |
1113 /* Initialize RTC. */
1114 writertc(RTC_STATUSA, rtc_statusa);
1115 writertc(RTC_STATUSB, RTCSB_24HR);
1117 if (ioapic_enable) {
1118 error = i8254_ioapic_trial(irq, cti);
1122 kprintf("IOAPIC: mixed mode for irq %d "
1123 "trial failed: %d\n",
1127 panic("IOAPIC: mixed mode for irq %d "
1128 "trial failed: %d\n", irq, error);
1131 kprintf("IOAPIC: warning 8254 is not connected "
1132 "to the correct pin, try mixed mode\n");
1133 unregister_int(clkdesc, 0);
1134 goto mixed_mode_setup;
1141 i8254_nointr = 1; /* don't try to register again */
1142 cputimer_intr_deregister(cti);
1146 setstatclockrate(int newhz)
1148 if (newhz == RTC_PROFRATE)
1149 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1151 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1152 writertc(RTC_STATUSA, rtc_statusa);
1157 tsc_get_timecount(struct timecounter *tc)
1163 #ifdef KERN_TIMESTAMP
1164 #define KERN_TIMESTAMP_SIZE 16384
1165 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1166 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1167 sizeof(tsc), "LU", "Kernel timestamps");
1173 tsc[i] = (u_int32_t)rdtsc();
1176 if (i >= KERN_TIMESTAMP_SIZE)
1178 tsc[i] = 0; /* mark last entry */
1180 #endif /* KERN_TIMESTAMP */
1187 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1194 if (sys_cputimer == &i8254_cputimer)
1195 count = sys_cputimer->count();
1203 ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1204 return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1207 struct tsc_mpsync_arg {
1208 volatile uint64_t tsc_target;
1209 volatile int tsc_mpsync;
1212 struct tsc_mpsync_thr {
1213 volatile int tsc_done_cnt;
1214 volatile int tsc_mpsync_cnt;
1218 tsc_mpsync_test_remote(void *xarg)
1220 struct tsc_mpsync_arg *arg = xarg;
1223 tsc = rdtsc_ordered();
1224 if (tsc < arg->tsc_target)
1225 arg->tsc_mpsync = 0;
1229 tsc_mpsync_test_loop(struct tsc_mpsync_arg *arg)
1231 struct globaldata *gd = mycpu;
1232 uint64_t test_end, test_begin;
1236 kprintf("cpu%d: TSC testing MP synchronization ...\n",
1240 test_begin = rdtsc_ordered();
1241 /* Run test for 100ms */
1242 test_end = test_begin + (tsc_frequency / 10);
1244 arg->tsc_mpsync = 1;
1245 arg->tsc_target = test_begin;
1247 #define TSC_TEST_TRYMAX 1000000 /* Make sure we could stop */
1248 #define TSC_TEST_TRYMIN 50000
1250 for (i = 0; i < TSC_TEST_TRYMAX; ++i) {
1251 struct lwkt_cpusync cs;
1254 lwkt_cpusync_init(&cs, gd->gd_other_cpus,
1255 tsc_mpsync_test_remote, arg);
1256 lwkt_cpusync_interlock(&cs);
1257 arg->tsc_target = rdtsc_ordered();
1259 lwkt_cpusync_deinterlock(&cs);
1262 if (!arg->tsc_mpsync) {
1263 kprintf("cpu%d: TSC is not MP synchronized @%u\n",
1267 if (arg->tsc_target > test_end && i >= TSC_TEST_TRYMIN)
1271 #undef TSC_TEST_TRYMIN
1272 #undef TSC_TEST_TRYMAX
1274 if (arg->tsc_target == test_begin) {
1275 kprintf("cpu%d: TSC does not tick?!\n", gd->gd_cpuid);
1276 /* XXX disable TSC? */
1278 arg->tsc_mpsync = 0;
1282 if (arg->tsc_mpsync && bootverbose) {
1283 kprintf("cpu%d: TSC is MP synchronized after %u tries\n",
1289 tsc_mpsync_ap_thread(void *xthr)
1291 struct tsc_mpsync_thr *thr = xthr;
1292 struct tsc_mpsync_arg arg;
1294 tsc_mpsync_test_loop(&arg);
1295 if (arg.tsc_mpsync) {
1296 atomic_add_int(&thr->tsc_mpsync_cnt, 1);
1299 atomic_add_int(&thr->tsc_done_cnt, 1);
1305 tsc_mpsync_test(void)
1307 struct tsc_mpsync_arg arg;
1309 if (!tsc_invariant) {
1310 /* Not even invariant TSC */
1321 * Forcing can be used w/qemu to reduce contention
1323 TUNABLE_INT_FETCH("hw.tsc_cputimer_force", &tsc_mpsync);
1325 kprintf("TSC as cputimer forced\n");
1329 if (cpu_vendor_id != CPU_VENDOR_INTEL) {
1330 /* XXX only Intel works */
1334 kprintf("TSC testing MP synchronization ...\n");
1336 tsc_mpsync_test_loop(&arg);
1337 if (arg.tsc_mpsync) {
1338 struct tsc_mpsync_thr thr;
1342 * Test TSC MP synchronization on APs.
1345 thr.tsc_done_cnt = 1;
1346 thr.tsc_mpsync_cnt = 1;
1348 for (cpu = 0; cpu < ncpus; ++cpu) {
1352 lwkt_create(tsc_mpsync_ap_thread, &thr, NULL,
1353 NULL, 0, cpu, "tsc mpsync %d", cpu);
1356 while (thr.tsc_done_cnt != ncpus) {
1360 if (thr.tsc_mpsync_cnt == ncpus)
1365 kprintf("TSC is MP synchronized\n");
1367 kprintf("TSC is not MP synchronized\n");
1369 SYSINIT(tsc_mpsync, SI_BOOT2_FINISH_SMP, SI_ORDER_ANY, tsc_mpsync_test, NULL);
1371 #define TSC_CPUTIMER_FREQMAX 128000000 /* 128Mhz */
1373 static int tsc_cputimer_shift;
1376 tsc_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
1379 timer->base = oldclock - timer->count();
1382 static __inline sysclock_t
1383 tsc_cputimer_count(void)
1388 tsc >>= tsc_cputimer_shift;
1390 return (tsc + tsc_cputimer.base);
1394 tsc_cputimer_count_lfence(void)
1397 return tsc_cputimer_count();
1401 tsc_cputimer_count_mfence(void)
1404 return tsc_cputimer_count();
1408 tsc_cputimer_register(void)
1416 TUNABLE_INT_FETCH("hw.tsc_cputimer_enable", &enable);
1420 freq = tsc_frequency;
1421 while (freq > TSC_CPUTIMER_FREQMAX) {
1423 ++tsc_cputimer_shift;
1425 kprintf("TSC: cputimer freq %ju, shift %d\n",
1426 (uintmax_t)freq, tsc_cputimer_shift);
1428 tsc_cputimer.freq = freq;
1430 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1431 tsc_cputimer.count = tsc_cputimer_count_lfence;
1433 tsc_cputimer.count = tsc_cputimer_count_mfence; /* safe bet */
1435 cputimer_register(&tsc_cputimer);
1436 cputimer_select(&tsc_cputimer, 0);
1438 SYSINIT(tsc_cputimer_reg, SI_BOOT2_POST_SMP, SI_ORDER_FIRST,
1439 tsc_cputimer_register, NULL);
1441 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1442 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1444 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1445 0, 0, hw_i8254_timestamp, "A", "");
1447 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1448 &tsc_present, 0, "TSC Available");
1449 SYSCTL_INT(_hw, OID_AUTO, tsc_invariant, CTLFLAG_RD,
1450 &tsc_invariant, 0, "Invariant TSC");
1451 SYSCTL_INT(_hw, OID_AUTO, tsc_mpsync, CTLFLAG_RD,
1452 &tsc_mpsync, 0, "TSC is synchronized across CPUs");
1453 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1454 &tsc_frequency, 0, "TSC Frequency");