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