]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - sys/amd64/isa/clock.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / sys / amd64 / isa / clock.c
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * William Jolitz and Don Ahn.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)clock.c       7.2 (Berkeley) 5/12/91
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 /*
39  * Routines to handle clock hardware.
40  */
41
42 #include "opt_clock.h"
43 #include "opt_isa.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bus.h>
48 #include <sys/lock.h>
49 #include <sys/kdb.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/timetc.h>
53 #include <sys/kernel.h>
54 #include <sys/module.h>
55 #include <sys/sched.h>
56 #include <sys/smp.h>
57 #include <sys/sysctl.h>
58
59 #include <machine/clock.h>
60 #include <machine/cpu.h>
61 #include <machine/intr_machdep.h>
62 #include <machine/md_var.h>
63 #include <machine/apicvar.h>
64 #include <machine/ppireg.h>
65 #include <machine/timerreg.h>
66 #include <machine/smp.h>
67
68 #include <isa/rtc.h>
69 #ifdef DEV_ISA
70 #include <isa/isareg.h>
71 #include <isa/isavar.h>
72 #endif
73
74 #define TIMER_DIV(x) ((i8254_freq + (x) / 2) / (x))
75
76 int     clkintr_pending;
77 static int pscnt = 1;
78 static int psdiv = 1;
79 #ifndef TIMER_FREQ
80 #define TIMER_FREQ   1193182
81 #endif
82 u_int   i8254_freq = TIMER_FREQ;
83 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
84 int     i8254_max_count;
85 static int i8254_real_max_count;
86
87 struct mtx clock_lock;
88 static  struct intsrc *i8254_intsrc;
89 static  u_int32_t i8254_lastcount;
90 static  u_int32_t i8254_offset;
91 static  int     (*i8254_pending)(struct intsrc *);
92 static  int     i8254_ticked;
93 static  int     using_atrtc_timer;
94 static  int     using_lapic_timer;
95
96 /* Values for timerX_state: */
97 #define RELEASED        0
98 #define RELEASE_PENDING 1
99 #define ACQUIRED        2
100 #define ACQUIRE_PENDING 3
101
102 static  u_char  timer2_state;
103
104 static  unsigned i8254_get_timecount(struct timecounter *tc);
105 static  unsigned i8254_simple_get_timecount(struct timecounter *tc);
106 static  void    set_i8254_freq(u_int freq, int intr_freq);
107
108 static struct timecounter i8254_timecounter = {
109         i8254_get_timecount,    /* get_timecount */
110         0,                      /* no poll_pps */
111         ~0u,                    /* counter_mask */
112         0,                      /* frequency */
113         "i8254",                /* name */
114         0                       /* quality */
115 };
116
117 int
118 hardclockintr(struct trapframe *frame)
119 {
120
121         if (PCPU_GET(cpuid) == 0)
122                 hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
123         else
124                 hardclock_cpu(TRAPF_USERMODE(frame));
125         return (FILTER_HANDLED);
126 }
127
128 int
129 statclockintr(struct trapframe *frame)
130 {
131
132         profclockintr(frame);
133         statclock(TRAPF_USERMODE(frame));
134         return (FILTER_HANDLED);
135 }
136
137 int
138 profclockintr(struct trapframe *frame)
139 {
140
141         if (!using_atrtc_timer)
142                 hardclockintr(frame);
143         if (profprocs != 0)
144                 profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
145         return (FILTER_HANDLED);
146 }
147
148 static int
149 clkintr(struct trapframe *frame)
150 {
151
152         if (timecounter->tc_get_timecount == i8254_get_timecount) {
153                 mtx_lock_spin(&clock_lock);
154                 if (i8254_ticked)
155                         i8254_ticked = 0;
156                 else {
157                         i8254_offset += i8254_max_count;
158                         i8254_lastcount = 0;
159                 }
160                 clkintr_pending = 0;
161                 mtx_unlock_spin(&clock_lock);
162         }
163         KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
164
165         if (using_atrtc_timer) {
166 #ifdef SMP
167                 if (smp_started)
168                         ipi_all_but_self(IPI_HARDCLOCK);
169 #endif
170                 hardclockintr(frame);
171         } else {
172                 if (--pscnt <= 0) {
173                         pscnt = psratio;
174 #ifdef SMP
175                         if (smp_started)
176                                 ipi_all_but_self(IPI_STATCLOCK);
177 #endif
178                         statclockintr(frame);
179                 } else {
180 #ifdef SMP
181                         if (smp_started)
182                                 ipi_all_but_self(IPI_PROFCLOCK);
183 #endif
184                         profclockintr(frame);
185                 }
186         }
187
188         return (FILTER_HANDLED);
189 }
190
191 int
192 timer_spkr_acquire(void)
193 {
194         int mode;
195
196         mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
197
198         if (timer2_state != RELEASED)
199                 return (-1);
200         timer2_state = ACQUIRED;
201
202         /*
203          * This access to the timer registers is as atomic as possible
204          * because it is a single instruction.  We could do better if we
205          * knew the rate.  Use of splclock() limits glitches to 10-100us,
206          * and this is probably good enough for timer2, so we aren't as
207          * careful with it as with timer0.
208          */
209         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
210         ppi_spkr_on();          /* enable counter2 output to speaker */
211         return (0);
212 }
213
214 int
215 timer_spkr_release(void)
216 {
217
218         if (timer2_state != ACQUIRED)
219                 return (-1);
220         timer2_state = RELEASED;
221         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
222         ppi_spkr_off();         /* disable counter2 output to speaker */
223         return (0);
224 }
225
226 void
227 timer_spkr_setfreq(int freq)
228 {
229
230         freq = i8254_freq / freq;
231         mtx_lock_spin(&clock_lock);
232         outb(TIMER_CNTR2, freq & 0xff);
233         outb(TIMER_CNTR2, freq >> 8);
234         mtx_unlock_spin(&clock_lock);
235 }
236
237 /*
238  * This routine receives statistical clock interrupts from the RTC.
239  * As explained above, these occur at 128 interrupts per second.
240  * When profiling, we receive interrupts at a rate of 1024 Hz.
241  *
242  * This does not actually add as much overhead as it sounds, because
243  * when the statistical clock is active, the hardclock driver no longer
244  * needs to keep (inaccurate) statistics on its own.  This decouples
245  * statistics gathering from scheduling interrupts.
246  *
247  * The RTC chip requires that we read status register C (RTC_INTR)
248  * to acknowledge an interrupt, before it will generate the next one.
249  * Under high interrupt load, rtcintr() can be indefinitely delayed and
250  * the clock can tick immediately after the read from RTC_INTR.  In this
251  * case, the mc146818A interrupt signal will not drop for long enough
252  * to register with the 8259 PIC.  If an interrupt is missed, the stat
253  * clock will halt, considerably degrading system performance.  This is
254  * why we use 'while' rather than a more straightforward 'if' below.
255  * Stat clock ticks can still be lost, causing minor loss of accuracy
256  * in the statistics, but the stat clock will no longer stop.
257  */
258 static int
259 rtcintr(struct trapframe *frame)
260 {
261         int flag = 0;
262
263         while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
264                 flag = 1;
265                 if (--pscnt <= 0) {
266                         pscnt = psdiv;
267 #ifdef SMP
268                         if (smp_started)
269                                 ipi_all_but_self(IPI_STATCLOCK);
270 #endif
271                         statclockintr(frame);
272                 } else {
273 #ifdef SMP
274                         if (smp_started)
275                                 ipi_all_but_self(IPI_PROFCLOCK);
276 #endif
277                         profclockintr(frame);
278                 }
279         }
280         return(flag ? FILTER_HANDLED : FILTER_STRAY);
281 }
282
283 static int
284 getit(void)
285 {
286         int high, low;
287
288         mtx_lock_spin(&clock_lock);
289
290         /* Select timer0 and latch counter value. */
291         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
292
293         low = inb(TIMER_CNTR0);
294         high = inb(TIMER_CNTR0);
295
296         mtx_unlock_spin(&clock_lock);
297         return ((high << 8) | low);
298 }
299
300 /*
301  * Wait "n" microseconds.
302  * Relies on timer 1 counting down from (i8254_freq / hz)
303  * Note: timer had better have been programmed before this is first used!
304  */
305 void
306 DELAY(int n)
307 {
308         int delta, prev_tick, tick, ticks_left;
309
310 #ifdef DELAYDEBUG
311         int getit_calls = 1;
312         int n1;
313         static int state = 0;
314 #endif
315
316         if (tsc_freq != 0 && !tsc_is_broken) {
317                 uint64_t start, end, now;
318
319                 sched_pin();
320                 start = rdtsc();
321                 end = start + (tsc_freq * n) / 1000000;
322                 do {
323                         cpu_spinwait();
324                         now = rdtsc();
325                 } while (now < end || (now > start && end < start));
326                 sched_unpin();
327                 return;
328         }
329 #ifdef DELAYDEBUG
330         if (state == 0) {
331                 state = 1;
332                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
333                         DELAY(n1);
334                 state = 2;
335         }
336         if (state == 1)
337                 printf("DELAY(%d)...", n);
338 #endif
339         /*
340          * Read the counter first, so that the rest of the setup overhead is
341          * counted.  Guess the initial overhead is 20 usec (on most systems it
342          * takes about 1.5 usec for each of the i/o's in getit().  The loop
343          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
344          * multiplications and divisions to scale the count take a while).
345          *
346          * However, if ddb is active then use a fake counter since reading
347          * the i8254 counter involves acquiring a lock.  ddb must not do
348          * locking for many reasons, but it calls here for at least atkbd
349          * input.
350          */
351 #ifdef KDB
352         if (kdb_active)
353                 prev_tick = 1;
354         else
355 #endif
356                 prev_tick = getit();
357         n -= 0;                 /* XXX actually guess no initial overhead */
358         /*
359          * Calculate (n * (i8254_freq / 1e6)) without using floating point
360          * and without any avoidable overflows.
361          */
362         if (n <= 0)
363                 ticks_left = 0;
364         else if (n < 256)
365                 /*
366                  * Use fixed point to avoid a slow division by 1000000.
367                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
368                  * 2^15 is the first power of 2 that gives exact results
369                  * for n between 0 and 256.
370                  */
371                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
372         else
373                 /*
374                  * Don't bother using fixed point, although gcc-2.7.2
375                  * generates particularly poor code for the long long
376                  * division, since even the slow way will complete long
377                  * before the delay is up (unless we're interrupted).
378                  */
379                 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
380                              / 1000000;
381
382         while (ticks_left > 0) {
383 #ifdef KDB
384                 if (kdb_active) {
385                         inb(0x84);
386                         tick = prev_tick - 1;
387                         if (tick <= 0)
388                                 tick = i8254_max_count;
389                 } else
390 #endif
391                         tick = getit();
392 #ifdef DELAYDEBUG
393                 ++getit_calls;
394 #endif
395                 delta = prev_tick - tick;
396                 prev_tick = tick;
397                 if (delta < 0) {
398                         delta += i8254_max_count;
399                         /*
400                          * Guard against i8254_max_count being wrong.
401                          * This shouldn't happen in normal operation,
402                          * but it may happen if set_i8254_freq() is
403                          * traced.
404                          */
405                         if (delta < 0)
406                                 delta = 0;
407                 }
408                 ticks_left -= delta;
409         }
410 #ifdef DELAYDEBUG
411         if (state == 1)
412                 printf(" %d calls to getit() at %d usec each\n",
413                        getit_calls, (n + 5) / getit_calls);
414 #endif
415 }
416
417 static void
418 set_i8254_freq(u_int freq, int intr_freq)
419 {
420         int new_i8254_real_max_count;
421
422         i8254_timecounter.tc_frequency = freq;
423         mtx_lock_spin(&clock_lock);
424         i8254_freq = freq;
425         if (using_lapic_timer)
426                 new_i8254_real_max_count = 0x10000;
427         else
428                 new_i8254_real_max_count = TIMER_DIV(intr_freq);
429         if (new_i8254_real_max_count != i8254_real_max_count) {
430                 i8254_real_max_count = new_i8254_real_max_count;
431                 if (i8254_real_max_count == 0x10000)
432                         i8254_max_count = 0xffff;
433                 else
434                         i8254_max_count = i8254_real_max_count;
435                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
436                 outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
437                 outb(TIMER_CNTR0, i8254_real_max_count >> 8);
438         }
439         mtx_unlock_spin(&clock_lock);
440 }
441
442 static void
443 i8254_restore(void)
444 {
445
446         mtx_lock_spin(&clock_lock);
447         outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
448         outb(TIMER_CNTR0, i8254_real_max_count & 0xff);
449         outb(TIMER_CNTR0, i8254_real_max_count >> 8);
450         mtx_unlock_spin(&clock_lock);
451 }
452
453 /* This is separate from startrtclock() so that it can be called early. */
454 void
455 i8254_init(void)
456 {
457
458         mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
459         set_i8254_freq(i8254_freq, hz);
460 }
461
462 void
463 startrtclock()
464 {
465
466         atrtc_start();
467
468         set_i8254_freq(i8254_freq, hz);
469         tc_init(&i8254_timecounter);
470
471         init_TSC();
472 }
473
474 /*
475  * Start both clocks running.
476  */
477 void
478 cpu_initclocks()
479 {
480
481         using_lapic_timer = lapic_setup_clock();
482         /*
483          * If we aren't using the local APIC timer to drive the kernel
484          * clocks, setup the interrupt handler for the 8254 timer 0 so
485          * that it can drive hardclock().  Otherwise, change the 8254
486          * timecounter to user a simpler algorithm.
487          */
488         if (!using_lapic_timer) {
489                 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL,
490                     NULL, INTR_TYPE_CLK, NULL);
491                 i8254_intsrc = intr_lookup_source(0);
492                 if (i8254_intsrc != NULL)
493                         i8254_pending =
494                             i8254_intsrc->is_pic->pic_source_pending;
495         } else {
496                 i8254_timecounter.tc_get_timecount =
497                     i8254_simple_get_timecount;
498                 i8254_timecounter.tc_counter_mask = 0xffff;
499                 set_i8254_freq(i8254_freq, hz);
500         }
501
502         /* Initialize RTC. */
503         atrtc_start();
504
505         /*
506          * If the separate statistics clock hasn't been explicility disabled
507          * and we aren't already using the local APIC timer to drive the
508          * kernel clocks, then setup the RTC to periodically interrupt to
509          * drive statclock() and profclock().
510          */
511         if (!using_lapic_timer) {
512                 using_atrtc_timer = atrtc_setup_clock();
513                 if (using_atrtc_timer) {
514                         /* Enable periodic interrupts from the RTC. */
515                         intr_add_handler("rtc", 8,
516                             (driver_filter_t *)rtcintr, NULL, NULL,
517                             INTR_TYPE_CLK, NULL);
518                         atrtc_enable_intr();
519                 } else {
520                         profhz = hz;
521                         if (hz < 128)
522                                 stathz = hz;
523                         else
524                                 stathz = hz / (hz / 128);
525                 }
526         }
527
528         init_TSC_tc();
529 }
530
531 void
532 cpu_startprofclock(void)
533 {
534
535         if (using_lapic_timer || !using_atrtc_timer)
536                 return;
537         atrtc_rate(RTCSA_PROF);
538         psdiv = pscnt = psratio;
539 }
540
541 void
542 cpu_stopprofclock(void)
543 {
544
545         if (using_lapic_timer || !using_atrtc_timer)
546                 return;
547         atrtc_rate(RTCSA_NOPROF);
548         psdiv = pscnt = 1;
549 }
550
551 static int
552 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
553 {
554         int error;
555         u_int freq;
556
557         /*
558          * Use `i8254' instead of `timer' in external names because `timer'
559          * is is too generic.  Should use it everywhere.
560          */
561         freq = i8254_freq;
562         error = sysctl_handle_int(oidp, &freq, 0, req);
563         if (error == 0 && req->newptr != NULL)
564                 set_i8254_freq(freq, hz);
565         return (error);
566 }
567
568 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
569     0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
570
571 static unsigned
572 i8254_simple_get_timecount(struct timecounter *tc)
573 {
574
575         return (i8254_max_count - getit());
576 }
577
578 static unsigned
579 i8254_get_timecount(struct timecounter *tc)
580 {
581         u_int count;
582         u_int high, low;
583         u_long rflags;
584
585         rflags = read_rflags();
586         mtx_lock_spin(&clock_lock);
587
588         /* Select timer0 and latch counter value. */
589         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
590
591         low = inb(TIMER_CNTR0);
592         high = inb(TIMER_CNTR0);
593         count = i8254_max_count - ((high << 8) | low);
594         if (count < i8254_lastcount ||
595             (!i8254_ticked && (clkintr_pending ||
596             ((count < 20 || (!(rflags & PSL_I) &&
597             count < i8254_max_count / 2u)) &&
598             i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
599                 i8254_ticked = 1;
600                 i8254_offset += i8254_max_count;
601         }
602         i8254_lastcount = count;
603         count += i8254_offset;
604         mtx_unlock_spin(&clock_lock);
605         return (count);
606 }
607
608 #ifdef DEV_ISA
609 /*
610  * Attach to the ISA PnP descriptors for the timer
611  */
612 static struct isa_pnp_id attimer_ids[] = {
613         { 0x0001d041 /* PNP0100 */, "AT timer" },
614         { 0 }
615 };
616
617 static int
618 attimer_probe(device_t dev)
619 {
620         int result;
621         
622         result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
623         if (result <= 0)
624                 device_quiet(dev);
625         return(result);
626 }
627
628 static int
629 attimer_attach(device_t dev)
630 {
631         return(0);
632 }
633
634 static int
635 attimer_resume(device_t dev)
636 {
637
638         i8254_restore();
639         return(0);
640 }
641
642 static device_method_t attimer_methods[] = {
643         /* Device interface */
644         DEVMETHOD(device_probe,         attimer_probe),
645         DEVMETHOD(device_attach,        attimer_attach),
646         DEVMETHOD(device_detach,        bus_generic_detach),
647         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
648         DEVMETHOD(device_suspend,       bus_generic_suspend),
649         DEVMETHOD(device_resume,        attimer_resume),
650         { 0, 0 }
651 };
652
653 static driver_t attimer_driver = {
654         "attimer",
655         attimer_methods,
656         1,              /* no softc */
657 };
658
659 static devclass_t attimer_devclass;
660
661 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
662 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
663
664 #endif /* DEV_ISA */