]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/tsc.c
Remove the tc_update() function. Any frequency change to the
[FreeBSD/FreeBSD.git] / sys / i386 / i386 / tsc.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$
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 #include "opt_isa.h"
53 #include "opt_mca.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/bus.h>
58 #include <sys/lock.h>
59 #include <sys/mutex.h>
60 #include <sys/proc.h>
61 #include <sys/time.h>
62 #include <sys/timetc.h>
63 #include <sys/kernel.h>
64 #include <sys/sysctl.h>
65 #include <sys/cons.h>
66 #include <sys/power.h>
67
68 #include <machine/clock.h>
69 #ifdef CLK_CALIBRATION_LOOP
70 #endif
71 #include <machine/cputypes.h>
72 #include <machine/frame.h>
73 #include <machine/limits.h>
74 #include <machine/md_var.h>
75 #include <machine/psl.h>
76 #ifdef APIC_IO
77 #include <machine/segments.h>
78 #endif
79 #if defined(SMP) || defined(APIC_IO)
80 #include <machine/smp.h>
81 #endif /* SMP || APIC_IO */
82 #include <machine/specialreg.h>
83
84 #include <i386/isa/icu.h>
85 #include <i386/isa/isa.h>
86 #include <isa/rtc.h>
87 #ifdef DEV_ISA
88 #include <isa/isavar.h>
89 #endif
90 #include <i386/isa/timerreg.h>
91
92 #include <i386/isa/intr_machdep.h>
93
94 #ifdef DEV_MCA
95 #include <i386/isa/mca_machdep.h>
96 #endif
97
98 #ifdef APIC_IO
99 #include <i386/isa/intr_machdep.h>
100 /* The interrupt triggered by the 8254 (timer) chip */
101 int apic_8254_intr;
102 static u_long read_intr_count(int vec);
103 static void setup_8254_mixed_mode(void);
104 #endif
105
106 /*
107  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
108  * can use a simple formula for leap years.
109  */
110 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
111 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
112
113 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
114
115 /*
116  * Time in timer cycles that it takes for microtime() to disable interrupts
117  * and latch the count.  microtime() currently uses "cli; outb ..." so it
118  * normally takes less than 2 timer cycles.  Add a few for cache misses.
119  * Add a few more to allow for latency in bogus calls to microtime() with
120  * interrupts already disabled.
121  */
122 #define TIMER0_LATCH_COUNT      20
123
124 /*
125  * Maximum frequency that we are willing to allow for timer0.  Must be
126  * low enough to guarantee that the timer interrupt handler returns
127  * before the next timer interrupt.
128  */
129 #define TIMER0_MAX_FREQ         20000
130
131 int     adjkerntz;              /* local offset from GMT in seconds */
132 int     clkintr_pending;
133 int     disable_rtc_set;        /* disable resettodr() if != 0 */
134 int     statclock_disable;
135 #ifndef TIMER_FREQ
136 #define TIMER_FREQ   1193182
137 #endif
138 u_int   timer_freq = TIMER_FREQ;
139 int     timer0_max_count;
140 u_int   tsc_freq;
141 int     tsc_is_broken;
142 u_int   tsc_present;
143 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
144 struct mtx clock_lock;
145
146 static  int     beeping = 0;
147 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
148 static  u_int   hardclock_max_count;
149 static  u_int32_t i8254_lastcount;
150 static  u_int32_t i8254_offset;
151 static  int     i8254_ticked;
152 /*
153  * XXX new_function and timer_func should not handle clockframes, but
154  * timer_func currently needs to hold hardclock to handle the
155  * timer0_state == 0 case.  We should use inthand_add()/inthand_remove()
156  * to switch between clkintr() and a slightly different timerintr().
157  */
158 static  void    (*new_function)(struct clockframe *frame);
159 static  u_int   new_rate;
160 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
161 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
162 static  u_int   timer0_prescaler_count;
163
164 /* Values for timerX_state: */
165 #define RELEASED        0
166 #define RELEASE_PENDING 1
167 #define ACQUIRED        2
168 #define ACQUIRE_PENDING 3
169
170 static  u_char  timer0_state;
171 static  u_char  timer2_state;
172 static  void    (*timer_func)(struct clockframe *frame) = hardclock;
173
174 static  unsigned i8254_get_timecount(struct timecounter *tc);
175 static  unsigned tsc_get_timecount(struct timecounter *tc);
176 static  void    set_timer_freq(u_int freq, int intr_freq);
177
178 static struct timecounter tsc_timecounter = {
179         tsc_get_timecount,      /* get_timecount */
180         0,                      /* no poll_pps */
181         ~0u,                    /* counter_mask */
182         0,                      /* frequency */
183          "TSC"                  /* name */
184 };
185
186 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD, 
187         &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
188
189 static struct timecounter i8254_timecounter = {
190         i8254_get_timecount,    /* get_timecount */
191         0,                      /* no poll_pps */
192         ~0u,                    /* counter_mask */
193         0,                      /* frequency */
194         "i8254"                 /* name */
195 };
196
197 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD, 
198         &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
199
200 static void
201 clkintr(struct clockframe frame)
202 {
203
204         if (timecounter->tc_get_timecount == i8254_get_timecount) {
205                 mtx_lock_spin(&clock_lock);
206                 if (i8254_ticked)
207                         i8254_ticked = 0;
208                 else {
209                         i8254_offset += timer0_max_count;
210                         i8254_lastcount = 0;
211                 }
212                 clkintr_pending = 0;
213                 mtx_unlock_spin(&clock_lock);
214         }
215         timer_func(&frame);
216 #ifdef SMP
217         if (timer_func == hardclock)
218                 forward_hardclock();
219 #endif
220         switch (timer0_state) {
221
222         case RELEASED:
223                 break;
224
225         case ACQUIRED:
226                 if ((timer0_prescaler_count += timer0_max_count)
227                     >= hardclock_max_count) {
228                         timer0_prescaler_count -= hardclock_max_count;
229                         hardclock(&frame);
230 #ifdef SMP
231                         forward_hardclock();
232 #endif
233                 }
234                 break;
235
236         case ACQUIRE_PENDING:
237                 mtx_lock_spin(&clock_lock);
238                 i8254_offset = i8254_get_timecount(NULL);
239                 i8254_lastcount = 0;
240                 timer0_max_count = TIMER_DIV(new_rate);
241                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
242                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
243                 outb(TIMER_CNTR0, timer0_max_count >> 8);
244                 mtx_unlock_spin(&clock_lock);
245                 timer_func = new_function;
246                 timer0_state = ACQUIRED;
247                 break;
248
249         case RELEASE_PENDING:
250                 if ((timer0_prescaler_count += timer0_max_count)
251                     >= hardclock_max_count) {
252                         mtx_lock_spin(&clock_lock);
253                         i8254_offset = i8254_get_timecount(NULL);
254                         i8254_lastcount = 0;
255                         timer0_max_count = hardclock_max_count;
256                         outb(TIMER_MODE,
257                              TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
258                         outb(TIMER_CNTR0, timer0_max_count & 0xff);
259                         outb(TIMER_CNTR0, timer0_max_count >> 8);
260                         mtx_unlock_spin(&clock_lock);
261                         timer0_prescaler_count = 0;
262                         timer_func = hardclock;
263                         timer0_state = RELEASED;
264                         hardclock(&frame);
265 #ifdef SMP
266                         forward_hardclock();
267 #endif
268                 }
269                 break;
270         }
271 #ifdef DEV_MCA
272         /* Reset clock interrupt by asserting bit 7 of port 0x61 */
273         if (MCA_system)
274                 outb(0x61, inb(0x61) | 0x80);
275 #endif
276 }
277
278 /*
279  * The acquire and release functions must be called at ipl >= splclock().
280  */
281 int
282 acquire_timer0(int rate, void (*function)(struct clockframe *frame))
283 {
284         static int old_rate;
285
286         if (rate <= 0 || rate > TIMER0_MAX_FREQ)
287                 return (-1);
288         switch (timer0_state) {
289
290         case RELEASED:
291                 timer0_state = ACQUIRE_PENDING;
292                 break;
293
294         case RELEASE_PENDING:
295                 if (rate != old_rate)
296                         return (-1);
297                 /*
298                  * The timer has been released recently, but is being
299                  * re-acquired before the release completed.  In this
300                  * case, we simply reclaim it as if it had not been
301                  * released at all.
302                  */
303                 timer0_state = ACQUIRED;
304                 break;
305
306         default:
307                 return (-1);    /* busy */
308         }
309         new_function = function;
310         old_rate = new_rate = rate;
311         return (0);
312 }
313
314 int
315 acquire_timer2(int mode)
316 {
317
318         if (timer2_state != RELEASED)
319                 return (-1);
320         timer2_state = ACQUIRED;
321
322         /*
323          * This access to the timer registers is as atomic as possible
324          * because it is a single instruction.  We could do better if we
325          * knew the rate.  Use of splclock() limits glitches to 10-100us,
326          * and this is probably good enough for timer2, so we aren't as
327          * careful with it as with timer0.
328          */
329         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
330
331         return (0);
332 }
333
334 int
335 release_timer0()
336 {
337         switch (timer0_state) {
338
339         case ACQUIRED:
340                 timer0_state = RELEASE_PENDING;
341                 break;
342
343         case ACQUIRE_PENDING:
344                 /* Nothing happened yet, release quickly. */
345                 timer0_state = RELEASED;
346                 break;
347
348         default:
349                 return (-1);
350         }
351         return (0);
352 }
353
354 int
355 release_timer2()
356 {
357
358         if (timer2_state != ACQUIRED)
359                 return (-1);
360         timer2_state = RELEASED;
361         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
362         return (0);
363 }
364
365 /*
366  * This routine receives statistical clock interrupts from the RTC.
367  * As explained above, these occur at 128 interrupts per second.
368  * When profiling, we receive interrupts at a rate of 1024 Hz.
369  *
370  * This does not actually add as much overhead as it sounds, because
371  * when the statistical clock is active, the hardclock driver no longer
372  * needs to keep (inaccurate) statistics on its own.  This decouples
373  * statistics gathering from scheduling interrupts.
374  *
375  * The RTC chip requires that we read status register C (RTC_INTR)
376  * to acknowledge an interrupt, before it will generate the next one.
377  * Under high interrupt load, rtcintr() can be indefinitely delayed and
378  * the clock can tick immediately after the read from RTC_INTR.  In this
379  * case, the mc146818A interrupt signal will not drop for long enough
380  * to register with the 8259 PIC.  If an interrupt is missed, the stat
381  * clock will halt, considerably degrading system performance.  This is
382  * why we use 'while' rather than a more straightforward 'if' below.
383  * Stat clock ticks can still be lost, causing minor loss of accuracy
384  * in the statistics, but the stat clock will no longer stop.
385  */
386 static void
387 rtcintr(struct clockframe frame)
388 {
389         while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
390                 statclock(&frame);
391 #ifdef SMP
392                 forward_statclock();
393 #endif
394         }
395 }
396
397 #include "opt_ddb.h"
398 #ifdef DDB
399 #include <ddb/ddb.h>
400
401 DB_SHOW_COMMAND(rtc, rtc)
402 {
403         printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
404                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
405                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
406                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
407 }
408 #endif /* DDB */
409
410 static int
411 getit(void)
412 {
413         int high, low;
414
415         mtx_lock_spin(&clock_lock);
416
417         /* Select timer0 and latch counter value. */
418         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
419
420         low = inb(TIMER_CNTR0);
421         high = inb(TIMER_CNTR0);
422
423         mtx_unlock_spin(&clock_lock);
424         return ((high << 8) | low);
425 }
426
427 /*
428  * Wait "n" microseconds.
429  * Relies on timer 1 counting down from (timer_freq / hz)
430  * Note: timer had better have been programmed before this is first used!
431  */
432 void
433 DELAY(int n)
434 {
435         int delta, prev_tick, tick, ticks_left;
436
437 #ifdef DELAYDEBUG
438         int getit_calls = 1;
439         int n1;
440         static int state = 0;
441
442         if (state == 0) {
443                 state = 1;
444                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
445                         DELAY(n1);
446                 state = 2;
447         }
448         if (state == 1)
449                 printf("DELAY(%d)...", n);
450 #endif
451         /*
452          * Guard against the timer being uninitialized if we are called
453          * early for console i/o.
454          */
455         if (timer0_max_count == 0)
456                 set_timer_freq(timer_freq, hz);
457
458         /*
459          * Read the counter first, so that the rest of the setup overhead is
460          * counted.  Guess the initial overhead is 20 usec (on most systems it
461          * takes about 1.5 usec for each of the i/o's in getit().  The loop
462          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
463          * multiplications and divisions to scale the count take a while).
464          */
465         prev_tick = getit();
466         n -= 0;                 /* XXX actually guess no initial overhead */
467         /*
468          * Calculate (n * (timer_freq / 1e6)) without using floating point
469          * and without any avoidable overflows.
470          */
471         if (n <= 0)
472                 ticks_left = 0;
473         else if (n < 256)
474                 /*
475                  * Use fixed point to avoid a slow division by 1000000.
476                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
477                  * 2^15 is the first power of 2 that gives exact results
478                  * for n between 0 and 256.
479                  */
480                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
481         else
482                 /*
483                  * Don't bother using fixed point, although gcc-2.7.2
484                  * generates particularly poor code for the long long
485                  * division, since even the slow way will complete long
486                  * before the delay is up (unless we're interrupted).
487                  */
488                 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
489                              / 1000000;
490
491         while (ticks_left > 0) {
492                 tick = getit();
493 #ifdef DELAYDEBUG
494                 ++getit_calls;
495 #endif
496                 delta = prev_tick - tick;
497                 prev_tick = tick;
498                 if (delta < 0) {
499                         delta += timer0_max_count;
500                         /*
501                          * Guard against timer0_max_count being wrong.
502                          * This shouldn't happen in normal operation,
503                          * but it may happen if set_timer_freq() is
504                          * traced.
505                          */
506                         if (delta < 0)
507                                 delta = 0;
508                 }
509                 ticks_left -= delta;
510         }
511 #ifdef DELAYDEBUG
512         if (state == 1)
513                 printf(" %d calls to getit() at %d usec each\n",
514                        getit_calls, (n + 5) / getit_calls);
515 #endif
516 }
517
518 static void
519 sysbeepstop(void *chan)
520 {
521         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
522         release_timer2();
523         beeping = 0;
524 }
525
526 int
527 sysbeep(int pitch, int period)
528 {
529         int x = splclock();
530
531         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
532                 if (!beeping) {
533                         /* Something else owns it. */
534                         splx(x);
535                         return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
536                 }
537         mtx_lock_spin(&clock_lock);
538         outb(TIMER_CNTR2, pitch);
539         outb(TIMER_CNTR2, (pitch>>8));
540         mtx_unlock_spin(&clock_lock);
541         if (!beeping) {
542                 /* enable counter2 output to speaker */
543                 outb(IO_PPI, inb(IO_PPI) | 3);
544                 beeping = period;
545                 timeout(sysbeepstop, (void *)NULL, period);
546         }
547         splx(x);
548         return (0);
549 }
550
551 /*
552  * RTC support routines
553  */
554
555 int
556 rtcin(reg)
557         int reg;
558 {
559         int s;
560         u_char val;
561
562         s = splhigh();
563         outb(IO_RTC, reg);
564         inb(0x84);
565         val = inb(IO_RTC + 1);
566         inb(0x84);
567         splx(s);
568         return (val);
569 }
570
571 static __inline void
572 writertc(u_char reg, u_char val)
573 {
574         int s;
575
576         s = splhigh();
577         inb(0x84);
578         outb(IO_RTC, reg);
579         inb(0x84);
580         outb(IO_RTC + 1, val);
581         inb(0x84);              /* XXX work around wrong order in rtcin() */
582         splx(s);
583 }
584
585 static __inline int
586 readrtc(int port)
587 {
588         return(bcd2bin(rtcin(port)));
589 }
590
591 static u_int
592 calibrate_clocks(void)
593 {
594         u_int64_t old_tsc;
595         u_int count, prev_count, tot_count;
596         int sec, start_sec, timeout;
597
598         if (bootverbose)
599                 printf("Calibrating clock(s) ... ");
600         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
601                 goto fail;
602         timeout = 100000000;
603
604         /* Read the mc146818A seconds counter. */
605         for (;;) {
606                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
607                         sec = rtcin(RTC_SEC);
608                         break;
609                 }
610                 if (--timeout == 0)
611                         goto fail;
612         }
613
614         /* Wait for the mC146818A seconds counter to change. */
615         start_sec = sec;
616         for (;;) {
617                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
618                         sec = rtcin(RTC_SEC);
619                         if (sec != start_sec)
620                                 break;
621                 }
622                 if (--timeout == 0)
623                         goto fail;
624         }
625
626         /* Start keeping track of the i8254 counter. */
627         prev_count = getit();
628         if (prev_count == 0 || prev_count > timer0_max_count)
629                 goto fail;
630         tot_count = 0;
631
632         if (tsc_present) 
633                 old_tsc = rdtsc();
634         else
635                 old_tsc = 0;            /* shut up gcc */
636
637         /*
638          * Wait for the mc146818A seconds counter to change.  Read the i8254
639          * counter for each iteration since this is convenient and only
640          * costs a few usec of inaccuracy. The timing of the final reads
641          * of the counters almost matches the timing of the initial reads,
642          * so the main cause of inaccuracy is the varying latency from 
643          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
644          * rtcin(RTC_SEC) that returns a changed seconds count.  The
645          * maximum inaccuracy from this cause is < 10 usec on 486's.
646          */
647         start_sec = sec;
648         for (;;) {
649                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
650                         sec = rtcin(RTC_SEC);
651                 count = getit();
652                 if (count == 0 || count > timer0_max_count)
653                         goto fail;
654                 if (count > prev_count)
655                         tot_count += prev_count - (count - timer0_max_count);
656                 else
657                         tot_count += prev_count - count;
658                 prev_count = count;
659                 if (sec != start_sec)
660                         break;
661                 if (--timeout == 0)
662                         goto fail;
663         }
664
665         /*
666          * Read the cpu cycle counter.  The timing considerations are
667          * similar to those for the i8254 clock.
668          */
669         if (tsc_present) 
670                 tsc_freq = rdtsc() - old_tsc;
671
672         if (bootverbose) {
673                 if (tsc_present)
674                         printf("TSC clock: %u Hz, ", tsc_freq);
675                 printf("i8254 clock: %u Hz\n", tot_count);
676         }
677         return (tot_count);
678
679 fail:
680         if (bootverbose)
681                 printf("failed, using default i8254 clock of %u Hz\n",
682                        timer_freq);
683         return (timer_freq);
684 }
685
686 static void
687 set_timer_freq(u_int freq, int intr_freq)
688 {
689         int new_timer0_max_count;
690
691         mtx_lock_spin(&clock_lock);
692         timer_freq = freq;
693         new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
694         if (new_timer0_max_count != timer0_max_count) {
695                 timer0_max_count = new_timer0_max_count;
696                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
697                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
698                 outb(TIMER_CNTR0, timer0_max_count >> 8);
699         }
700         mtx_unlock_spin(&clock_lock);
701 }
702
703 /*
704  * i8254_restore is called from apm_default_resume() to reload
705  * the countdown register.
706  * this should not be necessary but there are broken laptops that
707  * do not restore the countdown register on resume.
708  * when it happnes, it messes up the hardclock interval and system clock,
709  * which leads to the infamous "calcru: negative time" problem.
710  */
711 static void
712 i8254_restore(void)
713 {
714
715         mtx_lock_spin(&clock_lock);
716         outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
717         outb(TIMER_CNTR0, timer0_max_count & 0xff);
718         outb(TIMER_CNTR0, timer0_max_count >> 8);
719         mtx_unlock_spin(&clock_lock);
720 }
721
722 static void
723 rtc_restore(void)
724 {
725
726         /* Reenable RTC updates and interrupts. */
727         /* XXX locking is needed for RTC access? */
728         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
729         writertc(RTC_STATUSB, rtc_statusb);
730 }
731
732 /*
733  * Restore all the timers atomically.
734  */
735 void
736 timer_restore(void)
737 {
738
739         i8254_restore();                /* restore timer_freq and hz */
740         rtc_restore();                  /* reenable RTC interrupts */
741 }
742
743 /*
744  * Initialize 8254 timer 0 early so that it can be used in DELAY().
745  * XXX initialization of other timers is unintentionally left blank.
746  */
747 void
748 startrtclock()
749 {
750         u_int delta, freq;
751
752         if (cpu_feature & CPUID_TSC)
753                 tsc_present = 1;
754         else
755                 tsc_present = 0;
756
757         writertc(RTC_STATUSA, rtc_statusa);
758         writertc(RTC_STATUSB, RTCSB_24HR);
759
760         set_timer_freq(timer_freq, hz);
761         freq = calibrate_clocks();
762 #ifdef CLK_CALIBRATION_LOOP
763         if (bootverbose) {
764                 printf(
765                 "Press a key on the console to abort clock calibration\n");
766                 while (cncheckc() == -1)
767                         calibrate_clocks();
768         }
769 #endif
770
771         /*
772          * Use the calibrated i8254 frequency if it seems reasonable.
773          * Otherwise use the default, and don't use the calibrated i586
774          * frequency.
775          */
776         delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
777         if (delta < timer_freq / 100) {
778 #ifndef CLK_USE_I8254_CALIBRATION
779                 if (bootverbose)
780                         printf(
781 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
782                 freq = timer_freq;
783 #endif
784                 timer_freq = freq;
785         } else {
786                 if (bootverbose)
787                         printf(
788                     "%d Hz differs from default of %d Hz by more than 1%%\n",
789                                freq, timer_freq);
790                 tsc_freq = 0;
791         }
792
793         set_timer_freq(timer_freq, hz);
794         i8254_timecounter.tc_frequency = timer_freq;
795         tc_init(&i8254_timecounter);
796
797 #ifndef CLK_USE_TSC_CALIBRATION
798         if (tsc_freq != 0) {
799                 if (bootverbose)
800                         printf(
801 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
802                 tsc_freq = 0;
803         }
804 #endif
805         if (tsc_present && tsc_freq == 0) {
806                 /*
807                  * Calibration of the i586 clock relative to the mc146818A
808                  * clock failed.  Do a less accurate calibration relative
809                  * to the i8254 clock.
810                  */
811                 u_int64_t old_tsc = rdtsc();
812
813                 DELAY(1000000);
814                 tsc_freq = rdtsc() - old_tsc;
815 #ifdef CLK_USE_TSC_CALIBRATION
816                 if (bootverbose)
817                         printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
818 #endif
819         }
820
821 #if !defined(SMP)
822         /*
823          * We can not use the TSC in SMP mode, until we figure out a
824          * cheap (impossible), reliable and precise (yeah right!)  way
825          * to synchronize the TSCs of all the CPUs.
826          * Curse Intel for leaving the counter out of the I/O APIC.
827          */
828
829         /*
830          * We can not use the TSC if we support APM. Precise timekeeping
831          * on an APM'ed machine is at best a fools pursuit, since 
832          * any and all of the time spent in various SMM code can't 
833          * be reliably accounted for.  Reading the RTC is your only
834          * source of reliable time info.  The i8254 looses too of course
835          * but we need to have some kind of time...
836          * We don't know at this point whether APM is going to be used
837          * or not, nor when it might be activated.  Play it safe.
838          */
839         if (power_pm_get_type() == POWER_PM_TYPE_APM) {
840                 if (bootverbose)
841                         printf("TSC initialization skipped: APM enabled.\n");
842                 return;
843         }
844
845         if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
846                 tsc_timecounter.tc_frequency = tsc_freq;
847                 tc_init(&tsc_timecounter);
848         }
849
850 #endif /* !defined(SMP) */
851 }
852
853 /*
854  * Initialize the time of day register, based on the time base which is, e.g.
855  * from a filesystem.
856  */
857 void
858 inittodr(time_t base)
859 {
860         unsigned long   sec, days;
861         int             year, month;
862         int             y, m, s;
863         struct timespec ts;
864
865         if (base) {
866                 s = splclock();
867                 ts.tv_sec = base;
868                 ts.tv_nsec = 0;
869                 tc_setclock(&ts);
870                 splx(s);
871         }
872
873         /* Look if we have a RTC present and the time is valid */
874         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
875                 goto wrong_time;
876
877         /* wait for time update to complete */
878         /* If RTCSA_TUP is zero, we have at least 244us before next update */
879         s = splhigh();
880         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
881                 splx(s);
882                 s = splhigh();
883         }
884
885         days = 0;
886 #ifdef USE_RTC_CENTURY
887         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
888 #else
889         year = readrtc(RTC_YEAR) + 1900;
890         if (year < 1970)
891                 year += 100;
892 #endif
893         if (year < 1970) {
894                 splx(s);
895                 goto wrong_time;
896         }
897         month = readrtc(RTC_MONTH);
898         for (m = 1; m < month; m++)
899                 days += daysinmonth[m-1];
900         if ((month > 2) && LEAPYEAR(year))
901                 days ++;
902         days += readrtc(RTC_DAY) - 1;
903         for (y = 1970; y < year; y++)
904                 days += DAYSPERYEAR + LEAPYEAR(y);
905         sec = ((( days * 24 +
906                   readrtc(RTC_HRS)) * 60 +
907                   readrtc(RTC_MIN)) * 60 +
908                   readrtc(RTC_SEC));
909         /* sec now contains the number of seconds, since Jan 1 1970,
910            in the local time zone */
911
912         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
913
914         y = time_second - sec;
915         if (y <= -2 || y >= 2) {
916                 /* badly off, adjust it */
917                 ts.tv_sec = sec;
918                 ts.tv_nsec = 0;
919                 tc_setclock(&ts);
920         }
921         splx(s);
922         return;
923
924 wrong_time:
925         printf("Invalid time in real time clock.\n");
926         printf("Check and reset the date immediately!\n");
927 }
928
929 /*
930  * Write system time back to RTC
931  */
932 void
933 resettodr()
934 {
935         unsigned long   tm;
936         int             y, m, s;
937
938         if (disable_rtc_set)
939                 return;
940
941         s = splclock();
942         tm = time_second;
943         splx(s);
944
945         /* Disable RTC updates and interrupts. */
946         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
947
948         /* Calculate local time to put in RTC */
949
950         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
951
952         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
953         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
954         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
955
956         /* We have now the days since 01-01-1970 in tm */
957         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
958         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
959              tm >= m;
960              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
961              tm -= m;
962
963         /* Now we have the years in y and the day-of-the-year in tm */
964         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
965 #ifdef USE_RTC_CENTURY
966         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
967 #endif
968         for (m = 0; ; m++) {
969                 int ml;
970
971                 ml = daysinmonth[m];
972                 if (m == 1 && LEAPYEAR(y))
973                         ml++;
974                 if (tm < ml)
975                         break;
976                 tm -= ml;
977         }
978
979         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
980         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
981
982         /* Reenable RTC updates and interrupts. */
983         writertc(RTC_STATUSB, rtc_statusb);
984 }
985
986
987 /*
988  * Start both clocks running.
989  */
990 void
991 cpu_initclocks()
992 {
993         int diag;
994 #ifdef APIC_IO
995         int apic_8254_trial;
996         void *clkdesc;
997 #endif /* APIC_IO */
998         register_t crit;
999
1000         if (statclock_disable) {
1001                 /*
1002                  * The stat interrupt mask is different without the
1003                  * statistics clock.  Also, don't set the interrupt
1004                  * flag which would normally cause the RTC to generate
1005                  * interrupts.
1006                  */
1007                 rtc_statusb = RTCSB_24HR;
1008         } else {
1009                 /* Setting stathz to nonzero early helps avoid races. */
1010                 stathz = RTC_NOPROFRATE;
1011                 profhz = RTC_PROFRATE;
1012         }
1013
1014         /* Finish initializing 8253 timer 0. */
1015 #ifdef APIC_IO
1016
1017         apic_8254_intr = isa_apic_irq(0);
1018         apic_8254_trial = 0;
1019         if (apic_8254_intr >= 0 ) {
1020                 if (apic_int_type(0, 0) == 3)
1021                         apic_8254_trial = 1;
1022         } else {
1023                 /* look for ExtInt on pin 0 */
1024                 if (apic_int_type(0, 0) == 3) {
1025                         apic_8254_intr = apic_irq(0, 0);
1026                         setup_8254_mixed_mode();
1027                 } else 
1028                         panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1029         }
1030
1031         inthand_add("clk", apic_8254_intr, (driver_intr_t *)clkintr, NULL,
1032             INTR_TYPE_CLK | INTR_FAST, &clkdesc);
1033         crit = intr_disable();
1034         mtx_lock_spin(&icu_lock);
1035         INTREN(1 << apic_8254_intr);
1036         mtx_unlock_spin(&icu_lock);
1037         intr_restore(crit);
1038
1039 #else /* APIC_IO */
1040
1041         /*
1042          * XXX Check the priority of this interrupt handler.  I
1043          * couldn't find anything suitable in the BSD/OS code (grog,
1044          * 19 July 2000).
1045          */
1046         inthand_add("clk", 0, (driver_intr_t *)clkintr, NULL,
1047             INTR_TYPE_CLK | INTR_FAST, NULL);
1048         crit = intr_disable();
1049         mtx_lock_spin(&icu_lock);
1050         INTREN(IRQ0);
1051         mtx_unlock_spin(&icu_lock);
1052         intr_restore(crit);
1053
1054 #endif /* APIC_IO */
1055
1056         /* Initialize RTC. */
1057         writertc(RTC_STATUSA, rtc_statusa);
1058         writertc(RTC_STATUSB, RTCSB_24HR);
1059
1060         /* Don't bother enabling the statistics clock. */
1061         if (statclock_disable)
1062                 return;
1063         diag = rtcin(RTC_DIAG);
1064         if (diag != 0)
1065                 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1066
1067 #ifdef APIC_IO
1068         if (isa_apic_irq(8) != 8)
1069                 panic("APIC RTC != 8");
1070 #endif /* APIC_IO */
1071
1072         inthand_add("rtc", 8, (driver_intr_t *)rtcintr, NULL,
1073             INTR_TYPE_CLK | INTR_FAST, NULL);
1074
1075         crit = intr_disable();
1076         mtx_lock_spin(&icu_lock);
1077 #ifdef APIC_IO
1078         INTREN(APIC_IRQ8);
1079 #else
1080         INTREN(IRQ8);
1081 #endif /* APIC_IO */
1082         mtx_unlock_spin(&icu_lock);
1083         intr_restore(crit);
1084
1085         writertc(RTC_STATUSB, rtc_statusb);
1086
1087 #ifdef APIC_IO
1088         if (apic_8254_trial) {
1089
1090                 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1091                 while (read_intr_count(8) < 6)
1092                         ;       /* nothing */
1093                 if (read_intr_count(apic_8254_intr) < 3) {
1094                         /* 
1095                          * The MP table is broken.
1096                          * The 8254 was not connected to the specified pin
1097                          * on the IO APIC.
1098                          * Workaround: Limited variant of mixed mode.
1099                          */
1100
1101                         crit = intr_disable();
1102                         mtx_lock_spin(&icu_lock);
1103                         INTRDIS(1 << apic_8254_intr);
1104                         mtx_unlock_spin(&icu_lock);
1105                         intr_restore(crit);
1106                         inthand_remove(clkdesc);
1107                         printf("APIC_IO: Broken MP table detected: "
1108                                "8254 is not connected to "
1109                                "IOAPIC #%d intpin %d\n",
1110                                int_to_apicintpin[apic_8254_intr].ioapic,
1111                                int_to_apicintpin[apic_8254_intr].int_pin);
1112                         /* 
1113                          * Revoke current ISA IRQ 0 assignment and 
1114                          * configure a fallback interrupt routing from
1115                          * the 8254 Timer via the 8259 PIC to the
1116                          * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1117                          * We reuse the low level interrupt handler number.
1118                          */
1119                         if (apic_irq(0, 0) < 0) {
1120                                 revoke_apic_irq(apic_8254_intr);
1121                                 assign_apic_irq(0, 0, apic_8254_intr);
1122                         }
1123                         apic_8254_intr = apic_irq(0, 0);
1124                         setup_8254_mixed_mode();
1125                         inthand_add("clk", apic_8254_intr,
1126                                     (driver_intr_t *)clkintr, NULL,
1127                                     INTR_TYPE_CLK | INTR_FAST, NULL);
1128                         crit = intr_disable();
1129                         mtx_lock_spin(&icu_lock);
1130                         INTREN(1 << apic_8254_intr);
1131                         mtx_unlock_spin(&icu_lock);
1132                         intr_restore(crit);
1133                 }
1134                 
1135         }
1136         if (apic_int_type(0, 0) != 3 ||
1137             int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1138             int_to_apicintpin[apic_8254_intr].int_pin != 0)
1139                 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1140                        int_to_apicintpin[apic_8254_intr].ioapic,
1141                        int_to_apicintpin[apic_8254_intr].int_pin);
1142         else
1143                 printf("APIC_IO: "
1144                        "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1145 #endif
1146         
1147 }
1148
1149 #ifdef APIC_IO
1150 static u_long
1151 read_intr_count(int vec)
1152 {
1153         u_long *up;
1154         up = intr_countp[vec];
1155         if (up)
1156                 return *up;
1157         return 0UL;
1158 }
1159
1160 static void 
1161 setup_8254_mixed_mode()
1162 {
1163         /*
1164          * Allow 8254 timer to INTerrupt 8259:
1165          *  re-initialize master 8259:
1166          *   reset; prog 4 bytes, single ICU, edge triggered
1167          */
1168         outb(IO_ICU1, 0x13);
1169         outb(IO_ICU1 + 1, NRSVIDT);     /* start vector (unused) */
1170         outb(IO_ICU1 + 1, 0x00);        /* ignore slave */
1171         outb(IO_ICU1 + 1, 0x03);        /* auto EOI, 8086 */
1172         outb(IO_ICU1 + 1, 0xfe);        /* unmask INT0 */
1173         
1174         /* program IO APIC for type 3 INT on INT0 */
1175         if (ext_int_setup(0, 0) < 0)
1176                 panic("8254 redirect via APIC pin0 impossible!");
1177 }
1178 #endif
1179
1180 void
1181 setstatclockrate(int newhz)
1182 {
1183         if (newhz == RTC_PROFRATE)
1184                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1185         else
1186                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1187         writertc(RTC_STATUSA, rtc_statusa);
1188 }
1189
1190 static int
1191 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1192 {
1193         int error;
1194         u_int freq;
1195
1196         /*
1197          * Use `i8254' instead of `timer' in external names because `timer'
1198          * is is too generic.  Should use it everywhere.
1199          */
1200         freq = timer_freq;
1201         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1202         if (error == 0 && req->newptr != NULL) {
1203                 if (timer0_state != RELEASED)
1204                         return (EBUSY); /* too much trouble to handle */
1205                 set_timer_freq(freq, hz);
1206                 i8254_timecounter.tc_frequency = freq;
1207         }
1208         return (error);
1209 }
1210
1211 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1212     0, sizeof(u_int), sysctl_machdep_i8254_freq, "I", "");
1213
1214 static int
1215 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1216 {
1217         int error;
1218         u_int freq;
1219
1220         if (tsc_timecounter.tc_frequency == 0)
1221                 return (EOPNOTSUPP);
1222         freq = tsc_freq;
1223         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1224         if (error == 0 && req->newptr != NULL) {
1225                 tsc_freq = freq;
1226                 tsc_timecounter.tc_frequency = tsc_freq;
1227         }
1228         return (error);
1229 }
1230
1231 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1232     0, sizeof(u_int), sysctl_machdep_tsc_freq, "I", "");
1233
1234 static unsigned
1235 i8254_get_timecount(struct timecounter *tc)
1236 {
1237         u_int count;
1238         u_int high, low;
1239         u_int eflags;
1240
1241         eflags = read_eflags();
1242         mtx_lock_spin(&clock_lock);
1243
1244         /* Select timer0 and latch counter value. */
1245         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1246
1247         low = inb(TIMER_CNTR0);
1248         high = inb(TIMER_CNTR0);
1249         count = timer0_max_count - ((high << 8) | low);
1250         if (count < i8254_lastcount ||
1251             (!i8254_ticked && (clkintr_pending ||
1252             ((count < 20 || (!(eflags & PSL_I) && count < timer0_max_count / 2u)) &&
1253 #ifdef APIC_IO
1254 #define lapic_irr1      ((volatile u_int *)&lapic)[0x210 / 4]   /* XXX XXX */
1255             /* XXX this assumes that apic_8254_intr is < 24. */
1256             (lapic_irr1 & (1 << apic_8254_intr))))
1257 #else
1258             (inb(IO_ICU1) & 1)))
1259 #endif
1260             )) {
1261                 i8254_ticked = 1;
1262                 i8254_offset += timer0_max_count;
1263         }
1264         i8254_lastcount = count;
1265         count += i8254_offset;
1266         mtx_unlock_spin(&clock_lock);
1267         return (count);
1268 }
1269
1270 static unsigned
1271 tsc_get_timecount(struct timecounter *tc)
1272 {
1273         return (rdtsc());
1274 }
1275
1276 #ifdef DEV_ISA
1277 /*
1278  * Attach to the ISA PnP descriptors for the timer and realtime clock.
1279  */
1280 static struct isa_pnp_id attimer_ids[] = {
1281         { 0x0001d041 /* PNP0100 */, "AT timer" },
1282         { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
1283         { 0 }
1284 };
1285
1286 static int
1287 attimer_probe(device_t dev)
1288 {
1289         int result;
1290         
1291         if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
1292                 device_quiet(dev);
1293         return(result);
1294 }
1295
1296 static int
1297 attimer_attach(device_t dev)
1298 {
1299         return(0);
1300 }
1301
1302 static device_method_t attimer_methods[] = {
1303         /* Device interface */
1304         DEVMETHOD(device_probe,         attimer_probe),
1305         DEVMETHOD(device_attach,        attimer_attach),
1306         DEVMETHOD(device_detach,        bus_generic_detach),
1307         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
1308         DEVMETHOD(device_suspend,       bus_generic_suspend),   /* XXX stop statclock? */
1309         DEVMETHOD(device_resume,        bus_generic_resume),    /* XXX restart statclock? */
1310         { 0, 0 }
1311 };
1312
1313 static driver_t attimer_driver = {
1314         "attimer",
1315         attimer_methods,
1316         1,              /* no softc */
1317 };
1318
1319 static devclass_t attimer_devclass;
1320
1321 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
1322 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
1323 #endif /* DEV_ISA */