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