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