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