clock: Use sysclock_t to save value from sys_cputimer->count()
[dragonfly.git] / sys / platform / pc32 / 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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      from: @(#)clock.c       7.2 (Berkeley) 5/12/91
37  * $FreeBSD: src/sys/i386/isa/clock.c,v 1.149.2.6 2002/11/02 04:41:50 iwasaki Exp $
38  */
39
40 /*
41  * Routines to handle clock hardware.
42  */
43
44 /*
45  * inittodr, settodr and support routines written
46  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
47  *
48  * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
49  */
50
51 #include "opt_clock.h"
52
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/eventhandler.h>
56 #include <sys/time.h>
57 #include <sys/kernel.h>
58 #include <sys/bus.h>
59 #include <sys/sysctl.h>
60 #include <sys/cons.h>
61 #include <sys/systimer.h>
62 #include <sys/globaldata.h>
63 #include <sys/thread2.h>
64 #include <sys/systimer.h>
65 #include <sys/machintr.h>
66 #include <sys/interrupt.h>
67
68 #include <machine/clock.h>
69 #include <machine/cputypes.h>
70 #include <machine/frame.h>
71 #include <machine/ipl.h>
72 #include <machine/limits.h>
73 #include <machine/md_var.h>
74 #include <machine/psl.h>
75 #include <machine/segments.h>
76 #include <machine/smp.h>
77 #include <machine/specialreg.h>
78
79 #include <machine_base/apic/ioapic.h>
80 #include <machine_base/apic/ioapic_abi.h>
81 #include <machine_base/icu/icu.h>
82 #include <bus/isa/isa.h>
83 #include <bus/isa/rtc.h>
84 #include <machine_base/isa/timerreg.h>
85
86 #include <machine/intr_machdep.h>
87
88 static void i8254_restore(void);
89 static void resettodr_on_shutdown(void *arg __unused);
90
91 /*
92  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
93  * can use a simple formula for leap years.
94  */
95 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
96 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
97
98 #ifndef TIMER_FREQ
99 #define TIMER_FREQ   1193182
100 #endif
101
102 static uint8_t i8254_walltimer_sel;
103 static uint16_t i8254_walltimer_cntr;
104
105 int     adjkerntz;              /* local offset from GMT in seconds */
106 int     disable_rtc_set;        /* disable resettodr() if != 0 */
107 int     tsc_present;
108 int64_t tsc_frequency;
109 int     tsc_is_broken;
110 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
111 int     timer0_running;
112 enum tstate { RELEASED, ACQUIRED };
113 enum tstate timer0_state;
114 enum tstate timer1_state;
115 enum tstate timer2_state;
116
117 static  int     beeping = 0;
118 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
119 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
120 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
121 static  int     rtc_loaded;
122
123 static int i8254_cputimer_div;
124
125 static int i8254_nointr;
126 static int i8254_intr_disable = 1;
127 TUNABLE_INT("hw.i8254.intr_disable", &i8254_intr_disable);
128
129 static struct callout sysbeepstop_ch;
130
131 static sysclock_t i8254_cputimer_count(void);
132 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
133 static void i8254_cputimer_destruct(struct cputimer *cputimer);
134
135 static struct cputimer  i8254_cputimer = {
136     SLIST_ENTRY_INITIALIZER,
137     "i8254",
138     CPUTIMER_PRI_8254,
139     0,
140     i8254_cputimer_count,
141     cputimer_default_fromhz,
142     cputimer_default_fromus,
143     i8254_cputimer_construct,
144     i8254_cputimer_destruct,
145     TIMER_FREQ,
146     0, 0, 0
147 };
148
149 static void i8254_intr_reload(struct cputimer_intr *, sysclock_t);
150 static void i8254_intr_config(struct cputimer_intr *, const struct cputimer *);
151 static void i8254_intr_initclock(struct cputimer_intr *, boolean_t);
152
153 static struct cputimer_intr i8254_cputimer_intr = {
154     .freq = TIMER_FREQ,
155     .reload = i8254_intr_reload,
156     .enable = cputimer_intr_default_enable,
157     .config = i8254_intr_config,
158     .restart = cputimer_intr_default_restart,
159     .pmfixup = cputimer_intr_default_pmfixup,
160     .initclock = i8254_intr_initclock,
161     .next = SLIST_ENTRY_INITIALIZER,
162     .name = "i8254",
163     .type = CPUTIMER_INTR_8254,
164     .prio = CPUTIMER_INTR_PRIO_8254,
165     .caps = CPUTIMER_INTR_CAP_PS
166 };
167
168 /*
169  * timer0 clock interrupt.  Timer0 is in one-shot mode and has stopped
170  * counting as of this interrupt.  We use timer1 in free-running mode (not
171  * generating any interrupts) as our main counter.  Each cpu has timeouts
172  * pending.
173  *
174  * This code is INTR_MPSAFE and may be called without the BGL held.
175  */
176 static void
177 clkintr(void *dummy, void *frame_arg)
178 {
179         static sysclock_t sysclock_count;       /* NOTE! Must be static */
180         struct globaldata *gd = mycpu;
181         struct globaldata *gscan;
182         int n;
183
184         /*
185          * SWSTROBE mode is a one-shot, the timer is no longer running
186          */
187         timer0_running = 0;
188
189         /*
190          * XXX the dispatcher needs work.  right now we call systimer_intr()
191          * directly or via IPI for any cpu with systimers queued, which is
192          * usually *ALL* of them.  We need to use the LAPIC timer for this.
193          */
194         sysclock_count = sys_cputimer->count();
195         for (n = 0; n < ncpus; ++n) {
196             gscan = globaldata_find(n);
197             if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
198                 continue;
199             if (gscan != gd) {
200                 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr, 
201                                 &sysclock_count, 1);
202             } else {
203                 systimer_intr(&sysclock_count, 0, frame_arg);
204             }
205         }
206 }
207
208
209 /*
210  * NOTE! not MP safe.
211  */
212 int
213 acquire_timer2(int mode)
214 {
215         if (timer2_state != RELEASED)
216                 return (-1);
217         timer2_state = ACQUIRED;
218
219         /*
220          * This access to the timer registers is as atomic as possible
221          * because it is a single instruction.  We could do better if we
222          * knew the rate.
223          */
224         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
225         return (0);
226 }
227
228 int
229 release_timer2(void)
230 {
231         if (timer2_state != ACQUIRED)
232                 return (-1);
233         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
234         timer2_state = RELEASED;
235         return (0);
236 }
237
238 #include "opt_ddb.h"
239 #ifdef DDB
240 #include <ddb/ddb.h>
241
242 DB_SHOW_COMMAND(rtc, rtc)
243 {
244         kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
245                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
246                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
247                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
248 }
249 #endif /* DDB */
250
251 /*
252  * Return the current cpu timer count as a 32 bit integer.
253  */
254 static
255 sysclock_t
256 i8254_cputimer_count(void)
257 {
258         static __uint16_t cputimer_last;
259         __uint16_t count;
260         sysclock_t ret;
261
262         clock_lock();
263         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
264         count = (__uint8_t)inb(i8254_walltimer_cntr);           /* get countdown */
265         count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
266         count = -count;                                 /* -> countup */
267         if (count < cputimer_last)                      /* rollover */
268                 i8254_cputimer.base += 0x00010000;
269         ret = i8254_cputimer.base | count;
270         cputimer_last = count;
271         clock_unlock();
272         return(ret);
273 }
274
275 /*
276  * This function is called whenever the system timebase changes, allowing
277  * us to calculate what is needed to convert a system timebase tick 
278  * into an 8254 tick for the interrupt timer.  If we can convert to a
279  * simple shift, multiplication, or division, we do so.  Otherwise 64
280  * bit arithmatic is required every time the interrupt timer is reloaded.
281  */
282 static void
283 i8254_intr_config(struct cputimer_intr *cti, const struct cputimer *timer)
284 {
285     int freq;
286     int div;
287
288     /*
289      * Will a simple divide do the trick?
290      */
291     div = (timer->freq + (cti->freq / 2)) / cti->freq;
292     freq = cti->freq * div;
293
294     if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
295         i8254_cputimer_div = div;
296     else
297         i8254_cputimer_div = 0;
298 }
299
300 /*
301  * Reload for the next timeout.  It is possible for the reload value
302  * to be 0 or negative, indicating that an immediate timer interrupt
303  * is desired.  For now make the minimum 2 ticks.
304  *
305  * We may have to convert from the system timebase to the 8254 timebase.
306  */
307 static void
308 i8254_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
309 {
310     __uint16_t count;
311
312     if (i8254_cputimer_div)
313         reload /= i8254_cputimer_div;
314     else
315         reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
316
317     if ((int)reload < 2)
318         reload = 2;
319
320     clock_lock();
321     if (timer0_running) {
322         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);     /* count-down timer */
323         count = (__uint8_t)inb(TIMER_CNTR0);            /* lsb */
324         count |= ((__uint8_t)inb(TIMER_CNTR0) << 8);    /* msb */
325         if (reload < count) {
326             outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
327             outb(TIMER_CNTR0, (__uint8_t)reload);       /* lsb */
328             outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
329         }
330     } else {
331         timer0_running = 1;
332         if (reload > 0xFFFF)
333             reload = 0;         /* full count */
334         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
335         outb(TIMER_CNTR0, (__uint8_t)reload);           /* lsb */
336         outb(TIMER_CNTR0, (__uint8_t)(reload >> 8));    /* msb */
337     }
338     clock_unlock();
339 }
340
341 /*
342  * DELAY(usec)       - Spin for the specified number of microseconds.
343  * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
344  *                     but do a thread switch in the loop
345  *
346  * Relies on timer 1 counting down from (cputimer_freq / hz)
347  * Note: timer had better have been programmed before this is first used!
348  */
349 static void
350 DODELAY(int n, int doswitch)
351 {
352         ssysclock_t delta, ticks_left;
353         sysclock_t prev_tick, tick;
354
355 #ifdef DELAYDEBUG
356         int getit_calls = 1;
357         int n1;
358         static int state = 0;
359
360         if (state == 0) {
361                 state = 1;
362                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
363                         DELAY(n1);
364                 state = 2;
365         }
366         if (state == 1)
367                 kprintf("DELAY(%d)...", n);
368 #endif
369         /*
370          * Guard against the timer being uninitialized if we are called
371          * early for console i/o.
372          */
373         if (timer0_state == RELEASED)
374                 i8254_restore();
375
376         /*
377          * Read the counter first, so that the rest of the setup overhead is
378          * counted.  Then calculate the number of hardware timer ticks
379          * required, rounding up to be sure we delay at least the requested
380          * number of microseconds.
381          */
382         prev_tick = sys_cputimer->count();
383         ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
384                      1000000;
385
386         /*
387          * Loop until done.
388          */
389         while (ticks_left > 0) {
390                 tick = sys_cputimer->count();
391 #ifdef DELAYDEBUG
392                 ++getit_calls;
393 #endif
394                 delta = tick - prev_tick;
395                 prev_tick = tick;
396                 if (delta < 0)
397                         delta = 0;
398                 ticks_left -= delta;
399                 if (doswitch && ticks_left > 0)
400                         lwkt_switch();
401                 cpu_pause();
402         }
403 #ifdef DELAYDEBUG
404         if (state == 1)
405                 kprintf(" %d calls to getit() at %d usec each\n",
406                        getit_calls, (n + 5) / getit_calls);
407 #endif
408 }
409
410 /*
411  * DELAY() never switches
412  */
413 void
414 DELAY(int n)
415 {
416         DODELAY(n, 0);
417 }
418
419 int
420 CHECKTIMEOUT(TOTALDELAY *tdd)
421 {
422         sysclock_t delta;
423         int us;
424
425         if (tdd->started == 0) {
426                if (timer0_state == RELEASED)
427                        i8254_restore();
428                tdd->last_clock = sys_cputimer->count();
429                tdd->started = 1;
430                return(0);
431         }
432         delta = sys_cputimer->count() - tdd->last_clock;
433         us = (u_int64_t)delta * (u_int64_t)1000000 /
434              (u_int64_t)sys_cputimer->freq;
435         tdd->last_clock += (u_int64_t)us * (u_int64_t)sys_cputimer->freq /
436                            1000000;
437         tdd->us -= us;
438         return (tdd->us < 0);
439 }
440
441 /*
442  * DRIVERSLEEP() does not switch if called with a spinlock held or
443  * from a hard interrupt.
444  */
445 void
446 DRIVERSLEEP(int usec)
447 {
448         globaldata_t gd = mycpu;
449
450         if (gd->gd_intr_nesting_level || gd->gd_spinlocks) {
451                 DODELAY(usec, 0);
452         } else {
453                 DODELAY(usec, 1);
454         }
455 }
456
457 static void
458 sysbeepstop(void *chan)
459 {
460         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
461         beeping = 0;
462         release_timer2();
463 }
464
465 int
466 sysbeep(int pitch, int period)
467 {
468         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
469                 return(-1);
470         if (sysbeep_enable == 0)
471                 return(-1);
472         /*
473          * Nobody else is using timer2, we do not need the clock lock
474          */
475         outb(TIMER_CNTR2, pitch);
476         outb(TIMER_CNTR2, (pitch>>8));
477         if (!beeping) {
478                 /* enable counter2 output to speaker */
479                 outb(IO_PPI, inb(IO_PPI) | 3);
480                 beeping = period;
481                 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
482         }
483         return (0);
484 }
485
486 /*
487  * RTC support routines
488  */
489
490 int
491 rtcin(int reg)
492 {
493         u_char val;
494
495         crit_enter();
496         outb(IO_RTC, reg);
497         inb(0x84);
498         val = inb(IO_RTC + 1);
499         inb(0x84);
500         crit_exit();
501         return (val);
502 }
503
504 static __inline void
505 writertc(u_char reg, u_char val)
506 {
507         crit_enter();
508         inb(0x84);
509         outb(IO_RTC, reg);
510         inb(0x84);
511         outb(IO_RTC + 1, val);
512         inb(0x84);              /* XXX work around wrong order in rtcin() */
513         crit_exit();
514 }
515
516 static __inline int
517 readrtc(int port)
518 {
519         return(bcd2bin(rtcin(port)));
520 }
521
522 static u_int
523 calibrate_clocks(void)
524 {
525         u_int64_t old_tsc;
526         u_int tot_count;
527         sysclock_t count, prev_count;
528         int sec, start_sec, timeout;
529
530         if (bootverbose)
531                 kprintf("Calibrating clock(s) ... ");
532         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
533                 goto fail;
534         timeout = 100000000;
535
536         /* Read the mc146818A seconds counter. */
537         for (;;) {
538                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
539                         sec = rtcin(RTC_SEC);
540                         break;
541                 }
542                 if (--timeout == 0)
543                         goto fail;
544         }
545
546         /* Wait for the mC146818A seconds counter to change. */
547         start_sec = sec;
548         for (;;) {
549                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
550                         sec = rtcin(RTC_SEC);
551                         if (sec != start_sec)
552                                 break;
553                 }
554                 if (--timeout == 0)
555                         goto fail;
556         }
557
558         /* Start keeping track of the i8254 counter. */
559         prev_count = sys_cputimer->count();
560         tot_count = 0;
561
562         if (tsc_present) 
563                 old_tsc = rdtsc();
564         else
565                 old_tsc = 0;            /* shut up gcc */
566
567         /*
568          * Wait for the mc146818A seconds counter to change.  Read the i8254
569          * counter for each iteration since this is convenient and only
570          * costs a few usec of inaccuracy. The timing of the final reads
571          * of the counters almost matches the timing of the initial reads,
572          * so the main cause of inaccuracy is the varying latency from 
573          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
574          * rtcin(RTC_SEC) that returns a changed seconds count.  The
575          * maximum inaccuracy from this cause is < 10 usec on 486's.
576          */
577         start_sec = sec;
578         for (;;) {
579                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
580                         sec = rtcin(RTC_SEC);
581                 count = sys_cputimer->count();
582                 tot_count += (int)(count - prev_count);
583                 prev_count = count;
584                 if (sec != start_sec)
585                         break;
586                 if (--timeout == 0)
587                         goto fail;
588         }
589
590         /*
591          * Read the cpu cycle counter.  The timing considerations are
592          * similar to those for the i8254 clock.
593          */
594         if (tsc_present) {
595                 tsc_frequency = rdtsc() - old_tsc;
596         }
597
598         if (tsc_present)
599                 kprintf("TSC clock: %llu Hz, ", tsc_frequency);
600         kprintf("i8254 clock: %u Hz\n", tot_count);
601         return (tot_count);
602
603 fail:
604         kprintf("failed, using default i8254 clock of %u Hz\n",
605                 i8254_cputimer.freq);
606         return (i8254_cputimer.freq);
607 }
608
609 static void
610 i8254_restore(void)
611 {
612         timer0_state = ACQUIRED;
613
614         clock_lock();
615
616         /*
617          * Timer0 is our fine-grained variable clock interrupt
618          */
619         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
620         outb(TIMER_CNTR0, 2);   /* lsb */
621         outb(TIMER_CNTR0, 0);   /* msb */
622         clock_unlock();
623
624         if (!i8254_nointr) {
625                 cputimer_intr_register(&i8254_cputimer_intr);
626                 cputimer_intr_select(&i8254_cputimer_intr, 0);
627         }
628
629         /*
630          * Timer1 or timer2 is our free-running clock, but only if another
631          * has not been selected.
632          */
633         cputimer_register(&i8254_cputimer);
634         cputimer_select(&i8254_cputimer, 0);
635 }
636
637 static void
638 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
639 {
640         int which;
641
642         /*
643          * Should we use timer 1 or timer 2 ?
644          */
645         which = 0;
646         TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
647         if (which != 1 && which != 2)
648                 which = 2;
649
650         switch(which) {
651         case 1:
652                 timer->name = "i8254_timer1";
653                 timer->type = CPUTIMER_8254_SEL1;
654                 i8254_walltimer_sel = TIMER_SEL1;
655                 i8254_walltimer_cntr = TIMER_CNTR1;
656                 timer1_state = ACQUIRED;
657                 break;
658         case 2:
659                 timer->name = "i8254_timer2";
660                 timer->type = CPUTIMER_8254_SEL2;
661                 i8254_walltimer_sel = TIMER_SEL2;
662                 i8254_walltimer_cntr = TIMER_CNTR2;
663                 timer2_state = ACQUIRED;
664                 break;
665         }
666
667         timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
668
669         clock_lock();
670         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
671         outb(i8254_walltimer_cntr, 0);  /* lsb */
672         outb(i8254_walltimer_cntr, 0);  /* msb */
673         outb(IO_PPI, inb(IO_PPI) | 1);  /* bit 0: enable gate, bit 1: spkr */
674         clock_unlock();
675 }
676
677 static void
678 i8254_cputimer_destruct(struct cputimer *timer)
679 {
680         switch(timer->type) {
681         case CPUTIMER_8254_SEL1:
682             timer1_state = RELEASED;
683             break;
684         case CPUTIMER_8254_SEL2:
685             timer2_state = RELEASED;
686             break;
687         default:
688             break;
689         }
690         timer->type = 0;
691 }
692
693 static void
694 rtc_restore(void)
695 {
696         /* Restore all of the RTC's "status" (actually, control) registers. */
697         writertc(RTC_STATUSB, RTCSB_24HR);
698         writertc(RTC_STATUSA, rtc_statusa);
699         writertc(RTC_STATUSB, rtc_statusb);
700 }
701
702 /*
703  * Restore all the timers.
704  *
705  * This function is called to resynchronize our core timekeeping after a
706  * long halt, e.g. from apm_default_resume() and friends.  It is also 
707  * called if after a BIOS call we have detected munging of the 8254.
708  * It is necessary because cputimer_count() counter's delta may have grown
709  * too large for nanouptime() and friends to handle, or (in the case of 8254
710  * munging) might cause the SYSTIMER code to prematurely trigger.
711  */
712 void
713 timer_restore(void)
714 {
715         crit_enter();
716         i8254_restore();                /* restore timer_freq and hz */
717         rtc_restore();                  /* reenable RTC interrupts */
718         crit_exit();
719 }
720
721 /*
722  * Initialize 8254 timer 0 early so that it can be used in DELAY().
723  */
724 void
725 startrtclock(void)
726 {
727         u_int delta, freq;
728
729         /* 
730          * Can we use the TSC?
731          */
732         if (cpu_feature & CPUID_TSC)
733                 tsc_present = 1;
734         else
735                 tsc_present = 0;
736
737         /*
738          * Initial RTC state, don't do anything unexpected
739          */
740         writertc(RTC_STATUSA, rtc_statusa);
741         writertc(RTC_STATUSB, RTCSB_24HR);
742
743         /*
744          * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to 
745          * generate an interrupt, which we will ignore for now.
746          *
747          * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
748          * (so it counts a full 2^16 and repeats).  We will use this timer
749          * for our counting.
750          */
751         i8254_restore();
752         freq = calibrate_clocks();
753 #ifdef CLK_CALIBRATION_LOOP
754         if (bootverbose) {
755                 kprintf(
756                 "Press a key on the console to abort clock calibration\n");
757                 while (cncheckc() == -1)
758                         calibrate_clocks();
759         }
760 #endif
761
762         /*
763          * Use the calibrated i8254 frequency if it seems reasonable.
764          * Otherwise use the default, and don't use the calibrated i586
765          * frequency.
766          */
767         delta = freq > i8254_cputimer.freq ? 
768                         freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
769         if (delta < i8254_cputimer.freq / 100) {
770 #ifndef CLK_USE_I8254_CALIBRATION
771                 if (bootverbose)
772                         kprintf(
773 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
774                 freq = i8254_cputimer.freq;
775 #endif
776                 /*
777                  * NOTE:
778                  * Interrupt timer's freq must be adjusted
779                  * before we change the cuptimer's frequency.
780                  */
781                 i8254_cputimer_intr.freq = freq;
782                 cputimer_set_frequency(&i8254_cputimer, freq);
783         } else {
784                 if (bootverbose)
785                         kprintf(
786                     "%d Hz differs from default of %d Hz by more than 1%%\n",
787                                freq, i8254_cputimer.freq);
788                 tsc_frequency = 0;
789         }
790
791 #ifndef CLK_USE_TSC_CALIBRATION
792         if (tsc_frequency != 0) {
793                 if (bootverbose)
794                         kprintf(
795 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
796                 tsc_frequency = 0;
797         }
798 #endif
799         if (tsc_present && tsc_frequency == 0) {
800                 /*
801                  * Calibration of the i586 clock relative to the mc146818A
802                  * clock failed.  Do a less accurate calibration relative
803                  * to the i8254 clock.
804                  */
805                 u_int64_t old_tsc = rdtsc();
806
807                 DELAY(1000000);
808                 tsc_frequency = rdtsc() - old_tsc;
809 #ifdef CLK_USE_TSC_CALIBRATION
810                 if (bootverbose) {
811                         kprintf("TSC clock: %llu Hz (Method B)\n",
812                                 tsc_frequency);
813                 }
814 #endif
815         }
816
817         EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
818 }
819
820 /*
821  * Sync the time of day back to the RTC on shutdown, but only if
822  * we have already loaded it and have not crashed.
823  */
824 static void
825 resettodr_on_shutdown(void *arg __unused)
826 {
827         if (rtc_loaded && panicstr == NULL) {
828                 resettodr();
829         }
830 }
831
832 /*
833  * Initialize the time of day register, based on the time base which is, e.g.
834  * from a filesystem.
835  */
836 void
837 inittodr(time_t base)
838 {
839         unsigned long   sec, days;
840         int             year, month;
841         int             y, m;
842         struct timespec ts;
843
844         if (base) {
845                 ts.tv_sec = base;
846                 ts.tv_nsec = 0;
847                 set_timeofday(&ts);
848         }
849
850         /* Look if we have a RTC present and the time is valid */
851         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
852                 goto wrong_time;
853
854         /* wait for time update to complete */
855         /* If RTCSA_TUP is zero, we have at least 244us before next update */
856         crit_enter();
857         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
858                 crit_exit();
859                 crit_enter();
860         }
861
862         days = 0;
863 #ifdef USE_RTC_CENTURY
864         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
865 #else
866         year = readrtc(RTC_YEAR) + 1900;
867         if (year < 1970)
868                 year += 100;
869 #endif
870         if (year < 1970) {
871                 crit_exit();
872                 goto wrong_time;
873         }
874         month = readrtc(RTC_MONTH);
875         for (m = 1; m < month; m++)
876                 days += daysinmonth[m-1];
877         if ((month > 2) && LEAPYEAR(year))
878                 days ++;
879         days += readrtc(RTC_DAY) - 1;
880         for (y = 1970; y < year; y++)
881                 days += DAYSPERYEAR + LEAPYEAR(y);
882         sec = ((( days * 24 +
883                   readrtc(RTC_HRS)) * 60 +
884                   readrtc(RTC_MIN)) * 60 +
885                   readrtc(RTC_SEC));
886         /* sec now contains the number of seconds, since Jan 1 1970,
887            in the local time zone */
888
889         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
890
891         y = time_second - sec;
892         if (y <= -2 || y >= 2) {
893                 /* badly off, adjust it */
894                 ts.tv_sec = sec;
895                 ts.tv_nsec = 0;
896                 set_timeofday(&ts);
897         }
898         rtc_loaded = 1;
899         crit_exit();
900         return;
901
902 wrong_time:
903         kprintf("Invalid time in real time clock.\n");
904         kprintf("Check and reset the date immediately!\n");
905 }
906
907 /*
908  * Write system time back to RTC
909  */
910 void
911 resettodr(void)
912 {
913         struct timeval tv;
914         unsigned long tm;
915         int m;
916         int y;
917
918         if (disable_rtc_set)
919                 return;
920
921         microtime(&tv);
922         tm = tv.tv_sec;
923
924         crit_enter();
925         /* Disable RTC updates and interrupts. */
926         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
927
928         /* Calculate local time to put in RTC */
929
930         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
931
932         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
933         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
934         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
935
936         /* We have now the days since 01-01-1970 in tm */
937         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
938         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
939              tm >= m;
940              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
941              tm -= m;
942
943         /* Now we have the years in y and the day-of-the-year in tm */
944         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
945 #ifdef USE_RTC_CENTURY
946         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
947 #endif
948         for (m = 0; ; m++) {
949                 int ml;
950
951                 ml = daysinmonth[m];
952                 if (m == 1 && LEAPYEAR(y))
953                         ml++;
954                 if (tm < ml)
955                         break;
956                 tm -= ml;
957         }
958
959         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
960         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
961
962         /* Reenable RTC updates and interrupts. */
963         writertc(RTC_STATUSB, rtc_statusb);
964         crit_exit();
965 }
966
967 static int
968 i8254_ioapic_trial(int irq, struct cputimer_intr *cti)
969 {
970         sysclock_t base;
971         long lastcnt;
972
973         /*
974          * Following code assumes the 8254 is the cpu timer,
975          * so make sure it is.
976          */
977         KKASSERT(sys_cputimer == &i8254_cputimer);
978         KKASSERT(cti == &i8254_cputimer_intr);
979
980         lastcnt = get_interrupt_counter(irq, mycpuid);
981
982         /*
983          * Force an 8254 Timer0 interrupt and wait 1/100s for
984          * it to happen, then see if we got it.
985          */
986         kprintf("IOAPIC: testing 8254 interrupt delivery\n");
987
988         i8254_intr_reload(cti, 2);
989         base = sys_cputimer->count();
990         while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
991                 ; /* nothing */
992
993         if (get_interrupt_counter(irq, mycpuid) - lastcnt == 0)
994                 return ENOENT;
995         return 0;
996 }
997
998 /*
999  * Start both clocks running.  DragonFly note: the stat clock is no longer
1000  * used.  Instead, 8254 based systimers are used for all major clock
1001  * interrupts.
1002  */
1003 static void
1004 i8254_intr_initclock(struct cputimer_intr *cti, boolean_t selected)
1005 {
1006         void *clkdesc = NULL;
1007         int irq = 0, mixed_mode = 0, error;
1008
1009         KKASSERT(mycpuid == 0);
1010         callout_init(&sysbeepstop_ch);
1011
1012         if (!selected && i8254_intr_disable)
1013                 goto nointr;
1014
1015         /*
1016          * The stat interrupt mask is different without the
1017          * statistics clock.  Also, don't set the interrupt
1018          * flag which would normally cause the RTC to generate
1019          * interrupts.
1020          */
1021         rtc_statusb = RTCSB_24HR;
1022
1023         /* Finish initializing 8253 timer 0. */
1024         if (ioapic_enable) {
1025                 irq = machintr_legacy_intr_find(0, INTR_TRIGGER_EDGE,
1026                         INTR_POLARITY_HIGH);
1027                 if (irq < 0) {
1028 mixed_mode_setup:
1029                         error = ioapic_conf_legacy_extint(0);
1030                         if (!error) {
1031                                 irq = machintr_legacy_intr_find(0,
1032                                     INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
1033                                 if (irq < 0)
1034                                         error = ENOENT;
1035                         }
1036
1037                         if (error) {
1038                                 if (!selected) {
1039                                         kprintf("IOAPIC: setup mixed mode for "
1040                                                 "irq 0 failed: %d\n", error);
1041                                         goto nointr;
1042                                 } else {
1043                                         panic("IOAPIC: setup mixed mode for "
1044                                               "irq 0 failed: %d\n", error);
1045                                 }
1046                         }
1047                         mixed_mode = 1;
1048                 }
1049                 clkdesc = register_int(irq, clkintr, NULL, "clk",
1050                                        NULL,
1051                                        INTR_EXCL | INTR_CLOCK |
1052                                        INTR_NOPOLL | INTR_MPSAFE |
1053                                        INTR_NOENTROPY, 0);
1054         } else {
1055                 register_int(0, clkintr, NULL, "clk", NULL,
1056                              INTR_EXCL | INTR_CLOCK |
1057                              INTR_NOPOLL | INTR_MPSAFE |
1058                              INTR_NOENTROPY, 0);
1059         }
1060
1061         /* Initialize RTC. */
1062         writertc(RTC_STATUSA, rtc_statusa);
1063         writertc(RTC_STATUSB, RTCSB_24HR);
1064
1065         if (ioapic_enable) {
1066                 error = i8254_ioapic_trial(irq, cti);
1067                 if (error) {
1068                         if (mixed_mode) {
1069                                 if (!selected) {
1070                                         kprintf("IOAPIC: mixed mode for irq %d "
1071                                                 "trial failed: %d\n",
1072                                                 irq, error);
1073                                         goto nointr;
1074                                 } else {
1075                                         panic("IOAPIC: mixed mode for irq %d "
1076                                               "trial failed: %d\n", irq, error);
1077                                 }
1078                         } else {
1079                                 kprintf("IOAPIC: warning 8254 is not connected "
1080                                         "to the correct pin, try mixed mode\n");
1081                                 unregister_int(clkdesc, 0);
1082                                 goto mixed_mode_setup;
1083                         }
1084                 }
1085         }
1086         return;
1087
1088 nointr:
1089         i8254_nointr = 1; /* don't try to register again */
1090         cputimer_intr_deregister(cti);
1091 }
1092
1093 void
1094 setstatclockrate(int newhz)
1095 {
1096         if (newhz == RTC_PROFRATE)
1097                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1098         else
1099                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1100         writertc(RTC_STATUSA, rtc_statusa);
1101 }
1102
1103 #if 0
1104 static unsigned
1105 tsc_get_timecount(struct timecounter *tc)
1106 {
1107         return (rdtsc());
1108 }
1109 #endif
1110
1111 #ifdef KERN_TIMESTAMP
1112 #define KERN_TIMESTAMP_SIZE 16384
1113 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1114 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1115         sizeof(tsc), "LU", "Kernel timestamps");
1116 void  
1117 _TSTMP(u_int32_t x)
1118 {
1119         static int i;
1120
1121         tsc[i] = (u_int32_t)rdtsc();
1122         tsc[i+1] = x;
1123         i = i + 2;
1124         if (i >= KERN_TIMESTAMP_SIZE)
1125                 i = 0;
1126         tsc[i] = 0; /* mark last entry */
1127 }
1128 #endif /* KERN_TIMESTAMP */
1129
1130 /*
1131  *
1132  */
1133
1134 static int
1135 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1136 {
1137     sysclock_t count;
1138     __uint64_t tscval;
1139     char buf[32];
1140
1141     crit_enter();
1142     if (sys_cputimer == &i8254_cputimer)
1143         count = sys_cputimer->count();
1144     else
1145         count = 0;
1146     if (tsc_present)
1147         tscval = rdtsc();
1148     else
1149         tscval = 0;
1150     crit_exit();
1151     ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1152     return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1153 }
1154
1155 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1156 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1157             "frequency");
1158 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1159             0, 0, hw_i8254_timestamp, "A", "");
1160
1161 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1162             &tsc_present, 0, "TSC Available");
1163 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1164             &tsc_frequency, 0, "TSC Frequency");
1165