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