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