xref: /netbsd-src/sys/arch/x86/isa/clock.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: clock.c,v 1.39 2020/05/29 12:30:41 rin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * William Jolitz and Don Ahn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)clock.c	7.2 (Berkeley) 5/12/91
35  */
36 /*-
37  * Copyright (c) 1993, 1994 Charles M. Hannum.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * William Jolitz and Don Ahn.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  *
70  *	@(#)clock.c	7.2 (Berkeley) 5/12/91
71  */
72 /*
73  * Mach Operating System
74  * Copyright (c) 1991,1990,1989 Carnegie Mellon University
75  * All Rights Reserved.
76  *
77  * Permission to use, copy, modify and distribute this software and its
78  * documentation is hereby granted, provided that both the copyright
79  * notice and this permission notice appear in all copies of the
80  * software, derivative works or modified versions, and any portions
81  * thereof, and that both notices appear in supporting documentation.
82  *
83  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
84  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
85  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
86  *
87  * Carnegie Mellon requests users of this software to return to
88  *
89  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
90  *  School of Computer Science
91  *  Carnegie Mellon University
92  *  Pittsburgh PA 15213-3890
93  *
94  * any improvements or extensions that they make and grant Carnegie Mellon
95  * the rights to redistribute these changes.
96  */
97 /*
98   Copyright 1988, 1989 by Intel Corporation, Santa Clara, California.
99 
100 		All Rights Reserved
101 
102 Permission to use, copy, modify, and distribute this software and
103 its documentation for any purpose and without fee is hereby
104 granted, provided that the above copyright notice appears in all
105 copies and that both the copyright notice and this permission notice
106 appear in supporting documentation, and that the name of Intel
107 not be used in advertising or publicity pertaining to distribution
108 of the software without specific, written prior permission.
109 
110 INTEL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
111 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
112 IN NO EVENT SHALL INTEL BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
113 CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
114 LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
115 NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
116 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
117 */
118 
119 /*
120  * Primitive clock interrupt routines.
121  */
122 
123 #include <sys/cdefs.h>
124 __KERNEL_RCSID(0, "$NetBSD: clock.c,v 1.39 2020/05/29 12:30:41 rin Exp $");
125 
126 /* #define CLOCKDEBUG */
127 /* #define CLOCK_PARANOIA */
128 
129 #include "opt_multiprocessor.h"
130 #include "opt_ntp.h"
131 
132 #include <sys/param.h>
133 #include <sys/systm.h>
134 #include <sys/time.h>
135 #include <sys/timetc.h>
136 #include <sys/kernel.h>
137 #include <sys/device.h>
138 #include <sys/mutex.h>
139 #include <sys/cpu.h>
140 #include <sys/intr.h>
141 
142 #include <machine/pio.h>
143 #include <machine/cpufunc.h>
144 #include <machine/lock.h>
145 
146 #include <dev/isa/isareg.h>
147 #include <dev/isa/isavar.h>
148 #include <dev/ic/mc146818reg.h>
149 #include <dev/ic/i8253reg.h>
150 #include <i386/isa/nvram.h>
151 #include <x86/x86/tsc.h>
152 #include <x86/lock.h>
153 #include <machine/specialreg.h>
154 #include <x86/rtc.h>
155 
156 #ifndef __x86_64__
157 #include "mca.h"
158 #endif
159 #if NMCA > 0
160 #include <machine/mca_machdep.h>	/* for MCA_system */
161 #endif
162 
163 #include "pcppi.h"
164 #if (NPCPPI > 0)
165 #include <dev/isa/pcppivar.h>
166 
167 int sysbeepmatch(device_t, cfdata_t, void *);
168 void sysbeepattach(device_t, device_t, void *);
169 int sysbeepdetach(device_t, int);
170 
171 CFATTACH_DECL3_NEW(sysbeep, 0,
172     sysbeepmatch, sysbeepattach, sysbeepdetach, NULL, NULL, NULL,
173     DVF_DETACH_SHUTDOWN);
174 
175 static int ppi_attached;
176 static pcppi_tag_t ppicookie;
177 #endif /* PCPPI */
178 
179 #ifdef CLOCKDEBUG
180 int clock_debug = 0;
181 #define DPRINTF(arg) if (clock_debug) printf arg
182 #else
183 #define DPRINTF(arg)
184 #endif
185 
186 void (*x86_delay)(unsigned int) = i8254_delay;
187 
188 void		sysbeep(int, int);
189 static void     tickle_tc(void);
190 
191 static int	clockintr(void *, struct intrframe *);
192 
193 int 		sysbeepdetach(device_t, int);
194 
195 static unsigned int	gettick_broken_latch(void);
196 
197 static volatile uint32_t i8254_lastcount;
198 static volatile uint32_t i8254_offset;
199 static volatile int i8254_ticked;
200 
201 /* to protect TC timer variables */
202 static __cpu_simple_lock_t tmr_lock = __SIMPLELOCK_UNLOCKED;
203 
204 u_int i8254_get_timecount(struct timecounter *);
205 
206 static struct timecounter i8254_timecounter = {
207 	.tc_get_timecount = i8254_get_timecount,
208 	.tc_counter_mask = ~0u,
209 	.tc_frequency = TIMER_FREQ,
210 	.tc_name = "i8254",
211 	.tc_quality = 100,
212 };
213 
214 u_long x86_rtclock_tval;	/* i8254 reload value for countdown */
215 int    rtclock_init = 0;
216 
217 int clock_broken_latch = 0;
218 
219 #ifdef CLOCK_PARANOIA
220 static int ticks[6];
221 #endif
222 /*
223  * i8254 latch check routine:
224  *     National Geode (formerly Cyrix MediaGX) has a serious bug in
225  *     its built-in i8254-compatible clock module.
226  *     machdep sets the variable 'clock_broken_latch' to indicate it.
227  */
228 
229 static unsigned int
230 gettick_broken_latch(void)
231 {
232 	int v1, v2, v3;
233 	int w1, w2, w3;
234 	int s;
235 
236 	/* Don't want someone screwing with the counter while we're here. */
237 	s = splhigh();
238 	__cpu_simple_lock(&tmr_lock);
239 	v1 = inb(IO_TIMER1+TIMER_CNTR0);
240 	v1 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
241 	v2 = inb(IO_TIMER1+TIMER_CNTR0);
242 	v2 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
243 	v3 = inb(IO_TIMER1+TIMER_CNTR0);
244 	v3 |= inb(IO_TIMER1+TIMER_CNTR0) << 8;
245 	__cpu_simple_unlock(&tmr_lock);
246 	splx(s);
247 
248 #ifdef CLOCK_PARANOIA
249 	if (clock_debug) {
250 		ticks[0] = ticks[3];
251 		ticks[1] = ticks[4];
252 		ticks[2] = ticks[5];
253 		ticks[3] = v1;
254 		ticks[4] = v2;
255 		ticks[5] = v3;
256 	}
257 #endif
258 
259 	if (v1 >= v2 && v2 >= v3 && v1 - v3 < 0x200)
260 		return (v2);
261 
262 #define _swap_val(a, b) do { \
263 	int c = a; \
264 	a = b; \
265 	b = c; \
266 } while (0)
267 
268 	/*
269 	 * sort v1 v2 v3
270 	 */
271 	if (v1 < v2)
272 		_swap_val(v1, v2);
273 	if (v2 < v3)
274 		_swap_val(v2, v3);
275 	if (v1 < v2)
276 		_swap_val(v1, v2);
277 
278 	/*
279 	 * compute the middle value
280 	 */
281 
282 	if (v1 - v3 < 0x200)
283 		return (v2);
284 
285 	w1 = v2 - v3;
286 	w2 = v3 - v1 + x86_rtclock_tval;
287 	w3 = v1 - v2;
288 	if (w1 >= w2) {
289 		if (w1 >= w3)
290 		        return (v1);
291 	} else {
292 		if (w2 >= w3)
293 			return (v2);
294 	}
295 	return (v3);
296 }
297 
298 /* minimal initialization, enough for delay() */
299 void
300 initrtclock(u_long freq)
301 {
302 	u_long tval;
303 
304 	if (vm_guest == VM_GUEST_XENPVH)
305 		return;
306 
307 	/*
308 	 * Compute timer_count, the count-down count the timer will be
309 	 * set to.  Also, correctly round
310 	 * this by carrying an extra bit through the division.
311 	 */
312 	tval = (freq * 2) / (u_long) hz;
313 	tval = (tval / 2) + (tval & 0x1);
314 
315 	/* initialize 8254 clock */
316 	outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0|TIMER_RATEGEN|TIMER_16BIT);
317 
318 	/* Correct rounding will buy us a better precision in timekeeping */
319 	outb(IO_TIMER1+TIMER_CNTR0, tval % 256);
320 	outb(IO_TIMER1+TIMER_CNTR0, tval / 256);
321 
322 	x86_rtclock_tval = tval ? tval : 0xFFFF;
323 	rtclock_init = 1;
324 }
325 
326 void
327 startrtclock(void)
328 {
329 	int s;
330 
331 	if (!rtclock_init)
332 		initrtclock(TIMER_FREQ);
333 
334 	/* Check diagnostic status */
335 	if ((s = mc146818_read(NULL, NVRAM_DIAG)) != 0) { /* XXX softc */
336 		char bits[128];
337 		snprintb(bits, sizeof(bits), NVRAM_DIAG_BITS, s);
338 		printf("RTC BIOS diagnostic error %s\n", bits);
339 	}
340 
341 	tc_init(&i8254_timecounter);
342 	rtc_register();
343 }
344 
345 /*
346  * Must be called at splsched().
347  */
348 static void
349 tickle_tc(void)
350 {
351 #if defined(MULTIPROCESSOR)
352 	struct cpu_info *ci = curcpu();
353 	/*
354 	 * If we are not the primary CPU, we're not allowed to do
355 	 * any more work.
356 	 */
357 	if (CPU_IS_PRIMARY(ci) == 0)
358 		return;
359 #endif
360 	if (x86_rtclock_tval &&
361 	    timecounter->tc_get_timecount == i8254_get_timecount) {
362 		__cpu_simple_lock(&tmr_lock);
363 		if (i8254_ticked)
364 			i8254_ticked    = 0;
365 		else {
366 			i8254_offset   += x86_rtclock_tval;
367 			i8254_lastcount = 0;
368 		}
369 		__cpu_simple_unlock(&tmr_lock);
370 	}
371 
372 }
373 
374 static int
375 clockintr(void *arg, struct intrframe *frame)
376 {
377 	tickle_tc();
378 
379 	hardclock((struct clockframe *)frame);
380 
381 #if NMCA > 0
382 	if (MCA_system) {
383 		/* Reset PS/2 clock interrupt by asserting bit 7 of port 0x61 */
384 		outb(0x61, inb(0x61) | 0x80);
385 	}
386 #endif
387 	return -1;
388 }
389 
390 u_int
391 i8254_get_timecount(struct timecounter *tc)
392 {
393 	u_int count;
394 	uint16_t rdval;
395 	u_long psl;
396 
397 	/* Don't want someone screwing with the counter while we're here. */
398 	psl = x86_read_psl();
399 	x86_disable_intr();
400 	__cpu_simple_lock(&tmr_lock);
401 	/* Select timer0 and latch counter value. */
402 	outb(IO_TIMER1 + TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
403 	/* insb to make the read atomic */
404 	rdval = inb(IO_TIMER1+TIMER_CNTR0);
405 	rdval |= (inb(IO_TIMER1+TIMER_CNTR0) << 8);
406 	count = x86_rtclock_tval - rdval;
407 	if (x86_rtclock_tval && (count < i8254_lastcount &&
408 			     (!i8254_ticked || x86_rtclock_tval == 0xFFFF))) {
409 		i8254_ticked = 1;
410 		i8254_offset += x86_rtclock_tval;
411 	}
412 	i8254_lastcount = count;
413 	count += i8254_offset;
414 	__cpu_simple_unlock(&tmr_lock);
415 	x86_write_psl(psl);
416 
417 	return (count);
418 }
419 
420 unsigned int
421 gettick(void)
422 {
423 	uint16_t rdval;
424 	u_long psl;
425 
426 	if (clock_broken_latch)
427 		return (gettick_broken_latch());
428 
429 	/* Don't want someone screwing with the counter while we're here. */
430 	psl = x86_read_psl();
431 	x86_disable_intr();
432 	__cpu_simple_lock(&tmr_lock);
433 	/* Select counter 0 and latch it. */
434 	outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0 | TIMER_LATCH);
435 	rdval = inb(IO_TIMER1+TIMER_CNTR0);
436 	rdval |= (inb(IO_TIMER1+TIMER_CNTR0) << 8);
437 	__cpu_simple_unlock(&tmr_lock);
438 	x86_write_psl(psl);
439 
440 	return rdval;
441 }
442 
443 /*
444  * Wait approximately `n' microseconds.
445  * Relies on timer 1 counting down from (TIMER_FREQ / hz) at TIMER_FREQ Hz.
446  * Note: timer had better have been programmed before this is first used!
447  * (Note that we use `rate generator' mode, which counts at 1:1; `square
448  * wave' mode counts at 2:1).
449  * Don't rely on this being particularly accurate.
450  */
451 void
452 i8254_delay(unsigned int n)
453 {
454 	unsigned int cur_tick, initial_tick;
455 	int remaining;
456 
457 	/* allow DELAY() to be used before startrtclock() */
458 	if (!rtclock_init)
459 		initrtclock(TIMER_FREQ);
460 
461 	/*
462 	 * Read the counter first, so that the rest of the setup overhead is
463 	 * counted.
464 	 */
465 	initial_tick = gettick();
466 
467 	if (n <= UINT_MAX / TIMER_FREQ) {
468 		/*
469 		 * For unsigned arithmetic, division can be replaced with
470 		 * multiplication with the inverse and a shift.
471 		 */
472 		remaining = n * TIMER_FREQ / 1000000;
473 	} else {
474 		/* This is a very long delay.
475 		 * Being slow here doesn't matter.
476 		 */
477 		remaining = (unsigned long long) n * TIMER_FREQ / 1000000;
478 	}
479 
480 	while (remaining > 1) {
481 #ifdef CLOCK_PARANOIA
482 		int delta;
483 		cur_tick = gettick();
484 		if (cur_tick > initial_tick)
485 			delta = x86_rtclock_tval - (cur_tick - initial_tick);
486 		else
487 			delta = initial_tick - cur_tick;
488 		if (delta < 0 || delta >= x86_rtclock_tval / 2) {
489 			DPRINTF(("delay: ignore ticks %.4x-%.4x",
490 				 initial_tick, cur_tick));
491 			if (clock_broken_latch) {
492 				DPRINTF(("  (%.4x %.4x %.4x %.4x %.4x %.4x)\n",
493 				         ticks[0], ticks[1], ticks[2],
494 				         ticks[3], ticks[4], ticks[5]));
495 			} else {
496 				DPRINTF(("\n"));
497 			}
498 		} else
499 			remaining -= delta;
500 #else
501 		cur_tick = gettick();
502 		if (cur_tick > initial_tick)
503 			remaining -= x86_rtclock_tval - (cur_tick - initial_tick);
504 		else
505 			remaining -= initial_tick - cur_tick;
506 #endif
507 		initial_tick = cur_tick;
508 	}
509 }
510 
511 #if (NPCPPI > 0)
512 int
513 sysbeepmatch(device_t parent, cfdata_t match, void *aux)
514 {
515 	if (vm_guest == VM_GUEST_XENPVH)
516 		return 0;
517 	return (!ppi_attached);
518 }
519 
520 void
521 sysbeepattach(device_t parent, device_t self, void *aux)
522 {
523 	aprint_naive("\n");
524 	aprint_normal("\n");
525 
526 	ppicookie = ((struct pcppi_attach_args *)aux)->pa_cookie;
527 	ppi_attached = 1;
528 
529 	if (!pmf_device_register(self, NULL, NULL))
530 		aprint_error_dev(self, "couldn't establish power handler\n");
531 }
532 
533 int
534 sysbeepdetach(device_t self, int flags)
535 {
536 	pmf_device_deregister(self);
537 	ppi_attached = 0;
538 	return 0;
539 }
540 #endif
541 
542 void
543 sysbeep(int pitch, int period)
544 {
545 #if (NPCPPI > 0)
546 	if (ppi_attached)
547 		pcppi_bell(ppicookie, pitch, period, 0);
548 #endif
549 }
550 
551 void
552 i8254_initclocks(void)
553 {
554 
555 	/*
556 	 * XXX If you're doing strange things with multiple clocks, you might
557 	 * want to keep track of clock handlers.
558 	 */
559 	(void)isa_intr_establish(NULL, 0, IST_PULSE, IPL_CLOCK,
560 	    __FPTRCAST(int (*)(void *), clockintr), 0);
561 }
562 
563 void
564 setstatclockrate(int arg)
565 {
566 }
567