Merge from vendor branch FILE:
[dragonfly.git] / sys / platform / pc32 / isa / clock.c
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * William Jolitz and Don Ahn.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 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.
23  *
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
34  * SUCH DAMAGE.
35  *
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.23 2005/05/24 20:59:05 dillon Exp $
39  */
40
41 /*
42  * Routines to handle clock hardware.
43  */
44
45 /*
46  * inittodr, settodr and support routines written
47  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
48  *
49  * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
50  */
51
52 #include "use_apm.h"
53 #include "use_mca.h"
54 #include "opt_clock.h"
55
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/time.h>
59 #include <sys/kernel.h>
60 #include <sys/bus.h>
61 #ifndef SMP
62 #include <sys/lock.h>
63 #endif
64 #include <sys/sysctl.h>
65 #include <sys/cons.h>
66 #include <sys/systimer.h>
67 #include <sys/globaldata.h>
68 #include <sys/thread2.h>
69 #include <sys/systimer.h>
70
71 #include <machine/clock.h>
72 #ifdef CLK_CALIBRATION_LOOP
73 #endif
74 #include <machine/cputypes.h>
75 #include <machine/frame.h>
76 #include <machine/ipl.h>
77 #include <machine/limits.h>
78 #include <machine/md_var.h>
79 #include <machine/psl.h>
80 #ifdef APIC_IO
81 #include <machine/segments.h>
82 #endif
83 #if defined(SMP) || defined(APIC_IO)
84 #include <machine/smp.h>
85 #endif /* SMP || APIC_IO */
86 #include <machine/specialreg.h>
87
88 #include <i386/isa/icu.h>
89 #include <bus/isa/i386/isa.h>
90 #include <bus/isa/rtc.h>
91 #include <i386/isa/timerreg.h>
92
93 #include <i386/isa/intr_machdep.h>
94
95 #if NMCA > 0
96 #include <bus/mca/i386/mca_machdep.h>
97 #endif
98
99 #ifdef APIC_IO
100 #include <i386/isa/intr_machdep.h>
101 /* The interrupt triggered by the 8254 (timer) chip */
102 int apic_8254_intr;
103 static u_long read_intr_count (int vec);
104 static void setup_8254_mixed_mode (void);
105 #endif
106 static void i8254_restore(void);
107
108 /*
109  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
110  * can use a simple formula for leap years.
111  */
112 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
113 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
114
115 #ifndef TIMER_FREQ
116 #define TIMER_FREQ   1193182
117 #endif
118
119 int i8254_walltimer;
120 TUNABLE_INT("hw.i8254.walltimer", &i8254_walltimer);
121 static uint8_t i8254_walltimer_sel;
122 static uint16_t i8254_walltimer_cntr;
123
124 int     adjkerntz;              /* local offset from GMT in seconds */
125 int     disable_rtc_set;        /* disable resettodr() if != 0 */
126 volatile u_int  idelayed;
127 int     statclock_disable = 1;  /* we don't use the statclock right now */
128 u_int   stat_imask = SWI_CLOCK_MASK;
129 u_int   cputimer_freq = TIMER_FREQ;
130 #if 0
131 int64_t cputimer_freq64_usec = ((int64_t)TIMER_FREQ << 32) / 1000000;
132 int64_t cputimer_freq64_nsec = ((int64_t)TIMER_FREQ << 32) / 1000000000LL;
133 #endif
134 int64_t cputimer_freq64_usec = (1000000LL << 32) / TIMER_FREQ;
135 int64_t cputimer_freq64_nsec = (1000000000LL << 32) / TIMER_FREQ;
136 u_int   tsc_freq;
137 int     tsc_is_broken;
138 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
139 int     timer0_running;
140 enum tstate { RELEASED, ACQUIRED };
141 enum tstate timer0_state;
142 enum tstate timer1_state;
143 enum tstate timer2_state;
144
145 static  int     beeping = 0;
146 static  u_int   clk_imask = HWI_MASK | SWI_MASK;
147 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
148 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
149 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
150 static  u_int   tsc_present;
151
152 static struct callout sysbeepstop_ch;
153
154 /*
155  * timer0 clock interrupt.  Timer0 is in one-shot mode and has stopped
156  * counting as of this interrupt.  We use timer1 in free-running mode (not
157  * generating any interrupts) as our main counter.  Each cpu has timeouts
158  * pending.
159  */
160 static void
161 clkintr(struct intrframe frame)
162 {
163         static sysclock_t timer1_count;
164         struct globaldata *gd = mycpu;
165         struct globaldata *gscan;
166         int n;
167
168         /*
169          * SWSTROBE mode is a one-shot, the timer is no longer running
170          */
171         timer0_running = 0;
172
173         /*
174          * XXX the dispatcher needs work.  right now we call systimer_intr()
175          * directly or via IPI for any cpu with systimers queued, which is
176          * usually *ALL* of them.  We need a better way to do this.
177          */
178         timer1_count = cputimer_count();
179         for (n = 0; n < ncpus; ++n) {
180             gscan = globaldata_find(n);
181             if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
182                 continue;
183             if (gscan != gd) {
184                 lwkt_send_ipiq(gscan, (ipifunc_t)systimer_intr, &timer1_count);
185             } else {
186                 systimer_intr(&timer1_count, &frame);
187             }
188         }
189 #if NMCA > 0
190         /* Reset clock interrupt by asserting bit 7 of port 0x61 */
191         if (MCA_system)
192                 outb(0x61, inb(0x61) | 0x80);
193 #endif
194 }
195
196
197 /*
198  * NOTE! not MP safe.
199  */
200 int
201 acquire_timer2(int mode)
202 {
203         if (timer2_state != RELEASED)
204                 return (-1);
205         timer2_state = ACQUIRED;
206
207         /*
208          * This access to the timer registers is as atomic as possible
209          * because it is a single instruction.  We could do better if we
210          * knew the rate.
211          */
212         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
213         return (0);
214 }
215
216 int
217 release_timer2()
218 {
219         if (timer2_state != ACQUIRED)
220                 return (-1);
221         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
222         timer2_state = RELEASED;
223         return (0);
224 }
225
226 /*
227  * This routine receives statistical clock interrupts from the RTC.
228  * As explained above, these occur at 128 interrupts per second.
229  * When profiling, we receive interrupts at a rate of 1024 Hz.
230  *
231  * This does not actually add as much overhead as it sounds, because
232  * when the statistical clock is active, the hardclock driver no longer
233  * needs to keep (inaccurate) statistics on its own.  This decouples
234  * statistics gathering from scheduling interrupts.
235  *
236  * The RTC chip requires that we read status register C (RTC_INTR)
237  * to acknowledge an interrupt, before it will generate the next one.
238  * Under high interrupt load, rtcintr() can be indefinitely delayed and
239  * the clock can tick immediately after the read from RTC_INTR.  In this
240  * case, the mc146818A interrupt signal will not drop for long enough
241  * to register with the 8259 PIC.  If an interrupt is missed, the stat
242  * clock will halt, considerably degrading system performance.  This is
243  * why we use 'while' rather than a more straightforward 'if' below.
244  * Stat clock ticks can still be lost, causing minor loss of accuracy
245  * in the statistics, but the stat clock will no longer stop.
246  */
247 static void
248 rtcintr(struct intrframe frame)
249 {
250         while (rtcin(RTC_INTR) & RTCIR_PERIOD)
251                 ;
252                 /* statclock(&frame); no longer used */
253 }
254
255 #include "opt_ddb.h"
256 #ifdef DDB
257 #include <ddb/ddb.h>
258
259 DB_SHOW_COMMAND(rtc, rtc)
260 {
261         printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
262                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
263                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
264                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
265 }
266 #endif /* DDB */
267
268 /*
269  * Convert a frequency to a cpu timer count.
270  */
271 sysclock_t
272 cputimer_fromhz(int freq)
273 {
274         return(cputimer_freq / freq + 1);
275 }
276
277 sysclock_t
278 cputimer_fromus(int us)
279 {
280         return((int64_t)cputimer_freq * us / 1000000);
281 }
282
283 /*
284  * Return the current cpu timer count as a 32 bit integer.
285  */
286 sysclock_t
287 cputimer_count(void)
288 {
289         static sysclock_t cputimer_base;
290         static __uint16_t cputimer_last;
291         __uint16_t count;
292         sysclock_t ret;
293
294         clock_lock();
295         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
296         count = (__uint8_t)inb(i8254_walltimer_cntr);           /* get countdown */
297         count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
298         count = -count;                                 /* -> countup */
299         if (count < cputimer_last)                      /* rollover */
300                 cputimer_base += 0x00010000;
301         ret = cputimer_base | count;
302         cputimer_last = count;
303         clock_unlock();
304         return(ret);
305 }
306
307 /*
308  * Reload for the next timeout.  It is possible for the reload value
309  * to be 0 or negative, indicating that an immediate timer interrupt
310  * is desired.  For now make the minimum 2 ticks.
311  */
312 void
313 cputimer_intr_reload(sysclock_t reload)
314 {
315     __uint16_t count;
316
317     if ((int)reload < 2)
318         reload = 2;
319
320     clock_lock();
321     if (timer0_running) {
322         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);     /* count-down timer */
323         count = (__uint8_t)inb(TIMER_CNTR0);            /* lsb */
324         count |= ((__uint8_t)inb(TIMER_CNTR0) << 8);    /* msb */
325         if (reload < count) {
326             outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
327             outb(TIMER_CNTR0, (__uint8_t)reload);       /* lsb */
328             outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
329         }
330     } else {
331         timer0_running = 1;
332         if (reload > 0xFFFF)
333             reload = 0;         /* full count */
334         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
335         outb(TIMER_CNTR0, (__uint8_t)reload);           /* lsb */
336         outb(TIMER_CNTR0, (__uint8_t)(reload >> 8));    /* msb */
337     }
338     clock_unlock();
339 }
340
341 /*
342  * Wait "n" microseconds.
343  * Relies on timer 1 counting down from (cputimer_freq / hz)
344  * Note: timer had better have been programmed before this is first used!
345  */
346 void
347 DELAY(int n)
348 {
349         int delta, prev_tick, tick, ticks_left;
350
351 #ifdef DELAYDEBUG
352         int getit_calls = 1;
353         int n1;
354         static int state = 0;
355
356         if (state == 0) {
357                 state = 1;
358                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
359                         DELAY(n1);
360                 state = 2;
361         }
362         if (state == 1)
363                 printf("DELAY(%d)...", n);
364 #endif
365         /*
366          * Guard against the timer being uninitialized if we are called
367          * early for console i/o.
368          */
369         if (timer0_state == RELEASED)
370                 i8254_restore();
371
372         /*
373          * Read the counter first, so that the rest of the setup overhead is
374          * counted.  Guess the initial overhead is 20 usec (on most systems it
375          * takes about 1.5 usec for each of the i/o's in getit().  The loop
376          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
377          * multiplications and divisions to scale the count take a while).
378          */
379         prev_tick = cputimer_count();
380         n -= 0;                 /* XXX actually guess no initial overhead */
381         /*
382          * Calculate (n * (cputimer_freq / 1e6)) without using floating point
383          * and without any avoidable overflows.
384          */
385         if (n <= 0) {
386                 ticks_left = 0;
387         } else if (n < 256) {
388                 /*
389                  * Use fixed point to avoid a slow division by 1000000.
390                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
391                  * 2^15 is the first power of 2 that gives exact results
392                  * for n between 0 and 256.
393                  */
394                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
395         } else {
396                 /*
397                  * Don't bother using fixed point, although gcc-2.7.2
398                  * generates particularly poor code for the long long
399                  * division, since even the slow way will complete long
400                  * before the delay is up (unless we're interrupted).
401                  */
402                 ticks_left = ((u_int)n * (long long)cputimer_freq + 999999)
403                              / 1000000;
404         }
405
406         while (ticks_left > 0) {
407                 tick = cputimer_count();
408 #ifdef DELAYDEBUG
409                 ++getit_calls;
410 #endif
411                 delta = tick - prev_tick;
412                 prev_tick = tick;
413                 if (delta < 0)
414                         delta = 0;
415                 ticks_left -= delta;
416         }
417 #ifdef DELAYDEBUG
418         if (state == 1)
419                 printf(" %d calls to getit() at %d usec each\n",
420                        getit_calls, (n + 5) / getit_calls);
421 #endif
422 }
423
424 static void
425 sysbeepstop(void *chan)
426 {
427         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
428         beeping = 0;
429         release_timer2();
430 }
431
432 int
433 sysbeep(int pitch, int period)
434 {
435         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
436                 return(-1);
437         /*
438          * Nobody else is using timer2, we do not need the clock lock
439          */
440         outb(TIMER_CNTR2, pitch);
441         outb(TIMER_CNTR2, (pitch>>8));
442         if (!beeping) {
443                 /* enable counter2 output to speaker */
444                 outb(IO_PPI, inb(IO_PPI) | 3);
445                 beeping = period;
446                 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
447         }
448         return (0);
449 }
450
451 /*
452  * RTC support routines
453  */
454
455 int
456 rtcin(reg)
457         int reg;
458 {
459         int s;
460         u_char val;
461
462         s = splhigh();
463         outb(IO_RTC, reg);
464         inb(0x84);
465         val = inb(IO_RTC + 1);
466         inb(0x84);
467         splx(s);
468         return (val);
469 }
470
471 static __inline void
472 writertc(u_char reg, u_char val)
473 {
474         int s;
475
476         s = splhigh();
477         inb(0x84);
478         outb(IO_RTC, reg);
479         inb(0x84);
480         outb(IO_RTC + 1, val);
481         inb(0x84);              /* XXX work around wrong order in rtcin() */
482         splx(s);
483 }
484
485 static __inline int
486 readrtc(int port)
487 {
488         return(bcd2bin(rtcin(port)));
489 }
490
491 static u_int
492 calibrate_clocks(void)
493 {
494         u_int64_t old_tsc;
495         u_int count, prev_count, tot_count;
496         int sec, start_sec, timeout;
497
498         if (bootverbose)
499                 printf("Calibrating clock(s) ... ");
500         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
501                 goto fail;
502         timeout = 100000000;
503
504         /* Read the mc146818A seconds counter. */
505         for (;;) {
506                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
507                         sec = rtcin(RTC_SEC);
508                         break;
509                 }
510                 if (--timeout == 0)
511                         goto fail;
512         }
513
514         /* Wait for the mC146818A seconds counter to change. */
515         start_sec = sec;
516         for (;;) {
517                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
518                         sec = rtcin(RTC_SEC);
519                         if (sec != start_sec)
520                                 break;
521                 }
522                 if (--timeout == 0)
523                         goto fail;
524         }
525
526         /* Start keeping track of the i8254 counter. */
527         prev_count = cputimer_count();
528         tot_count = 0;
529
530         if (tsc_present) 
531                 old_tsc = rdtsc();
532         else
533                 old_tsc = 0;            /* shut up gcc */
534
535         /*
536          * Wait for the mc146818A seconds counter to change.  Read the i8254
537          * counter for each iteration since this is convenient and only
538          * costs a few usec of inaccuracy. The timing of the final reads
539          * of the counters almost matches the timing of the initial reads,
540          * so the main cause of inaccuracy is the varying latency from 
541          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
542          * rtcin(RTC_SEC) that returns a changed seconds count.  The
543          * maximum inaccuracy from this cause is < 10 usec on 486's.
544          */
545         start_sec = sec;
546         for (;;) {
547                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
548                         sec = rtcin(RTC_SEC);
549                 count = cputimer_count();
550                 tot_count += (int)(count - prev_count);
551                 prev_count = count;
552                 if (sec != start_sec)
553                         break;
554                 if (--timeout == 0)
555                         goto fail;
556         }
557
558         /*
559          * Read the cpu cycle counter.  The timing considerations are
560          * similar to those for the i8254 clock.
561          */
562         if (tsc_present) 
563                 tsc_freq = rdtsc() - old_tsc;
564
565         if (tsc_present)
566                 printf("TSC clock: %u Hz, ", tsc_freq);
567         printf("i8254 clock: %u Hz\n", tot_count);
568         return (tot_count);
569
570 fail:
571         printf("failed, using default i8254 clock of %u Hz\n", cputimer_freq);
572         return (cputimer_freq);
573 }
574
575 static void
576 i8254_restore(void)
577 {
578         timer0_state = ACQUIRED;
579         if (i8254_walltimer != 1 && i8254_walltimer != 2)
580                 i8254_walltimer = 2;
581
582         if (i8254_walltimer == 1) {
583                 i8254_walltimer_sel = TIMER_SEL1;
584                 i8254_walltimer_cntr = TIMER_CNTR1;
585                 timer1_state = ACQUIRED;
586         } else {
587                 i8254_walltimer_sel = TIMER_SEL2;
588                 i8254_walltimer_cntr = TIMER_CNTR2;
589                 timer2_state = ACQUIRED;
590         }
591         clock_lock();
592         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
593         outb(TIMER_CNTR0, 2);   /* lsb */
594         outb(TIMER_CNTR0, 0);   /* msb */
595         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
596         outb(i8254_walltimer_cntr, 0);  /* lsb */
597         outb(i8254_walltimer_cntr, 0);  /* msb */
598         outb(IO_PPI, inb(IO_PPI) | 1);  /* bit 0: enable gate, bit 1: spkr */
599         clock_unlock();
600 }
601
602 static void
603 rtc_restore(void)
604 {
605         /* Restore all of the RTC's "status" (actually, control) registers. */
606         writertc(RTC_STATUSB, RTCSB_24HR);
607         writertc(RTC_STATUSA, rtc_statusa);
608         writertc(RTC_STATUSB, rtc_statusb);
609 }
610
611 /*
612  * Restore all the timers.
613  *
614  * This function is called to resynchronize our core timekeeping after a
615  * long halt, e.g. from apm_default_resume() and friends.  It is also 
616  * called if after a BIOS call we have detected munging of the 8254.
617  * It is necessary because cputimer_count() counter's delta may have grown
618  * too large for nanouptime() and friends to handle, or (in the case of 8254
619  * munging) might cause the SYSTIMER code to prematurely trigger.
620  */
621 void
622 timer_restore(void)
623 {
624         crit_enter();
625         i8254_restore();                /* restore timer_freq and hz */
626         rtc_restore();                  /* reenable RTC interrupts */
627         crit_exit();
628 }
629
630 /*
631  * Initialize 8254 timer 0 early so that it can be used in DELAY().
632  */
633 void
634 startrtclock()
635 {
636         u_int delta, freq;
637
638         /* 
639          * Can we use the TSC?
640          */
641         if (cpu_feature & CPUID_TSC)
642                 tsc_present = 1;
643         else
644                 tsc_present = 0;
645
646         /*
647          * Initial RTC state, don't do anything unexpected
648          */
649         writertc(RTC_STATUSA, rtc_statusa);
650         writertc(RTC_STATUSB, RTCSB_24HR);
651
652         /*
653          * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to 
654          * generate an interrupt, which we will ignore for now.
655          *
656          * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
657          * (so it counts a full 2^16 and repeats).  We will use this timer
658          * for our counting.
659          */
660         i8254_restore();
661         freq = calibrate_clocks();
662 #ifdef CLK_CALIBRATION_LOOP
663         if (bootverbose) {
664                 printf(
665                 "Press a key on the console to abort clock calibration\n");
666                 while (cncheckc() == -1)
667                         calibrate_clocks();
668         }
669 #endif
670
671         /*
672          * Use the calibrated i8254 frequency if it seems reasonable.
673          * Otherwise use the default, and don't use the calibrated i586
674          * frequency.
675          */
676         delta = freq > cputimer_freq ? 
677                         freq - cputimer_freq : cputimer_freq - freq;
678         if (delta < cputimer_freq / 100) {
679 #ifndef CLK_USE_I8254_CALIBRATION
680                 if (bootverbose)
681                         printf(
682 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
683                 freq = cputimer_freq;
684 #endif
685                 cputimer_freq = freq;
686                 cputimer_freq64_usec = (1000000LL << 32) / freq;
687                 cputimer_freq64_nsec = (1000000000LL << 32) / freq;
688         } else {
689                 if (bootverbose)
690                         printf(
691                     "%d Hz differs from default of %d Hz by more than 1%%\n",
692                                freq, cputimer_freq);
693                 tsc_freq = 0;
694         }
695
696 #ifndef CLK_USE_TSC_CALIBRATION
697         if (tsc_freq != 0) {
698                 if (bootverbose)
699                         printf(
700 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
701                 tsc_freq = 0;
702         }
703 #endif
704         if (tsc_present && tsc_freq == 0) {
705                 /*
706                  * Calibration of the i586 clock relative to the mc146818A
707                  * clock failed.  Do a less accurate calibration relative
708                  * to the i8254 clock.
709                  */
710                 u_int64_t old_tsc = rdtsc();
711
712                 DELAY(1000000);
713                 tsc_freq = rdtsc() - old_tsc;
714 #ifdef CLK_USE_TSC_CALIBRATION
715                 if (bootverbose)
716                         printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
717 #endif
718         }
719
720 #if !defined(SMP)
721         /*
722          * We can not use the TSC in SMP mode, until we figure out a
723          * cheap (impossible), reliable and precise (yeah right!)  way
724          * to synchronize the TSCs of all the CPUs.
725          * Curse Intel for leaving the counter out of the I/O APIC.
726          */
727
728 #if NAPM > 0
729         /*
730          * We can not use the TSC if we support APM. Precise timekeeping
731          * on an APM'ed machine is at best a fools pursuit, since 
732          * any and all of the time spent in various SMM code can't 
733          * be reliably accounted for.  Reading the RTC is your only
734          * source of reliable time info.  The i8254 looses too of course
735          * but we need to have some kind of time...
736          * We don't know at this point whether APM is going to be used
737          * or not, nor when it might be activated.  Play it safe.
738          */
739         return;
740 #endif /* NAPM > 0 */
741
742 #endif /* !defined(SMP) */
743 }
744
745 /*
746  * Initialize the time of day register, based on the time base which is, e.g.
747  * from a filesystem.
748  */
749 void
750 inittodr(time_t base)
751 {
752         unsigned long   sec, days;
753         int             yd;
754         int             year, month;
755         int             y, m;
756         struct timespec ts;
757
758         if (base) {
759                 ts.tv_sec = base;
760                 ts.tv_nsec = 0;
761                 set_timeofday(&ts);
762         }
763
764         /* Look if we have a RTC present and the time is valid */
765         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
766                 goto wrong_time;
767
768         /* wait for time update to complete */
769         /* If RTCSA_TUP is zero, we have at least 244us before next update */
770         crit_enter();
771         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
772                 crit_exit();
773                 crit_enter();
774         }
775
776         days = 0;
777 #ifdef USE_RTC_CENTURY
778         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
779 #else
780         year = readrtc(RTC_YEAR) + 1900;
781         if (year < 1970)
782                 year += 100;
783 #endif
784         if (year < 1970) {
785                 crit_exit();
786                 goto wrong_time;
787         }
788         month = readrtc(RTC_MONTH);
789         for (m = 1; m < month; m++)
790                 days += daysinmonth[m-1];
791         if ((month > 2) && LEAPYEAR(year))
792                 days ++;
793         days += readrtc(RTC_DAY) - 1;
794         yd = days;
795         for (y = 1970; y < year; y++)
796                 days += DAYSPERYEAR + LEAPYEAR(y);
797         sec = ((( days * 24 +
798                   readrtc(RTC_HRS)) * 60 +
799                   readrtc(RTC_MIN)) * 60 +
800                   readrtc(RTC_SEC));
801         /* sec now contains the number of seconds, since Jan 1 1970,
802            in the local time zone */
803
804         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
805
806         y = time_second - sec;
807         if (y <= -2 || y >= 2) {
808                 /* badly off, adjust it */
809                 ts.tv_sec = sec;
810                 ts.tv_nsec = 0;
811                 set_timeofday(&ts);
812         }
813         crit_exit();
814         return;
815
816 wrong_time:
817         printf("Invalid time in real time clock.\n");
818         printf("Check and reset the date immediately!\n");
819 }
820
821 /*
822  * Write system time back to RTC
823  */
824 void
825 resettodr()
826 {
827         struct timeval tv;
828         unsigned long tm;
829         int m;
830         int y;
831
832         if (disable_rtc_set)
833                 return;
834
835         microtime(&tv);
836         tm = tv.tv_sec;
837
838         crit_enter();
839         /* Disable RTC updates and interrupts. */
840         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
841
842         /* Calculate local time to put in RTC */
843
844         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
845
846         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
847         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
848         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
849
850         /* We have now the days since 01-01-1970 in tm */
851         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
852         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
853              tm >= m;
854              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
855              tm -= m;
856
857         /* Now we have the years in y and the day-of-the-year in tm */
858         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
859 #ifdef USE_RTC_CENTURY
860         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
861 #endif
862         for (m = 0; ; m++) {
863                 int ml;
864
865                 ml = daysinmonth[m];
866                 if (m == 1 && LEAPYEAR(y))
867                         ml++;
868                 if (tm < ml)
869                         break;
870                 tm -= ml;
871         }
872
873         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
874         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
875
876         /* Reenable RTC updates and interrupts. */
877         writertc(RTC_STATUSB, rtc_statusb);
878         crit_exit();
879 }
880
881
882 /*
883  * Start both clocks running.  DragonFly note: the stat clock is no longer
884  * used.  Instead, 8254 based systimers are used for all major clock
885  * interrupts.  statclock_disable is set by default.
886  */
887 void
888 cpu_initclocks()
889 {
890         int diag;
891 #ifdef APIC_IO
892         int apic_8254_trial;
893         struct intrec *clkdesc;
894 #endif /* APIC_IO */
895
896         if (statclock_disable) {
897                 /*
898                  * The stat interrupt mask is different without the
899                  * statistics clock.  Also, don't set the interrupt
900                  * flag which would normally cause the RTC to generate
901                  * interrupts.
902                  */
903                 stat_imask = HWI_MASK | SWI_MASK;
904                 rtc_statusb = RTCSB_24HR;
905         } else {
906                 /* Setting stathz to nonzero early helps avoid races. */
907                 stathz = RTC_NOPROFRATE;
908                 profhz = RTC_PROFRATE;
909         }
910
911         /* Finish initializing 8253 timer 0. */
912 #ifdef APIC_IO
913
914         apic_8254_intr = isa_apic_irq(0);
915         apic_8254_trial = 0;
916         if (apic_8254_intr >= 0 ) {
917                 if (apic_int_type(0, 0) == 3)
918                         apic_8254_trial = 1;
919         } else {
920                 /* look for ExtInt on pin 0 */
921                 if (apic_int_type(0, 0) == 3) {
922                         apic_8254_intr = apic_irq(0, 0);
923                         setup_8254_mixed_mode();
924                 } else 
925                         panic("APIC_IO: Cannot route 8254 interrupt to CPU");
926         }
927
928         clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
929                               NULL, &clk_imask, INTR_EXCL | INTR_FAST, NULL);
930         INTREN(1 << apic_8254_intr);
931         
932 #else /* APIC_IO */
933
934         inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
935                     INTR_EXCL | INTR_FAST, NULL);
936         INTREN(IRQ0);
937
938 #endif /* APIC_IO */
939
940         /* Initialize RTC. */
941         writertc(RTC_STATUSA, rtc_statusa);
942         writertc(RTC_STATUSB, RTCSB_24HR);
943
944         if (statclock_disable == 0) {
945                 diag = rtcin(RTC_DIAG);
946                 if (diag != 0)
947                         printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
948
949 #ifdef APIC_IO
950                 if (isa_apic_irq(8) != 8)
951                         panic("APIC RTC != 8");
952 #endif /* APIC_IO */
953
954                 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
955                             INTR_EXCL | INTR_FAST, NULL);
956
957 #ifdef APIC_IO
958                 INTREN(APIC_IRQ8);
959 #else
960                 INTREN(IRQ8);
961 #endif /* APIC_IO */
962
963                 writertc(RTC_STATUSB, rtc_statusb);
964         }
965
966 #ifdef APIC_IO
967         if (apic_8254_trial) {
968                 sysclock_t base;
969                 int lastcnt = read_intr_count(apic_8254_intr);
970
971                 /*
972                  * XXX this assumes the 8254 is the cpu timer.  Force an
973                  * 8254 Timer0 interrupt and wait 1/100s for it to happen,
974                  * then see if we got it.
975                  */
976                 printf("APIC_IO: Testing 8254 interrupt delivery\n");
977                 cputimer_intr_reload(2);        /* XXX assumes 8254 */
978                 base = cputimer_count();
979                 while (cputimer_count() - base < cputimer_freq / 100)
980                         ;       /* nothing */
981                 if (read_intr_count(apic_8254_intr) - lastcnt == 0) {
982                         /* 
983                          * The MP table is broken.
984                          * The 8254 was not connected to the specified pin
985                          * on the IO APIC.
986                          * Workaround: Limited variant of mixed mode.
987                          */
988                         INTRDIS(1 << apic_8254_intr);
989                         inthand_remove(clkdesc);
990                         printf("APIC_IO: Broken MP table detected: "
991                                "8254 is not connected to "
992                                "IOAPIC #%d intpin %d\n",
993                                int_to_apicintpin[apic_8254_intr].ioapic,
994                                int_to_apicintpin[apic_8254_intr].int_pin);
995                         /* 
996                          * Revoke current ISA IRQ 0 assignment and 
997                          * configure a fallback interrupt routing from
998                          * the 8254 Timer via the 8259 PIC to the
999                          * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1000                          * We reuse the low level interrupt handler number.
1001                          */
1002                         if (apic_irq(0, 0) < 0) {
1003                                 revoke_apic_irq(apic_8254_intr);
1004                                 assign_apic_irq(0, 0, apic_8254_intr);
1005                         }
1006                         apic_8254_intr = apic_irq(0, 0);
1007                         setup_8254_mixed_mode();
1008                         inthand_add("clk", apic_8254_intr,
1009                                     (inthand2_t *)clkintr,
1010                                     NULL, &clk_imask, 
1011                                     INTR_EXCL | INTR_FAST, NULL);
1012                         INTREN(1 << apic_8254_intr);
1013                 }
1014                 
1015         }
1016         if (apic_int_type(0, 0) != 3 ||
1017             int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1018             int_to_apicintpin[apic_8254_intr].int_pin != 0) {
1019                 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1020                        int_to_apicintpin[apic_8254_intr].ioapic,
1021                        int_to_apicintpin[apic_8254_intr].int_pin);
1022         } else {
1023                 printf("APIC_IO: "
1024                        "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1025         }
1026 #endif
1027         callout_init(&sysbeepstop_ch);
1028 }
1029
1030 #ifdef APIC_IO
1031 static u_long
1032 read_intr_count(int vec)
1033 {
1034         u_long *up;
1035         up = intr_countp[vec];
1036         if (up)
1037                 return *up;
1038         return 0UL;
1039 }
1040
1041 static void 
1042 setup_8254_mixed_mode()
1043 {
1044         /*
1045          * Allow 8254 timer to INTerrupt 8259:
1046          *  re-initialize master 8259:
1047          *   reset; prog 4 bytes, single ICU, edge triggered
1048          */
1049         outb(IO_ICU1, 0x13);
1050         outb(IO_ICU1 + 1, NRSVIDT);     /* start vector (unused) */
1051         outb(IO_ICU1 + 1, 0x00);        /* ignore slave */
1052         outb(IO_ICU1 + 1, 0x03);        /* auto EOI, 8086 */
1053         outb(IO_ICU1 + 1, 0xfe);        /* unmask INT0 */
1054         
1055         /* program IO APIC for type 3 INT on INT0 */
1056         if (ext_int_setup(0, 0) < 0)
1057                 panic("8254 redirect via APIC pin0 impossible!");
1058 }
1059 #endif
1060
1061 void
1062 setstatclockrate(int newhz)
1063 {
1064         if (newhz == RTC_PROFRATE)
1065                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1066         else
1067                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1068         writertc(RTC_STATUSA, rtc_statusa);
1069 }
1070
1071 #if 0
1072 static unsigned
1073 tsc_get_timecount(struct timecounter *tc)
1074 {
1075         return (rdtsc());
1076 }
1077 #endif
1078
1079 #ifdef KERN_TIMESTAMP
1080 #define KERN_TIMESTAMP_SIZE 16384
1081 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1082 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1083         sizeof(tsc), "LU", "Kernel timestamps");
1084 void  
1085 _TSTMP(u_int32_t x)
1086 {
1087         static int i;
1088
1089         tsc[i] = (u_int32_t)rdtsc();
1090         tsc[i+1] = x;
1091         i = i + 2;
1092         if (i >= KERN_TIMESTAMP_SIZE)
1093                 i = 0;
1094         tsc[i] = 0; /* mark last entry */
1095 }
1096 #endif /* KERN_TIMESTAMP */
1097
1098 /*
1099  *
1100  */
1101
1102 static int
1103 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1104 {
1105     sysclock_t count;
1106     __uint64_t tscval;
1107     char buf[32];
1108
1109     crit_enter();
1110     count = cputimer_count();
1111     if (tsc_present)
1112         tscval = rdtsc();
1113     else
1114         tscval = 0;
1115     crit_exit();
1116     snprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1117     return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1118 }
1119
1120 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1121 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &cputimer_freq, 0,
1122     "frequency");
1123 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1124                 0, 0, hw_i8254_timestamp, "A", "");
1125 SYSCTL_INT(_hw_i8254, OID_AUTO, walltimer, CTLFLAG_RD, &i8254_walltimer, 0,
1126     "timer used for the wall time; either 1 or 2");
1127