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