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