Merge from vendor branch BIND:
[dragonfly.git] / sys / i386 / 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/i386/isa/Attic/clock.c,v 1.17 2004/09/17 00:18:13 joerg 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 #define TIMER_SELX      TIMER_SEL2
120 #define TIMER_CNTRX     TIMER_CNTR2
121
122 int     adjkerntz;              /* local offset from GMT in seconds */
123 int     disable_rtc_set;        /* disable resettodr() if != 0 */
124 volatile u_int  idelayed;
125 int     statclock_disable = 1;  /* we don't use the statclock right now */
126 u_int   stat_imask = SWI_CLOCK_MASK;
127 u_int   cputimer_freq = TIMER_FREQ;
128 #if 0
129 int64_t cputimer_freq64_usec = ((int64_t)TIMER_FREQ << 32) / 1000000;
130 int64_t cputimer_freq64_nsec = ((int64_t)TIMER_FREQ << 32) / 1000000000LL;
131 #endif
132 int64_t cputimer_freq64_usec = (1000000LL << 32) / TIMER_FREQ;
133 int64_t cputimer_freq64_nsec = (1000000000LL << 32) / TIMER_FREQ;
134 u_int   tsc_freq;
135 int     tsc_is_broken;
136 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
137 int     timer0_running;
138 enum tstate { RELEASED, ACQUIRED };
139 enum tstate timer0_state;
140 enum tstate timer1_state;
141 enum tstate timer2_state;
142
143 static  int     beeping = 0;
144 static  u_int   clk_imask = HWI_MASK | SWI_MASK;
145 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
146 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
147 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
148 static  u_int   tsc_present;
149
150 static struct callout sysbeepstop_ch;
151
152 /*
153  * timer0 clock interrupt.  Timer0 is in one-shot mode and has stopped
154  * counting as of this interrupt.  We use timer1 in free-running mode (not
155  * generating any interrupts) as our main counter.  Each cpu has timeouts
156  * pending.
157  */
158 static void
159 clkintr(struct intrframe frame)
160 {
161         static sysclock_t timer1_count;
162         struct globaldata *gd = mycpu;
163         struct globaldata *gscan;
164         int n;
165
166         /*
167          * SWSTROBE mode is a one-shot, the timer is no longer running
168          */
169         timer0_running = 0;
170
171         /*
172          * XXX this could be done more efficiently by using a bitmask?
173          */
174         timer1_count = cputimer_count();
175         for (n = 0; n < ncpus; ++n) {
176             gscan = globaldata_find(n);
177             if (gscan->gd_nextclock == 0)
178                 continue;
179             if (gscan != gd) {
180                 lwkt_send_ipiq(gscan, (ipifunc_t)systimer_intr, &timer1_count);
181             } else {
182                 systimer_intr(&timer1_count, &frame);
183             }
184         }
185 #if NMCA > 0
186         /* Reset clock interrupt by asserting bit 7 of port 0x61 */
187         if (MCA_system)
188                 outb(0x61, inb(0x61) | 0x80);
189 #endif
190 }
191
192
193 /*
194  * NOTE! not MP safe.
195  */
196 int
197 acquire_timer2(int mode)
198 {
199         /* Timer2 is being used for time count operation */
200         return(-1);
201 #if 0
202         if (timer2_state != RELEASED)
203                 return (-1);
204         timer2_state = ACQUIRED;
205
206         /*
207          * This access to the timer registers is as atomic as possible
208          * because it is a single instruction.  We could do better if we
209          * knew the rate.
210          */
211         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
212         return (0);
213 #endif
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, TIMER_SELX | TIMER_LATCH);
296         count = (__uint8_t)inb(TIMER_CNTRX);            /* get countdown */
297         count |= ((__uint8_t)inb(TIMER_CNTRX) << 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         timer1_state = ACQUIRED;
580         clock_lock();
581         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
582         outb(TIMER_CNTR0, 2);   /* lsb */
583         outb(TIMER_CNTR0, 0);   /* msb */
584         outb(TIMER_MODE, TIMER_SELX | TIMER_RATEGEN | TIMER_16BIT);
585         outb(TIMER_CNTRX, 0);   /* lsb */
586         outb(TIMER_CNTRX, 0);   /* msb */
587         outb(IO_PPI, inb(IO_PPI) | 1);  /* bit 0: enable gate, bit 1: spkr */
588         clock_unlock();
589 }
590
591 static void
592 rtc_restore(void)
593 {
594         /* Restore all of the RTC's "status" (actually, control) registers. */
595         writertc(RTC_STATUSB, RTCSB_24HR);
596         writertc(RTC_STATUSA, rtc_statusa);
597         writertc(RTC_STATUSB, rtc_statusb);
598 }
599
600 /*
601  * Restore all the timers.
602  *
603  * This function is called from apm_default_resume() / pmtimer to restore
604  * all the timers.  We also have to restore our timebases, especially on
605  * MP systems, because cputimer_count() counter's delta may have grown
606  * too large for nanouptime() and friends to handle.
607  */
608 void
609 timer_restore(void)
610 {
611         crit_enter();
612         i8254_restore();                /* restore timer_freq and hz */
613         rtc_restore();                  /* reenable RTC interrupts */
614         restoreclocks();
615         crit_exit();
616 }
617
618 /*
619  * Initialize 8254 timer 0 early so that it can be used in DELAY().
620  */
621 void
622 startrtclock()
623 {
624         u_int delta, freq;
625
626         /* 
627          * Can we use the TSC?
628          */
629         if (cpu_feature & CPUID_TSC)
630                 tsc_present = 1;
631         else
632                 tsc_present = 0;
633
634         /*
635          * Initial RTC state, don't do anything unexpected
636          */
637         writertc(RTC_STATUSA, rtc_statusa);
638         writertc(RTC_STATUSB, RTCSB_24HR);
639
640         /*
641          * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to 
642          * generate an interrupt, which we will ignore for now.
643          *
644          * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
645          * (so it counts a full 2^16 and repeats).  We will use this timer
646          * for our counting.
647          */
648         i8254_restore();
649         freq = calibrate_clocks();
650 #ifdef CLK_CALIBRATION_LOOP
651         if (bootverbose) {
652                 printf(
653                 "Press a key on the console to abort clock calibration\n");
654                 while (cncheckc() == -1)
655                         calibrate_clocks();
656         }
657 #endif
658
659         /*
660          * Use the calibrated i8254 frequency if it seems reasonable.
661          * Otherwise use the default, and don't use the calibrated i586
662          * frequency.
663          */
664         delta = freq > cputimer_freq ? 
665                         freq - cputimer_freq : cputimer_freq - freq;
666         if (delta < cputimer_freq / 100) {
667 #ifndef CLK_USE_I8254_CALIBRATION
668                 if (bootverbose)
669                         printf(
670 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
671                 freq = cputimer_freq;
672 #endif
673                 cputimer_freq = freq;
674                 cputimer_freq64_usec = (1000000LL << 32) / freq;
675                 cputimer_freq64_nsec = (1000000000LL << 32) / freq;
676         } else {
677                 if (bootverbose)
678                         printf(
679                     "%d Hz differs from default of %d Hz by more than 1%%\n",
680                                freq, cputimer_freq);
681                 tsc_freq = 0;
682         }
683
684 #ifndef CLK_USE_TSC_CALIBRATION
685         if (tsc_freq != 0) {
686                 if (bootverbose)
687                         printf(
688 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
689                 tsc_freq = 0;
690         }
691 #endif
692         if (tsc_present && tsc_freq == 0) {
693                 /*
694                  * Calibration of the i586 clock relative to the mc146818A
695                  * clock failed.  Do a less accurate calibration relative
696                  * to the i8254 clock.
697                  */
698                 u_int64_t old_tsc = rdtsc();
699
700                 DELAY(1000000);
701                 tsc_freq = rdtsc() - old_tsc;
702 #ifdef CLK_USE_TSC_CALIBRATION
703                 if (bootverbose)
704                         printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
705 #endif
706         }
707
708 #if !defined(SMP)
709         /*
710          * We can not use the TSC in SMP mode, until we figure out a
711          * cheap (impossible), reliable and precise (yeah right!)  way
712          * to synchronize the TSCs of all the CPUs.
713          * Curse Intel for leaving the counter out of the I/O APIC.
714          */
715
716 #if NAPM > 0
717         /*
718          * We can not use the TSC if we support APM. Precise timekeeping
719          * on an APM'ed machine is at best a fools pursuit, since 
720          * any and all of the time spent in various SMM code can't 
721          * be reliably accounted for.  Reading the RTC is your only
722          * source of reliable time info.  The i8254 looses too of course
723          * but we need to have some kind of time...
724          * We don't know at this point whether APM is going to be used
725          * or not, nor when it might be activated.  Play it safe.
726          */
727         return;
728 #endif /* NAPM > 0 */
729
730 #endif /* !defined(SMP) */
731 }
732
733 /*
734  * Initialize the time of day register, based on the time base which is, e.g.
735  * from a filesystem.
736  */
737 void
738 inittodr(time_t base)
739 {
740         unsigned long   sec, days;
741         int             yd;
742         int             year, month;
743         int             y, m;
744         struct timespec ts;
745
746         if (base) {
747                 ts.tv_sec = base;
748                 ts.tv_nsec = 0;
749                 set_timeofday(&ts);
750         }
751
752         /* Look if we have a RTC present and the time is valid */
753         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
754                 goto wrong_time;
755
756         /* wait for time update to complete */
757         /* If RTCSA_TUP is zero, we have at least 244us before next update */
758         crit_enter();
759         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
760                 crit_exit();
761                 crit_enter();
762         }
763
764         days = 0;
765 #ifdef USE_RTC_CENTURY
766         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
767 #else
768         year = readrtc(RTC_YEAR) + 1900;
769         if (year < 1970)
770                 year += 100;
771 #endif
772         if (year < 1970) {
773                 crit_exit();
774                 goto wrong_time;
775         }
776         month = readrtc(RTC_MONTH);
777         for (m = 1; m < month; m++)
778                 days += daysinmonth[m-1];
779         if ((month > 2) && LEAPYEAR(year))
780                 days ++;
781         days += readrtc(RTC_DAY) - 1;
782         yd = days;
783         for (y = 1970; y < year; y++)
784                 days += DAYSPERYEAR + LEAPYEAR(y);
785         sec = ((( days * 24 +
786                   readrtc(RTC_HRS)) * 60 +
787                   readrtc(RTC_MIN)) * 60 +
788                   readrtc(RTC_SEC));
789         /* sec now contains the number of seconds, since Jan 1 1970,
790            in the local time zone */
791
792         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
793
794         y = time_second - sec;
795         if (y <= -2 || y >= 2) {
796                 /* badly off, adjust it */
797                 ts.tv_sec = sec;
798                 ts.tv_nsec = 0;
799                 set_timeofday(&ts);
800         }
801         crit_exit();
802         return;
803
804 wrong_time:
805         printf("Invalid time in real time clock.\n");
806         printf("Check and reset the date immediately!\n");
807 }
808
809 /*
810  * Write system time back to RTC
811  */
812 void
813 resettodr()
814 {
815         struct timeval tv;
816         unsigned long tm;
817         int m;
818         int y;
819
820         if (disable_rtc_set)
821                 return;
822
823         microtime(&tv);
824         tm = tv.tv_sec;
825
826         crit_enter();
827         /* Disable RTC updates and interrupts. */
828         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
829
830         /* Calculate local time to put in RTC */
831
832         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
833
834         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
835         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
836         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
837
838         /* We have now the days since 01-01-1970 in tm */
839         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
840         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
841              tm >= m;
842              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
843              tm -= m;
844
845         /* Now we have the years in y and the day-of-the-year in tm */
846         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
847 #ifdef USE_RTC_CENTURY
848         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
849 #endif
850         for (m = 0; ; m++) {
851                 int ml;
852
853                 ml = daysinmonth[m];
854                 if (m == 1 && LEAPYEAR(y))
855                         ml++;
856                 if (tm < ml)
857                         break;
858                 tm -= ml;
859         }
860
861         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
862         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
863
864         /* Reenable RTC updates and interrupts. */
865         writertc(RTC_STATUSB, rtc_statusb);
866         crit_exit();
867 }
868
869
870 /*
871  * Start both clocks running.  DragonFly note: the stat clock is no longer
872  * used.  Instead, 8254 based systimers are used for all major clock
873  * interrupts.  statclock_disable is set by default.
874  */
875 void
876 cpu_initclocks()
877 {
878         int diag;
879 #ifdef APIC_IO
880         int apic_8254_trial;
881         struct intrec *clkdesc;
882 #endif /* APIC_IO */
883
884         if (statclock_disable) {
885                 /*
886                  * The stat interrupt mask is different without the
887                  * statistics clock.  Also, don't set the interrupt
888                  * flag which would normally cause the RTC to generate
889                  * interrupts.
890                  */
891                 stat_imask = HWI_MASK | SWI_MASK;
892                 rtc_statusb = RTCSB_24HR;
893         } else {
894                 /* Setting stathz to nonzero early helps avoid races. */
895                 stathz = RTC_NOPROFRATE;
896                 profhz = RTC_PROFRATE;
897         }
898
899         /* Finish initializing 8253 timer 0. */
900 #ifdef APIC_IO
901
902         apic_8254_intr = isa_apic_irq(0);
903         apic_8254_trial = 0;
904         if (apic_8254_intr >= 0 ) {
905                 if (apic_int_type(0, 0) == 3)
906                         apic_8254_trial = 1;
907         } else {
908                 /* look for ExtInt on pin 0 */
909                 if (apic_int_type(0, 0) == 3) {
910                         apic_8254_intr = apic_irq(0, 0);
911                         setup_8254_mixed_mode();
912                 } else 
913                         panic("APIC_IO: Cannot route 8254 interrupt to CPU");
914         }
915
916         clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
917                               NULL, &clk_imask, INTR_EXCL | INTR_FAST);
918         INTREN(1 << apic_8254_intr);
919         
920 #else /* APIC_IO */
921
922         inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
923                     INTR_EXCL | INTR_FAST);
924         INTREN(IRQ0);
925
926 #endif /* APIC_IO */
927
928         /* Initialize RTC. */
929         writertc(RTC_STATUSA, rtc_statusa);
930         writertc(RTC_STATUSB, RTCSB_24HR);
931
932         if (statclock_disable == 0) {
933                 diag = rtcin(RTC_DIAG);
934                 if (diag != 0)
935                         printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
936
937 #ifdef APIC_IO
938                 if (isa_apic_irq(8) != 8)
939                         panic("APIC RTC != 8");
940 #endif /* APIC_IO */
941
942                 inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
943                             INTR_EXCL | INTR_FAST);
944
945 #ifdef APIC_IO
946                 INTREN(APIC_IRQ8);
947 #else
948                 INTREN(IRQ8);
949 #endif /* APIC_IO */
950
951                 writertc(RTC_STATUSB, rtc_statusb);
952         }
953
954 #ifdef APIC_IO
955         if (apic_8254_trial) {
956                 sysclock_t base;
957                 int lastcnt = read_intr_count(apic_8254_intr);
958
959                 /*
960                  * XXX this assumes the 8254 is the cpu timer.  Force an
961                  * 8254 Timer0 interrupt and wait 1/100s for it to happen,
962                  * then see if we got it.
963                  */
964                 printf("APIC_IO: Testing 8254 interrupt delivery\n");
965                 cputimer_intr_reload(2);        /* XXX assumes 8254 */
966                 base = cputimer_count();
967                 while (cputimer_count() - base < cputimer_freq / 100)
968                         ;       /* nothing */
969                 if (read_intr_count(apic_8254_intr) - lastcnt == 0) {
970                         /* 
971                          * The MP table is broken.
972                          * The 8254 was not connected to the specified pin
973                          * on the IO APIC.
974                          * Workaround: Limited variant of mixed mode.
975                          */
976                         INTRDIS(1 << apic_8254_intr);
977                         inthand_remove(clkdesc);
978                         printf("APIC_IO: Broken MP table detected: "
979                                "8254 is not connected to "
980                                "IOAPIC #%d intpin %d\n",
981                                int_to_apicintpin[apic_8254_intr].ioapic,
982                                int_to_apicintpin[apic_8254_intr].int_pin);
983                         /* 
984                          * Revoke current ISA IRQ 0 assignment and 
985                          * configure a fallback interrupt routing from
986                          * the 8254 Timer via the 8259 PIC to the
987                          * an ExtInt interrupt line on IOAPIC #0 intpin 0.
988                          * We reuse the low level interrupt handler number.
989                          */
990                         if (apic_irq(0, 0) < 0) {
991                                 revoke_apic_irq(apic_8254_intr);
992                                 assign_apic_irq(0, 0, apic_8254_intr);
993                         }
994                         apic_8254_intr = apic_irq(0, 0);
995                         setup_8254_mixed_mode();
996                         inthand_add("clk", apic_8254_intr,
997                                     (inthand2_t *)clkintr,
998                                     NULL, &clk_imask, INTR_EXCL | INTR_FAST);
999                         INTREN(1 << apic_8254_intr);
1000                 }
1001                 
1002         }
1003         if (apic_int_type(0, 0) != 3 ||
1004             int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1005             int_to_apicintpin[apic_8254_intr].int_pin != 0) {
1006                 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1007                        int_to_apicintpin[apic_8254_intr].ioapic,
1008                        int_to_apicintpin[apic_8254_intr].int_pin);
1009         } else {
1010                 printf("APIC_IO: "
1011                        "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1012         }
1013 #endif
1014         callout_init(&sysbeepstop_ch);
1015 }
1016
1017 #ifdef APIC_IO
1018 static u_long
1019 read_intr_count(int vec)
1020 {
1021         u_long *up;
1022         up = intr_countp[vec];
1023         if (up)
1024                 return *up;
1025         return 0UL;
1026 }
1027
1028 static void 
1029 setup_8254_mixed_mode()
1030 {
1031         /*
1032          * Allow 8254 timer to INTerrupt 8259:
1033          *  re-initialize master 8259:
1034          *   reset; prog 4 bytes, single ICU, edge triggered
1035          */
1036         outb(IO_ICU1, 0x13);
1037         outb(IO_ICU1 + 1, NRSVIDT);     /* start vector (unused) */
1038         outb(IO_ICU1 + 1, 0x00);        /* ignore slave */
1039         outb(IO_ICU1 + 1, 0x03);        /* auto EOI, 8086 */
1040         outb(IO_ICU1 + 1, 0xfe);        /* unmask INT0 */
1041         
1042         /* program IO APIC for type 3 INT on INT0 */
1043         if (ext_int_setup(0, 0) < 0)
1044                 panic("8254 redirect via APIC pin0 impossible!");
1045 }
1046 #endif
1047
1048 void
1049 setstatclockrate(int newhz)
1050 {
1051         if (newhz == RTC_PROFRATE)
1052                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1053         else
1054                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1055         writertc(RTC_STATUSA, rtc_statusa);
1056 }
1057
1058 #if 0
1059 static unsigned
1060 tsc_get_timecount(struct timecounter *tc)
1061 {
1062         return (rdtsc());
1063 }
1064 #endif
1065
1066 #ifdef KERN_TIMESTAMP
1067 #define KERN_TIMESTAMP_SIZE 16384
1068 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1069 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1070         sizeof(tsc), "LU", "Kernel timestamps");
1071 void  
1072 _TSTMP(u_int32_t x)
1073 {
1074         static int i;
1075
1076         tsc[i] = (u_int32_t)rdtsc();
1077         tsc[i+1] = x;
1078         i = i + 2;
1079         if (i >= KERN_TIMESTAMP_SIZE)
1080                 i = 0;
1081         tsc[i] = 0; /* mark last entry */
1082 }
1083 #endif /* KERN_TIMESTAMP */
1084
1085 /*
1086  *
1087  */
1088
1089 static int
1090 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1091 {
1092     sysclock_t count;
1093     __uint64_t tscval;
1094     char buf[32];
1095
1096     crit_enter();
1097     count = cputimer_count();
1098     if (tsc_present)
1099         tscval = rdtsc();
1100     else
1101         tscval = 0;
1102     crit_exit();
1103     snprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1104     return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1105 }
1106
1107 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1108 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &cputimer_freq, 0, "");
1109 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1110                 0, 0, hw_i8254_timestamp, "A", "");
1111