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