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