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