1/*-
2 * Copyright (c) 2008 Poul-Henning Kamp
3 * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 * $FreeBSD: stable/11/sys/x86/isa/atrtc.c 345590 2019-03-27 19:17:42Z wulf $
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: stable/11/sys/x86/isa/atrtc.c 345590 2019-03-27 19:17:42Z wulf $");
32
33#include "opt_acpi.h"
34#include "opt_isa.h"
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/bus.h>
39#include <sys/clock.h>
40#include <sys/lock.h>
41#include <sys/mutex.h>
42#include <sys/kdb.h>
43#include <sys/kernel.h>
44#include <sys/module.h>
45#include <sys/proc.h>
46#include <sys/rman.h>
47#include <sys/timeet.h>
48
49#include <isa/rtc.h>
50#ifdef DEV_ISA
51#include <isa/isareg.h>
52#include <isa/isavar.h>
53#endif
54#include <machine/intr_machdep.h>
55#include "clock_if.h"
56#ifdef DEV_ACPI
57#include <contrib/dev/acpica/include/acpi.h>
58#include <contrib/dev/acpica/include/accommon.h>
59#include <dev/acpica/acpivar.h>
60#include <machine/md_var.h>
61#endif
62
63/*
64 * atrtc_lock protects low-level access to individual hardware registers.
65 * atrtc_time_lock protects the entire sequence of accessing multiple registers
66 * to read or write the date and time.
67 */
68static struct mtx atrtc_lock;
69MTX_SYSINIT(atrtc_lock_init, &atrtc_lock, "atrtc", MTX_SPIN);
70
71struct mtx atrtc_time_lock;
72MTX_SYSINIT(atrtc_time_lock_init, &atrtc_time_lock, "atrtc_time", MTX_DEF);
73
74int	atrtcclock_disable = 0;
75
76static	int	rtc_reg = -1;
77static	u_char	rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF;
78static	u_char	rtc_statusb = RTCSB_24HR;
79
80#ifdef DEV_ACPI
81#define	_COMPONENT	ACPI_TIMER
82ACPI_MODULE_NAME("ATRTC")
83#endif
84
85/*
86 * RTC support routines
87 */
88
89static inline u_char
90rtcin_locked(int reg)
91{
92
93	if (rtc_reg != reg) {
94		inb(0x84);
95		outb(IO_RTC, reg);
96		rtc_reg = reg;
97		inb(0x84);
98	}
99	return (inb(IO_RTC + 1));
100}
101
102static inline void
103rtcout_locked(int reg, u_char val)
104{
105
106	if (rtc_reg != reg) {
107		inb(0x84);
108		outb(IO_RTC, reg);
109		rtc_reg = reg;
110		inb(0x84);
111	}
112	outb(IO_RTC + 1, val);
113	inb(0x84);
114}
115
116int
117rtcin(int reg)
118{
119	u_char val;
120
121	mtx_lock_spin(&atrtc_lock);
122	val = rtcin_locked(reg);
123	mtx_unlock_spin(&atrtc_lock);
124	return (val);
125}
126
127void
128writertc(int reg, u_char val)
129{
130
131	mtx_lock_spin(&atrtc_lock);
132	rtcout_locked(reg, val);
133	mtx_unlock_spin(&atrtc_lock);
134}
135
136static void
137atrtc_start(void)
138{
139
140	mtx_lock_spin(&atrtc_lock);
141	rtcout_locked(RTC_STATUSA, rtc_statusa);
142	rtcout_locked(RTC_STATUSB, RTCSB_24HR);
143	mtx_unlock_spin(&atrtc_lock);
144}
145
146static void
147atrtc_rate(unsigned rate)
148{
149
150	rtc_statusa = RTCSA_DIVIDER | rate;
151	writertc(RTC_STATUSA, rtc_statusa);
152}
153
154static void
155atrtc_enable_intr(void)
156{
157
158	rtc_statusb |= RTCSB_PINTR;
159	mtx_lock_spin(&atrtc_lock);
160	rtcout_locked(RTC_STATUSB, rtc_statusb);
161	rtcin_locked(RTC_INTR);
162	mtx_unlock_spin(&atrtc_lock);
163}
164
165static void
166atrtc_disable_intr(void)
167{
168
169	rtc_statusb &= ~RTCSB_PINTR;
170	mtx_lock_spin(&atrtc_lock);
171	rtcout_locked(RTC_STATUSB, rtc_statusb);
172	rtcin_locked(RTC_INTR);
173	mtx_unlock_spin(&atrtc_lock);
174}
175
176void
177atrtc_restore(void)
178{
179
180	/* Restore all of the RTC's "status" (actually, control) registers. */
181	mtx_lock_spin(&atrtc_lock);
182	rtcin_locked(RTC_STATUSA);	/* dummy to get rtc_reg set */
183	rtcout_locked(RTC_STATUSB, RTCSB_24HR);
184	rtcout_locked(RTC_STATUSA, rtc_statusa);
185	rtcout_locked(RTC_STATUSB, rtc_statusb);
186	rtcin_locked(RTC_INTR);
187	mtx_unlock_spin(&atrtc_lock);
188}
189
190/**********************************************************************
191 * RTC driver for subr_rtc
192 */
193
194struct atrtc_softc {
195	int port_rid, intr_rid;
196	struct resource *port_res;
197	struct resource *intr_res;
198	void *intr_handler;
199	struct eventtimer et;
200#ifdef DEV_ACPI
201	ACPI_HANDLE acpi_handle;
202#endif
203};
204
205static int
206rtc_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
207{
208
209	atrtc_rate(max(fls(period + (period >> 1)) - 17, 1));
210	atrtc_enable_intr();
211	return (0);
212}
213
214static int
215rtc_stop(struct eventtimer *et)
216{
217
218	atrtc_disable_intr();
219	return (0);
220}
221
222/*
223 * This routine receives statistical clock interrupts from the RTC.
224 * As explained above, these occur at 128 interrupts per second.
225 * When profiling, we receive interrupts at a rate of 1024 Hz.
226 *
227 * This does not actually add as much overhead as it sounds, because
228 * when the statistical clock is active, the hardclock driver no longer
229 * needs to keep (inaccurate) statistics on its own.  This decouples
230 * statistics gathering from scheduling interrupts.
231 *
232 * The RTC chip requires that we read status register C (RTC_INTR)
233 * to acknowledge an interrupt, before it will generate the next one.
234 * Under high interrupt load, rtcintr() can be indefinitely delayed and
235 * the clock can tick immediately after the read from RTC_INTR.  In this
236 * case, the mc146818A interrupt signal will not drop for long enough
237 * to register with the 8259 PIC.  If an interrupt is missed, the stat
238 * clock will halt, considerably degrading system performance.  This is
239 * why we use 'while' rather than a more straightforward 'if' below.
240 * Stat clock ticks can still be lost, causing minor loss of accuracy
241 * in the statistics, but the stat clock will no longer stop.
242 */
243static int
244rtc_intr(void *arg)
245{
246	struct atrtc_softc *sc = (struct atrtc_softc *)arg;
247	int flag = 0;
248
249	while (rtcin(RTC_INTR) & RTCIR_PERIOD) {
250		flag = 1;
251		if (sc->et.et_active)
252			sc->et.et_event_cb(&sc->et, sc->et.et_arg);
253	}
254	return(flag ? FILTER_HANDLED : FILTER_STRAY);
255}
256
257#ifdef DEV_ACPI
258/*
259 *  ACPI RTC CMOS address space handler
260 */
261#define	ATRTC_LAST_REG	0x40
262
263static void
264rtcin_region(int reg, void *buf, int len)
265{
266	u_char *ptr = buf;
267
268	/* Drop lock after each IO as intr and settime have greater priority */
269	while (len-- > 0)
270		*ptr++ = rtcin(reg++) & 0xff;
271}
272
273static void
274rtcout_region(int reg, const void *buf, int len)
275{
276	const u_char *ptr = buf;
277
278	while (len-- > 0)
279		writertc(reg++, *ptr++);
280}
281
282static bool
283atrtc_check_cmos_access(bool is_read, ACPI_PHYSICAL_ADDRESS addr, UINT32 len)
284{
285
286	/* Block address space wrapping on out-of-bound access */
287	if (addr >= ATRTC_LAST_REG || addr + len > ATRTC_LAST_REG)
288		return (false);
289
290	if (is_read) {
291		/* Reading 0x0C will muck with interrupts */
292		if (addr <= RTC_INTR && addr + len > RTC_INTR)
293			return (false);
294	} else {
295		/*
296		 * Allow single-byte writes to alarm registers and
297		 * multi-byte writes to addr >= 0x30, else deny.
298		 */
299		if (!((len == 1 && (addr == RTC_SECALRM ||
300				    addr == RTC_MINALRM ||
301				    addr == RTC_HRSALRM)) ||
302		      addr >= 0x30))
303			return (false);
304	}
305	return (true);
306}
307
308static ACPI_STATUS
309atrtc_acpi_cmos_handler(UINT32 func, ACPI_PHYSICAL_ADDRESS addr,
310    UINT32 bitwidth, UINT64 *value, void *context, void *region_context)
311{
312	device_t dev = context;
313	UINT32 bytewidth = howmany(bitwidth, 8);
314	bool is_read = func == ACPI_READ;
315
316	/* ACPICA is very verbose on CMOS handler failures, so we, too */
317#define	CMOS_HANDLER_ERR(fmt, ...) \
318	device_printf(dev, "ACPI [SystemCMOS] handler: " fmt, ##__VA_ARGS__)
319
320	ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
321
322	if (value == NULL) {
323		CMOS_HANDLER_ERR("NULL parameter\n");
324		return (AE_BAD_PARAMETER);
325	}
326	if (bitwidth == 0 || (bitwidth & 0x07) != 0) {
327		CMOS_HANDLER_ERR("Invalid bitwidth: %u\n", bitwidth);
328		return (AE_BAD_PARAMETER);
329	}
330	if (!atrtc_check_cmos_access(is_read, addr, bytewidth)) {
331		CMOS_HANDLER_ERR("%s access rejected: addr=%#04jx, len=%u\n",
332		    is_read ? "Read" : "Write", (uintmax_t)addr, bytewidth);
333		return (AE_BAD_PARAMETER);
334	}
335
336	switch (func) {
337	case ACPI_READ:
338		rtcin_region(addr, value, bytewidth);
339		break;
340	case ACPI_WRITE:
341		rtcout_region(addr, value, bytewidth);
342		break;
343	default:
344		CMOS_HANDLER_ERR("Invalid function: %u\n", func);
345		return (AE_BAD_PARAMETER);
346	}
347
348	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
349	    "ACPI RTC CMOS %s access: addr=%#04x, len=%u, val=%*D\n",
350	    is_read ? "read" : "write", (unsigned)addr, bytewidth,
351	    bytewidth, value, " ");
352
353	return (AE_OK);
354}
355
356static int
357atrtc_reg_acpi_cmos_handler(device_t dev)
358{
359	struct atrtc_softc *sc = device_get_softc(dev);
360
361	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
362
363	/* Don't handle address space events if driver is disabled. */
364	if (acpi_disabled("atrtc"))
365		return (ENXIO);
366
367	sc->acpi_handle = acpi_get_handle(dev);
368	if (sc->acpi_handle == NULL ||
369	    ACPI_FAILURE(AcpiInstallAddressSpaceHandler(sc->acpi_handle,
370	      ACPI_ADR_SPACE_CMOS, atrtc_acpi_cmos_handler, NULL, dev))) {
371		sc->acpi_handle = NULL;
372		device_printf(dev,
373		    "Can't register ACPI CMOS address space handler\n");
374		return (ENXIO);
375        }
376
377        return (0);
378}
379
380static int
381atrtc_unreg_acpi_cmos_handler(device_t dev)
382{
383	struct atrtc_softc *sc = device_get_softc(dev);
384
385	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
386
387	if (sc->acpi_handle != NULL)
388		AcpiRemoveAddressSpaceHandler(sc->acpi_handle,
389		    ACPI_ADR_SPACE_CMOS, atrtc_acpi_cmos_handler);
390
391	return (0);
392}
393#endif	/* DEV_ACPI */
394
395/*
396 * Attach to the ISA PnP descriptors for the timer and realtime clock.
397 */
398static struct isa_pnp_id atrtc_ids[] = {
399	{ 0x000bd041 /* PNP0B00 */, "AT realtime clock" },
400	{ 0 }
401};
402
403static int
404atrtc_probe(device_t dev)
405{
406	int result;
407
408	result = ISA_PNP_PROBE(device_get_parent(dev), dev, atrtc_ids);
409	/* ENOENT means no PnP-ID, device is hinted. */
410	if (result == ENOENT) {
411		device_set_desc(dev, "AT realtime clock");
412		return (BUS_PROBE_LOW_PRIORITY);
413	}
414	return (result);
415}
416
417static int
418atrtc_attach(device_t dev)
419{
420	struct atrtc_softc *sc;
421	rman_res_t s;
422	int i;
423
424	sc = device_get_softc(dev);
425	sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT, &sc->port_rid,
426	    IO_RTC, IO_RTC + 1, 2, RF_ACTIVE);
427	if (sc->port_res == NULL)
428		device_printf(dev, "Warning: Couldn't map I/O.\n");
429	atrtc_start();
430	clock_register(dev, 1000000);
431	bzero(&sc->et, sizeof(struct eventtimer));
432	if (!atrtcclock_disable &&
433	    (resource_int_value(device_get_name(dev), device_get_unit(dev),
434	     "clock", &i) != 0 || i != 0)) {
435		sc->intr_rid = 0;
436		while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid,
437		    &s, NULL) == 0 && s != 8)
438			sc->intr_rid++;
439		sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
440		    &sc->intr_rid, 8, 8, 1, RF_ACTIVE);
441		if (sc->intr_res == NULL) {
442			device_printf(dev, "Can't map interrupt.\n");
443			return (0);
444		} else if ((bus_setup_intr(dev, sc->intr_res, INTR_TYPE_CLK,
445		    rtc_intr, NULL, sc, &sc->intr_handler))) {
446			device_printf(dev, "Can't setup interrupt.\n");
447			return (0);
448		} else {
449			/* Bind IRQ to BSP to avoid live migration. */
450			bus_bind_intr(dev, sc->intr_res, 0);
451		}
452		sc->et.et_name = "RTC";
453		sc->et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_POW2DIV;
454		sc->et.et_quality = 0;
455		sc->et.et_frequency = 32768;
456		sc->et.et_min_period = 0x00080000;
457		sc->et.et_max_period = 0x80000000;
458		sc->et.et_start = rtc_start;
459		sc->et.et_stop = rtc_stop;
460		sc->et.et_priv = dev;
461		et_register(&sc->et);
462	}
463	return(0);
464}
465
466static int
467atrtc_isa_attach(device_t dev)
468{
469
470	return (atrtc_attach(dev));
471}
472
473#ifdef DEV_ACPI
474static int
475atrtc_acpi_attach(device_t dev)
476{
477	int ret;
478
479	ret = atrtc_attach(dev);
480	if (ret)
481		return (ret);
482
483	(void)atrtc_reg_acpi_cmos_handler(dev);
484
485	return (0);
486}
487
488static int
489atrtc_acpi_detach(device_t dev)
490{
491
492	(void)atrtc_unreg_acpi_cmos_handler(dev);
493	return (0);
494}
495#endif	/* DEV_ACPI */
496
497static int
498atrtc_resume(device_t dev)
499{
500
501	atrtc_restore();
502	return(0);
503}
504
505static int
506atrtc_settime(device_t dev __unused, struct timespec *ts)
507{
508	struct bcd_clocktime bct;
509
510	clock_ts_to_bcd(ts, &bct, false);
511	clock_dbgprint_bcd(dev, CLOCK_DBG_WRITE, &bct);
512
513	mtx_lock(&atrtc_time_lock);
514	mtx_lock_spin(&atrtc_lock);
515
516	/* Disable RTC updates and interrupts.  */
517	rtcout_locked(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR);
518
519	/* Write all the time registers. */
520	rtcout_locked(RTC_SEC,   bct.sec);
521	rtcout_locked(RTC_MIN,   bct.min);
522	rtcout_locked(RTC_HRS,   bct.hour);
523	rtcout_locked(RTC_WDAY,  bct.dow + 1);
524	rtcout_locked(RTC_DAY,   bct.day);
525	rtcout_locked(RTC_MONTH, bct.mon);
526	rtcout_locked(RTC_YEAR,  bct.year & 0xff);
527#ifdef USE_RTC_CENTURY
528	rtcout_locked(RTC_CENTURY, bct.year >> 8);
529#endif
530
531	/*
532	 * Re-enable RTC updates and interrupts.
533	 */
534	rtcout_locked(RTC_STATUSB, rtc_statusb);
535	rtcin_locked(RTC_INTR);
536
537	mtx_unlock_spin(&atrtc_lock);
538	mtx_unlock(&atrtc_time_lock);
539
540	return (0);
541}
542
543static int
544atrtc_gettime(device_t dev, struct timespec *ts)
545{
546	struct bcd_clocktime bct;
547
548	/* Look if we have a RTC present and the time is valid */
549	if (!(rtcin(RTC_STATUSD) & RTCSD_PWR)) {
550		device_printf(dev, "WARNING: Battery failure indication\n");
551		return (EINVAL);
552	}
553
554	/*
555	 * wait for time update to complete
556	 * If RTCSA_TUP is zero, we have at least 244us before next update.
557	 * This is fast enough on most hardware, but a refinement would be
558	 * to make sure that no more than 240us pass after we start reading,
559	 * and try again if so.
560	 */
561	mtx_lock(&atrtc_time_lock);
562	while (rtcin(RTC_STATUSA) & RTCSA_TUP)
563		continue;
564	mtx_lock_spin(&atrtc_lock);
565	bct.sec  = rtcin_locked(RTC_SEC);
566	bct.min  = rtcin_locked(RTC_MIN);
567	bct.hour = rtcin_locked(RTC_HRS);
568	bct.day  = rtcin_locked(RTC_DAY);
569	bct.mon  = rtcin_locked(RTC_MONTH);
570	bct.year = rtcin_locked(RTC_YEAR);
571#ifdef USE_RTC_CENTURY
572	bct.year |= rtcin_locked(RTC_CENTURY) << 8;
573#endif
574	mtx_unlock_spin(&atrtc_lock);
575	mtx_unlock(&atrtc_time_lock);
576	/* dow is unused in timespec conversion and we have no nsec info. */
577	bct.dow  = 0;
578	bct.nsec = 0;
579	clock_dbgprint_bcd(dev, CLOCK_DBG_READ, &bct);
580	return (clock_bcd_to_ts(&bct, ts, false));
581}
582
583static device_method_t atrtc_isa_methods[] = {
584	/* Device interface */
585	DEVMETHOD(device_probe,		atrtc_probe),
586	DEVMETHOD(device_attach,	atrtc_isa_attach),
587	DEVMETHOD(device_detach,	bus_generic_detach),
588	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
589	DEVMETHOD(device_suspend,	bus_generic_suspend),
590		/* XXX stop statclock? */
591	DEVMETHOD(device_resume,	atrtc_resume),
592
593	/* clock interface */
594	DEVMETHOD(clock_gettime,	atrtc_gettime),
595	DEVMETHOD(clock_settime,	atrtc_settime),
596
597	{ 0, 0 }
598};
599
600static driver_t atrtc_isa_driver = {
601	"atrtc",
602	atrtc_isa_methods,
603	sizeof(struct atrtc_softc),
604};
605
606#ifdef DEV_ACPI
607static device_method_t atrtc_acpi_methods[] = {
608	/* Device interface */
609	DEVMETHOD(device_probe,		atrtc_probe),
610	DEVMETHOD(device_attach,	atrtc_acpi_attach),
611	DEVMETHOD(device_detach,	atrtc_acpi_detach),
612		/* XXX stop statclock? */
613	DEVMETHOD(device_resume,	atrtc_resume),
614
615	/* clock interface */
616	DEVMETHOD(clock_gettime,	atrtc_gettime),
617	DEVMETHOD(clock_settime,	atrtc_settime),
618
619	{ 0, 0 }
620};
621
622static driver_t atrtc_acpi_driver = {
623	"atrtc",
624	atrtc_acpi_methods,
625	sizeof(struct atrtc_softc),
626};
627#endif	/* DEV_ACPI */
628
629static devclass_t atrtc_devclass;
630
631DRIVER_MODULE(atrtc, isa, atrtc_isa_driver, atrtc_devclass, 0, 0);
632#ifdef DEV_ACPI
633DRIVER_MODULE(atrtc, acpi, atrtc_acpi_driver, atrtc_devclass, 0, 0);
634#endif
635