i386: Remove old IOAPIC code
[dragonfly.git] / sys / platform / pc32 / 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  * 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: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki Exp $
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 "use_apm.h"
52 #include "opt_clock.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/eventhandler.h>
57 #include <sys/time.h>
58 #include <sys/kernel.h>
59 #include <sys/bus.h>
60 #ifndef SMP
61 #include <sys/lock.h>
62 #endif
63 #include <sys/sysctl.h>
64 #include <sys/cons.h>
65 #include <sys/systimer.h>
66 #include <sys/globaldata.h>
67 #include <sys/thread2.h>
68 #include <sys/systimer.h>
69 #include <sys/machintr.h>
70 #include <sys/interrupt.h>
71
72 #include <machine/clock.h>
73 #ifdef CLK_CALIBRATION_LOOP
74 #endif
75 #include <machine/cputypes.h>
76 #include <machine/frame.h>
77 #include <machine/ipl.h>
78 #include <machine/limits.h>
79 #include <machine/md_var.h>
80 #include <machine/psl.h>
81 #include <machine/segments.h>
82 #include <machine/smp.h>
83 #include <machine/specialreg.h>
84
85 #ifdef SMP
86 #include <machine_base/apic/ioapic_abi.h>
87 #endif
88 #include <machine_base/icu/icu.h>
89 #include <bus/isa/isa.h>
90 #include <bus/isa/rtc.h>
91 #include <machine_base/isa/timerreg.h>
92
93 #include <machine/intr_machdep.h>
94
95 static void i8254_restore(void);
96 static void resettodr_on_shutdown(void *arg __unused);
97
98 /*
99  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
100  * can use a simple formula for leap years.
101  */
102 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
103 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
104
105 #ifndef TIMER_FREQ
106 #define TIMER_FREQ   1193182
107 #endif
108
109 static uint8_t i8254_walltimer_sel;
110 static uint16_t i8254_walltimer_cntr;
111
112 int     adjkerntz;              /* local offset from GMT in seconds */
113 int     disable_rtc_set;        /* disable resettodr() if != 0 */
114 int     tsc_present;
115 int64_t tsc_frequency;
116 int     tsc_is_broken;
117 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
118 int     timer0_running;
119 enum tstate { RELEASED, ACQUIRED };
120 enum tstate timer0_state;
121 enum tstate timer1_state;
122 enum tstate timer2_state;
123
124 static  int     beeping = 0;
125 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
126 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
127 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
128 static  int     rtc_loaded;
129
130 static int i8254_cputimer_div;
131
132 static int i8254_nointr;
133 static int i8254_intr_disable = 1;
134 TUNABLE_INT("hw.i8254.intr_disable", &i8254_intr_disable);
135
136 static struct callout sysbeepstop_ch;
137
138 static sysclock_t i8254_cputimer_count(void);
139 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
140 static void i8254_cputimer_destruct(struct cputimer *cputimer);
141
142 static struct cputimer  i8254_cputimer = {
143     SLIST_ENTRY_INITIALIZER,
144     "i8254",
145     CPUTIMER_PRI_8254,
146     0,
147     i8254_cputimer_count,
148     cputimer_default_fromhz,
149     cputimer_default_fromus,
150     i8254_cputimer_construct,
151     i8254_cputimer_destruct,
152     TIMER_FREQ,
153     0, 0, 0
154 };
155
156 static void i8254_intr_reload(struct cputimer_intr *, sysclock_t);
157 static void i8254_intr_config(struct cputimer_intr *, const struct cputimer *);
158 static void i8254_intr_initclock(struct cputimer_intr *, boolean_t);
159
160 static struct cputimer_intr i8254_cputimer_intr = {
161     .freq = TIMER_FREQ,
162     .reload = i8254_intr_reload,
163     .enable = cputimer_intr_default_enable,
164     .config = i8254_intr_config,
165     .restart = cputimer_intr_default_restart,
166     .pmfixup = cputimer_intr_default_pmfixup,
167     .initclock = i8254_intr_initclock,
168     .next = SLIST_ENTRY_INITIALIZER,
169     .name = "i8254",
170     .type = CPUTIMER_INTR_8254,
171     .prio = CPUTIMER_INTR_PRIO_8254,
172     .caps = CPUTIMER_INTR_CAP_PS
173 };
174
175 /*
176  * timer0 clock interrupt.  Timer0 is in one-shot mode and has stopped
177  * counting as of this interrupt.  We use timer1 in free-running mode (not
178  * generating any interrupts) as our main counter.  Each cpu has timeouts
179  * pending.
180  *
181  * This code is INTR_MPSAFE and may be called without the BGL held.
182  */
183 static void
184 clkintr(void *dummy, void *frame_arg)
185 {
186         static sysclock_t sysclock_count;       /* NOTE! Must be static */
187         struct globaldata *gd = mycpu;
188 #ifdef SMP
189         struct globaldata *gscan;
190         int n;
191 #endif
192
193         /*
194          * SWSTROBE mode is a one-shot, the timer is no longer running
195          */
196         timer0_running = 0;
197
198         /*
199          * XXX the dispatcher needs work.  right now we call systimer_intr()
200          * directly or via IPI for any cpu with systimers queued, which is
201          * usually *ALL* of them.  We need to use the LAPIC timer for this.
202          */
203         sysclock_count = sys_cputimer->count();
204 #ifdef SMP
205         for (n = 0; n < ncpus; ++n) {
206             gscan = globaldata_find(n);
207             if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
208                 continue;
209             if (gscan != gd) {
210                 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr, 
211                                 &sysclock_count, 1);
212             } else {
213                 systimer_intr(&sysclock_count, 0, frame_arg);
214             }
215         }
216 #else
217         if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
218             systimer_intr(&sysclock_count, 0, frame_arg);
219 #endif
220 }
221
222
223 /*
224  * NOTE! not MP safe.
225  */
226 int
227 acquire_timer2(int mode)
228 {
229         if (timer2_state != RELEASED)
230                 return (-1);
231         timer2_state = ACQUIRED;
232
233         /*
234          * This access to the timer registers is as atomic as possible
235          * because it is a single instruction.  We could do better if we
236          * knew the rate.
237          */
238         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
239         return (0);
240 }
241
242 int
243 release_timer2(void)
244 {
245         if (timer2_state != ACQUIRED)
246                 return (-1);
247         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
248         timer2_state = RELEASED;
249         return (0);
250 }
251
252 #include "opt_ddb.h"
253 #ifdef DDB
254 #include <ddb/ddb.h>
255
256 DB_SHOW_COMMAND(rtc, rtc)
257 {
258         kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
259                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
260                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
261                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
262 }
263 #endif /* DDB */
264
265 /*
266  * Return the current cpu timer count as a 32 bit integer.
267  */
268 static
269 sysclock_t
270 i8254_cputimer_count(void)
271 {
272         static __uint16_t cputimer_last;
273         __uint16_t count;
274         sysclock_t ret;
275
276         clock_lock();
277         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
278         count = (__uint8_t)inb(i8254_walltimer_cntr);           /* get countdown */
279         count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
280         count = -count;                                 /* -> countup */
281         if (count < cputimer_last)                      /* rollover */
282                 i8254_cputimer.base += 0x00010000;
283         ret = i8254_cputimer.base | count;
284         cputimer_last = count;
285         clock_unlock();
286         return(ret);
287 }
288
289 /*
290  * This function is called whenever the system timebase changes, allowing
291  * us to calculate what is needed to convert a system timebase tick 
292  * into an 8254 tick for the interrupt timer.  If we can convert to a
293  * simple shift, multiplication, or division, we do so.  Otherwise 64
294  * bit arithmatic is required every time the interrupt timer is reloaded.
295  */
296 static void
297 i8254_intr_config(struct cputimer_intr *cti, const struct cputimer *timer)
298 {
299     int freq;
300     int div;
301
302     /*
303      * Will a simple divide do the trick?
304      */
305     div = (timer->freq + (cti->freq / 2)) / cti->freq;
306     freq = cti->freq * div;
307
308     if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
309         i8254_cputimer_div = div;
310     else
311         i8254_cputimer_div = 0;
312 }
313
314 /*
315  * Reload for the next timeout.  It is possible for the reload value
316  * to be 0 or negative, indicating that an immediate timer interrupt
317  * is desired.  For now make the minimum 2 ticks.
318  *
319  * We may have to convert from the system timebase to the 8254 timebase.
320  */
321 static void
322 i8254_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
323 {
324     __uint16_t count;
325
326     if (i8254_cputimer_div)
327         reload /= i8254_cputimer_div;
328     else
329         reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
330
331     if ((int)reload < 2)
332         reload = 2;
333
334     clock_lock();
335     if (timer0_running) {
336         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);     /* count-down timer */
337         count = (__uint8_t)inb(TIMER_CNTR0);            /* lsb */
338         count |= ((__uint8_t)inb(TIMER_CNTR0) << 8);    /* msb */
339         if (reload < count) {
340             outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
341             outb(TIMER_CNTR0, (__uint8_t)reload);       /* lsb */
342             outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
343         }
344     } else {
345         timer0_running = 1;
346         if (reload > 0xFFFF)
347             reload = 0;         /* full count */
348         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
349         outb(TIMER_CNTR0, (__uint8_t)reload);           /* lsb */
350         outb(TIMER_CNTR0, (__uint8_t)(reload >> 8));    /* msb */
351     }
352     clock_unlock();
353 }
354
355 /*
356  * DELAY(usec)       - Spin for the specified number of microseconds.
357  * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
358  *                     but do a thread switch in the loop
359  *
360  * Relies on timer 1 counting down from (cputimer_freq / hz)
361  * Note: timer had better have been programmed before this is first used!
362  */
363 static void
364 DODELAY(int n, int doswitch)
365 {
366         int delta, prev_tick, tick, ticks_left;
367
368 #ifdef DELAYDEBUG
369         int getit_calls = 1;
370         int n1;
371         static int state = 0;
372
373         if (state == 0) {
374                 state = 1;
375                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
376                         DELAY(n1);
377                 state = 2;
378         }
379         if (state == 1)
380                 kprintf("DELAY(%d)...", n);
381 #endif
382         /*
383          * Guard against the timer being uninitialized if we are called
384          * early for console i/o.
385          */
386         if (timer0_state == RELEASED)
387                 i8254_restore();
388
389         /*
390          * Read the counter first, so that the rest of the setup overhead is
391          * counted.  Then calculate the number of hardware timer ticks
392          * required, rounding up to be sure we delay at least the requested
393          * number of microseconds.
394          */
395         prev_tick = sys_cputimer->count();
396         ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
397                      1000000;
398
399         /*
400          * Loop until done.
401          */
402         while (ticks_left > 0) {
403                 tick = sys_cputimer->count();
404 #ifdef DELAYDEBUG
405                 ++getit_calls;
406 #endif
407                 delta = tick - prev_tick;
408                 prev_tick = tick;
409                 if (delta < 0)
410                         delta = 0;
411                 ticks_left -= delta;
412                 if (doswitch && ticks_left > 0)
413                         lwkt_switch();
414                 cpu_pause();
415         }
416 #ifdef DELAYDEBUG
417         if (state == 1)
418                 kprintf(" %d calls to getit() at %d usec each\n",
419                        getit_calls, (n + 5) / getit_calls);
420 #endif
421 }
422
423 /*
424  * DELAY() never switches
425  */
426 void
427 DELAY(int n)
428 {
429         DODELAY(n, 0);
430 }
431
432 int
433 CHECKTIMEOUT(TOTALDELAY *tdd)
434 {
435         sysclock_t delta;
436         int us;
437
438         if (tdd->started == 0) {
439                if (timer0_state == RELEASED)
440                        i8254_restore();
441                tdd->last_clock = sys_cputimer->count();
442                tdd->started = 1;
443                return(0);
444         }
445         delta = sys_cputimer->count() - tdd->last_clock;
446         us = (u_int64_t)delta * (u_int64_t)1000000 /
447              (u_int64_t)sys_cputimer->freq;
448         tdd->last_clock += (u_int64_t)us * (u_int64_t)sys_cputimer->freq /
449                            1000000;
450         tdd->us -= us;
451         return (tdd->us < 0);
452 }
453
454 /*
455  * DRIVERSLEEP() does not switch if called with a spinlock held or
456  * from a hard interrupt.
457  */
458 void
459 DRIVERSLEEP(int usec)
460 {
461         globaldata_t gd = mycpu;
462
463         if (gd->gd_intr_nesting_level || gd->gd_spinlocks_wr) {
464                 DODELAY(usec, 0);
465         } else {
466                 DODELAY(usec, 1);
467         }
468 }
469
470 static void
471 sysbeepstop(void *chan)
472 {
473         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
474         beeping = 0;
475         release_timer2();
476 }
477
478 int
479 sysbeep(int pitch, int period)
480 {
481         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
482                 return(-1);
483         if (sysbeep_enable == 0)
484                 return(-1);
485         /*
486          * Nobody else is using timer2, we do not need the clock lock
487          */
488         outb(TIMER_CNTR2, pitch);
489         outb(TIMER_CNTR2, (pitch>>8));
490         if (!beeping) {
491                 /* enable counter2 output to speaker */
492                 outb(IO_PPI, inb(IO_PPI) | 3);
493                 beeping = period;
494                 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
495         }
496         return (0);
497 }
498
499 /*
500  * RTC support routines
501  */
502
503 int
504 rtcin(int reg)
505 {
506         u_char val;
507
508         crit_enter();
509         outb(IO_RTC, reg);
510         inb(0x84);
511         val = inb(IO_RTC + 1);
512         inb(0x84);
513         crit_exit();
514         return (val);
515 }
516
517 static __inline void
518 writertc(u_char reg, u_char val)
519 {
520         crit_enter();
521         inb(0x84);
522         outb(IO_RTC, reg);
523         inb(0x84);
524         outb(IO_RTC + 1, val);
525         inb(0x84);              /* XXX work around wrong order in rtcin() */
526         crit_exit();
527 }
528
529 static __inline int
530 readrtc(int port)
531 {
532         return(bcd2bin(rtcin(port)));
533 }
534
535 static u_int
536 calibrate_clocks(void)
537 {
538         u_int64_t old_tsc;
539         u_int count, prev_count, tot_count;
540         int sec, start_sec, timeout;
541
542         if (bootverbose)
543                 kprintf("Calibrating clock(s) ... ");
544         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
545                 goto fail;
546         timeout = 100000000;
547
548         /* Read the mc146818A seconds counter. */
549         for (;;) {
550                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
551                         sec = rtcin(RTC_SEC);
552                         break;
553                 }
554                 if (--timeout == 0)
555                         goto fail;
556         }
557
558         /* Wait for the mC146818A seconds counter to change. */
559         start_sec = sec;
560         for (;;) {
561                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
562                         sec = rtcin(RTC_SEC);
563                         if (sec != start_sec)
564                                 break;
565                 }
566                 if (--timeout == 0)
567                         goto fail;
568         }
569
570         /* Start keeping track of the i8254 counter. */
571         prev_count = sys_cputimer->count();
572         tot_count = 0;
573
574         if (tsc_present) 
575                 old_tsc = rdtsc();
576         else
577                 old_tsc = 0;            /* shut up gcc */
578
579         /*
580          * Wait for the mc146818A seconds counter to change.  Read the i8254
581          * counter for each iteration since this is convenient and only
582          * costs a few usec of inaccuracy. The timing of the final reads
583          * of the counters almost matches the timing of the initial reads,
584          * so the main cause of inaccuracy is the varying latency from 
585          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
586          * rtcin(RTC_SEC) that returns a changed seconds count.  The
587          * maximum inaccuracy from this cause is < 10 usec on 486's.
588          */
589         start_sec = sec;
590         for (;;) {
591                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
592                         sec = rtcin(RTC_SEC);
593                 count = sys_cputimer->count();
594                 tot_count += (int)(count - prev_count);
595                 prev_count = count;
596                 if (sec != start_sec)
597                         break;
598                 if (--timeout == 0)
599                         goto fail;
600         }
601
602         /*
603          * Read the cpu cycle counter.  The timing considerations are
604          * similar to those for the i8254 clock.
605          */
606         if (tsc_present) {
607                 tsc_frequency = rdtsc() - old_tsc;
608         }
609
610         if (tsc_present)
611                 kprintf("TSC clock: %llu Hz, ", tsc_frequency);
612         kprintf("i8254 clock: %u Hz\n", tot_count);
613         return (tot_count);
614
615 fail:
616         kprintf("failed, using default i8254 clock of %u Hz\n",
617                 i8254_cputimer.freq);
618         return (i8254_cputimer.freq);
619 }
620
621 static void
622 i8254_restore(void)
623 {
624         timer0_state = ACQUIRED;
625
626         clock_lock();
627
628         /*
629          * Timer0 is our fine-grained variable clock interrupt
630          */
631         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
632         outb(TIMER_CNTR0, 2);   /* lsb */
633         outb(TIMER_CNTR0, 0);   /* msb */
634         clock_unlock();
635
636         if (!i8254_nointr) {
637                 cputimer_intr_register(&i8254_cputimer_intr);
638                 cputimer_intr_select(&i8254_cputimer_intr, 0);
639         }
640
641         /*
642          * Timer1 or timer2 is our free-running clock, but only if another
643          * has not been selected.
644          */
645         cputimer_register(&i8254_cputimer);
646         cputimer_select(&i8254_cputimer, 0);
647 }
648
649 static void
650 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
651 {
652         int which;
653
654         /*
655          * Should we use timer 1 or timer 2 ?
656          */
657         which = 0;
658         TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
659         if (which != 1 && which != 2)
660                 which = 2;
661
662         switch(which) {
663         case 1:
664                 timer->name = "i8254_timer1";
665                 timer->type = CPUTIMER_8254_SEL1;
666                 i8254_walltimer_sel = TIMER_SEL1;
667                 i8254_walltimer_cntr = TIMER_CNTR1;
668                 timer1_state = ACQUIRED;
669                 break;
670         case 2:
671                 timer->name = "i8254_timer2";
672                 timer->type = CPUTIMER_8254_SEL2;
673                 i8254_walltimer_sel = TIMER_SEL2;
674                 i8254_walltimer_cntr = TIMER_CNTR2;
675                 timer2_state = ACQUIRED;
676                 break;
677         }
678
679         timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
680
681         clock_lock();
682         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
683         outb(i8254_walltimer_cntr, 0);  /* lsb */
684         outb(i8254_walltimer_cntr, 0);  /* msb */
685         outb(IO_PPI, inb(IO_PPI) | 1);  /* bit 0: enable gate, bit 1: spkr */
686         clock_unlock();
687 }
688
689 static void
690 i8254_cputimer_destruct(struct cputimer *timer)
691 {
692         switch(timer->type) {
693         case CPUTIMER_8254_SEL1:
694             timer1_state = RELEASED;
695             break;
696         case CPUTIMER_8254_SEL2:
697             timer2_state = RELEASED;
698             break;
699         default:
700             break;
701         }
702         timer->type = 0;
703 }
704
705 static void
706 rtc_restore(void)
707 {
708         /* Restore all of the RTC's "status" (actually, control) registers. */
709         writertc(RTC_STATUSB, RTCSB_24HR);
710         writertc(RTC_STATUSA, rtc_statusa);
711         writertc(RTC_STATUSB, rtc_statusb);
712 }
713
714 /*
715  * Restore all the timers.
716  *
717  * This function is called to resynchronize our core timekeeping after a
718  * long halt, e.g. from apm_default_resume() and friends.  It is also 
719  * called if after a BIOS call we have detected munging of the 8254.
720  * It is necessary because cputimer_count() counter's delta may have grown
721  * too large for nanouptime() and friends to handle, or (in the case of 8254
722  * munging) might cause the SYSTIMER code to prematurely trigger.
723  */
724 void
725 timer_restore(void)
726 {
727         crit_enter();
728         i8254_restore();                /* restore timer_freq and hz */
729         rtc_restore();                  /* reenable RTC interrupts */
730         crit_exit();
731 }
732
733 /*
734  * Initialize 8254 timer 0 early so that it can be used in DELAY().
735  */
736 void
737 startrtclock(void)
738 {
739         u_int delta, freq;
740
741         /* 
742          * Can we use the TSC?
743          */
744         if (cpu_feature & CPUID_TSC)
745                 tsc_present = 1;
746         else
747                 tsc_present = 0;
748
749         /*
750          * Initial RTC state, don't do anything unexpected
751          */
752         writertc(RTC_STATUSA, rtc_statusa);
753         writertc(RTC_STATUSB, RTCSB_24HR);
754
755         /*
756          * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to 
757          * generate an interrupt, which we will ignore for now.
758          *
759          * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
760          * (so it counts a full 2^16 and repeats).  We will use this timer
761          * for our counting.
762          */
763         i8254_restore();
764         freq = calibrate_clocks();
765 #ifdef CLK_CALIBRATION_LOOP
766         if (bootverbose) {
767                 kprintf(
768                 "Press a key on the console to abort clock calibration\n");
769                 while (cncheckc() == -1)
770                         calibrate_clocks();
771         }
772 #endif
773
774         /*
775          * Use the calibrated i8254 frequency if it seems reasonable.
776          * Otherwise use the default, and don't use the calibrated i586
777          * frequency.
778          */
779         delta = freq > i8254_cputimer.freq ? 
780                         freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
781         if (delta < i8254_cputimer.freq / 100) {
782 #ifndef CLK_USE_I8254_CALIBRATION
783                 if (bootverbose)
784                         kprintf(
785 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
786                 freq = i8254_cputimer.freq;
787 #endif
788                 /*
789                  * NOTE:
790                  * Interrupt timer's freq must be adjusted
791                  * before we change the cuptimer's frequency.
792                  */
793                 i8254_cputimer_intr.freq = freq;
794                 cputimer_set_frequency(&i8254_cputimer, freq);
795         } else {
796                 if (bootverbose)
797                         kprintf(
798                     "%d Hz differs from default of %d Hz by more than 1%%\n",
799                                freq, i8254_cputimer.freq);
800                 tsc_frequency = 0;
801         }
802
803 #ifndef CLK_USE_TSC_CALIBRATION
804         if (tsc_frequency != 0) {
805                 if (bootverbose)
806                         kprintf(
807 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
808                 tsc_frequency = 0;
809         }
810 #endif
811         if (tsc_present && tsc_frequency == 0) {
812                 /*
813                  * Calibration of the i586 clock relative to the mc146818A
814                  * clock failed.  Do a less accurate calibration relative
815                  * to the i8254 clock.
816                  */
817                 u_int64_t old_tsc = rdtsc();
818
819                 DELAY(1000000);
820                 tsc_frequency = rdtsc() - old_tsc;
821 #ifdef CLK_USE_TSC_CALIBRATION
822                 if (bootverbose) {
823                         kprintf("TSC clock: %llu Hz (Method B)\n",
824                                 tsc_frequency);
825                 }
826 #endif
827         }
828
829         EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
830
831 #if !defined(SMP)
832         /*
833          * We can not use the TSC in SMP mode, until we figure out a
834          * cheap (impossible), reliable and precise (yeah right!)  way
835          * to synchronize the TSCs of all the CPUs.
836          * Curse Intel for leaving the counter out of the I/O APIC.
837          */
838
839 #if NAPM > 0
840         /*
841          * We can not use the TSC if we support APM. Precise timekeeping
842          * on an APM'ed machine is at best a fools pursuit, since 
843          * any and all of the time spent in various SMM code can't 
844          * be reliably accounted for.  Reading the RTC is your only
845          * source of reliable time info.  The i8254 looses too of course
846          * but we need to have some kind of time...
847          * We don't know at this point whether APM is going to be used
848          * or not, nor when it might be activated.  Play it safe.
849          */
850         return;
851 #endif /* NAPM > 0 */
852
853 #endif /* !defined(SMP) */
854 }
855
856 /*
857  * Sync the time of day back to the RTC on shutdown, but only if
858  * we have already loaded it and have not crashed.
859  */
860 static void
861 resettodr_on_shutdown(void *arg __unused)
862 {
863         if (rtc_loaded && panicstr == NULL) {
864                 resettodr();
865         }
866 }
867
868 /*
869  * Initialize the time of day register, based on the time base which is, e.g.
870  * from a filesystem.
871  */
872 void
873 inittodr(time_t base)
874 {
875         unsigned long   sec, days;
876         int             year, month;
877         int             y, m;
878         struct timespec ts;
879
880         if (base) {
881                 ts.tv_sec = base;
882                 ts.tv_nsec = 0;
883                 set_timeofday(&ts);
884         }
885
886         /* Look if we have a RTC present and the time is valid */
887         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
888                 goto wrong_time;
889
890         /* wait for time update to complete */
891         /* If RTCSA_TUP is zero, we have at least 244us before next update */
892         crit_enter();
893         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
894                 crit_exit();
895                 crit_enter();
896         }
897
898         days = 0;
899 #ifdef USE_RTC_CENTURY
900         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
901 #else
902         year = readrtc(RTC_YEAR) + 1900;
903         if (year < 1970)
904                 year += 100;
905 #endif
906         if (year < 1970) {
907                 crit_exit();
908                 goto wrong_time;
909         }
910         month = readrtc(RTC_MONTH);
911         for (m = 1; m < month; m++)
912                 days += daysinmonth[m-1];
913         if ((month > 2) && LEAPYEAR(year))
914                 days ++;
915         days += readrtc(RTC_DAY) - 1;
916         for (y = 1970; y < year; y++)
917                 days += DAYSPERYEAR + LEAPYEAR(y);
918         sec = ((( days * 24 +
919                   readrtc(RTC_HRS)) * 60 +
920                   readrtc(RTC_MIN)) * 60 +
921                   readrtc(RTC_SEC));
922         /* sec now contains the number of seconds, since Jan 1 1970,
923            in the local time zone */
924
925         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
926
927         y = time_second - sec;
928         if (y <= -2 || y >= 2) {
929                 /* badly off, adjust it */
930                 ts.tv_sec = sec;
931                 ts.tv_nsec = 0;
932                 set_timeofday(&ts);
933         }
934         rtc_loaded = 1;
935         crit_exit();
936         return;
937
938 wrong_time:
939         kprintf("Invalid time in real time clock.\n");
940         kprintf("Check and reset the date immediately!\n");
941 }
942
943 /*
944  * Write system time back to RTC
945  */
946 void
947 resettodr(void)
948 {
949         struct timeval tv;
950         unsigned long tm;
951         int m;
952         int y;
953
954         if (disable_rtc_set)
955                 return;
956
957         microtime(&tv);
958         tm = tv.tv_sec;
959
960         crit_enter();
961         /* Disable RTC updates and interrupts. */
962         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
963
964         /* Calculate local time to put in RTC */
965
966         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
967
968         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
969         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
970         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
971
972         /* We have now the days since 01-01-1970 in tm */
973         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
974         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
975              tm >= m;
976              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
977              tm -= m;
978
979         /* Now we have the years in y and the day-of-the-year in tm */
980         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
981 #ifdef USE_RTC_CENTURY
982         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
983 #endif
984         for (m = 0; ; m++) {
985                 int ml;
986
987                 ml = daysinmonth[m];
988                 if (m == 1 && LEAPYEAR(y))
989                         ml++;
990                 if (tm < ml)
991                         break;
992                 tm -= ml;
993         }
994
995         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
996         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
997
998         /* Reenable RTC updates and interrupts. */
999         writertc(RTC_STATUSB, rtc_statusb);
1000         crit_exit();
1001 }
1002
1003 #ifdef SMP
1004
1005 static int
1006 i8254_ioapic_trial(int irq, struct cputimer_intr *cti)
1007 {
1008         sysclock_t base;
1009         long lastcnt;
1010
1011         /*
1012          * Following code assumes the 8254 is the cpu timer,
1013          * so make sure it is.
1014          */
1015         KKASSERT(sys_cputimer == &i8254_cputimer);
1016         KKASSERT(cti == &i8254_cputimer_intr);
1017
1018         lastcnt = get_interrupt_counter(irq);
1019
1020         /*
1021          * Force an 8254 Timer0 interrupt and wait 1/100s for
1022          * it to happen, then see if we got it.
1023          */
1024         kprintf("IOAPIC: testing 8254 interrupt delivery\n");
1025
1026         i8254_intr_reload(cti, 2);
1027         base = sys_cputimer->count();
1028         while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1029                 ; /* nothing */
1030
1031         if (get_interrupt_counter(irq) - lastcnt == 0)
1032                 return ENOENT;
1033         return 0;
1034 }
1035
1036 #endif  /* SMP */
1037
1038 /*
1039  * Start both clocks running.  DragonFly note: the stat clock is no longer
1040  * used.  Instead, 8254 based systimers are used for all major clock
1041  * interrupts.
1042  */
1043 static void
1044 i8254_intr_initclock(struct cputimer_intr *cti, boolean_t selected)
1045 {
1046 #ifdef SMP /* APIC-IO */
1047         void *clkdesc = NULL;
1048         int irq = 0, mixed_mode = 0, error;
1049 #endif
1050
1051         callout_init(&sysbeepstop_ch);
1052
1053         if (!selected && i8254_intr_disable)
1054                 goto nointr;
1055
1056         /*
1057          * The stat interrupt mask is different without the
1058          * statistics clock.  Also, don't set the interrupt
1059          * flag which would normally cause the RTC to generate
1060          * interrupts.
1061          */
1062         rtc_statusb = RTCSB_24HR;
1063
1064         /* Finish initializing 8253 timer 0. */
1065 #ifdef SMP /* APIC-IO */
1066         if (apic_io_enable) {
1067                 irq = ioapic_abi_find_irq(0, INTR_TRIGGER_EDGE,
1068                         INTR_POLARITY_HIGH);
1069                 if (irq < 0) {
1070 mixed_mode_setup:
1071                         error = ioapic_abi_extint_irqmap(0);
1072                         if (!error) {
1073                                 irq = ioapic_abi_find_irq(0, INTR_TRIGGER_EDGE,
1074                                         INTR_POLARITY_HIGH);
1075                                 if (irq < 0)
1076                                         error = ENOENT;
1077                         }
1078
1079                         if (error) {
1080                                 if (!selected) {
1081                                         kprintf("IOAPIC: setup mixed mode for "
1082                                                 "irq 0 failed: %d\n", error);
1083                                         goto nointr;
1084                                 } else {
1085                                         panic("IOAPIC: setup mixed mode for "
1086                                               "irq 0 failed: %d\n", error);
1087                                 }
1088                         }
1089                         mixed_mode = 1;
1090                 }
1091                 clkdesc = register_int(irq, clkintr, NULL, "clk",
1092                                        NULL,
1093                                        INTR_EXCL | INTR_CLOCK |
1094                                        INTR_NOPOLL | INTR_MPSAFE |
1095                                        INTR_NOENTROPY);
1096                 machintr_intren(irq);
1097         } else {
1098 #endif
1099         register_int(0, clkintr, NULL, "clk", NULL,
1100                      INTR_EXCL | INTR_CLOCK |
1101                      INTR_NOPOLL | INTR_MPSAFE |
1102                      INTR_NOENTROPY);
1103         machintr_intren(0);
1104 #ifdef SMP /* APIC-IO */
1105         }
1106 #endif
1107
1108         /* Initialize RTC. */
1109         writertc(RTC_STATUSA, rtc_statusa);
1110         writertc(RTC_STATUSB, RTCSB_24HR);
1111
1112 #ifdef SMP /* APIC-IO */
1113         if (apic_io_enable) {
1114                 error = i8254_ioapic_trial(irq, cti);
1115                 if (error) {
1116                         if (mixed_mode) {
1117                                 if (!selected) {
1118                                         kprintf("IOAPIC: mixed mode for irq %d "
1119                                                 "trial failed: %d\n",
1120                                                 irq, error);
1121                                         goto nointr;
1122                                 } else {
1123                                         panic("IOAPIC: mixed mode for irq %d "
1124                                               "trial failed: %d\n", irq, error);
1125                                 }
1126                         } else {
1127                                 kprintf("IOAPIC: warning 8254 is not connected "
1128                                         "to the correct pin, try mixed mode\n");
1129                                 machintr_intrdis(irq);
1130                                 unregister_int(clkdesc);
1131                                 goto mixed_mode_setup;
1132                         }
1133                 }
1134         }
1135 #endif
1136         return;
1137
1138 nointr:
1139         i8254_nointr = 1; /* don't try to register again */
1140         cputimer_intr_deregister(cti);
1141 }
1142
1143 void
1144 setstatclockrate(int newhz)
1145 {
1146         if (newhz == RTC_PROFRATE)
1147                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1148         else
1149                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1150         writertc(RTC_STATUSA, rtc_statusa);
1151 }
1152
1153 #if 0
1154 static unsigned
1155 tsc_get_timecount(struct timecounter *tc)
1156 {
1157         return (rdtsc());
1158 }
1159 #endif
1160
1161 #ifdef KERN_TIMESTAMP
1162 #define KERN_TIMESTAMP_SIZE 16384
1163 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1164 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1165         sizeof(tsc), "LU", "Kernel timestamps");
1166 void  
1167 _TSTMP(u_int32_t x)
1168 {
1169         static int i;
1170
1171         tsc[i] = (u_int32_t)rdtsc();
1172         tsc[i+1] = x;
1173         i = i + 2;
1174         if (i >= KERN_TIMESTAMP_SIZE)
1175                 i = 0;
1176         tsc[i] = 0; /* mark last entry */
1177 }
1178 #endif /* KERN_TIMESTAMP */
1179
1180 /*
1181  *
1182  */
1183
1184 static int
1185 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1186 {
1187     sysclock_t count;
1188     __uint64_t tscval;
1189     char buf[32];
1190
1191     crit_enter();
1192     if (sys_cputimer == &i8254_cputimer)
1193         count = sys_cputimer->count();
1194     else
1195         count = 0;
1196     if (tsc_present)
1197         tscval = rdtsc();
1198     else
1199         tscval = 0;
1200     crit_exit();
1201     ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1202     return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1203 }
1204
1205 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1206 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1207             "frequency");
1208 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1209             0, 0, hw_i8254_timestamp, "A", "");
1210
1211 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1212             &tsc_present, 0, "TSC Available");
1213 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1214             &tsc_frequency, 0, "TSC Frequency");
1215