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