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