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