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