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