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