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