]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/isa/clock.c
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302418, and update
[FreeBSD/FreeBSD.git] / sys / x86 / isa / clock.c
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * William Jolitz and Don Ahn.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      from: @(#)clock.c       7.2 (Berkeley) 5/12/91
34  */
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 /*
40  * Routines to handle clock hardware.
41  */
42
43 #include "opt_clock.h"
44 #include "opt_isa.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/bus.h>
49 #include <sys/lock.h>
50 #include <sys/kdb.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/kernel.h>
54 #include <sys/module.h>
55 #include <sys/rman.h>
56 #include <sys/sched.h>
57 #include <sys/smp.h>
58 #include <sys/sysctl.h>
59 #include <sys/timeet.h>
60 #include <sys/timetc.h>
61
62 #include <machine/clock.h>
63 #include <machine/cpu.h>
64 #include <machine/intr_machdep.h>
65 #include <machine/ppireg.h>
66 #include <machine/timerreg.h>
67 #include <x86/init.h>
68
69 #include <isa/rtc.h>
70 #ifdef DEV_ISA
71 #include <isa/isareg.h>
72 #include <isa/isavar.h>
73 #endif
74
75 int     clkintr_pending;
76 #ifndef TIMER_FREQ
77 #define TIMER_FREQ   1193182
78 #endif
79 u_int   i8254_freq = TIMER_FREQ;
80 TUNABLE_INT("hw.i8254.freq", &i8254_freq);
81 int     i8254_max_count;
82 static int i8254_timecounter = 1;
83
84 struct mtx clock_lock;
85 static  struct intsrc *i8254_intsrc;
86 static  uint16_t i8254_lastcount;
87 static  uint16_t i8254_offset;
88 static  int     (*i8254_pending)(struct intsrc *);
89 static  int     i8254_ticked;
90
91 struct attimer_softc {
92         int intr_en;
93         int port_rid, intr_rid;
94         struct resource *port_res;
95         struct resource *intr_res;
96         void *intr_handler;
97         struct timecounter tc;
98         struct eventtimer et;
99         int             mode;
100 #define MODE_STOP       0
101 #define MODE_PERIODIC   1
102 #define MODE_ONESHOT    2
103         uint32_t        period;
104 };
105 static struct attimer_softc *attimer_sc = NULL;
106
107 static int timer0_period = -2;
108 static int timer0_mode = 0xffff;
109 static int timer0_last = 0xffff;
110
111 /* Values for timerX_state: */
112 #define RELEASED        0
113 #define RELEASE_PENDING 1
114 #define ACQUIRED        2
115 #define ACQUIRE_PENDING 3
116
117 static  u_char  timer2_state;
118
119 static  unsigned i8254_get_timecount(struct timecounter *tc);
120 static  void    set_i8254_freq(int mode, uint32_t period);
121
122 void
123 clock_init(void)
124 {
125         /* Init the clock lock */
126         mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
127         /* Init the clock in order to use DELAY */
128         init_ops.early_clock_source_init();
129 }
130
131 static int
132 clkintr(void *arg)
133 {
134         struct attimer_softc *sc = (struct attimer_softc *)arg;
135
136         if (i8254_timecounter && sc->period != 0) {
137                 mtx_lock_spin(&clock_lock);
138                 if (i8254_ticked)
139                         i8254_ticked = 0;
140                 else {
141                         i8254_offset += i8254_max_count;
142                         i8254_lastcount = 0;
143                 }
144                 clkintr_pending = 0;
145                 mtx_unlock_spin(&clock_lock);
146         }
147
148         if (sc->et.et_active && sc->mode != MODE_STOP)
149                 sc->et.et_event_cb(&sc->et, sc->et.et_arg);
150
151         return (FILTER_HANDLED);
152 }
153
154 int
155 timer_spkr_acquire(void)
156 {
157         int mode;
158
159         mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT;
160
161         if (timer2_state != RELEASED)
162                 return (-1);
163         timer2_state = ACQUIRED;
164
165         /*
166          * This access to the timer registers is as atomic as possible
167          * because it is a single instruction.  We could do better if we
168          * knew the rate.  Use of splclock() limits glitches to 10-100us,
169          * and this is probably good enough for timer2, so we aren't as
170          * careful with it as with timer0.
171          */
172         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
173
174         ppi_spkr_on();          /* enable counter2 output to speaker */
175         return (0);
176 }
177
178 int
179 timer_spkr_release(void)
180 {
181
182         if (timer2_state != ACQUIRED)
183                 return (-1);
184         timer2_state = RELEASED;
185         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
186
187         ppi_spkr_off();         /* disable counter2 output to speaker */
188         return (0);
189 }
190
191 void
192 timer_spkr_setfreq(int freq)
193 {
194
195         freq = i8254_freq / freq;
196         mtx_lock_spin(&clock_lock);
197         outb(TIMER_CNTR2, freq & 0xff);
198         outb(TIMER_CNTR2, freq >> 8);
199         mtx_unlock_spin(&clock_lock);
200 }
201
202 static int
203 getit(void)
204 {
205         int high, low;
206
207         mtx_lock_spin(&clock_lock);
208
209         /* Select timer0 and latch counter value. */
210         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
211
212         low = inb(TIMER_CNTR0);
213         high = inb(TIMER_CNTR0);
214
215         mtx_unlock_spin(&clock_lock);
216         return ((high << 8) | low);
217 }
218
219 /*
220  * Wait "n" microseconds.
221  * Relies on timer 1 counting down from (i8254_freq / hz)
222  * Note: timer had better have been programmed before this is first used!
223  */
224 void
225 i8254_delay(int n)
226 {
227         int delta, prev_tick, tick, ticks_left;
228 #ifdef DELAYDEBUG
229         int getit_calls = 1;
230         int n1;
231         static int state = 0;
232
233         if (state == 0) {
234                 state = 1;
235                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
236                         DELAY(n1);
237                 state = 2;
238         }
239         if (state == 1)
240                 printf("DELAY(%d)...", n);
241 #endif
242         /*
243          * Read the counter first, so that the rest of the setup overhead is
244          * counted.  Guess the initial overhead is 20 usec (on most systems it
245          * takes about 1.5 usec for each of the i/o's in getit().  The loop
246          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
247          * multiplications and divisions to scale the count take a while).
248          *
249          * However, if ddb is active then use a fake counter since reading
250          * the i8254 counter involves acquiring a lock.  ddb must not do
251          * locking for many reasons, but it calls here for at least atkbd
252          * input.
253          */
254 #ifdef KDB
255         if (kdb_active)
256                 prev_tick = 1;
257         else
258 #endif
259                 prev_tick = getit();
260         n -= 0;                 /* XXX actually guess no initial overhead */
261         /*
262          * Calculate (n * (i8254_freq / 1e6)) without using floating point
263          * and without any avoidable overflows.
264          */
265         if (n <= 0)
266                 ticks_left = 0;
267         else if (n < 256)
268                 /*
269                  * Use fixed point to avoid a slow division by 1000000.
270                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
271                  * 2^15 is the first power of 2 that gives exact results
272                  * for n between 0 and 256.
273                  */
274                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
275         else
276                 /*
277                  * Don't bother using fixed point, although gcc-2.7.2
278                  * generates particularly poor code for the long long
279                  * division, since even the slow way will complete long
280                  * before the delay is up (unless we're interrupted).
281                  */
282                 ticks_left = ((u_int)n * (long long)i8254_freq + 999999)
283                              / 1000000;
284
285         while (ticks_left > 0) {
286 #ifdef KDB
287                 if (kdb_active) {
288                         inb(0x84);
289                         tick = prev_tick - 1;
290                         if (tick <= 0)
291                                 tick = i8254_max_count;
292                 } else
293 #endif
294                         tick = getit();
295 #ifdef DELAYDEBUG
296                 ++getit_calls;
297 #endif
298                 delta = prev_tick - tick;
299                 prev_tick = tick;
300                 if (delta < 0) {
301                         delta += i8254_max_count;
302                         /*
303                          * Guard against i8254_max_count being wrong.
304                          * This shouldn't happen in normal operation,
305                          * but it may happen if set_i8254_freq() is
306                          * traced.
307                          */
308                         if (delta < 0)
309                                 delta = 0;
310                 }
311                 ticks_left -= delta;
312         }
313 #ifdef DELAYDEBUG
314         if (state == 1)
315                 printf(" %d calls to getit() at %d usec each\n",
316                        getit_calls, (n + 5) / getit_calls);
317 #endif
318 }
319
320 static void
321 set_i8254_freq(int mode, uint32_t period)
322 {
323         int new_count, new_mode;
324
325         mtx_lock_spin(&clock_lock);
326         if (mode == MODE_STOP) {
327                 if (i8254_timecounter) {
328                         mode = MODE_PERIODIC;
329                         new_count = 0x10000;
330                 } else
331                         new_count = -1;
332         } else {
333                 new_count = min(((uint64_t)i8254_freq * period +
334                     0x80000000LLU) >> 32, 0x10000);
335         }
336         if (new_count == timer0_period)
337                 goto out;
338         i8254_max_count = ((new_count & ~0xffff) != 0) ? 0xffff : new_count;
339         timer0_period = (mode == MODE_PERIODIC) ? new_count : -1;
340         switch (mode) {
341         case MODE_STOP:
342                 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
343                 outb(TIMER_MODE, new_mode);
344                 outb(TIMER_CNTR0, 0);
345                 outb(TIMER_CNTR0, 0);
346                 break;
347         case MODE_PERIODIC:
348                 new_mode = TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT;
349                 outb(TIMER_MODE, new_mode);
350                 outb(TIMER_CNTR0, new_count & 0xff);
351                 outb(TIMER_CNTR0, new_count >> 8);
352                 break;
353         case MODE_ONESHOT:
354                 if (new_count < 256 && timer0_last < 256) {
355                         new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_LSB;
356                         if (new_mode != timer0_mode)
357                                 outb(TIMER_MODE, new_mode);
358                         outb(TIMER_CNTR0, new_count & 0xff);
359                         break;
360                 }
361                 new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT;
362                 if (new_mode != timer0_mode)
363                         outb(TIMER_MODE, new_mode);
364                 outb(TIMER_CNTR0, new_count & 0xff);
365                 outb(TIMER_CNTR0, new_count >> 8);
366                 break;
367         default:
368                 panic("set_i8254_freq: unknown operational mode");
369         }
370         timer0_mode = new_mode;
371         timer0_last = new_count;
372 out:
373         mtx_unlock_spin(&clock_lock);
374 }
375
376 static void
377 i8254_restore(void)
378 {
379
380         timer0_period = -2;
381         timer0_mode = 0xffff;
382         timer0_last = 0xffff;
383         if (attimer_sc != NULL)
384                 set_i8254_freq(attimer_sc->mode, attimer_sc->period);
385         else
386                 set_i8254_freq(MODE_STOP, 0);
387 }
388
389 #ifndef __amd64__
390 /*
391  * Restore all the timers non-atomically (XXX: should be atomically).
392  *
393  * This function is called from pmtimer_resume() to restore all the timers.
394  * This should not be necessary, but there are broken laptops that do not
395  * restore all the timers on resume. The APM spec was at best vague on the
396  * subject.
397  * pmtimer is used only with the old APM power management, and not with
398  * acpi, which is required for amd64, so skip it in that case.
399  */
400 void
401 timer_restore(void)
402 {
403
404         i8254_restore();                /* restore i8254_freq and hz */
405         atrtc_restore();                /* reenable RTC interrupts */
406 }
407 #endif
408
409 /* This is separate from startrtclock() so that it can be called early. */
410 void
411 i8254_init(void)
412 {
413
414         set_i8254_freq(MODE_STOP, 0);
415 }
416
417 void
418 startrtclock()
419 {
420
421         init_TSC();
422 }
423
424 void
425 cpu_initclocks(void)
426 {
427 #ifdef EARLY_AP_STARTUP
428         struct thread *td;
429         int i;
430
431         td = curthread;
432         cpu_initclocks_bsp();
433         CPU_FOREACH(i) {
434                 if (i == 0)
435                         continue;
436                 thread_lock(td);
437                 sched_bind(td, i);
438                 thread_unlock(td);
439                 cpu_initclocks_ap();
440         }
441         thread_lock(td);
442         if (sched_is_bound(td))
443                 sched_unbind(td);
444         thread_unlock(td);
445 #else
446         cpu_initclocks_bsp();
447 #endif
448 }
449
450 static int
451 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
452 {
453         int error;
454         u_int freq;
455
456         /*
457          * Use `i8254' instead of `timer' in external names because `timer'
458          * is too generic.  Should use it everywhere.
459          */
460         freq = i8254_freq;
461         error = sysctl_handle_int(oidp, &freq, 0, req);
462         if (error == 0 && req->newptr != NULL) {
463                 i8254_freq = freq;
464                 if (attimer_sc != NULL) {
465                         set_i8254_freq(attimer_sc->mode, attimer_sc->period);
466                         attimer_sc->tc.tc_frequency = freq;
467                 } else {
468                         set_i8254_freq(MODE_STOP, 0);
469                 }
470         }
471         return (error);
472 }
473
474 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
475     0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU",
476     "i8254 timer frequency");
477
478 static unsigned
479 i8254_get_timecount(struct timecounter *tc)
480 {
481         device_t dev = (device_t)tc->tc_priv;
482         struct attimer_softc *sc = device_get_softc(dev);
483         register_t flags;
484         uint16_t count;
485         u_int high, low;
486
487         if (sc->period == 0)
488                 return (i8254_max_count - getit());
489
490 #ifdef __amd64__
491         flags = read_rflags();
492 #else
493         flags = read_eflags();
494 #endif
495         mtx_lock_spin(&clock_lock);
496
497         /* Select timer0 and latch counter value. */
498         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
499
500         low = inb(TIMER_CNTR0);
501         high = inb(TIMER_CNTR0);
502         count = i8254_max_count - ((high << 8) | low);
503         if (count < i8254_lastcount ||
504             (!i8254_ticked && (clkintr_pending ||
505             ((count < 20 || (!(flags & PSL_I) &&
506             count < i8254_max_count / 2u)) &&
507             i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
508                 i8254_ticked = 1;
509                 i8254_offset += i8254_max_count;
510         }
511         i8254_lastcount = count;
512         count += i8254_offset;
513         mtx_unlock_spin(&clock_lock);
514         return (count);
515 }
516
517 static int
518 attimer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
519 {
520         device_t dev = (device_t)et->et_priv;
521         struct attimer_softc *sc = device_get_softc(dev);
522
523         if (period != 0) {
524                 sc->mode = MODE_PERIODIC;
525                 sc->period = period;
526         } else {
527                 sc->mode = MODE_ONESHOT;
528                 sc->period = first;
529         }
530         if (!sc->intr_en) {
531                 i8254_intsrc->is_pic->pic_enable_source(i8254_intsrc);
532                 sc->intr_en = 1;
533         }
534         set_i8254_freq(sc->mode, sc->period);
535         return (0);
536 }
537
538 static int
539 attimer_stop(struct eventtimer *et)
540 {
541         device_t dev = (device_t)et->et_priv;
542         struct attimer_softc *sc = device_get_softc(dev);
543         
544         sc->mode = MODE_STOP;
545         sc->period = 0;
546         set_i8254_freq(sc->mode, sc->period);
547         return (0);
548 }
549
550 #ifdef DEV_ISA
551 /*
552  * Attach to the ISA PnP descriptors for the timer
553  */
554 static struct isa_pnp_id attimer_ids[] = {
555         { 0x0001d041 /* PNP0100 */, "AT timer" },
556         { 0 }
557 };
558
559 static int
560 attimer_probe(device_t dev)
561 {
562         int result;
563         
564         result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids);
565         /* ENOENT means no PnP-ID, device is hinted. */
566         if (result == ENOENT) {
567                 device_set_desc(dev, "AT timer");
568                 return (BUS_PROBE_LOW_PRIORITY);
569         }
570         return (result);
571 }
572
573 static int
574 attimer_attach(device_t dev)
575 {
576         struct attimer_softc *sc;
577         rman_res_t s;
578         int i;
579
580         attimer_sc = sc = device_get_softc(dev);
581         bzero(sc, sizeof(struct attimer_softc));
582         if (!(sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
583             &sc->port_rid, IO_TIMER1, IO_TIMER1 + 3, 4, RF_ACTIVE)))
584                 device_printf(dev,"Warning: Couldn't map I/O.\n");
585         i8254_intsrc = intr_lookup_source(0);
586         if (i8254_intsrc != NULL)
587                 i8254_pending = i8254_intsrc->is_pic->pic_source_pending;
588         resource_int_value(device_get_name(dev), device_get_unit(dev),
589             "timecounter", &i8254_timecounter);
590         set_i8254_freq(MODE_STOP, 0);
591         if (i8254_timecounter) {
592                 sc->tc.tc_get_timecount = i8254_get_timecount;
593                 sc->tc.tc_counter_mask = 0xffff;
594                 sc->tc.tc_frequency = i8254_freq;
595                 sc->tc.tc_name = "i8254";
596                 sc->tc.tc_quality = 0;
597                 sc->tc.tc_priv = dev;
598                 tc_init(&sc->tc);
599         }
600         if (resource_int_value(device_get_name(dev), device_get_unit(dev),
601             "clock", &i) != 0 || i != 0) {
602                 sc->intr_rid = 0;
603                 while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid,
604                     &s, NULL) == 0 && s != 0)
605                         sc->intr_rid++;
606                 if (!(sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
607                     &sc->intr_rid, 0, 0, 1, RF_ACTIVE))) {
608                         device_printf(dev,"Can't map interrupt.\n");
609                         return (0);
610                 }
611                 /* Dirty hack, to make bus_setup_intr to not enable source. */
612                 i8254_intsrc->is_handlers++;
613                 if ((bus_setup_intr(dev, sc->intr_res,
614                     INTR_MPSAFE | INTR_TYPE_CLK,
615                     (driver_filter_t *)clkintr, NULL,
616                     sc, &sc->intr_handler))) {
617                         device_printf(dev, "Can't setup interrupt.\n");
618                         i8254_intsrc->is_handlers--;
619                         return (0);
620                 }
621                 i8254_intsrc->is_handlers--;
622                 i8254_intsrc->is_pic->pic_enable_intr(i8254_intsrc);
623                 sc->et.et_name = "i8254";
624                 sc->et.et_flags = ET_FLAGS_PERIODIC;
625                 if (!i8254_timecounter)
626                         sc->et.et_flags |= ET_FLAGS_ONESHOT;
627                 sc->et.et_quality = 100;
628                 sc->et.et_frequency = i8254_freq;
629                 sc->et.et_min_period = (0x0002LLU << 32) / i8254_freq;
630                 sc->et.et_max_period = (0xfffeLLU << 32) / i8254_freq;
631                 sc->et.et_start = attimer_start;
632                 sc->et.et_stop = attimer_stop;
633                 sc->et.et_priv = dev;
634                 et_register(&sc->et);
635         }
636         return(0);
637 }
638
639 static int
640 attimer_resume(device_t dev)
641 {
642
643         i8254_restore();
644         return (0);
645 }
646
647 static device_method_t attimer_methods[] = {
648         /* Device interface */
649         DEVMETHOD(device_probe,         attimer_probe),
650         DEVMETHOD(device_attach,        attimer_attach),
651         DEVMETHOD(device_detach,        bus_generic_detach),
652         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
653         DEVMETHOD(device_suspend,       bus_generic_suspend),
654         DEVMETHOD(device_resume,        attimer_resume),
655         { 0, 0 }
656 };
657
658 static driver_t attimer_driver = {
659         "attimer",
660         attimer_methods,
661         sizeof(struct attimer_softc),
662 };
663
664 static devclass_t attimer_devclass;
665
666 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
667 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
668
669 #endif /* DEV_ISA */