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