1 /* $NetBSD: clock.c,v 1.44 2026/09/16 21:57:37 riastradh 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 (at) 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.44 2026/09/16 21:57:37 riastradh 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 #include <x86/intr_private.h> 156 157 #ifndef __x86_64__ 158 #include "mca.h" 159 #endif 160 #if NMCA > 0 161 #include <machine/mca_machdep.h> /* for MCA_system */ 162 #endif 163 164 #include "pcppi.h" 165 #if (NPCPPI > 0) 166 #include <dev/isa/pcppivar.h> 167 168 int sysbeepmatch(device_t, cfdata_t, void *); 169 void sysbeepattach(device_t, device_t, void *); 170 int sysbeepdetach(device_t, int); 171 172 CFATTACH_DECL3_NEW(sysbeep, 0, 173 sysbeepmatch, sysbeepattach, sysbeepdetach, NULL, NULL, NULL, 174 0); 175 176 static int ppi_attached; 177 static pcppi_tag_t ppicookie; 178 #endif /* PCPPI */ 179 180 #ifdef CLOCKDEBUG 181 int clock_debug = 0; 182 #define DPRINTF(arg) if (clock_debug) printf arg 183 #else 184 #define DPRINTF(arg) 185 #endif 186 187 void (*x86_delay)(unsigned int) = i8254_delay; 188 189 void sysbeep(int, int); 190 static void tickle_tc(void); 191 192 int sysbeepdetach(device_t, int); 193 194 static unsigned int gettick_broken_latch(void); 195 196 static volatile uint32_t i8254_lastcount; 197 static volatile uint32_t i8254_offset; 198 static volatile int i8254_ticked; 199 200 /* to protect TC timer variables */ 201 static __cpu_simple_lock_t tmr_lock = __SIMPLELOCK_UNLOCKED; 202 203 u_int i8254_get_timecount(struct timecounter *); 204 205 static struct timecounter i8254_timecounter = { 206 .tc_get_timecount = i8254_get_timecount, 207 .tc_counter_mask = ~0u, 208 .tc_frequency = TIMER_FREQ, 209 .tc_name = "i8254", 210 .tc_quality = 100, 211 }; 212 213 u_long x86_rtclock_tval; /* i8254 reload value for countdown */ 214 int rtclock_init = 0; 215 216 int clock_broken_latch = 0; 217 218 #ifdef CLOCK_PARANOIA 219 static int ticks[6]; 220 #endif 221 /* 222 * i8254 latch check routine: 223 * National Geode (formerly Cyrix MediaGX) has a serious bug in 224 * its built-in i8254-compatible clock module. 225 * machdep sets the variable 'clock_broken_latch' to indicate it. 226 */ 227 228 static unsigned int 229 gettick_broken_latch(void) 230 { 231 int v1, v2, v3; 232 int w1, w2, w3; 233 int s; 234 235 /* Don't want someone screwing with the counter while we're here. */ 236 s = splhigh(); 237 __cpu_simple_lock(&tmr_lock); 238 v1 = inb(IO_TIMER1+TIMER_CNTR0); 239 v1 |= inb(IO_TIMER1+TIMER_CNTR0) << 8; 240 v2 = inb(IO_TIMER1+TIMER_CNTR0); 241 v2 |= inb(IO_TIMER1+TIMER_CNTR0) << 8; 242 v3 = inb(IO_TIMER1+TIMER_CNTR0); 243 v3 |= inb(IO_TIMER1+TIMER_CNTR0) << 8; 244 __cpu_simple_unlock(&tmr_lock); 245 splx(s); 246 247 #ifdef CLOCK_PARANOIA 248 if (clock_debug) { 249 ticks[0] = ticks[3]; 250 ticks[1] = ticks[4]; 251 ticks[2] = ticks[5]; 252 ticks[3] = v1; 253 ticks[4] = v2; 254 ticks[5] = v3; 255 } 256 #endif 257 258 if (v1 >= v2 && v2 >= v3 && v1 - v3 < 0x200) 259 return (v2); 260 261 #define _swap_val(a, b) do { \ 262 int c = a; \ 263 a = b; \ 264 b = c; \ 265 } while (0) 266 267 /* 268 * sort v1 v2 v3 269 */ 270 if (v1 < v2) 271 _swap_val(v1, v2); 272 if (v2 < v3) 273 _swap_val(v2, v3); 274 if (v1 < v2) 275 _swap_val(v1, v2); 276 277 /* 278 * compute the middle value 279 */ 280 281 if (v1 - v3 < 0x200) 282 return (v2); 283 284 w1 = v2 - v3; 285 w2 = v3 - v1 + x86_rtclock_tval; 286 w3 = v1 - v2; 287 if (w1 >= w2) { 288 if (w1 >= w3) 289 return (v1); 290 } else { 291 if (w2 >= w3) 292 return (v2); 293 } 294 return (v3); 295 } 296 297 /* minimal initialization, enough for delay() */ 298 void 299 initrtclock(u_long freq) 300 { 301 u_long tval; 302 303 if (vm_guest == VM_GUEST_XENPVH) 304 return; 305 306 /* 307 * Compute timer_count, the count-down count the timer will be 308 * set to. Also, correctly round 309 * this by carrying an extra bit through the division. 310 */ 311 tval = (freq * 2) / (u_long) hz; 312 tval = (tval / 2) + (tval & 0x1); 313 314 /* initialize 8254 clock */ 315 outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0|TIMER_RATEGEN|TIMER_16BIT); 316 317 /* Correct rounding will buy us a better precision in timekeeping */ 318 outb(IO_TIMER1+TIMER_CNTR0, tval % 256); 319 outb(IO_TIMER1+TIMER_CNTR0, tval / 256); 320 321 x86_rtclock_tval = tval ? tval : 0xFFFF; 322 rtclock_init = 1; 323 } 324 325 void 326 startrtclock(void) 327 { 328 int s; 329 330 /* 331 * For VM guests, check that the RTC is present. On QEMU/microvm, 332 * when rtc=off, bits 0 to 6 of register D are set to 1. On actual 333 * hardware these bits may be used for a date alarm, so this test 334 * would fail. 335 */ 336 if ((vm_guest != VM_GUEST_NO) && 337 (mc146818_read(NULL, MC_REGD) & 0x7f) != 0) 338 return; 339 340 if (!rtclock_init) 341 initrtclock(TIMER_FREQ); 342 343 /* Check diagnostic status */ 344 if ((s = mc146818_read(NULL, NVRAM_DIAG)) != 0) { /* XXX softc */ 345 char bits[128]; 346 snprintb(bits, sizeof(bits), NVRAM_DIAG_BITS, s); 347 printf("RTC BIOS diagnostic error %s\n", bits); 348 } 349 350 tc_init(&i8254_timecounter); 351 rtc_register(); 352 } 353 354 /* 355 * Must be called at splsched(). 356 */ 357 static void 358 tickle_tc(void) 359 { 360 #if defined(MULTIPROCESSOR) 361 struct cpu_info *ci = curcpu(); 362 /* 363 * If we are not the primary CPU, we're not allowed to do 364 * any more work. 365 */ 366 if (CPU_IS_PRIMARY(ci) == 0) 367 return; 368 #endif 369 if (x86_rtclock_tval && 370 timecounter->tc_get_timecount == i8254_get_timecount) { 371 __cpu_simple_lock(&tmr_lock); 372 if (i8254_ticked) 373 i8254_ticked = 0; 374 else { 375 i8254_offset += x86_rtclock_tval; 376 i8254_lastcount = 0; 377 } 378 __cpu_simple_unlock(&tmr_lock); 379 } 380 381 } 382 383 int 384 i8254_clockintr(void *arg, struct intrframe *frame) 385 { 386 tickle_tc(); 387 388 hardclock((struct clockframe *)frame); 389 390 #if NMCA > 0 391 if (MCA_system) { 392 /* Reset PS/2 clock interrupt by asserting bit 7 of port 0x61 */ 393 outb(0x61, inb(0x61) | 0x80); 394 } 395 #endif 396 return -1; 397 } 398 399 u_int 400 i8254_get_timecount(struct timecounter *tc) 401 { 402 u_int count; 403 uint16_t rdval; 404 u_long psl; 405 406 /* Don't want someone screwing with the counter while we're here. */ 407 psl = x86_read_psl(); 408 x86_disable_intr(); 409 __cpu_simple_lock(&tmr_lock); 410 /* Select timer0 and latch counter value. */ 411 outb(IO_TIMER1 + TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); 412 /* insb to make the read atomic */ 413 rdval = inb(IO_TIMER1+TIMER_CNTR0); 414 rdval |= (inb(IO_TIMER1+TIMER_CNTR0) << 8); 415 count = x86_rtclock_tval - rdval; 416 if (x86_rtclock_tval && (count < i8254_lastcount && 417 (!i8254_ticked || x86_rtclock_tval == 0xFFFF))) { 418 i8254_ticked = 1; 419 i8254_offset += x86_rtclock_tval; 420 } 421 i8254_lastcount = count; 422 count += i8254_offset; 423 __cpu_simple_unlock(&tmr_lock); 424 x86_write_psl(psl); 425 426 return (count); 427 } 428 429 unsigned int 430 gettick(void) 431 { 432 uint16_t rdval; 433 u_long psl; 434 435 if (clock_broken_latch) 436 return (gettick_broken_latch()); 437 438 /* Don't want someone screwing with the counter while we're here. */ 439 psl = x86_read_psl(); 440 x86_disable_intr(); 441 __cpu_simple_lock(&tmr_lock); 442 /* Select counter 0 and latch it. */ 443 outb(IO_TIMER1+TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); 444 rdval = inb(IO_TIMER1+TIMER_CNTR0); 445 rdval |= (inb(IO_TIMER1+TIMER_CNTR0) << 8); 446 __cpu_simple_unlock(&tmr_lock); 447 x86_write_psl(psl); 448 449 return rdval; 450 } 451 452 /* 453 * Wait approximately `n' microseconds. 454 * Relies on timer 1 counting down from (TIMER_FREQ / hz) at TIMER_FREQ Hz. 455 * Note: timer had better have been programmed before this is first used! 456 * (Note that we use `rate generator' mode, which counts at 1:1; `square 457 * wave' mode counts at 2:1). 458 * Don't rely on this being particularly accurate. 459 */ 460 void 461 i8254_delay(unsigned int n) 462 { 463 unsigned int cur_tick, initial_tick; 464 int remaining; 465 466 /* allow DELAY() to be used before startrtclock() */ 467 if (!rtclock_init) 468 initrtclock(TIMER_FREQ); 469 470 /* 471 * Read the counter first, so that the rest of the setup overhead is 472 * counted. 473 */ 474 initial_tick = gettick(); 475 476 if (n <= UINT_MAX / TIMER_FREQ) { 477 /* 478 * For unsigned arithmetic, division can be replaced with 479 * multiplication with the inverse and a shift. 480 */ 481 remaining = n * TIMER_FREQ / 1000000; 482 } else { 483 /* This is a very long delay. 484 * Being slow here doesn't matter. 485 */ 486 remaining = (unsigned long long) n * TIMER_FREQ / 1000000; 487 } 488 489 while (remaining > 1) { 490 #ifdef CLOCK_PARANOIA 491 int delta; 492 cur_tick = gettick(); 493 if (cur_tick > initial_tick) 494 delta = x86_rtclock_tval - (cur_tick - initial_tick); 495 else 496 delta = initial_tick - cur_tick; 497 if (delta < 0 || delta >= x86_rtclock_tval / 2) { 498 DPRINTF(("delay: ignore ticks %.4x-%.4x", 499 initial_tick, cur_tick)); 500 if (clock_broken_latch) { 501 DPRINTF((" (%.4x %.4x %.4x %.4x %.4x %.4x)\n", 502 ticks[0], ticks[1], ticks[2], 503 ticks[3], ticks[4], ticks[5])); 504 } else { 505 DPRINTF(("\n")); 506 } 507 } else 508 remaining -= delta; 509 #else 510 cur_tick = gettick(); 511 if (cur_tick > initial_tick) 512 remaining -= x86_rtclock_tval - (cur_tick - initial_tick); 513 else 514 remaining -= initial_tick - cur_tick; 515 #endif 516 initial_tick = cur_tick; 517 } 518 } 519 520 #if (NPCPPI > 0) 521 int 522 sysbeepmatch(device_t parent, cfdata_t match, void *aux) 523 { 524 if (vm_guest == VM_GUEST_XENPVH) 525 return 0; 526 return (!ppi_attached); 527 } 528 529 void 530 sysbeepattach(device_t parent, device_t self, void *aux) 531 { 532 aprint_naive("\n"); 533 aprint_normal("\n"); 534 535 ppicookie = ((struct pcppi_attach_args *)aux)->pa_cookie; 536 ppi_attached = 1; 537 538 if (!pmf_device_register(self, NULL, NULL)) 539 aprint_error_dev(self, "couldn't establish power handler\n"); 540 } 541 542 int 543 sysbeepdetach(device_t self, int flags) 544 { 545 pmf_device_deregister(self); 546 ppi_attached = 0; 547 return 0; 548 } 549 #endif 550 551 void 552 sysbeep(int pitch, int period) 553 { 554 #if (NPCPPI > 0) 555 if (ppi_attached) 556 pcppi_bell(ppicookie, pitch, period, 0); 557 #endif 558 } 559 560 void 561 i8254_initclocks(void) 562 { 563 564 /* 565 * XXX If you're doing strange things with multiple clocks, you might 566 * want to keep track of clock handlers. 567 * 568 * XXX This is an abuse of the interrupt handler signature with 569 * __FPTRCAST which requires a special case for IPL_CLOCK in 570 * intr_establish_xname. Please fix this nonsense! See also 571 * the comments about i8254_clockintr in x86/x86/intr.c. 572 */ 573 (void)isa_intr_establish(NULL, 0, IST_PULSE, IPL_CLOCK, 574 __FPTRCAST(int (*)(void *), i8254_clockintr), 0); 575 } 576 577 void 578 setstatclockrate(int arg) 579 { 580 } 581