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