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