Allow one shot timer to be switched on a running system between i8254 and
[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  * $DragonFly: src/sys/platform/pc32/isa/clock.c,v 1.55 2008/08/02 01:14:43 dillon Exp $
39  */
40
41 /*
42  * Routines to handle clock hardware.
43  */
44
45 /*
46  * inittodr, settodr and support routines written
47  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>
48  *
49  * reintroduced and updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
50  */
51
52 #include "use_apm.h"
53 #include "opt_clock.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/eventhandler.h>
58 #include <sys/time.h>
59 #include <sys/kernel.h>
60 #include <sys/bus.h>
61 #ifndef SMP
62 #include <sys/lock.h>
63 #endif
64 #include <sys/sysctl.h>
65 #include <sys/cons.h>
66 #include <sys/systimer.h>
67 #include <sys/globaldata.h>
68 #include <sys/thread2.h>
69 #include <sys/systimer.h>
70 #include <sys/machintr.h>
71
72 #include <machine/clock.h>
73 #ifdef CLK_CALIBRATION_LOOP
74 #endif
75 #include <machine/cputypes.h>
76 #include <machine/frame.h>
77 #include <machine/ipl.h>
78 #include <machine/limits.h>
79 #include <machine/md_var.h>
80 #include <machine/psl.h>
81 #include <machine/segments.h>
82 #include <machine/smp.h>
83 #include <machine/specialreg.h>
84
85 #include <machine_base/icu/icu.h>
86 #include <bus/isa/isa.h>
87 #include <bus/isa/rtc.h>
88 #include <machine_base/isa/timerreg.h>
89
90 #include <machine_base/isa/intr_machdep.h>
91
92 #ifdef APIC_IO
93 /* The interrupt triggered by the 8254 (timer) chip */
94 int apic_8254_intr;
95 static void setup_8254_mixed_mode (void);
96 #endif
97 static void i8254_restore(void);
98 static void resettodr_on_shutdown(void *arg __unused);
99
100 /*
101  * 32-bit time_t's can't reach leap years before 1904 or after 2036, so we
102  * can use a simple formula for leap years.
103  */
104 #define LEAPYEAR(y) ((u_int)(y) % 4 == 0)
105 #define DAYSPERYEAR   (31+28+31+30+31+30+31+31+30+31+30+31)
106
107 #ifndef TIMER_FREQ
108 #define TIMER_FREQ   1193182
109 #endif
110
111 static uint8_t i8254_walltimer_sel;
112 static uint16_t i8254_walltimer_cntr;
113
114 int     adjkerntz;              /* local offset from GMT in seconds */
115 int     disable_rtc_set;        /* disable resettodr() if != 0 */
116 int     statclock_disable = 1;  /* we don't use the statclock right now */
117 int     tsc_present;
118 int64_t tsc_frequency;
119 int     tsc_is_broken;
120 int     wall_cmos_clock;        /* wall CMOS clock assumed if != 0 */
121 int     timer0_running;
122 enum tstate { RELEASED, ACQUIRED };
123 enum tstate timer0_state;
124 enum tstate timer1_state;
125 enum tstate timer2_state;
126
127 static void     i8254_intr_reload(sysclock_t);
128 void            (*cputimer_intr_reload)(sysclock_t) = i8254_intr_reload;
129
130 static  int     beeping = 0;
131 static  const u_char daysinmonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
132 static  u_char  rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
133 static  u_char  rtc_statusb = RTCSB_24HR | RTCSB_PINTR;
134 static  int     rtc_loaded;
135
136 static int i8254_cputimer_div;
137
138 static struct callout sysbeepstop_ch;
139
140 static sysclock_t i8254_cputimer_count(void);
141 static void i8254_cputimer_construct(struct cputimer *cputimer, sysclock_t last);
142 static void i8254_cputimer_destruct(struct cputimer *cputimer);
143
144 static struct cputimer  i8254_cputimer = {
145     SLIST_ENTRY_INITIALIZER,
146     "i8254",
147     CPUTIMER_PRI_8254,
148     0,
149     i8254_cputimer_count,
150     cputimer_default_fromhz,
151     cputimer_default_fromus,
152     i8254_cputimer_construct,
153     i8254_cputimer_destruct,
154     TIMER_FREQ,
155     0, 0, 0
156 };
157
158 /*
159  * timer0 clock interrupt.  Timer0 is in one-shot mode and has stopped
160  * counting as of this interrupt.  We use timer1 in free-running mode (not
161  * generating any interrupts) as our main counter.  Each cpu has timeouts
162  * pending.
163  *
164  * This code is INTR_MPSAFE and may be called without the BGL held.
165  */
166 static void
167 clkintr(void *dummy, void *frame_arg)
168 {
169         static sysclock_t sysclock_count;       /* NOTE! Must be static */
170         struct globaldata *gd = mycpu;
171 #ifdef SMP
172         struct globaldata *gscan;
173         int n;
174 #endif
175
176         /*
177          * SWSTROBE mode is a one-shot, the timer is no longer running
178          */
179         timer0_running = 0;
180
181         /*
182          * XXX the dispatcher needs work.  right now we call systimer_intr()
183          * directly or via IPI for any cpu with systimers queued, which is
184          * usually *ALL* of them.  We need to use the LAPIC timer for this.
185          */
186         sysclock_count = sys_cputimer->count();
187 #ifdef SMP
188         for (n = 0; n < ncpus; ++n) {
189             gscan = globaldata_find(n);
190             if (TAILQ_FIRST(&gscan->gd_systimerq) == NULL)
191                 continue;
192             if (gscan != gd) {
193                 lwkt_send_ipiq3(gscan, (ipifunc3_t)systimer_intr, 
194                                 &sysclock_count, 0);
195             } else {
196                 systimer_intr(&sysclock_count, 0, frame_arg);
197             }
198         }
199 #else
200         if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
201             systimer_intr(&sysclock_count, 0, frame_arg);
202 #endif
203 }
204
205
206 /*
207  * NOTE! not MP safe.
208  */
209 int
210 acquire_timer2(int mode)
211 {
212         if (timer2_state != RELEASED)
213                 return (-1);
214         timer2_state = ACQUIRED;
215
216         /*
217          * This access to the timer registers is as atomic as possible
218          * because it is a single instruction.  We could do better if we
219          * knew the rate.
220          */
221         outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f));
222         return (0);
223 }
224
225 int
226 release_timer2(void)
227 {
228         if (timer2_state != ACQUIRED)
229                 return (-1);
230         outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT);
231         timer2_state = RELEASED;
232         return (0);
233 }
234
235 /*
236  * This routine receives statistical clock interrupts from the RTC.
237  * As explained above, these occur at 128 interrupts per second.
238  * When profiling, we receive interrupts at a rate of 1024 Hz.
239  *
240  * This does not actually add as much overhead as it sounds, because
241  * when the statistical clock is active, the hardclock driver no longer
242  * needs to keep (inaccurate) statistics on its own.  This decouples
243  * statistics gathering from scheduling interrupts.
244  *
245  * The RTC chip requires that we read status register C (RTC_INTR)
246  * to acknowledge an interrupt, before it will generate the next one.
247  * Under high interrupt load, rtcintr() can be indefinitely delayed and
248  * the clock can tick immediately after the read from RTC_INTR.  In this
249  * case, the mc146818A interrupt signal will not drop for long enough
250  * to register with the 8259 PIC.  If an interrupt is missed, the stat
251  * clock will halt, considerably degrading system performance.  This is
252  * why we use 'while' rather than a more straightforward 'if' below.
253  * Stat clock ticks can still be lost, causing minor loss of accuracy
254  * in the statistics, but the stat clock will no longer stop.
255  */
256 static void
257 rtcintr(void *dummy, void *frame)
258 {
259         while (rtcin(RTC_INTR) & RTCIR_PERIOD)
260                 ;
261                 /* statclock(frame); no longer used */
262 }
263
264 #include "opt_ddb.h"
265 #ifdef DDB
266 #include <ddb/ddb.h>
267
268 DB_SHOW_COMMAND(rtc, rtc)
269 {
270         kprintf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n",
271                rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY),
272                rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC),
273                rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR));
274 }
275 #endif /* DDB */
276
277 /*
278  * Return the current cpu timer count as a 32 bit integer.
279  */
280 static
281 sysclock_t
282 i8254_cputimer_count(void)
283 {
284         static __uint16_t cputimer_last;
285         __uint16_t count;
286         sysclock_t ret;
287
288         clock_lock();
289         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_LATCH);
290         count = (__uint8_t)inb(i8254_walltimer_cntr);           /* get countdown */
291         count |= ((__uint8_t)inb(i8254_walltimer_cntr) << 8);
292         count = -count;                                 /* -> countup */
293         if (count < cputimer_last)                      /* rollover */
294                 i8254_cputimer.base += 0x00010000;
295         ret = i8254_cputimer.base | count;
296         cputimer_last = count;
297         clock_unlock();
298         return(ret);
299 }
300
301 /*
302  * This function is called whenever the system timebase changes, allowing
303  * us to calculate what is needed to convert a system timebase tick 
304  * into an 8254 tick for the interrupt timer.  If we can convert to a
305  * simple shift, multiplication, or division, we do so.  Otherwise 64
306  * bit arithmatic is required every time the interrupt timer is reloaded.
307  */
308 void
309 cputimer_intr_config(struct cputimer *timer)
310 {
311     int freq;
312     int div;
313
314     /*
315      * Will a simple divide do the trick?
316      */
317     div = (timer->freq + (i8254_cputimer.freq / 2)) / i8254_cputimer.freq;
318     freq = i8254_cputimer.freq * div;
319
320     if (freq >= timer->freq - 1 && freq <= timer->freq + 1)
321         i8254_cputimer_div = div;
322     else
323         i8254_cputimer_div = 0;
324 }
325
326 /*
327  * Reload for the next timeout.  It is possible for the reload value
328  * to be 0 or negative, indicating that an immediate timer interrupt
329  * is desired.  For now make the minimum 2 ticks.
330  *
331  * We may have to convert from the system timebase to the 8254 timebase.
332  */
333 static void
334 i8254_intr_reload(sysclock_t reload)
335 {
336     __uint16_t count;
337
338     if (i8254_cputimer_div)
339         reload /= i8254_cputimer_div;
340     else
341         reload = (int64_t)reload * i8254_cputimer.freq / sys_cputimer->freq;
342
343     if ((int)reload < 2)
344         reload = 2;
345
346     clock_lock();
347     if (timer0_running) {
348         outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);     /* count-down timer */
349         count = (__uint8_t)inb(TIMER_CNTR0);            /* lsb */
350         count |= ((__uint8_t)inb(TIMER_CNTR0) << 8);    /* msb */
351         if (reload < count) {
352             outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
353             outb(TIMER_CNTR0, (__uint8_t)reload);       /* lsb */
354             outb(TIMER_CNTR0, (__uint8_t)(reload >> 8)); /* msb */
355         }
356     } else {
357         timer0_running = 1;
358         if (reload > 0xFFFF)
359             reload = 0;         /* full count */
360         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
361         outb(TIMER_CNTR0, (__uint8_t)reload);           /* lsb */
362         outb(TIMER_CNTR0, (__uint8_t)(reload >> 8));    /* msb */
363     }
364     clock_unlock();
365 }
366
367 #ifdef SMP
368
369 extern int      lapic_timer_test;
370 extern int      lapic_timer_enable;
371 extern void     lapic_timer_oneshot_intr_enable(void);
372 extern void     lapic_timer_intr_test(void);
373 extern void     lapic_timer_restart(void);
374
375 /* Piggyback lapic_timer test */
376 static void
377 i8254_intr_reload_test(sysclock_t reload)
378 {
379         i8254_intr_reload(reload);
380         if (__predict_false(lapic_timer_test))
381                 lapic_timer_intr_test();
382 }
383
384 #endif  /* SMP */
385
386 void
387 cputimer_intr_enable(void)
388 {
389 #ifdef SMP
390         if (lapic_timer_test || lapic_timer_enable) {
391                 lapic_timer_oneshot_intr_enable();
392                 if (lapic_timer_test) /* XXX */
393                         cputimer_intr_reload = i8254_intr_reload_test;
394         }
395 #endif
396 }
397
398 void
399 cputimer_intr_switch(enum cputimer_intr_type type)
400 {
401 #ifdef SMP
402         if (lapic_timer_enable || lapic_timer_test) {
403                 switch (type) {
404                 case CPUTIMER_INTRT_C3:
405                         cputimer_intr_reload = i8254_intr_reload;
406                         /* Force a quick reload */
407                         i8254_intr_reload(0);
408                         break;
409
410                 case CPUTIMER_INTRT_FAST:
411                         if (lapic_timer_test) /* XXX */
412                                 cputimer_intr_reload = i8254_intr_reload_test;
413                         else if (lapic_timer_enable)
414                                 lapic_timer_restart();
415                         break;
416                 }
417         }
418 #endif
419 }
420
421 static int
422 sysctl_cputimer_intr_switch(SYSCTL_HANDLER_ARGS)
423 {
424         enum cputimer_intr_type type = CPUTIMER_INTRT_FAST;
425         int error;
426
427         error = sysctl_handle_int(oidp, &type, 0, req);
428         if (error || req->newptr == NULL)
429                 return error;
430         switch (type) {
431         case CPUTIMER_INTRT_C3:
432         case CPUTIMER_INTRT_FAST:
433                 break;
434         default:
435                 return EINVAL;
436         }
437         cputimer_intr_switch(type);
438         return 0;
439 }
440 SYSCTL_PROC(_hw, OID_AUTO, cputimer_intr_type, CTLTYPE_INT | CTLFLAG_RW,
441             0, 0, sysctl_cputimer_intr_switch, "I",
442             "cputimer_intr switch [0|1]");
443
444 /*
445  * DELAY(usec)       - Spin for the specified number of microseconds.
446  * DRIVERSLEEP(usec) - Spin for the specified number of microseconds,
447  *                     but do a thread switch in the loop
448  *
449  * Relies on timer 1 counting down from (cputimer_freq / hz)
450  * Note: timer had better have been programmed before this is first used!
451  */
452 static void
453 DODELAY(int n, int doswitch)
454 {
455         int delta, prev_tick, tick, ticks_left;
456
457 #ifdef DELAYDEBUG
458         int getit_calls = 1;
459         int n1;
460         static int state = 0;
461
462         if (state == 0) {
463                 state = 1;
464                 for (n1 = 1; n1 <= 10000000; n1 *= 10)
465                         DELAY(n1);
466                 state = 2;
467         }
468         if (state == 1)
469                 kprintf("DELAY(%d)...", n);
470 #endif
471         /*
472          * Guard against the timer being uninitialized if we are called
473          * early for console i/o.
474          */
475         if (timer0_state == RELEASED)
476                 i8254_restore();
477
478         /*
479          * Read the counter first, so that the rest of the setup overhead is
480          * counted.  Then calculate the number of hardware timer ticks
481          * required, rounding up to be sure we delay at least the requested
482          * number of microseconds.
483          */
484         prev_tick = sys_cputimer->count();
485         ticks_left = ((u_int)n * (int64_t)sys_cputimer->freq + 999999) /
486                      1000000;
487
488         /*
489          * Loop until done.
490          */
491         while (ticks_left > 0) {
492                 tick = sys_cputimer->count();
493 #ifdef DELAYDEBUG
494                 ++getit_calls;
495 #endif
496                 delta = tick - prev_tick;
497                 prev_tick = tick;
498                 if (delta < 0)
499                         delta = 0;
500                 ticks_left -= delta;
501                 if (doswitch && ticks_left > 0)
502                         lwkt_switch();
503         }
504 #ifdef DELAYDEBUG
505         if (state == 1)
506                 kprintf(" %d calls to getit() at %d usec each\n",
507                        getit_calls, (n + 5) / getit_calls);
508 #endif
509 }
510
511 void
512 DELAY(int n)
513 {
514         DODELAY(n, 0);
515 }
516
517 void
518 DRIVERSLEEP(int usec)
519 {
520         globaldata_t gd = mycpu;
521
522         if (gd->gd_intr_nesting_level || 
523             gd->gd_spinlock_rd ||
524             gd->gd_spinlocks_wr) {
525                 DODELAY(usec, 0);
526         } else {
527                 DODELAY(usec, 1);
528         }
529 }
530
531 static void
532 sysbeepstop(void *chan)
533 {
534         outb(IO_PPI, inb(IO_PPI)&0xFC); /* disable counter2 output to speaker */
535         beeping = 0;
536         release_timer2();
537 }
538
539 int
540 sysbeep(int pitch, int period)
541 {
542         if (acquire_timer2(TIMER_SQWAVE|TIMER_16BIT))
543                 return(-1);
544         /*
545          * Nobody else is using timer2, we do not need the clock lock
546          */
547         outb(TIMER_CNTR2, pitch);
548         outb(TIMER_CNTR2, (pitch>>8));
549         if (!beeping) {
550                 /* enable counter2 output to speaker */
551                 outb(IO_PPI, inb(IO_PPI) | 3);
552                 beeping = period;
553                 callout_reset(&sysbeepstop_ch, period, sysbeepstop, NULL);
554         }
555         return (0);
556 }
557
558 /*
559  * RTC support routines
560  */
561
562 int
563 rtcin(int reg)
564 {
565         u_char val;
566
567         crit_enter();
568         outb(IO_RTC, reg);
569         inb(0x84);
570         val = inb(IO_RTC + 1);
571         inb(0x84);
572         crit_exit();
573         return (val);
574 }
575
576 static __inline void
577 writertc(u_char reg, u_char val)
578 {
579         crit_enter();
580         inb(0x84);
581         outb(IO_RTC, reg);
582         inb(0x84);
583         outb(IO_RTC + 1, val);
584         inb(0x84);              /* XXX work around wrong order in rtcin() */
585         crit_exit();
586 }
587
588 static __inline int
589 readrtc(int port)
590 {
591         return(bcd2bin(rtcin(port)));
592 }
593
594 static u_int
595 calibrate_clocks(void)
596 {
597         u_int64_t old_tsc;
598         u_int count, prev_count, tot_count;
599         int sec, start_sec, timeout;
600
601         if (bootverbose)
602                 kprintf("Calibrating clock(s) ... ");
603         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
604                 goto fail;
605         timeout = 100000000;
606
607         /* Read the mc146818A seconds counter. */
608         for (;;) {
609                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
610                         sec = rtcin(RTC_SEC);
611                         break;
612                 }
613                 if (--timeout == 0)
614                         goto fail;
615         }
616
617         /* Wait for the mC146818A seconds counter to change. */
618         start_sec = sec;
619         for (;;) {
620                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP)) {
621                         sec = rtcin(RTC_SEC);
622                         if (sec != start_sec)
623                                 break;
624                 }
625                 if (--timeout == 0)
626                         goto fail;
627         }
628
629         /* Start keeping track of the i8254 counter. */
630         prev_count = sys_cputimer->count();
631         tot_count = 0;
632
633         if (tsc_present) 
634                 old_tsc = rdtsc();
635         else
636                 old_tsc = 0;            /* shut up gcc */
637
638         /*
639          * Wait for the mc146818A seconds counter to change.  Read the i8254
640          * counter for each iteration since this is convenient and only
641          * costs a few usec of inaccuracy. The timing of the final reads
642          * of the counters almost matches the timing of the initial reads,
643          * so the main cause of inaccuracy is the varying latency from 
644          * inside getit() or rtcin(RTC_STATUSA) to the beginning of the
645          * rtcin(RTC_SEC) that returns a changed seconds count.  The
646          * maximum inaccuracy from this cause is < 10 usec on 486's.
647          */
648         start_sec = sec;
649         for (;;) {
650                 if (!(rtcin(RTC_STATUSA) & RTCSA_TUP))
651                         sec = rtcin(RTC_SEC);
652                 count = sys_cputimer->count();
653                 tot_count += (int)(count - prev_count);
654                 prev_count = count;
655                 if (sec != start_sec)
656                         break;
657                 if (--timeout == 0)
658                         goto fail;
659         }
660
661         /*
662          * Read the cpu cycle counter.  The timing considerations are
663          * similar to those for the i8254 clock.
664          */
665         if (tsc_present) {
666                 tsc_frequency = rdtsc() - old_tsc;
667         }
668
669         if (tsc_present)
670                 kprintf("TSC clock: %llu Hz, ", tsc_frequency);
671         kprintf("i8254 clock: %u Hz\n", tot_count);
672         return (tot_count);
673
674 fail:
675         kprintf("failed, using default i8254 clock of %u Hz\n",
676                 i8254_cputimer.freq);
677         return (i8254_cputimer.freq);
678 }
679
680 static void
681 i8254_restore(void)
682 {
683         timer0_state = ACQUIRED;
684
685         clock_lock();
686
687         /*
688          * Timer0 is our fine-grained variable clock interrupt
689          */
690         outb(TIMER_MODE, TIMER_SEL0 | TIMER_SWSTROBE | TIMER_16BIT);
691         outb(TIMER_CNTR0, 2);   /* lsb */
692         outb(TIMER_CNTR0, 0);   /* msb */
693         clock_unlock();
694
695         /*
696          * Timer1 or timer2 is our free-running clock, but only if another
697          * has not been selected.
698          */
699         cputimer_register(&i8254_cputimer);
700         cputimer_select(&i8254_cputimer, 0);
701 }
702
703 static void
704 i8254_cputimer_construct(struct cputimer *timer, sysclock_t oldclock)
705 {
706         int which;
707
708         /*
709          * Should we use timer 1 or timer 2 ?
710          */
711         which = 0;
712         TUNABLE_INT_FETCH("hw.i8254.walltimer", &which);
713         if (which != 1 && which != 2)
714                 which = 2;
715
716         switch(which) {
717         case 1:
718                 timer->name = "i8254_timer1";
719                 timer->type = CPUTIMER_8254_SEL1;
720                 i8254_walltimer_sel = TIMER_SEL1;
721                 i8254_walltimer_cntr = TIMER_CNTR1;
722                 timer1_state = ACQUIRED;
723                 break;
724         case 2:
725                 timer->name = "i8254_timer2";
726                 timer->type = CPUTIMER_8254_SEL2;
727                 i8254_walltimer_sel = TIMER_SEL2;
728                 i8254_walltimer_cntr = TIMER_CNTR2;
729                 timer2_state = ACQUIRED;
730                 break;
731         }
732
733         timer->base = (oldclock + 0xFFFF) & ~0xFFFF;
734
735         clock_lock();
736         outb(TIMER_MODE, i8254_walltimer_sel | TIMER_RATEGEN | TIMER_16BIT);
737         outb(i8254_walltimer_cntr, 0);  /* lsb */
738         outb(i8254_walltimer_cntr, 0);  /* msb */
739         outb(IO_PPI, inb(IO_PPI) | 1);  /* bit 0: enable gate, bit 1: spkr */
740         clock_unlock();
741 }
742
743 static void
744 i8254_cputimer_destruct(struct cputimer *timer)
745 {
746         switch(timer->type) {
747         case CPUTIMER_8254_SEL1:
748             timer1_state = RELEASED;
749             break;
750         case CPUTIMER_8254_SEL2:
751             timer2_state = RELEASED;
752             break;
753         default:
754             break;
755         }
756         timer->type = 0;
757 }
758
759 static void
760 rtc_restore(void)
761 {
762         /* Restore all of the RTC's "status" (actually, control) registers. */
763         writertc(RTC_STATUSB, RTCSB_24HR);
764         writertc(RTC_STATUSA, rtc_statusa);
765         writertc(RTC_STATUSB, rtc_statusb);
766 }
767
768 /*
769  * Restore all the timers.
770  *
771  * This function is called to resynchronize our core timekeeping after a
772  * long halt, e.g. from apm_default_resume() and friends.  It is also 
773  * called if after a BIOS call we have detected munging of the 8254.
774  * It is necessary because cputimer_count() counter's delta may have grown
775  * too large for nanouptime() and friends to handle, or (in the case of 8254
776  * munging) might cause the SYSTIMER code to prematurely trigger.
777  */
778 void
779 timer_restore(void)
780 {
781         crit_enter();
782         i8254_restore();                /* restore timer_freq and hz */
783         rtc_restore();                  /* reenable RTC interrupts */
784         crit_exit();
785 }
786
787 /*
788  * Initialize 8254 timer 0 early so that it can be used in DELAY().
789  */
790 void
791 startrtclock(void)
792 {
793         u_int delta, freq;
794
795         /* 
796          * Can we use the TSC?
797          */
798         if (cpu_feature & CPUID_TSC)
799                 tsc_present = 1;
800         else
801                 tsc_present = 0;
802
803         /*
804          * Initial RTC state, don't do anything unexpected
805          */
806         writertc(RTC_STATUSA, rtc_statusa);
807         writertc(RTC_STATUSB, RTCSB_24HR);
808
809         /*
810          * Set the 8254 timer0 in TIMER_SWSTROBE mode and cause it to 
811          * generate an interrupt, which we will ignore for now.
812          *
813          * Set the 8254 timer1 in TIMER_RATEGEN mode and load 0x0000
814          * (so it counts a full 2^16 and repeats).  We will use this timer
815          * for our counting.
816          */
817         i8254_restore();
818         freq = calibrate_clocks();
819 #ifdef CLK_CALIBRATION_LOOP
820         if (bootverbose) {
821                 kprintf(
822                 "Press a key on the console to abort clock calibration\n");
823                 while (cncheckc() == -1)
824                         calibrate_clocks();
825         }
826 #endif
827
828         /*
829          * Use the calibrated i8254 frequency if it seems reasonable.
830          * Otherwise use the default, and don't use the calibrated i586
831          * frequency.
832          */
833         delta = freq > i8254_cputimer.freq ? 
834                         freq - i8254_cputimer.freq : i8254_cputimer.freq - freq;
835         if (delta < i8254_cputimer.freq / 100) {
836 #ifndef CLK_USE_I8254_CALIBRATION
837                 if (bootverbose)
838                         kprintf(
839 "CLK_USE_I8254_CALIBRATION not specified - using default frequency\n");
840                 freq = i8254_cputimer.freq;
841 #endif
842                 cputimer_set_frequency(&i8254_cputimer, freq);
843         } else {
844                 if (bootverbose)
845                         kprintf(
846                     "%d Hz differs from default of %d Hz by more than 1%%\n",
847                                freq, i8254_cputimer.freq);
848                 tsc_frequency = 0;
849         }
850
851 #ifndef CLK_USE_TSC_CALIBRATION
852         if (tsc_frequency != 0) {
853                 if (bootverbose)
854                         kprintf(
855 "CLK_USE_TSC_CALIBRATION not specified - using old calibration method\n");
856                 tsc_frequency = 0;
857         }
858 #endif
859         if (tsc_present && tsc_frequency == 0) {
860                 /*
861                  * Calibration of the i586 clock relative to the mc146818A
862                  * clock failed.  Do a less accurate calibration relative
863                  * to the i8254 clock.
864                  */
865                 u_int64_t old_tsc = rdtsc();
866
867                 DELAY(1000000);
868                 tsc_frequency = rdtsc() - old_tsc;
869 #ifdef CLK_USE_TSC_CALIBRATION
870                 if (bootverbose) {
871                         kprintf("TSC clock: %llu Hz (Method B)\n",
872                                 tsc_frequency);
873                 }
874 #endif
875         }
876
877         EVENTHANDLER_REGISTER(shutdown_post_sync, resettodr_on_shutdown, NULL, SHUTDOWN_PRI_LAST);
878
879 #if !defined(SMP)
880         /*
881          * We can not use the TSC in SMP mode, until we figure out a
882          * cheap (impossible), reliable and precise (yeah right!)  way
883          * to synchronize the TSCs of all the CPUs.
884          * Curse Intel for leaving the counter out of the I/O APIC.
885          */
886
887 #if NAPM > 0
888         /*
889          * We can not use the TSC if we support APM. Precise timekeeping
890          * on an APM'ed machine is at best a fools pursuit, since 
891          * any and all of the time spent in various SMM code can't 
892          * be reliably accounted for.  Reading the RTC is your only
893          * source of reliable time info.  The i8254 looses too of course
894          * but we need to have some kind of time...
895          * We don't know at this point whether APM is going to be used
896          * or not, nor when it might be activated.  Play it safe.
897          */
898         return;
899 #endif /* NAPM > 0 */
900
901 #endif /* !defined(SMP) */
902 }
903
904 /*
905  * Sync the time of day back to the RTC on shutdown, but only if
906  * we have already loaded it and have not crashed.
907  */
908 static void
909 resettodr_on_shutdown(void *arg __unused)
910 {
911         if (rtc_loaded && panicstr == NULL) {
912                 resettodr();
913         }
914 }
915
916 /*
917  * Initialize the time of day register, based on the time base which is, e.g.
918  * from a filesystem.
919  */
920 void
921 inittodr(time_t base)
922 {
923         unsigned long   sec, days;
924         int             yd;
925         int             year, month;
926         int             y, m;
927         struct timespec ts;
928
929         if (base) {
930                 ts.tv_sec = base;
931                 ts.tv_nsec = 0;
932                 set_timeofday(&ts);
933         }
934
935         /* Look if we have a RTC present and the time is valid */
936         if (!(rtcin(RTC_STATUSD) & RTCSD_PWR))
937                 goto wrong_time;
938
939         /* wait for time update to complete */
940         /* If RTCSA_TUP is zero, we have at least 244us before next update */
941         crit_enter();
942         while (rtcin(RTC_STATUSA) & RTCSA_TUP) {
943                 crit_exit();
944                 crit_enter();
945         }
946
947         days = 0;
948 #ifdef USE_RTC_CENTURY
949         year = readrtc(RTC_YEAR) + readrtc(RTC_CENTURY) * 100;
950 #else
951         year = readrtc(RTC_YEAR) + 1900;
952         if (year < 1970)
953                 year += 100;
954 #endif
955         if (year < 1970) {
956                 crit_exit();
957                 goto wrong_time;
958         }
959         month = readrtc(RTC_MONTH);
960         for (m = 1; m < month; m++)
961                 days += daysinmonth[m-1];
962         if ((month > 2) && LEAPYEAR(year))
963                 days ++;
964         days += readrtc(RTC_DAY) - 1;
965         yd = days;
966         for (y = 1970; y < year; y++)
967                 days += DAYSPERYEAR + LEAPYEAR(y);
968         sec = ((( days * 24 +
969                   readrtc(RTC_HRS)) * 60 +
970                   readrtc(RTC_MIN)) * 60 +
971                   readrtc(RTC_SEC));
972         /* sec now contains the number of seconds, since Jan 1 1970,
973            in the local time zone */
974
975         sec += tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
976
977         y = time_second - sec;
978         if (y <= -2 || y >= 2) {
979                 /* badly off, adjust it */
980                 ts.tv_sec = sec;
981                 ts.tv_nsec = 0;
982                 set_timeofday(&ts);
983         }
984         rtc_loaded = 1;
985         crit_exit();
986         return;
987
988 wrong_time:
989         kprintf("Invalid time in real time clock.\n");
990         kprintf("Check and reset the date immediately!\n");
991 }
992
993 /*
994  * Write system time back to RTC
995  */
996 void
997 resettodr(void)
998 {
999         struct timeval tv;
1000         unsigned long tm;
1001         int m;
1002         int y;
1003
1004         if (disable_rtc_set)
1005                 return;
1006
1007         microtime(&tv);
1008         tm = tv.tv_sec;
1009
1010         crit_enter();
1011         /* Disable RTC updates and interrupts. */
1012         writertc(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
1013
1014         /* Calculate local time to put in RTC */
1015
1016         tm -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
1017
1018         writertc(RTC_SEC, bin2bcd(tm%60)); tm /= 60;    /* Write back Seconds */
1019         writertc(RTC_MIN, bin2bcd(tm%60)); tm /= 60;    /* Write back Minutes */
1020         writertc(RTC_HRS, bin2bcd(tm%24)); tm /= 24;    /* Write back Hours   */
1021
1022         /* We have now the days since 01-01-1970 in tm */
1023         writertc(RTC_WDAY, (tm+4)%7);                   /* Write back Weekday */
1024         for (y = 1970, m = DAYSPERYEAR + LEAPYEAR(y);
1025              tm >= m;
1026              y++,      m = DAYSPERYEAR + LEAPYEAR(y))
1027              tm -= m;
1028
1029         /* Now we have the years in y and the day-of-the-year in tm */
1030         writertc(RTC_YEAR, bin2bcd(y%100));             /* Write back Year    */
1031 #ifdef USE_RTC_CENTURY
1032         writertc(RTC_CENTURY, bin2bcd(y/100));          /* ... and Century    */
1033 #endif
1034         for (m = 0; ; m++) {
1035                 int ml;
1036
1037                 ml = daysinmonth[m];
1038                 if (m == 1 && LEAPYEAR(y))
1039                         ml++;
1040                 if (tm < ml)
1041                         break;
1042                 tm -= ml;
1043         }
1044
1045         writertc(RTC_MONTH, bin2bcd(m + 1));            /* Write back Month   */
1046         writertc(RTC_DAY, bin2bcd(tm + 1));             /* Write back Month Day */
1047
1048         /* Reenable RTC updates and interrupts. */
1049         writertc(RTC_STATUSB, rtc_statusb);
1050         crit_exit();
1051 }
1052
1053
1054 /*
1055  * Start both clocks running.  DragonFly note: the stat clock is no longer
1056  * used.  Instead, 8254 based systimers are used for all major clock
1057  * interrupts.  statclock_disable is set by default.
1058  */
1059 void
1060 cpu_initclocks(void *arg __unused)
1061 {
1062         int diag;
1063 #ifdef APIC_IO
1064         int apic_8254_trial;
1065         void *clkdesc;
1066 #endif /* APIC_IO */
1067
1068         callout_init(&sysbeepstop_ch);
1069
1070         if (statclock_disable) {
1071                 /*
1072                  * The stat interrupt mask is different without the
1073                  * statistics clock.  Also, don't set the interrupt
1074                  * flag which would normally cause the RTC to generate
1075                  * interrupts.
1076                  */
1077                 rtc_statusb = RTCSB_24HR;
1078         } else {
1079                 /* Setting stathz to nonzero early helps avoid races. */
1080                 stathz = RTC_NOPROFRATE;
1081                 profhz = RTC_PROFRATE;
1082         }
1083
1084         /* Finish initializing 8253 timer 0. */
1085 #ifdef APIC_IO
1086
1087         apic_8254_intr = isa_apic_irq(0);
1088         apic_8254_trial = 0;
1089         if (apic_8254_intr >= 0 ) {
1090                 if (apic_int_type(0, 0) == 3)
1091                         apic_8254_trial = 1;
1092         } else {
1093                 /* look for ExtInt on pin 0 */
1094                 if (apic_int_type(0, 0) == 3) {
1095                         apic_8254_intr = apic_irq(0, 0);
1096                         setup_8254_mixed_mode();
1097                 } else 
1098                         panic("APIC_IO: Cannot route 8254 interrupt to CPU");
1099         }
1100
1101         clkdesc = register_int(apic_8254_intr, clkintr, NULL, "clk",
1102                                NULL,
1103                                INTR_EXCL | INTR_FAST | 
1104                                INTR_NOPOLL | INTR_MPSAFE | 
1105                                INTR_NOENTROPY);
1106         machintr_intren(apic_8254_intr);
1107         
1108 #else /* APIC_IO */
1109
1110         register_int(0, clkintr, NULL, "clk", NULL,
1111                      INTR_EXCL | INTR_FAST | 
1112                      INTR_NOPOLL | INTR_MPSAFE |
1113                      INTR_NOENTROPY);
1114         machintr_intren(ICU_IRQ0);
1115
1116 #endif /* APIC_IO */
1117
1118         /* Initialize RTC. */
1119         writertc(RTC_STATUSA, rtc_statusa);
1120         writertc(RTC_STATUSB, RTCSB_24HR);
1121
1122         if (statclock_disable == 0) {
1123                 diag = rtcin(RTC_DIAG);
1124                 if (diag != 0)
1125                         kprintf("RTC BIOS diagnostic error %b\n", diag, RTCDG_BITS);
1126
1127 #ifdef APIC_IO
1128                 if (isa_apic_irq(8) != 8)
1129                         panic("APIC RTC != 8");
1130 #endif /* APIC_IO */
1131
1132                 register_int(8, (inthand2_t *)rtcintr, NULL, "rtc", NULL,
1133                              INTR_EXCL | INTR_FAST | INTR_NOPOLL |
1134                              INTR_NOENTROPY);
1135                 machintr_intren(8);
1136
1137                 writertc(RTC_STATUSB, rtc_statusb);
1138         }
1139
1140 #ifdef APIC_IO
1141         if (apic_8254_trial) {
1142                 sysclock_t base;
1143                 long lastcnt;
1144
1145                 /*
1146                  * Following code assumes the 8254 is the cpu timer,
1147                  * so make sure it is.
1148                  */
1149                 KKASSERT(sys_cputimer == &i8254_cputimer);
1150
1151                 lastcnt = get_interrupt_counter(apic_8254_intr);
1152
1153                 /*
1154                  * Force an 8254 Timer0 interrupt and wait 1/100s for
1155                  * it to happen, then see if we got it.
1156                  */
1157                 kprintf("APIC_IO: Testing 8254 interrupt delivery\n");
1158                 i8254_intr_reload(2);
1159                 base = sys_cputimer->count();
1160                 while (sys_cputimer->count() - base < sys_cputimer->freq / 100)
1161                         ;       /* nothing */
1162                 if (get_interrupt_counter(apic_8254_intr) - lastcnt == 0) {
1163                         /* 
1164                          * The MP table is broken.
1165                          * The 8254 was not connected to the specified pin
1166                          * on the IO APIC.
1167                          * Workaround: Limited variant of mixed mode.
1168                          */
1169                         machintr_intrdis(apic_8254_intr);
1170                         unregister_int(clkdesc);
1171                         kprintf("APIC_IO: Broken MP table detected: "
1172                                "8254 is not connected to "
1173                                "IOAPIC #%d intpin %d\n",
1174                                int_to_apicintpin[apic_8254_intr].ioapic,
1175                                int_to_apicintpin[apic_8254_intr].int_pin);
1176                         /* 
1177                          * Revoke current ISA IRQ 0 assignment and 
1178                          * configure a fallback interrupt routing from
1179                          * the 8254 Timer via the 8259 PIC to the
1180                          * an ExtInt interrupt line on IOAPIC #0 intpin 0.
1181                          * We reuse the low level interrupt handler number.
1182                          */
1183                         if (apic_irq(0, 0) < 0) {
1184                                 revoke_apic_irq(apic_8254_intr);
1185                                 assign_apic_irq(0, 0, apic_8254_intr);
1186                         }
1187                         apic_8254_intr = apic_irq(0, 0);
1188                         setup_8254_mixed_mode();
1189                         register_int(apic_8254_intr, clkintr, NULL, "clk",
1190                                      NULL,
1191                                      INTR_EXCL | INTR_FAST | 
1192                                      INTR_NOPOLL | INTR_MPSAFE |
1193                                      INTR_NOENTROPY);
1194                         machintr_intren(apic_8254_intr);
1195                 }
1196                 
1197         }
1198         if (apic_int_type(0, 0) != 3 ||
1199             int_to_apicintpin[apic_8254_intr].ioapic != 0 ||
1200             int_to_apicintpin[apic_8254_intr].int_pin != 0) {
1201                 kprintf("APIC_IO: routing 8254 via IOAPIC #%d intpin %d\n",
1202                        int_to_apicintpin[apic_8254_intr].ioapic,
1203                        int_to_apicintpin[apic_8254_intr].int_pin);
1204         } else {
1205                 kprintf("APIC_IO: "
1206                        "routing 8254 via 8259 and IOAPIC #0 intpin 0\n");
1207         }
1208 #endif
1209 }
1210 SYSINIT(clocks8254, SI_BOOT2_CLOCKREG, SI_ORDER_FIRST, cpu_initclocks, NULL)
1211
1212 #ifdef APIC_IO
1213
1214 static void 
1215 setup_8254_mixed_mode(void)
1216 {
1217         /*
1218          * Allow 8254 timer to INTerrupt 8259:
1219          *  re-initialize master 8259:
1220          *   reset; prog 4 bytes, single ICU, edge triggered
1221          */
1222         outb(IO_ICU1, 0x13);
1223         outb(IO_ICU1 + 1, IDT_OFFSET);  /* start vector (unused) */
1224         outb(IO_ICU1 + 1, 0x00);        /* ignore slave */
1225         outb(IO_ICU1 + 1, 0x03);        /* auto EOI, 8086 */
1226         outb(IO_ICU1 + 1, 0xfe);        /* unmask INT0 */
1227         
1228         /* program IO APIC for type 3 INT on INT0 */
1229         if (ext_int_setup(0, 0) < 0)
1230                 panic("8254 redirect via APIC pin0 impossible!");
1231 }
1232 #endif
1233
1234 void
1235 setstatclockrate(int newhz)
1236 {
1237         if (newhz == RTC_PROFRATE)
1238                 rtc_statusa = RTCSA_DIVIDER | RTCSA_PROF;
1239         else
1240                 rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
1241         writertc(RTC_STATUSA, rtc_statusa);
1242 }
1243
1244 #if 0
1245 static unsigned
1246 tsc_get_timecount(struct timecounter *tc)
1247 {
1248         return (rdtsc());
1249 }
1250 #endif
1251
1252 #ifdef KERN_TIMESTAMP
1253 #define KERN_TIMESTAMP_SIZE 16384
1254 static u_long tsc[KERN_TIMESTAMP_SIZE] ;
1255 SYSCTL_OPAQUE(_debug, OID_AUTO, timestamp, CTLFLAG_RD, tsc,
1256         sizeof(tsc), "LU", "Kernel timestamps");
1257 void  
1258 _TSTMP(u_int32_t x)
1259 {
1260         static int i;
1261
1262         tsc[i] = (u_int32_t)rdtsc();
1263         tsc[i+1] = x;
1264         i = i + 2;
1265         if (i >= KERN_TIMESTAMP_SIZE)
1266                 i = 0;
1267         tsc[i] = 0; /* mark last entry */
1268 }
1269 #endif /* KERN_TIMESTAMP */
1270
1271 /*
1272  *
1273  */
1274
1275 static int
1276 hw_i8254_timestamp(SYSCTL_HANDLER_ARGS)
1277 {
1278     sysclock_t count;
1279     __uint64_t tscval;
1280     char buf[32];
1281
1282     crit_enter();
1283     if (sys_cputimer == &i8254_cputimer)
1284         count = sys_cputimer->count();
1285     else
1286         count = 0;
1287     if (tsc_present)
1288         tscval = rdtsc();
1289     else
1290         tscval = 0;
1291     crit_exit();
1292     ksnprintf(buf, sizeof(buf), "%08x %016llx", count, (long long)tscval);
1293     return(SYSCTL_OUT(req, buf, strlen(buf) + 1));
1294 }
1295
1296 SYSCTL_NODE(_hw, OID_AUTO, i8254, CTLFLAG_RW, 0, "I8254");
1297 SYSCTL_UINT(_hw_i8254, OID_AUTO, freq, CTLFLAG_RD, &i8254_cputimer.freq, 0,
1298             "frequency");
1299 SYSCTL_PROC(_hw_i8254, OID_AUTO, timestamp, CTLTYPE_STRING|CTLFLAG_RD,
1300             0, 0, hw_i8254_timestamp, "A", "");
1301
1302 SYSCTL_INT(_hw, OID_AUTO, tsc_present, CTLFLAG_RD,
1303             &tsc_present, 0, "TSC Available");
1304 SYSCTL_QUAD(_hw, OID_AUTO, tsc_frequency, CTLFLAG_RD,
1305             &tsc_frequency, 0, "TSC Frequency");
1306