]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/amd64/isa/clock.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / amd64 / 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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)clock.c       7.2 (Berkeley) 5/12/91
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 /*
39  * Routines to handle clock hardware.
40  */
41
42 /*
43  * inittodr, settodr and support routines written
44  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
45  *
46  * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
47  */
48
49 #include "opt_clock.h"
50 #include "opt_isa.h"
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/bus.h>
55 #include <sys/clock.h>
56 #include <sys/conf.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/kdb.h>
60 #include <sys/mutex.h>
61 #include <sys/proc.h>
62 #include <sys/time.h>
63 #include <sys/timetc.h>
64 #include <sys/uio.h>
65 #include <sys/kernel.h>
66 #include <sys/limits.h>
67 #include <sys/module.h>
68 #include <sys/sched.h>
69 #include <sys/sysctl.h>
70 #include <sys/cons.h>
71 #include <sys/power.h>
72
73 #include <machine/clock.h>
74 #include <machine/cpu.h>
75 #include <machine/frame.h>
76 #include <machine/intr_machdep.h>
77 #include <machine/md_var.h>
78 #include <machine/psl.h>
79 #include <machine/apicvar.h>
80 #include <machine/specialreg.h>
81 #include <machine/ppireg.h>
82 #include <machine/timerreg.h>
83
84 #include <isa/rtc.h>
85 #ifdef DEV_ISA
86 #include <isa/isareg.h>
87 #include <isa/isavar.h>
88 #endif
89
90 /*
91  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
92  * can use a simple formula for leap years.
93  */
94 #define LEAPYEAR(y) (((u_int)(y) % 4 == 0) ? 1 : 0)
95 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
96
97 #define TIMER_DIV(x) ((timer_freq + (x) / 2) / (x))
98
99 int     clkintr_pending;
100 int     pscnt = 1;
101 int     psdiv = 1;
102 int     statclock_disable;
103 #ifndef TIMER_FREQ
104 #define TIMER_FREQ   1193182
105 #endif
106 u_int   timer_freq = TIMER_FREQ;
107 int     timer0_max_count;
108 int     timer0_real_max_count;
109 #define RTC_LOCK        mtx_lock_spin(&clock_lock)
110 #define RTC_UNLOCK      mtx_unlock_spin(&clock_lock)
111
112 static  int     beeping = 0;
113 static  struct mtx clock_lock;
114 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
115 static  struct intsrc *i8254_intsrc;
116 static  u_int32_t i8254_lastcount;
117 static  u_int32_t i8254_offset;
118 static  int     (*i8254_pending)(struct intsrc *);
119 static  int     i8254_ticked;
120 static  int     using_lapic_timer;
121 static  int     rtc_reg = -1;
122 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
123 static  u_char  rtc_statusb = RTCSB_24HR;
124
125 /* Values for timerX_state: */
126 #define RELEASED        0
127 #define RELEASE_PENDING 1
128 #define ACQUIRED        2
129 #define ACQUIRE_PENDING 3
130
131 static  u_char  timer2_state;
132
133 static  unsigned i8254_get_timecount(struct timecounter *tc);
134 static  unsigned i8254_simple_get_timecount(struct timecounter *tc);
135 static  void    set_timer_freq(u_int freq, int intr_freq);
136
137 static struct timecounter i8254_timecounter = {
138         i8254_get_timecount,    /* get_timecount */
139         0,                      /* no poll_pps */
140         ~0u,                    /* counter_mask */
141         0,                      /* frequency */
142         "i8254",                /* name */
143         0                       /* quality */
144 };
145
146 static int
147 clkintr(struct trapframe *frame)
148 {
149
150         if (timecounter->tc_get_timecount == i8254_get_timecount) {
151                 mtx_lock_spin(&clock_lock);
152                 if (i8254_ticked)
153                         i8254_ticked = 0;
154                 else {
155                         i8254_offset += timer0_max_count;
156                         i8254_lastcount = 0;
157                 }
158                 clkintr_pending = 0;
159                 mtx_unlock_spin(&clock_lock);
160         }
161         KASSERT(!using_lapic_timer, ("clk interrupt enabled with lapic timer"));
162         hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
163         return (FILTER_HANDLED);
164 }
165
166 int
167 acquire_timer2(int mode)
168 {
169
170         if (timer2_state != RELEASED)
171                 return (-1);
172         timer2_state = ACQUIRED;
173
174         /*
175          * This access to the timer registers is as atomic as possible
176          * because it is a single instruction.  We could do better if we
177          * knew the rate.  Use of splclock() limits glitches to 10-100us,
178          * and this is probably good enough for timer2, so we aren't as
179          * careful with it as with timer0.
180          */
181         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
182
183         return (0);
184 }
185
186 int
187 release_timer2()
188 {
189
190         if (timer2_state != ACQUIRED)
191                 return (-1);
192         timer2_state = RELEASED;
193         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
194         return (0);
195 }
196
197 /*
198  * This routine receives statistical clock interrupts from the RTC.
199  * As explained above, these occur at 128 interrupts per second.
200  * When profiling, we receive interrupts at a rate of 1024 Hz.
201  *
202  * This does not actually add as much overhead as it sounds, because
203  * when the statistical clock is active, the hardclock driver no longer
204  * needs to keep (inaccurate) statistics on its own.  This decouples
205  * statistics gathering from scheduling interrupts.
206  *
207  * The RTC chip requires that we read status register C (RTC_INTR)
208  * to acknowledge an interrupt, before it will generate the next one.
209  * Under high interrupt load, rtcintr() can be indefinitely delayed and
210  * the clock can tick immediately after the read from RTC_INTR.  In this
211  * case, the mc146818A interrupt signal will not drop for long enough
212  * to register with the 8259 PIC.  If an interrupt is missed, the stat
213  * clock will halt, considerably degrading system performance.  This is
214  * why we use 'while' rather than a more straightforward 'if' below.
215  * Stat clock ticks can still be lost, causing minor loss of accuracy
216  * in the statistics, but the stat clock will no longer stop.
217  */
218 static int
219 rtcintr(struct trapframe *frame)
220 {
221         int flag = 0;
222
223         while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
224                 flag = 1;
225                 if (profprocs != 0) {
226                         if (--pscnt == 0)
227                                 pscnt = psdiv;
228                         profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
229                 }
230                 if (pscnt == psdiv)
231                         statclock(TRAPF_USERMODE(frame));
232         }
233         return(flag ? FILTER_HANDLED : FILTER_STRAY);
234 }
235
236 #include "opt_ddb.h"
237 #ifdef DDB
238 #include <ddb/ddb.h>
239
240 DB_SHOW_COMMAND(rtc, rtc)
241 {
242         printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
243                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
244                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
245                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
246 }
247 #endif /* DDB */
248
249 static int
250 getit(void)
251 {
252         int high, low;
253
254         mtx_lock_spin(&clock_lock);
255
256         /* Select timer0 and latch counter value. */
257         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
258
259         low = inb(TIMER_CNTR0);
260         high = inb(TIMER_CNTR0);
261
262         mtx_unlock_spin(&clock_lock);
263         return ((high << 8) | low);
264 }
265
266 /*
267  * Wait "n" microseconds.
268  * Relies on timer 1 counting down from (timer_freq / hz)
269  * Note: timer had better have been programmed before this is first used!
270  */
271 void
272 DELAY(int n)
273 {
274         int delta, prev_tick, tick, ticks_left;
275
276 #ifdef DELAYDEBUG
277         int getit_calls = 1;
278         int n1;
279         static int state = 0;
280 #endif
281
282         if (tsc_freq != 0 && !tsc_is_broken) {
283                 uint64_t start, end, now;
284
285                 sched_pin();
286                 start = rdtsc();
287                 end = start + (tsc_freq * n) / 1000000;
288                 do {
289                         cpu_spinwait();
290                         now = rdtsc();
291                 } while (now < end || (now > start && end < start));
292                 sched_unpin();
293                 return;
294         }
295 #ifdef DELAYDEBUG
296         if (state == 0) {
297                 state = 1;
298                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
299                         DELAY(n1);
300                 state = 2;
301         }
302         if (state == 1)
303                 printf("DELAY(%d)...", n);
304 #endif
305         /*
306          * Read the counter first, so that the rest of the setup overhead is
307          * counted.  Guess the initial overhead is 20 usec (on most systems it
308          * takes about 1.5 usec for each of the i/o's in getit().  The loop
309          * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
310          * multiplications and divisions to scale the count take a while).
311          *
312          * However, if ddb is active then use a fake counter since reading
313          * the i8254 counter involves acquiring a lock.  ddb must not do
314          * locking for many reasons, but it calls here for at least atkbd
315          * input.
316          */
317 #ifdef KDB
318         if (kdb_active)
319                 prev_tick = 1;
320         else
321 #endif
322                 prev_tick = getit();
323         n -= 0;                 /* XXX actually guess no initial overhead */
324         /*
325          * Calculate (n * (timer_freq / 1e6)) without using floating point
326          * and without any avoidable overflows.
327          */
328         if (n <= 0)
329                 ticks_left = 0;
330         else if (n < 256)
331                 /*
332                  * Use fixed point to avoid a slow division by 1000000.
333                  * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest.
334                  * 2^15 is the first power of 2 that gives exact results
335                  * for n between 0 and 256.
336                  */
337                 ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15;
338         else
339                 /*
340                  * Don't bother using fixed point, although gcc-2.7.2
341                  * generates particularly poor code for the long long
342                  * division, since even the slow way will complete long
343                  * before the delay is up (unless we're interrupted).
344                  */
345                 ticks_left = ((u_int)n * (long long)timer_freq + 999999)
346                              / 1000000;
347
348         while (ticks_left > 0) {
349 #ifdef KDB
350                 if (kdb_active) {
351                         inb(0x84);
352                         tick = prev_tick - 1;
353                         if (tick <= 0)
354                                 tick = timer0_max_count;
355                 } else
356 #endif
357                         tick = getit();
358 #ifdef DELAYDEBUG
359                 ++getit_calls;
360 #endif
361                 delta = prev_tick - tick;
362                 prev_tick = tick;
363                 if (delta < 0) {
364                         delta += timer0_max_count;
365                         /*
366                          * Guard against timer0_max_count being wrong.
367                          * This shouldn't happen in normal operation,
368                          * but it may happen if set_timer_freq() is
369                          * traced.
370                          */
371                         if (delta < 0)
372                                 delta = 0;
373                 }
374                 ticks_left -= delta;
375         }
376 #ifdef DELAYDEBUG
377         if (state == 1)
378                 printf(" %d calls to getit() at %d usec each\n",
379                        getit_calls, (n + 5) / getit_calls);
380 #endif
381 }
382
383 static void
384 sysbeepstop(void *chan)
385 {
386         ppi_spkr_off();         /* disable counter2 output to speaker */
387         timer_spkr_release();
388         beeping = 0;
389 }
390
391 int
392 sysbeep(int pitch, int period)
393 {
394         int x = splclock();
395
396         if (timer_spkr_acquire())
397                 if (!beeping) {
398                         /* Something else owns it. */
399                         splx(x);
400                         return (-1); /* XXX Should be EBUSY, but nobody cares anyway. */
401                 }
402         mtx_lock_spin(&clock_lock);
403         spkr_set_pitch(pitch);
404         mtx_unlock_spin(&clock_lock);
405         if (!beeping) {
406                 /* enable counter2 output to speaker */
407                 ppi_spkr_on();
408                 beeping = period;
409                 timeout(sysbeepstop, (void *)NULL, period);
410         }
411         splx(x);
412         return (0);
413 }
414
415 /*
416  * RTC support routines
417  */
418
419 int
420 rtcin(reg)
421         int reg;
422 {
423         u_char val;
424
425         RTC_LOCK;
426         if (rtc_reg != reg) {
427                 inb(0x84);
428                 outb(IO_RTC, reg);
429                 rtc_reg = reg;
430                 inb(0x84);
431         }
432         val = inb(IO_RTC + 1);
433         RTC_UNLOCK;
434         return (val);
435 }
436
437 void
438 writertc(int reg, u_char val)
439 {
440
441         RTC_LOCK;
442         if (rtc_reg != reg) {
443                 inb(0x84);
444                 outb(IO_RTC, reg);
445                 rtc_reg = reg;
446                 inb(0x84);
447         }
448         outb(IO_RTC + 1, val);
449         inb(0x84);
450         RTC_UNLOCK;
451 }
452
453 static __inline int
454 readrtc(int port)
455 {
456         return(bcd2bin(rtcin(port)));
457 }
458
459 static u_int
460 calibrate_clocks(void)
461 {
462         u_int count, prev_count, tot_count;
463         int sec, start_sec, timeout;
464
465         if (bootverbose)
466                 printf("Calibrating clock(s) ... ");
467         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
468                 goto fail;
469         timeout = 100000000;
470
471         /* Read the mc146818A seconds counter. */
472         for (;;) {
473                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
474                         sec = rtcin(RTC_SEC);
475                         break;
476                 }
477                 if (--timeout == 0)
478                         goto fail;
479         }
480
481         /* Wait for the mC146818A seconds counter to change. */
482         start_sec = sec;
483         for (;;) {
484                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
485                         sec = rtcin(RTC_SEC);
486                         if (sec != start_sec)
487                                 break;
488                 }
489                 if (--timeout == 0)
490                         goto fail;
491         }
492
493         /* Start keeping track of the i8254 counter. */
494         prev_count = getit();
495         if (prev_count == 0 || prev_count > timer0_max_count)
496                 goto fail;
497         tot_count = 0;
498
499         /*
500          * Wait for the mc146818A seconds counter to change.  Read the i8254
501          * counter for each iteration since this is convenient and only
502          * costs a few usec of inaccuracy. The timing of the final reads
503          * of the counters almost matches the timing of the initial reads,
504          * so the main cause of inaccuracy is the varying latency from 
505          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
506          * rtcin(RTC_SEC) that returns a changed seconds count.  The
507          * maximum inaccuracy from this cause is < 10 usec on 486's.
508          */
509         start_sec = sec;
510         for (;;) {
511                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
512                         sec = rtcin(RTC_SEC);
513                 count = getit();
514                 if (count == 0 || count > timer0_max_count)
515                         goto fail;
516                 if (count > prev_count)
517                         tot_count += prev_count - (count - timer0_max_count);
518                 else
519                         tot_count += prev_count - count;
520                 prev_count = count;
521                 if (sec != start_sec)
522                         break;
523                 if (--timeout == 0)
524                         goto fail;
525         }
526
527         if (bootverbose) {
528                 printf("i8254 clock: %u Hz\n", tot_count);
529         }
530         return (tot_count);
531
532 fail:
533         if (bootverbose)
534                 printf("failed, using default i8254 clock of %u Hz\n",
535                        timer_freq);
536         return (timer_freq);
537 }
538
539 static void
540 set_timer_freq(u_int freq, int intr_freq)
541 {
542         int new_timer0_real_max_count;
543
544         i8254_timecounter.tc_frequency = freq;
545         mtx_lock_spin(&clock_lock);
546         timer_freq = freq;
547         if (using_lapic_timer)
548                 new_timer0_real_max_count = 0x10000;
549         else
550                 new_timer0_real_max_count = TIMER_DIV(intr_freq);
551         if (new_timer0_real_max_count != timer0_real_max_count) {
552                 timer0_real_max_count = new_timer0_real_max_count;
553                 if (timer0_real_max_count == 0x10000)
554                         timer0_max_count = 0xffff;
555                 else
556                         timer0_max_count = timer0_real_max_count;
557                 outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT);
558                 outb(TIMER_CNTR0, timer0_real_max_count & 0xff);
559                 outb(TIMER_CNTR0, timer0_real_max_count >> 8);
560         }
561         mtx_unlock_spin(&clock_lock);
562 }
563
564 /* This is separate from startrtclock() so that it can be called early. */
565 void
566 i8254_init(void)
567 {
568
569         mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE);
570         set_timer_freq(timer_freq, hz);
571 }
572
573 void
574 startrtclock()
575 {
576         u_int delta, freq;
577
578         writertc(RTC_STATUSA, rtc_statusa);
579         writertc(RTC_STATUSB, RTCSB_24HR);
580
581         freq = calibrate_clocks();
582 #ifdef CLK_CALIBRATION_LOOP
583         if (bootverbose) {
584                 printf(
585                 "Press a key on the console to abort clock calibration\n");
586                 while (cncheckc() == -1)
587                         calibrate_clocks();
588         }
589 #endif
590
591         /*
592          * Use the calibrated i8254 frequency if it seems reasonable.
593          * Otherwise use the default, and don't use the calibrated i586
594          * frequency.
595          */
596         delta = freq > timer_freq ? freq - timer_freq : timer_freq - freq;
597         if (delta < timer_freq / 100) {
598 #ifndef CLK_USE_I8254_CALIBRATION
599                 if (bootverbose)
600                         printf(
601 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
602                 freq = timer_freq;
603 #endif
604                 timer_freq = freq;
605         } else {
606                 if (bootverbose)
607                         printf(
608                     "%d Hz differs from default of %d Hz by more than 1%%\n",
609                                freq, timer_freq);
610         }
611
612         set_timer_freq(timer_freq, hz);
613         tc_init(&i8254_timecounter);
614
615         init_TSC();
616 }
617
618 /*
619  * Initialize the time of day register, based on the time base which is, e.g.
620  * from a filesystem.
621  */
622 void
623 inittodr(time_t base)
624 {
625         unsigned long   sec, days;
626         int             year, month;
627         int             y, m, s;
628         struct timespec ts;
629
630         if (base) {
631                 s = splclock();
632                 ts.tv_sec = base;
633                 ts.tv_nsec = 0;
634                 tc_setclock(&ts);
635                 splx(s);
636         }
637
638         /* Look if we have a RTC present and the time is valid */
639         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
640                 goto wrong_time;
641
642         /* wait for time update to complete */
643         /* If RTCSA_TUP is zero, we have at least 244us before next update */
644         s = splhigh();
645         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
646                 splx(s);
647                 s = splhigh();
648         }
649
650         days = 0;
651 #ifdef USE_RTC_CENTURY
652         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
653 #else
654         year = readrtc(RTC_YEAR) + 1900;
655         if (year < 1970)
656                 year += 100;
657 #endif
658         if (year < 1970) {
659                 splx(s);
660                 goto wrong_time;
661         }
662         month = readrtc(RTC_MONTH);
663         for (m = 1; m < month; m++)
664                 days += daysinmonth[m-1];
665         if ((month > 2) && LEAPYEAR(year))
666                 days ++;
667         days += readrtc(RTC_DAY) - 1;
668         for (y = 1970; y < year; y++)
669                 days += DAYSPERYEAR + LEAPYEAR(y);
670         sec = ((( days * 24 +
671                   readrtc(RTC_HRS)) * 60 +
672                   readrtc(RTC_MIN)) * 60 +
673                   readrtc(RTC_SEC));
674         /* sec now contains the number of seconds, since Jan 1 1970,
675            in the local time zone */
676
677         sec += utc_offset();
678
679         y = time_second - sec;
680         if (y <= -2 || y >= 2) {
681                 /* badly off, adjust it */
682                 ts.tv_sec = sec;
683                 ts.tv_nsec = 0;
684                 tc_setclock(&ts);
685         }
686         splx(s);
687         return;
688
689 wrong_time:
690         printf("Invalid time in clock: check and reset the date!\n");
691 }
692
693 /*
694  * Write system time back to RTC
695  */
696 void
697 resettodr()
698 {
699         unsigned long   tm;
700         int             y, m, s;
701
702         if (disable_rtc_set)
703                 return;
704
705         s = splclock();
706         tm = time_second;
707         splx(s);
708
709         /* Disable RTC updates and interrupts. */
710         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
711
712         /* Calculate local time to put in RTC */
713
714         tm -= utc_offset();
715
716         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
717         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
718         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
719
720         /* We have now the days since 01-01-1970 in tm */
721         writertc(RTC_WDAY, (tm + 4) % 7 + 1);           /* Write back Weekday */
722         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
723              tm >= m;
724              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
725              tm -= m;
726
727         /* Now we have the years in y and the day-of-the-year in tm */
728         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
729 #ifdef USE_RTC_CENTURY
730         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
731 #endif
732         for (m = 0; ; m++) {
733                 int ml;
734
735                 ml = daysinmonth[m];
736                 if (m == 1 && LEAPYEAR(y))
737                         ml++;
738                 if (tm < ml)
739                         break;
740                 tm -= ml;
741         }
742
743         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
744         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
745
746         /* Reenable RTC updates and interrupts. */
747         writertc(RTC_STATUSB, rtc_statusb);
748         rtcin(RTC_INTR);
749 }
750
751
752 /*
753  * Start both clocks running.
754  */
755 void
756 cpu_initclocks()
757 {
758         int diag;
759
760         using_lapic_timer = lapic_setup_clock();
761         /*
762          * If we aren't using the local APIC timer to drive the kernel
763          * clocks, setup the interrupt handler for the 8254 timer 0 so
764          * that it can drive hardclock().  Otherwise, change the 8254
765          * timecounter to user a simpler algorithm.
766          */
767         if (!using_lapic_timer) {
768                 intr_add_handler("clk", 0, (driver_filter_t *)clkintr, NULL, NULL,
769                     INTR_TYPE_CLK, NULL);
770                 i8254_intsrc = intr_lookup_source(0);
771                 if (i8254_intsrc != NULL)
772                         i8254_pending =
773                             i8254_intsrc->is_pic->pic_source_pending;
774         } else {
775                 i8254_timecounter.tc_get_timecount =
776                     i8254_simple_get_timecount;
777                 i8254_timecounter.tc_counter_mask = 0xffff;
778                 set_timer_freq(timer_freq, hz);
779         }
780
781         /* Initialize RTC. */
782         writertc(RTC_STATUSA, rtc_statusa);
783         writertc(RTC_STATUSB, RTCSB_24HR);
784
785         /*
786          * If the separate statistics clock hasn't been explicility disabled
787          * and we aren't already using the local APIC timer to drive the
788          * kernel clocks, then setup the RTC to periodically interrupt to
789          * drive statclock() and profclock().
790          */
791         if (!statclock_disable && !using_lapic_timer) {
792                 diag = rtcin(RTC_DIAG);
793                 if (diag != 0)
794                         printf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
795
796                 /* Setting stathz to nonzero early helps avoid races. */
797                 stathz = RTC_NOPROFRATE;
798                 profhz = RTC_PROFRATE;
799
800                 /* Enable periodic interrupts from the RTC. */
801                 rtc_statusb |= RTCSB_PINTR;
802                 intr_add_handler("rtc", 8, (driver_filter_t *)rtcintr, NULL, NULL,
803                     INTR_TYPE_CLK, NULL);
804
805                 writertc(RTC_STATUSB, rtc_statusb);
806                 rtcin(RTC_INTR);
807         }
808
809         init_TSC_tc();
810 }
811
812 void
813 cpu_startprofclock(void)
814 {
815
816         if (using_lapic_timer)
817                 return;
818         rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
819         writertc(RTC_STATUSA, rtc_statusa);
820         psdiv = pscnt = psratio;
821 }
822
823 void
824 cpu_stopprofclock(void)
825 {
826
827         if (using_lapic_timer)
828                 return;
829         rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
830         writertc(RTC_STATUSA, rtc_statusa);
831         psdiv = pscnt = 1;
832 }
833
834 static int
835 sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS)
836 {
837         int error;
838         u_int freq;
839
840         /*
841          * Use `i8254' instead of `timer' in external names because `timer'
842          * is is too generic.  Should use it everywhere.
843          */
844         freq = timer_freq;
845         error = sysctl_handle_int(oidp, &freq, 0, req);
846         if (error == 0 && req->newptr != NULL)
847                 set_timer_freq(freq, hz);
848         return (error);
849 }
850
851 SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW,
852     0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "");
853
854 static unsigned
855 i8254_simple_get_timecount(struct timecounter *tc)
856 {
857
858         return (timer0_max_count - getit());
859 }
860
861 static unsigned
862 i8254_get_timecount(struct timecounter *tc)
863 {
864         u_int count;
865         u_int high, low;
866         u_long rflags;
867
868         rflags = read_rflags();
869         mtx_lock_spin(&clock_lock);
870
871         /* Select timer0 and latch counter value. */
872         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
873
874         low = inb(TIMER_CNTR0);
875         high = inb(TIMER_CNTR0);
876         count = timer0_max_count - ((high << 8) | low);
877         if (count < i8254_lastcount ||
878             (!i8254_ticked && (clkintr_pending ||
879             ((count < 20 || (!(rflags & PSL_I) && count < timer0_max_count / 2u)) &&
880             i8254_pending != NULL && i8254_pending(i8254_intsrc))))) {
881                 i8254_ticked = 1;
882                 i8254_offset += timer0_max_count;
883         }
884         i8254_lastcount = count;
885         count += i8254_offset;
886         mtx_unlock_spin(&clock_lock);
887         return (count);
888 }
889
890 #ifdef DEV_ISA
891 /*
892  * Attach to the ISA PnP descriptors for the timer and realtime clock.
893  */
894 static struct isa_pnp_id attimer_ids[] = {
895         { 0x0001d041 /* PNP0100 */, "AT timer" },
896         { 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
897         { 0 }
898 };
899
900 static int
901 attimer_probe(device_t dev)
902 {
903         int result;
904         
905         if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids)) <= 0)
906                 device_quiet(dev);
907         return(result);
908 }
909
910 static int
911 attimer_attach(device_t dev)
912 {
913         return(0);
914 }
915
916 static device_method_t attimer_methods[] = {
917         /* Device interface */
918         DEVMETHOD(device_probe,         attimer_probe),
919         DEVMETHOD(device_attach,        attimer_attach),
920         DEVMETHOD(device_detach,        bus_generic_detach),
921         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
922         DEVMETHOD(device_suspend,       bus_generic_suspend),   /* XXX stop statclock? */
923         DEVMETHOD(device_resume,        bus_generic_resume),    /* XXX restart statclock? */
924         { 0, 0 }
925 };
926
927 static driver_t attimer_driver = {
928         "attimer",
929         attimer_methods,
930         1,              /* no softc */
931 };
932
933 static devclass_t attimer_devclass;
934
935 DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0);
936 DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0);
937
938 #endif /* DEV_ISA */