Make the phase synchronization of the hz clock interrupt (I8254 timer0)
[dragonfly.git] / sys / i386 / isa / clock.c
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * William Jolitz and Don Ahn.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 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/i386/isa/Attic/clock.c,v 1.10 2004/01/08 08:11:12 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 #ifndef SMP
61 #include <sys/lock.h>
62 #endif
63 #include <sys/sysctl.h>
64 #include <sys/cons.h>
65
66 #include <machine/clock.h>
67 #ifdef CLK_CALIBRATION_LOOP
68 #endif
69 #include <machine/cputypes.h>
70 #include <machine/frame.h>
71 #include <machine/ipl.h>
72 #include <machine/limits.h>
73 #include <machine/md_var.h>
74 #include <machine/psl.h>
75 #ifdef APIC_IO
76 #include <machine/segments.h>
77 #endif
78 #if defined(SMP) || defined(APIC_IO)
79 #include <machine/smp.h>
80 #endif /* SMP || APIC_IO */
81 #include <machine/specialreg.h>
82
83 #include <i386/isa/icu.h>
84 #include <bus/isa/i386/isa.h>
85 #include <bus/isa/rtc.h>
86 #include <i386/isa/timerreg.h>
87
88 #include <i386/isa/intr_machdep.h>
89
90 #if NMCA > 0
91 #include <bus/mca/i386/mca_machdep.h>
92 #endif
93
94 #ifdef APIC_IO
95 #include <i386/isa/intr_machdep.h>
96 /* The interrupt triggered by the 8254 (timer) chip */
97 int apic_8254_intr;
98 static u_long read_intr_count (int vec);
99 static void setup_8254_mixed_mode (void);
100 #endif
101
102 /*
103  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
104  * can use a simple formula for leap years.
105  */
106 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
107 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
108
109 #define TIMER_DIV(x) (timer_freq / (x))
110 #define FRAC_ADJUST(x) (timer_freq - ((timer_freq / (x)) * (x)))
111
112 /*
113  * Time in timer cycles that it takes for microtime() to disable interrupts
114  * and latch the count.  microtime() currently uses "cli; outb ..." so it
115  * normally takes less than 2 timer cycles.  Add a few for cache misses.
116  * Add a few more to allow for latency in bogus calls to microtime() with
117  * interrupts already disabled.
118  */
119 #define TIMER0_LATCH_COUNT      20
120
121 /*
122  * Maximum frequency that we are willing to allow for timer0.  Must be
123  * low enough to guarantee that the timer interrupt handler returns
124  * before the next timer interrupt.
125  */
126 #define TIMER0_MAX_FREQ         20000
127
128 int     adjkerntz;              /* local offset from GMT in seconds */
129 int     clkintr_pending;
130 int     disable_rtc_set;        /* disable resettodr() if != 0 */
131 volatile u_int  idelayed;
132 int     statclock_disable;
133 u_int   stat_imask = SWI_CLOCK_MASK;
134 #ifndef TIMER_FREQ
135 #define TIMER_FREQ   1193182
136 #endif
137 u_int   timer_freq = TIMER_FREQ;
138 int     timer0_max_count;
139 u_int   timer0_frac_freq;
140 u_int   tsc_freq;
141 int     tsc_is_broken;
142 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
143
144 static  int     beeping = 0;
145 static  u_int   clk_imask = HWI_MASK | SWI_MASK;
146 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
147 static  u_int   hardclock_max_count;
148 static  u_int32_t i8254_lastcount;
149 static  u_int32_t i8254_offset;
150 static  int     i8254_ticked;
151 /*
152  * XXX new_function and timer_func should not handle clockframes, but
153  * timer_func currently needs to hold hardclock to handle the
154  * timer0_state == 0 case.  We should use inthand_add()/inthand_remove()
155  * to switch between clkintr() and a slightly different timerintr().
156  */
157 static  void    (*new_function) (struct clockframe *frame);
158 static  u_int   new_rate;
159 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
160 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
161 static  u_int   timer0_prescaler_count;
162
163 /* Values for timerX_state: */
164 #define RELEASED        0
165 #define RELEASE_PENDING 1
166 #define ACQUIRED        2
167 #define ACQUIRE_PENDING 3
168
169 static  u_char  timer0_state;
170 static  u_char  timer2_state;
171 static  void    (*timer_func) (struct clockframe *frame) = hardclock;
172 static  u_int   tsc_present;
173
174 static  unsigned i8254_get_timecount (struct timecounter *tc);
175 static  unsigned tsc_get_timecount (struct timecounter *tc);
176 static  void    set_timer_freq(u_int freq, int intr_freq);
177
178 static struct timecounter tsc_timecounter = {
179         tsc_get_timecount,      /* get_timecount */
180         0,                      /* no poll_pps */
181         ~0u,                    /* counter_mask */
182         0,                      /* frequency */
183          "TSC"                  /* name */
184 };
185
186 SYSCTL_OPAQUE(_debug, OID_AUTO, tsc_timecounter, CTLFLAG_RD, 
187         &tsc_timecounter, sizeof(tsc_timecounter), "S,timecounter", "");
188
189 static struct timecounter i8254_timecounter = {
190         i8254_get_timecount,    /* get_timecount */
191         0,                      /* no poll_pps */
192         ~0u,                    /* counter_mask */
193         0,                      /* frequency */
194         "i8254"                 /* name */
195 };
196
197 SYSCTL_OPAQUE(_debug, OID_AUTO, i8254_timecounter, CTLFLAG_RD, 
198         &i8254_timecounter, sizeof(i8254_timecounter), "S,timecounter", "");
199
200 static void
201 clkintr(struct clockframe frame)
202 {
203         int phase;
204         int delta;
205
206         if (timecounter->tc_get_timecount == i8254_get_timecount) {
207                 clock_lock();
208                 if (i8254_ticked) {
209                         i8254_ticked = 0;
210                 } else {
211                         i8254_offset += timer0_max_count;
212                         i8254_lastcount = 0;
213                 }
214                 /*
215                  * Lets say we are running at 100Hz.  Our counter load will
216                  * be 1193182 / 100 = 11931.82, which is really only 11931.
217                  * The fractional code accounts for the .82 count.  When it
218                  * exceeds 1.00 count we adjust the reload register by + 1
219                  * to compensate for the error.  We must also adjust 
220                  * i8254_offset.
221                  *
222                  * If we did not do this a high frequency would cause the
223                  * actual interrupt rate to seriously diverge from 'hz'.
224                  */
225                 clkintr_pending = 0;
226                 clock_unlock();
227         }
228
229         /*
230          * Use the previously synchronized timecounter value to phase-sync
231          * our hz clock interrupt.  We do this by reloading the initial count
232          * register of timer0, which takes effect the next time it reloads.
233          */
234         phase = 1000000 / timer0_frac_freq;
235         delta = timecounter->tc_microtime.tv_usec % phase;
236 #if 1
237         clock_lock();
238         if (delta < (phase >> 1)) {
239                 /*
240                  * Current time is a bit past what we expect, speed up the
241                  * clock interrupt.
242                  */
243                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
244                 outb(TIMER_CNTR0, timer0_max_count >> 8);
245         } else {
246                 /*
247                  * Current time is a bit before what we expect, slow down
248                  * the clock interrupt.
249                  */
250                 outb(TIMER_CNTR0, (timer0_max_count + 1) & 0xff);
251                 outb(TIMER_CNTR0, (timer0_max_count + 1) >> 8);
252                 ++i8254_offset; /* take into account extra count for tc==8254*/
253         }
254         clock_unlock();
255 #endif
256
257         timer_func(&frame);
258
259         switch (timer0_state) {
260         case RELEASED:
261                 setdelayed();
262                 break;
263         case ACQUIRED:
264                 timer0_prescaler_count += timer0_max_count;
265                 if (timer0_prescaler_count >= hardclock_max_count) {
266                         timer0_prescaler_count -= hardclock_max_count;
267                         hardclock(&frame);
268                         setdelayed();
269                 }
270                 break;
271         case ACQUIRE_PENDING:
272                 clock_lock();
273                 i8254_offset = i8254_get_timecount(NULL);
274                 i8254_lastcount = 0;
275                 timer0_max_count = TIMER_DIV(new_rate);
276                 timer0_frac_freq = new_rate;
277                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
278                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
279                 outb(TIMER_CNTR0, timer0_max_count >> 8);
280                 clock_unlock();
281                 timer_func = new_function;
282                 timer0_state = ACQUIRED;
283                 setdelayed();
284                 break;
285         case RELEASE_PENDING:
286                 timer0_prescaler_count += timer0_max_count;
287                 if (timer0_prescaler_count >= hardclock_max_count) {
288                         clock_lock();
289                         i8254_offset = i8254_get_timecount(NULL);
290                         i8254_lastcount = 0;
291                         timer0_max_count = hardclock_max_count;
292                         outb(TIMER_MODE,
293                              TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
294                         outb(TIMER_CNTR0, timer0_max_count & 0xff);
295                         outb(TIMER_CNTR0, timer0_max_count >> 8);
296                         clock_unlock();
297                         timer0_prescaler_count = 0;
298                         timer_func = hardclock;
299                         timer0_state = RELEASED;
300                         hardclock(&frame);
301                         setdelayed();
302                 }
303                 break;
304         }
305 #if NMCA > 0
306         /* Reset clock interrupt by asserting bit 7 of port 0x61 */
307         if (MCA_system)
308                 outb(0x61, inb(0x61) | 0x80);
309 #endif
310 }
311
312 /*
313  * The acquire and release functions must be called at ipl >= splclock().
314  */
315 int
316 acquire_timer0(int rate, void (*function) (struct clockframe *frame))
317 {
318         static int old_rate;
319
320         if (rate <= 0 || rate > TIMER0_MAX_FREQ)
321                 return (-1);
322         switch (timer0_state) {
323
324         case RELEASED:
325                 timer0_state = ACQUIRE_PENDING;
326                 break;
327
328         case RELEASE_PENDING:
329                 if (rate != old_rate)
330                         return (-1);
331                 /*
332                  * The timer has been released recently, but is being
333                  * re-acquired before the release completed.  In this
334                  * case, we simply reclaim it as if it had not been
335                  * released at all.
336                  */
337                 timer0_state = ACQUIRED;
338                 break;
339
340         default:
341                 return (-1);    /* busy */
342         }
343         new_function = function;
344         old_rate = new_rate = rate;
345         return (0);
346 }
347
348 int
349 acquire_timer2(int mode)
350 {
351
352         if (timer2_state != RELEASED)
353                 return (-1);
354         timer2_state = ACQUIRED;
355
356         /*
357          * This access to the timer registers is as atomic as possible
358          * because it is a single instruction.  We could do better if we
359          * knew the rate.  Use of splclock() limits glitches to 10-100us,
360          * and this is probably good enough for timer2, so we aren't as
361          * careful with it as with timer0.
362          */
363         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
364
365         return (0);
366 }
367
368 int
369 release_timer0()
370 {
371         switch (timer0_state) {
372
373         case ACQUIRED:
374                 timer0_state = RELEASE_PENDING;
375                 break;
376
377         case ACQUIRE_PENDING:
378                 /* Nothing happened yet, release quickly. */
379                 timer0_state = RELEASED;
380                 break;
381
382         default:
383                 return (-1);
384         }
385         return (0);
386 }
387
388 int
389 release_timer2()
390 {
391
392         if (timer2_state != ACQUIRED)
393                 return (-1);
394         timer2_state = RELEASED;
395         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
396         return (0);
397 }
398
399 /*
400  * This routine receives statistical clock interrupts from the RTC.
401  * As explained above, these occur at 128 interrupts per second.
402  * When profiling, we receive interrupts at a rate of 1024 Hz.
403  *
404  * This does not actually add as much overhead as it sounds, because
405  * when the statistical clock is active, the hardclock driver no longer
406  * needs to keep (inaccurate) statistics on its own.  This decouples
407  * statistics gathering from scheduling interrupts.
408  *
409  * The RTC chip requires that we read status register C (RTC_INTR)
410  * to acknowledge an interrupt, before it will generate the next one.
411  * Under high interrupt load, rtcintr() can be indefinitely delayed and
412  * the clock can tick immediately after the read from RTC_INTR.  In this
413  * case, the mc146818A interrupt signal will not drop for long enough
414  * to register with the 8259 PIC.  If an interrupt is missed, the stat
415  * clock will halt, considerably degrading system performance.  This is
416  * why we use 'while' rather than a more straightforward 'if' below.
417  * Stat clock ticks can still be lost, causing minor loss of accuracy
418  * in the statistics, but the stat clock will no longer stop.
419  */
420 static void
421 rtcintr(struct clockframe frame)
422 {
423         while (rtcin(RTC_INTR) & RTCIR_PERIOD)
424                 statclock(&frame);
425 }
426
427 #include "opt_ddb.h"
428 #ifdef DDB
429 #include <ddb/ddb.h>
430
431 DB_SHOW_COMMAND(rtc, rtc)
432 {
433         printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
434                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
435                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
436                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
437 }
438 #endif /* DDB */
439
440 static int
441 getit(void)
442 {
443         int high, low;
444
445         clock_lock();
446
447         /* Select timer0 and latch counter value. */
448         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
449
450         low = inb(TIMER_CNTR0);
451         high = inb(TIMER_CNTR0);
452
453         clock_unlock();
454         return ((high << 8) | low);
455 }
456
457 /*
458  * Wait "n" microseconds.
459  * Relies on timer 1 counting down from (timer_freq / hz)
460  * Note: timer had better have been programmed before this is first used!
461  */
462 void
463 DELAY(int n)
464 {
465         int delta, prev_tick, tick, ticks_left;
466
467 #ifdef DELAYDEBUG
468         int getit_calls = 1;
469         int n1;
470         static int state = 0;
471
472         if (state == 0) {
473                 state = 1;
474                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
475                         DELAY(n1);
476                 state = 2;
477         }
478         if (state == 1)
479                 printf("DELAY(%d)...", n);
480 #endif
481         /*
482          * Guard against the timer being uninitialized if we are called
483          * early for console i/o.
484          */
485         if (timer0_max_count == 0)
486                 set_timer_freq(timer_freq, hz);
487
488         /*
489          * Read the counter first, so that the rest of the setup overhead is
490          * counted.  Guess the initial overhead is 20 usec (on most systems it
491          * takes about 1.5 usec for each of the i/o's in getit().  The loop
492          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
493          * multiplications and divisions to scale the count take a while).
494          */
495         prev_tick = getit();
496         n -= 0;                 /* XXX actually guess no initial overhead */
497         /*
498          * Calculate (n * (timer_freq / 1e6)) without using floating point
499          * and without any avoidable overflows.
500          */
501         if (n <= 0)
502                 ticks_left = 0;
503         else if (n < 256)
504                 /*
505                  * Use fixed point to avoid a slow division by 1000000.
506                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
507                  * 2^15 is the first power of 2 that gives exact results
508                  * for n between 0 and 256.
509                  */
510                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
511         else
512                 /*
513                  * Don't bother using fixed point, although gcc-2.7.2
514                  * generates particularly poor code for the long long
515                  * division, since even the slow way will complete long
516                  * before the delay is up (unless we're interrupted).
517                  */
518                 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
519                              / 1000000;
520
521         while (ticks_left > 0) {
522                 tick = getit();
523 #ifdef DELAYDEBUG
524                 ++getit_calls;
525 #endif
526                 delta = prev_tick - tick;
527                 prev_tick = tick;
528                 if (delta < 0) {
529                         delta += timer0_max_count;
530                         /*
531                          * Guard against timer0_max_count being wrong.
532                          * This shouldn't happen in normal operation,
533                          * but it may happen if set_timer_freq() is
534                          * traced.
535                          */
536                         if (delta < 0)
537                                 delta = 0;
538                 }
539                 ticks_left -= delta;
540         }
541 #ifdef DELAYDEBUG
542         if (state == 1)
543                 printf(" %d calls to getit() at %d usec each\n",
544                        getit_calls, (n + 5) / getit_calls);
545 #endif
546 }
547
548 static void
549 sysbeepstop(void *chan)
550 {
551         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
552         release_timer2();
553         beeping = 0;
554 }
555
556 int
557 sysbeep(int pitch, int period)
558 {
559         int x = splclock();
560
561         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
562                 if (!beeping) {
563                         /* Something else owns it. */
564                         splx(x);
565                         return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
566                 }
567         clock_lock();
568         outb(TIMER_CNTR2, pitch);
569         outb(TIMER_CNTR2, (pitch>>8));
570         clock_unlock();
571         if (!beeping) {
572                 /* enable counter2 output to speaker */
573                 outb(IO_PPI, inb(IO_PPI) | 3);
574                 beeping = period;
575                 timeout(sysbeepstop, (void *)NULL, period);
576         }
577         splx(x);
578         return (0);
579 }
580
581 /*
582  * RTC support routines
583  */
584
585 int
586 rtcin(reg)
587         int reg;
588 {
589         int s;
590         u_char val;
591
592         s = splhigh();
593         outb(IO_RTC, reg);
594         inb(0x84);
595         val = inb(IO_RTC + 1);
596         inb(0x84);
597         splx(s);
598         return (val);
599 }
600
601 static __inline void
602 writertc(u_char reg, u_char val)
603 {
604         int s;
605
606         s = splhigh();
607         inb(0x84);
608         outb(IO_RTC, reg);
609         inb(0x84);
610         outb(IO_RTC + 1, val);
611         inb(0x84);              /* XXX work around wrong order in rtcin() */
612         splx(s);
613 }
614
615 static __inline int
616 readrtc(int port)
617 {
618         return(bcd2bin(rtcin(port)));
619 }
620
621 static u_int
622 calibrate_clocks(void)
623 {
624         u_int64_t old_tsc;
625         u_int count, prev_count, tot_count;
626         int sec, start_sec, timeout;
627
628         if (bootverbose)
629                 printf("Calibrating clock(s) ... ");
630         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
631                 goto fail;
632         timeout = 100000000;
633
634         /* Read the mc146818A seconds counter. */
635         for (;;) {
636                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
637                         sec = rtcin(RTC_SEC);
638                         break;
639                 }
640                 if (--timeout == 0)
641                         goto fail;
642         }
643
644         /* Wait for the mC146818A seconds counter to change. */
645         start_sec = sec;
646         for (;;) {
647                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
648                         sec = rtcin(RTC_SEC);
649                         if (sec != start_sec)
650                                 break;
651                 }
652                 if (--timeout == 0)
653                         goto fail;
654         }
655
656         /* Start keeping track of the i8254 counter. */
657         prev_count = getit();
658         if (prev_count == 0 || prev_count > timer0_max_count)
659                 goto fail;
660         tot_count = 0;
661
662         if (tsc_present) 
663                 old_tsc = rdtsc();
664         else
665                 old_tsc = 0;            /* shut up gcc */
666
667         /*
668          * Wait for the mc146818A seconds counter to change.  Read the i8254
669          * counter for each iteration since this is convenient and only
670          * costs a few usec of inaccuracy. The timing of the final reads
671          * of the counters almost matches the timing of the initial reads,
672          * so the main cause of inaccuracy is the varying latency from 
673          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
674          * rtcin(RTC_SEC) that returns a changed seconds count.  The
675          * maximum inaccuracy from this cause is < 10 usec on 486's.
676          */
677         start_sec = sec;
678         for (;;) {
679                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
680                         sec = rtcin(RTC_SEC);
681                 count = getit();
682                 if (count == 0 || count > timer0_max_count)
683                         goto fail;
684                 if (count > prev_count)
685                         tot_count += prev_count - (count - timer0_max_count);
686                 else
687                         tot_count += prev_count - count;
688                 prev_count = count;
689                 if (sec != start_sec)
690                         break;
691                 if (--timeout == 0)
692                         goto fail;
693         }
694
695         /*
696          * Read the cpu cycle counter.  The timing considerations are
697          * similar to those for the i8254 clock.
698          */
699         if (tsc_present) 
700                 tsc_freq = rdtsc() - old_tsc;
701
702         if (bootverbose) {
703                 if (tsc_present)
704                         printf("TSC clock: %u Hz, ", tsc_freq);
705                 printf("i8254 clock: %u Hz\n", tot_count);
706         }
707         return (tot_count);
708
709 fail:
710         if (bootverbose)
711                 printf("failed, using default i8254 clock of %u Hz\n",
712                        timer_freq);
713         return (timer_freq);
714 }
715
716 static void
717 set_timer_freq(u_int freq, int intr_freq)
718 {
719         int new_timer0_max_count;
720
721         clock_lock();
722         timer_freq = freq;
723         new_timer0_max_count = hardclock_max_count = TIMER_DIV(intr_freq);
724         timer0_frac_freq = intr_freq;
725         if (new_timer0_max_count != timer0_max_count) {
726                 timer0_max_count = new_timer0_max_count;
727                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
728                 outb(TIMER_CNTR0, timer0_max_count & 0xff);
729                 outb(TIMER_CNTR0, timer0_max_count >> 8);
730         }
731         clock_unlock();
732 }
733
734 static void
735 i8254_restore(void)
736 {
737         clock_lock();
738         outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
739         outb(TIMER_CNTR0, timer0_max_count & 0xff);
740         outb(TIMER_CNTR0, timer0_max_count >> 8);
741         clock_unlock();
742 }
743
744 static void
745 rtc_restore(void)
746 {
747
748         /* Restore all of the RTC's "status" (actually, control) registers. */
749         writertc(RTC_STATUSB, RTCSB_24HR);
750         writertc(RTC_STATUSA, rtc_statusa);
751         writertc(RTC_STATUSB, rtc_statusb);
752 }
753
754 /*
755  * Restore all the timers non-atomically (XXX: should be atomically).
756  *
757  * This function is called from apm_default_resume() to restore all the timers.
758  * This should not be necessary, but there are broken laptops that do not
759  * restore all the timers on resume.
760  */
761 void
762 timer_restore(void)
763 {
764
765         i8254_restore();                /* restore timer_freq and hz */
766         rtc_restore();                  /* reenable RTC interrupts */
767 }
768
769 /*
770  * Initialize 8254 timer 0 early so that it can be used in DELAY().
771  * XXX initialization of other timers is unintentionally left blank.
772  */
773 void
774 startrtclock()
775 {
776         u_int delta, freq;
777
778         if (cpu_feature & CPUID_TSC)
779                 tsc_present = 1;
780         else
781                 tsc_present = 0;
782
783         writertc(RTC_STATUSA, rtc_statusa);
784         writertc(RTC_STATUSB, RTCSB_24HR);
785
786         set_timer_freq(timer_freq, hz);
787         freq = calibrate_clocks();
788 #ifdef CLK_CALIBRATION_LOOP
789         if (bootverbose) {
790                 printf(
791                 "Press a key on the console to abort clock calibration\n");
792                 while (cncheckc() == -1)
793                         calibrate_clocks();
794         }
795 #endif
796
797         /*
798          * Use the calibrated i8254 frequency if it seems reasonable.
799          * Otherwise use the default, and don't use the calibrated i586
800          * frequency.
801          */
802         delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
803         if (delta < timer_freq / 100) {
804 #ifndef CLK_USE_I8254_CALIBRATION
805                 if (bootverbose)
806                         printf(
807 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
808                 freq = timer_freq;
809 #endif
810                 timer_freq = freq;
811         } else {
812                 if (bootverbose)
813                         printf(
814                     "%d Hz differs from default of %d Hz by more than 1%%\n",
815                                freq, timer_freq);
816                 tsc_freq = 0;
817         }
818
819         set_timer_freq(timer_freq, hz);
820         i8254_timecounter.tc_frequency = timer_freq;
821         init_timecounter(&i8254_timecounter);
822
823 #ifndef CLK_USE_TSC_CALIBRATION
824         if (tsc_freq != 0) {
825                 if (bootverbose)
826                         printf(
827 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
828                 tsc_freq = 0;
829         }
830 #endif
831         if (tsc_present && tsc_freq == 0) {
832                 /*
833                  * Calibration of the i586 clock relative to the mc146818A
834                  * clock failed.  Do a less accurate calibration relative
835                  * to the i8254 clock.
836                  */
837                 u_int64_t old_tsc = rdtsc();
838
839                 DELAY(1000000);
840                 tsc_freq = rdtsc() - old_tsc;
841 #ifdef CLK_USE_TSC_CALIBRATION
842                 if (bootverbose)
843                         printf("TSC clock: %u Hz (Method B)\n", tsc_freq);
844 #endif
845         }
846
847 #if !defined(SMP)
848         /*
849          * We can not use the TSC in SMP mode, until we figure out a
850          * cheap (impossible), reliable and precise (yeah right!)  way
851          * to synchronize the TSCs of all the CPUs.
852          * Curse Intel for leaving the counter out of the I/O APIC.
853          */
854
855 #if NAPM > 0
856         /*
857          * We can not use the TSC if we support APM. Precise timekeeping
858          * on an APM'ed machine is at best a fools pursuit, since 
859          * any and all of the time spent in various SMM code can't 
860          * be reliably accounted for.  Reading the RTC is your only
861          * source of reliable time info.  The i8254 looses too of course
862          * but we need to have some kind of time...
863          * We don't know at this point whether APM is going to be used
864          * or not, nor when it might be activated.  Play it safe.
865          */
866         return;
867 #endif /* NAPM > 0 */
868
869         if (tsc_present && tsc_freq != 0 && !tsc_is_broken) {
870                 tsc_timecounter.tc_frequency = tsc_freq;
871                 init_timecounter(&tsc_timecounter);
872         }
873
874 #endif /* !defined(SMP) */
875 }
876
877 /*
878  * Initialize the time of day register, based on the time base which is, e.g.
879  * from a filesystem.
880  */
881 void
882 inittodr(time_t base)
883 {
884         unsigned long   sec, days;
885         int             yd;
886         int             year, month;
887         int             y, m, s;
888         struct timespec ts;
889
890         if (base) {
891                 s = splclock();
892                 ts.tv_sec = base;
893                 ts.tv_nsec = 0;
894                 set_timecounter(&ts);
895                 splx(s);
896         }
897
898         /* Look if we have a RTC present and the time is valid */
899         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
900                 goto wrong_time;
901
902         /* wait for time update to complete */
903         /* If RTCSA_TUP is zero, we have at least 244us before next update */
904         s = splhigh();
905         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
906                 splx(s);
907                 s = splhigh();
908         }
909
910         days = 0;
911 #ifdef USE_RTC_CENTURY
912         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
913 #else
914         year = readrtc(RTC_YEAR) + 1900;
915         if (year < 1970)
916                 year += 100;
917 #endif
918         if (year < 1970) {
919                 splx(s);
920                 goto wrong_time;
921         }
922         month = readrtc(RTC_MONTH);
923         for (m = 1; m < month; m++)
924                 days += daysinmonth[m-1];
925         if ((month > 2) && LEAPYEAR(year))
926                 days ++;
927         days += readrtc(RTC_DAY) - 1;
928         yd = days;
929         for (y = 1970; y < year; y++)
930                 days += DAYSPERYEAR + LEAPYEAR(y);
931         sec = ((( days * 24 +
932                   readrtc(RTC_HRS)) * 60 +
933                   readrtc(RTC_MIN)) * 60 +
934                   readrtc(RTC_SEC));
935         /* sec now contains the number of seconds, since Jan 1 1970,
936            in the local time zone */
937
938         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
939
940         y = time_second - sec;
941         if (y <= -2 || y >= 2) {
942                 /* badly off, adjust it */
943                 ts.tv_sec = sec;
944                 ts.tv_nsec = 0;
945                 set_timecounter(&ts);
946         }
947         splx(s);
948         return;
949
950 wrong_time:
951         printf("Invalid time in real time clock.\n");
952         printf("Check and reset the date immediately!\n");
953 }
954
955 /*
956  * Write system time back to RTC
957  */
958 void
959 resettodr()
960 {
961         unsigned long   tm;
962         int             y, m, s;
963
964         if (disable_rtc_set)
965                 return;
966
967         s = splclock();
968         tm = time_second;
969         splx(s);
970
971         /* Disable RTC updates and interrupts. */
972         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
973
974         /* Calculate local time to put in RTC */
975
976         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
977
978         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
979         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
980         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
981
982         /* We have now the days since 01-01-1970 in tm */
983         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
984         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
985              tm >= m;
986              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
987              tm -= m;
988
989         /* Now we have the years in y and the day-of-the-year in tm */
990         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
991 #ifdef USE_RTC_CENTURY
992         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
993 #endif
994         for (m = 0; ; m++) {
995                 int ml;
996
997                 ml = daysinmonth[m];
998                 if (m == 1 && LEAPYEAR(y))
999                         ml++;
1000                 if (tm < ml)
1001                         break;
1002                 tm -= ml;
1003         }
1004
1005         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
1006         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
1007
1008         /* Reenable RTC updates and interrupts. */
1009         writertc(RTC_STATUSB, rtc_statusb);
1010 }
1011
1012
1013 /*
1014  * Start both clocks running.
1015  */
1016 void
1017 cpu_initclocks()
1018 {
1019         int diag;
1020 #ifdef APIC_IO
1021         int apic_8254_trial;
1022         struct intrec *clkdesc;
1023 #endif /* APIC_IO */
1024
1025         if (statclock_disable) {
1026                 /*
1027                  * The stat interrupt mask is different without the
1028                  * statistics clock.  Also, don't set the interrupt
1029                  * flag which would normally cause the RTC to generate
1030                  * interrupts.
1031                  */
1032                 stat_imask = HWI_MASK | SWI_MASK;
1033                 rtc_statusb = RTCSB_24HR;
1034         } else {
1035                 /* Setting stathz to nonzero early helps avoid races. */
1036                 stathz = RTC_NOPROFRATE;
1037                 profhz = RTC_PROFRATE;
1038         }
1039
1040         /* Finish initializing 8253 timer 0. */
1041 #ifdef APIC_IO
1042
1043         apic_8254_intr = isa_apic_irq(0);
1044         apic_8254_trial = 0;
1045         if (apic_8254_intr >= 0 ) {
1046                 if (apic_int_type(0, 0) == 3)
1047                         apic_8254_trial = 1;
1048         } else {
1049                 /* look for ExtInt on pin 0 */
1050                 if (apic_int_type(0, 0) == 3) {
1051                         apic_8254_intr = apic_irq(0, 0);
1052                         setup_8254_mixed_mode();
1053                 } else 
1054                         panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1055         }
1056
1057         clkdesc = inthand_add("clk", apic_8254_intr, (inthand2_t *)clkintr,
1058                               NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1059         INTREN(1 << apic_8254_intr);
1060         
1061 #else /* APIC_IO */
1062
1063         inthand_add("clk", 0, (inthand2_t *)clkintr, NULL, &clk_imask,
1064                     INTR_EXCL | INTR_FAST);
1065         INTREN(IRQ0);
1066
1067 #endif /* APIC_IO */
1068
1069         /* Initialize RTC. */
1070         writertc(RTC_STATUSA, rtc_statusa);
1071         writertc(RTC_STATUSB, RTCSB_24HR);
1072
1073         /* Don't bother enabling the statistics clock. */
1074         if (statclock_disable)
1075                 return;
1076         diag = rtcin(RTC_DIAG);
1077         if (diag != 0)
1078                 printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1079
1080 #ifdef APIC_IO
1081         if (isa_apic_irq(8) != 8)
1082                 panic("APIC RTC != 8");
1083 #endif /* APIC_IO */
1084
1085         inthand_add("rtc", 8, (inthand2_t *)rtcintr, NULL, &stat_imask,
1086                     INTR_EXCL | INTR_FAST);
1087
1088 #ifdef APIC_IO
1089         INTREN(APIC_IRQ8);
1090 #else
1091         INTREN(IRQ8);
1092 #endif /* APIC_IO */
1093
1094         writertc(RTC_STATUSB, rtc_statusb);
1095
1096 #ifdef APIC_IO
1097         if (apic_8254_trial) {
1098                 
1099                 printf("APIC_IO: Testing 8254 interrupt delivery\n");
1100                 while (read_intr_count(8) < 6)
1101                         ;       /* nothing */
1102                 if (read_intr_count(apic_8254_intr) < 3) {
1103                         /* 
1104                          * The MP table is broken.
1105                          * The 8254 was not connected to the specified pin
1106                          * on the IO APIC.
1107                          * Workaround: Limited variant of mixed mode.
1108                          */
1109                         INTRDIS(1 << apic_8254_intr);
1110                         inthand_remove(clkdesc);
1111                         printf("APIC_IO: Broken MP table detected: "
1112                                "8254 is not connected to "
1113                                "IOAPIC #%d intpin %d\n",
1114                                int_to_apicintpin[apic_8254_intr].ioapic,
1115                                int_to_apicintpin[apic_8254_intr].int_pin);
1116                         /* 
1117                          * Revoke current ISA IRQ 0 assignment and 
1118                          * configure a fallback interrupt routing from
1119                          * the 8254 Timer via the 8259 PIC to the
1120                          * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1121                          * We reuse the low level interrupt handler number.
1122                          */
1123                         if (apic_irq(0, 0) < 0) {
1124                                 revoke_apic_irq(apic_8254_intr);
1125                                 assign_apic_irq(0, 0, apic_8254_intr);
1126                         }
1127                         apic_8254_intr = apic_irq(0, 0);
1128                         setup_8254_mixed_mode();
1129                         inthand_add("clk", apic_8254_intr,
1130                                     (inthand2_t *)clkintr,
1131                                     NULL, &clk_imask, INTR_EXCL | INTR_FAST);
1132                         INTREN(1 << apic_8254_intr);
1133                 }
1134                 
1135         }
1136         if (apic_int_type(0, 0) != 3 ||
1137             int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1138             int_to_apicintpin[apic_8254_intr].int_pin != 0)
1139                 printf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1140                        int_to_apicintpin[apic_8254_intr].ioapic,
1141                        int_to_apicintpin[apic_8254_intr].int_pin);
1142         else
1143                 printf("APIC_IO: "
1144                        "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1145 #endif
1146         
1147 }
1148
1149 #ifdef APIC_IO
1150 static u_long
1151 read_intr_count(int vec)
1152 {
1153         u_long *up;
1154         up = intr_countp[vec];
1155         if (up)
1156                 return *up;
1157         return 0UL;
1158 }
1159
1160 static void 
1161 setup_8254_mixed_mode()
1162 {
1163         /*
1164          * Allow 8254 timer to INTerrupt 8259:
1165          *  re-initialize master 8259:
1166          *   reset; prog 4 bytes, single ICU, edge triggered
1167          */
1168         outb(IO_ICU1, 0x13);
1169         outb(IO_ICU1 + 1, NRSVIDT);     /* start vector (unused) */
1170         outb(IO_ICU1 + 1, 0x00);        /* ignore slave */
1171         outb(IO_ICU1 + 1, 0x03);        /* auto EOI, 8086 */
1172         outb(IO_ICU1 + 1, 0xfe);        /* unmask INT0 */
1173         
1174         /* program IO APIC for type 3 INT on INT0 */
1175         if (ext_int_setup(0, 0) < 0)
1176                 panic("8254 redirect via APIC pin0 impossible!");
1177 }
1178 #endif
1179
1180 void
1181 setstatclockrate(int newhz)
1182 {
1183         if (newhz == RTC_PROFRATE)
1184                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1185         else
1186                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1187         writertc(RTC_STATUSA, rtc_statusa);
1188 }
1189
1190 static int
1191 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
1192 {
1193         int error;
1194         u_int freq;
1195
1196         /*
1197          * Use `i8254' instead of `timer' in external names because `timer'
1198          * is is too generic.  Should use it everywhere.
1199          */
1200         freq = timer_freq;
1201         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1202         if (error == 0 && req->newptr != NULL) {
1203                 if (timer0_state != RELEASED)
1204                         return (EBUSY); /* too much trouble to handle */
1205                 set_timer_freq(freq, hz);
1206                 i8254_timecounter.tc_frequency = freq;
1207                 update_timecounter(&i8254_timecounter);
1208         }
1209         return (error);
1210 }
1211
1212 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
1213     0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
1214
1215 static int
1216 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
1217 {
1218         int error;
1219         u_int freq;
1220
1221         if (tsc_timecounter.tc_frequency == 0)
1222                 return (EOPNOTSUPP);
1223         freq = tsc_freq;
1224         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
1225         if (error == 0 && req->newptr != NULL) {
1226                 tsc_freq = freq;
1227                 tsc_timecounter.tc_frequency = tsc_freq;
1228                 update_timecounter(&tsc_timecounter);
1229         }
1230         return (error);
1231 }
1232
1233 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_INT | CTLFLAG_RW,
1234     0, sizeof(u_int), sysctl_machdep_tsc_freq, "IU", "");
1235
1236 static unsigned
1237 i8254_get_timecount(struct timecounter *tc)
1238 {
1239         u_int count;
1240         u_long ef;
1241         u_int high, low;
1242
1243         ef = read_eflags();
1244         clock_lock();
1245
1246         /* 
1247          * Select timer0 and latch counter value.   Because we may reload
1248          * the counter with timer0_max_count + 1 to correct the frequency
1249          * our delta count calculation must use timer0_max_count + 1.
1250          */
1251         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
1252
1253         low = inb(TIMER_CNTR0);
1254         high = inb(TIMER_CNTR0);
1255         count = timer0_max_count + 1 - ((high << 8) | low);
1256         if (count < i8254_lastcount ||
1257             (!i8254_ticked && (clkintr_pending ||
1258             ((count < 20 || (!(ef & PSL_I) && count < timer0_max_count / 2u)) &&
1259 #ifdef APIC_IO
1260 #define lapic_irr1      ((volatile u_int *)&lapic)[0x210 / 4]   /* XXX XXX */
1261             /* XXX this assumes that apic_8254_intr is < 24. */
1262             (lapic_irr1 & (1 << apic_8254_intr))))
1263 #else
1264             (inb(IO_ICU1) & 1)))
1265 #endif
1266             )) {
1267                 i8254_ticked = 1;
1268                 i8254_offset += timer0_max_count;
1269         }
1270         i8254_lastcount = count;
1271         count += i8254_offset;
1272         clock_unlock();
1273         return (count);
1274 }
1275
1276 static unsigned
1277 tsc_get_timecount(struct timecounter *tc)
1278 {
1279         return (rdtsc());
1280 }
1281
1282 #ifdef KERN_TIMESTAMP
1283 #define KERN_TIMESTAMP_SIZE 16384
1284 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1285 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1286         sizeof(tsc), "LU", "Kernel timestamps");
1287 void  
1288 _TSTMP(u_int32_t x)
1289 {
1290         static int i;
1291
1292         tsc[i] = (u_int32_t)rdtsc();
1293         tsc[i+1] = x;
1294         i = i + 2;
1295         if (i >= KERN_TIMESTAMP_SIZE)
1296                 i = 0;
1297         tsc[i] = 0; /* mark last entry */
1298 }
1299 #endif /* KERN_TIMESTAMP */
1300