1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2014, Neel Natu (neel@freebsd.org)
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/queue.h>
35#include <sys/kernel.h>
36#include <sys/malloc.h>
37#include <sys/lock.h>
38#include <sys/mutex.h>
39#include <sys/clock.h>
40#include <sys/sysctl.h>
41
42#include <machine/vmm.h>
43
44#include <isa/rtc.h>
45
46#include "vmm_ktr.h"
47#include "vatpic.h"
48#include "vioapic.h"
49#include "vrtc.h"
50
51/* Register layout of the RTC */
52struct rtcdev {
53	uint8_t	sec;
54	uint8_t	alarm_sec;
55	uint8_t	min;
56	uint8_t	alarm_min;
57	uint8_t	hour;
58	uint8_t	alarm_hour;
59	uint8_t	day_of_week;
60	uint8_t	day_of_month;
61	uint8_t	month;
62	uint8_t	year;
63	uint8_t	reg_a;
64	uint8_t	reg_b;
65	uint8_t	reg_c;
66	uint8_t	reg_d;
67	uint8_t	nvram[36];
68	uint8_t	century;
69	uint8_t	nvram2[128 - 51];
70} __packed;
71CTASSERT(sizeof(struct rtcdev) == 128);
72CTASSERT(offsetof(struct rtcdev, century) == RTC_CENTURY);
73
74struct vrtc {
75	struct vm	*vm;
76	struct mtx	mtx;
77	struct callout	callout;
78	u_int		addr;		/* RTC register to read or write */
79	sbintime_t	base_uptime;
80	time_t		base_rtctime;
81	struct rtcdev	rtcdev;
82};
83
84#define	VRTC_LOCK(vrtc)		mtx_lock(&((vrtc)->mtx))
85#define	VRTC_UNLOCK(vrtc)	mtx_unlock(&((vrtc)->mtx))
86#define	VRTC_LOCKED(vrtc)	mtx_owned(&((vrtc)->mtx))
87
88/*
89 * RTC time is considered "broken" if:
90 * - RTC updates are halted by the guest
91 * - RTC date/time fields have invalid values
92 */
93#define	VRTC_BROKEN_TIME	((time_t)-1)
94
95#define	RTC_IRQ			8
96#define	RTCSB_BIN		0x04
97#define	RTCSB_ALL_INTRS		(RTCSB_UINTR | RTCSB_AINTR | RTCSB_PINTR)
98#define	rtc_halted(vrtc)	((vrtc->rtcdev.reg_b & RTCSB_HALT) != 0)
99#define	aintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_AINTR) != 0)
100#define	pintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_PINTR) != 0)
101#define	uintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_UINTR) != 0)
102
103static void vrtc_callout_handler(void *arg);
104static void vrtc_set_reg_c(struct vrtc *vrtc, uint8_t newval);
105
106static MALLOC_DEFINE(M_VRTC, "vrtc", "bhyve virtual rtc");
107
108SYSCTL_DECL(_hw_vmm);
109SYSCTL_NODE(_hw_vmm, OID_AUTO, vrtc, CTLFLAG_RW, NULL, NULL);
110
111static int rtc_flag_broken_time = 1;
112SYSCTL_INT(_hw_vmm_vrtc, OID_AUTO, flag_broken_time, CTLFLAG_RDTUN,
113    &rtc_flag_broken_time, 0, "Stop guest when invalid RTC time is detected");
114
115static __inline bool
116divider_enabled(int reg_a)
117{
118	/*
119	 * The RTC is counting only when dividers are not held in reset.
120	 */
121	return ((reg_a & 0x70) == 0x20);
122}
123
124static __inline bool
125update_enabled(struct vrtc *vrtc)
126{
127	/*
128	 * RTC date/time can be updated only if:
129	 * - divider is not held in reset
130	 * - guest has not disabled updates
131	 * - the date/time fields have valid contents
132	 */
133	if (!divider_enabled(vrtc->rtcdev.reg_a))
134		return (false);
135
136	if (rtc_halted(vrtc))
137		return (false);
138
139	if (vrtc->base_rtctime == VRTC_BROKEN_TIME)
140		return (false);
141
142	return (true);
143}
144
145static time_t
146vrtc_curtime(struct vrtc *vrtc, sbintime_t *basetime)
147{
148	sbintime_t now, delta;
149	time_t t, secs;
150
151	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
152
153	t = vrtc->base_rtctime;
154	*basetime = vrtc->base_uptime;
155	if (update_enabled(vrtc)) {
156		now = sbinuptime();
157		delta = now - vrtc->base_uptime;
158		KASSERT(delta >= 0, ("vrtc_curtime: uptime went backwards: "
159		    "%#lx to %#lx", vrtc->base_uptime, now));
160		secs = delta / SBT_1S;
161		t += secs;
162		*basetime += secs * SBT_1S;
163	}
164	return (t);
165}
166
167static __inline uint8_t
168rtcset(struct rtcdev *rtc, int val)
169{
170
171	KASSERT(val >= 0 && val < 100, ("%s: invalid bin2bcd index %d",
172	    __func__, val));
173
174	return ((rtc->reg_b & RTCSB_BIN) ? val : bin2bcd_data[val]);
175}
176
177static void
178secs_to_rtc(time_t rtctime, struct vrtc *vrtc, int force_update)
179{
180	struct clocktime ct;
181	struct timespec ts;
182	struct rtcdev *rtc;
183	int hour;
184
185	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
186
187	if (rtctime < 0) {
188		KASSERT(rtctime == VRTC_BROKEN_TIME,
189		    ("%s: invalid vrtc time %#lx", __func__, rtctime));
190		return;
191	}
192
193	/*
194	 * If the RTC is halted then the guest has "ownership" of the
195	 * date/time fields. Don't update the RTC date/time fields in
196	 * this case (unless forced).
197	 */
198	if (rtc_halted(vrtc) && !force_update)
199		return;
200
201	ts.tv_sec = rtctime;
202	ts.tv_nsec = 0;
203	clock_ts_to_ct(&ts, &ct);
204
205	KASSERT(ct.sec >= 0 && ct.sec <= 59, ("invalid clocktime sec %d",
206	    ct.sec));
207	KASSERT(ct.min >= 0 && ct.min <= 59, ("invalid clocktime min %d",
208	    ct.min));
209	KASSERT(ct.hour >= 0 && ct.hour <= 23, ("invalid clocktime hour %d",
210	    ct.hour));
211	KASSERT(ct.dow >= 0 && ct.dow <= 6, ("invalid clocktime wday %d",
212	    ct.dow));
213	KASSERT(ct.day >= 1 && ct.day <= 31, ("invalid clocktime mday %d",
214	    ct.day));
215	KASSERT(ct.mon >= 1 && ct.mon <= 12, ("invalid clocktime month %d",
216	    ct.mon));
217	KASSERT(ct.year >= POSIX_BASE_YEAR, ("invalid clocktime year %d",
218	    ct.year));
219
220	rtc = &vrtc->rtcdev;
221	rtc->sec = rtcset(rtc, ct.sec);
222	rtc->min = rtcset(rtc, ct.min);
223
224	if (rtc->reg_b & RTCSB_24HR) {
225		hour = ct.hour;
226	} else {
227		/*
228		 * Convert to the 12-hour format.
229		 */
230		switch (ct.hour) {
231		case 0:			/* 12 AM */
232		case 12:		/* 12 PM */
233			hour = 12;
234			break;
235		default:
236			/*
237			 * The remaining 'ct.hour' values are interpreted as:
238			 * [1  - 11] ->  1 - 11 AM
239			 * [13 - 23] ->  1 - 11 PM
240			 */
241			hour = ct.hour % 12;
242			break;
243		}
244	}
245
246	rtc->hour = rtcset(rtc, hour);
247
248	if ((rtc->reg_b & RTCSB_24HR) == 0 && ct.hour >= 12)
249		rtc->hour |= 0x80;	    /* set MSB to indicate PM */
250
251	rtc->day_of_week = rtcset(rtc, ct.dow + 1);
252	rtc->day_of_month = rtcset(rtc, ct.day);
253	rtc->month = rtcset(rtc, ct.mon);
254	rtc->year = rtcset(rtc, ct.year % 100);
255	rtc->century = rtcset(rtc, ct.year / 100);
256}
257
258static int
259rtcget(struct rtcdev *rtc, int val, int *retval)
260{
261	uint8_t upper, lower;
262
263	if (rtc->reg_b & RTCSB_BIN) {
264		*retval = val;
265		return (0);
266	}
267
268	lower = val & 0xf;
269	upper = (val >> 4) & 0xf;
270
271	if (lower > 9 || upper > 9)
272		return (-1);
273
274	*retval = upper * 10 + lower;
275	return (0);
276}
277
278static time_t
279rtc_to_secs(struct vrtc *vrtc)
280{
281	struct clocktime ct;
282	struct timespec ts;
283	struct rtcdev *rtc;
284	struct vm *vm;
285	int century, error, hour, pm, year;
286
287	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
288
289	vm = vrtc->vm;
290	rtc = &vrtc->rtcdev;
291
292	bzero(&ct, sizeof(struct clocktime));
293
294	error = rtcget(rtc, rtc->sec, &ct.sec);
295	if (error || ct.sec < 0 || ct.sec > 59) {
296		VM_CTR2(vm, "Invalid RTC sec %#x/%d", rtc->sec, ct.sec);
297		goto fail;
298	}
299
300	error = rtcget(rtc, rtc->min, &ct.min);
301	if (error || ct.min < 0 || ct.min > 59) {
302		VM_CTR2(vm, "Invalid RTC min %#x/%d", rtc->min, ct.min);
303		goto fail;
304	}
305
306	pm = 0;
307	hour = rtc->hour;
308	if ((rtc->reg_b & RTCSB_24HR) == 0) {
309		if (hour & 0x80) {
310			hour &= ~0x80;
311			pm = 1;
312		}
313	}
314	error = rtcget(rtc, hour, &ct.hour);
315	if ((rtc->reg_b & RTCSB_24HR) == 0) {
316		if (ct.hour >= 1 && ct.hour <= 12) {
317			/*
318			 * Convert from 12-hour format to internal 24-hour
319			 * representation as follows:
320			 *
321			 *    12-hour format		ct.hour
322			 *	12	AM		0
323			 *	1 - 11	AM		1 - 11
324			 *	12	PM		12
325			 *	1 - 11	PM		13 - 23
326			 */
327			if (ct.hour == 12)
328				ct.hour = 0;
329			if (pm)
330				ct.hour += 12;
331		} else {
332			VM_CTR2(vm, "Invalid RTC 12-hour format %#x/%d",
333			    rtc->hour, ct.hour);
334			goto fail;
335		}
336	}
337
338	if (error || ct.hour < 0 || ct.hour > 23) {
339		VM_CTR2(vm, "Invalid RTC hour %#x/%d", rtc->hour, ct.hour);
340		goto fail;
341	}
342
343	/*
344	 * Ignore 'rtc->dow' because some guests like Linux don't bother
345	 * setting it at all while others like OpenBSD/i386 set it incorrectly.
346	 *
347	 * clock_ct_to_ts() does not depend on 'ct.dow' anyways so ignore it.
348	 */
349	ct.dow = -1;
350
351	error = rtcget(rtc, rtc->day_of_month, &ct.day);
352	if (error || ct.day < 1 || ct.day > 31) {
353		VM_CTR2(vm, "Invalid RTC mday %#x/%d", rtc->day_of_month,
354		    ct.day);
355		goto fail;
356	}
357
358	error = rtcget(rtc, rtc->month, &ct.mon);
359	if (error || ct.mon < 1 || ct.mon > 12) {
360		VM_CTR2(vm, "Invalid RTC month %#x/%d", rtc->month, ct.mon);
361		goto fail;
362	}
363
364	error = rtcget(rtc, rtc->year, &year);
365	if (error || year < 0 || year > 99) {
366		VM_CTR2(vm, "Invalid RTC year %#x/%d", rtc->year, year);
367		goto fail;
368	}
369
370	error = rtcget(rtc, rtc->century, &century);
371	ct.year = century * 100 + year;
372	if (error || ct.year < POSIX_BASE_YEAR) {
373		VM_CTR2(vm, "Invalid RTC century %#x/%d", rtc->century,
374		    ct.year);
375		goto fail;
376	}
377
378	error = clock_ct_to_ts(&ct, &ts);
379	if (error || ts.tv_sec < 0) {
380		VM_CTR3(vm, "Invalid RTC clocktime.date %04d-%02d-%02d",
381		    ct.year, ct.mon, ct.day);
382		VM_CTR3(vm, "Invalid RTC clocktime.time %02d:%02d:%02d",
383		    ct.hour, ct.min, ct.sec);
384		goto fail;
385	}
386	return (ts.tv_sec);		/* success */
387fail:
388	/*
389	 * Stop updating the RTC if the date/time fields programmed by
390	 * the guest are invalid.
391	 */
392	VM_CTR0(vrtc->vm, "Invalid RTC date/time programming detected");
393	return (VRTC_BROKEN_TIME);
394}
395
396static int
397vrtc_time_update(struct vrtc *vrtc, time_t newtime, sbintime_t newbase)
398{
399	struct rtcdev *rtc;
400	sbintime_t oldbase;
401	time_t oldtime;
402	uint8_t alarm_sec, alarm_min, alarm_hour;
403
404	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
405
406	rtc = &vrtc->rtcdev;
407	alarm_sec = rtc->alarm_sec;
408	alarm_min = rtc->alarm_min;
409	alarm_hour = rtc->alarm_hour;
410
411	oldtime = vrtc->base_rtctime;
412	VM_CTR2(vrtc->vm, "Updating RTC secs from %#lx to %#lx",
413	    oldtime, newtime);
414
415	oldbase = vrtc->base_uptime;
416	VM_CTR2(vrtc->vm, "Updating RTC base uptime from %#lx to %#lx",
417	    oldbase, newbase);
418	vrtc->base_uptime = newbase;
419
420	if (newtime == oldtime)
421		return (0);
422
423	/*
424	 * If 'newtime' indicates that RTC updates are disabled then just
425	 * record that and return. There is no need to do alarm interrupt
426	 * processing in this case.
427	 */
428	if (newtime == VRTC_BROKEN_TIME) {
429		vrtc->base_rtctime = VRTC_BROKEN_TIME;
430		return (0);
431	}
432
433	/*
434	 * Return an error if RTC updates are halted by the guest.
435	 */
436	if (rtc_halted(vrtc)) {
437		VM_CTR0(vrtc->vm, "RTC update halted by guest");
438		return (EBUSY);
439	}
440
441	do {
442		/*
443		 * If the alarm interrupt is enabled and 'oldtime' is valid
444		 * then visit all the seconds between 'oldtime' and 'newtime'
445		 * to check for the alarm condition.
446		 *
447		 * Otherwise move the RTC time forward directly to 'newtime'.
448		 */
449		if (aintr_enabled(vrtc) && oldtime != VRTC_BROKEN_TIME)
450			vrtc->base_rtctime++;
451		else
452			vrtc->base_rtctime = newtime;
453
454		if (aintr_enabled(vrtc)) {
455			/*
456			 * Update the RTC date/time fields before checking
457			 * if the alarm conditions are satisfied.
458			 */
459			secs_to_rtc(vrtc->base_rtctime, vrtc, 0);
460
461			if ((alarm_sec >= 0xC0 || alarm_sec == rtc->sec) &&
462			    (alarm_min >= 0xC0 || alarm_min == rtc->min) &&
463			    (alarm_hour >= 0xC0 || alarm_hour == rtc->hour)) {
464				vrtc_set_reg_c(vrtc, rtc->reg_c | RTCIR_ALARM);
465			}
466		}
467	} while (vrtc->base_rtctime != newtime);
468
469	if (uintr_enabled(vrtc))
470		vrtc_set_reg_c(vrtc, rtc->reg_c | RTCIR_UPDATE);
471
472	return (0);
473}
474
475static sbintime_t
476vrtc_freq(struct vrtc *vrtc)
477{
478	int ratesel;
479
480	static sbintime_t pf[16] = {
481		0,
482		SBT_1S / 256,
483		SBT_1S / 128,
484		SBT_1S / 8192,
485		SBT_1S / 4096,
486		SBT_1S / 2048,
487		SBT_1S / 1024,
488		SBT_1S / 512,
489		SBT_1S / 256,
490		SBT_1S / 128,
491		SBT_1S / 64,
492		SBT_1S / 32,
493		SBT_1S / 16,
494		SBT_1S / 8,
495		SBT_1S / 4,
496		SBT_1S / 2,
497	};
498
499	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
500
501	/*
502	 * If both periodic and alarm interrupts are enabled then use the
503	 * periodic frequency to drive the callout. The minimum periodic
504	 * frequency (2 Hz) is higher than the alarm frequency (1 Hz) so
505	 * piggyback the alarm on top of it. The same argument applies to
506	 * the update interrupt.
507	 */
508	if (pintr_enabled(vrtc) && divider_enabled(vrtc->rtcdev.reg_a)) {
509		ratesel = vrtc->rtcdev.reg_a & 0xf;
510		return (pf[ratesel]);
511	} else if (aintr_enabled(vrtc) && update_enabled(vrtc)) {
512		return (SBT_1S);
513	} else if (uintr_enabled(vrtc) && update_enabled(vrtc)) {
514		return (SBT_1S);
515	} else {
516		return (0);
517	}
518}
519
520static void
521vrtc_callout_reset(struct vrtc *vrtc, sbintime_t freqsbt)
522{
523
524	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
525
526	if (freqsbt == 0) {
527		if (callout_active(&vrtc->callout)) {
528			VM_CTR0(vrtc->vm, "RTC callout stopped");
529			callout_stop(&vrtc->callout);
530		}
531		return;
532	}
533	VM_CTR1(vrtc->vm, "RTC callout frequency %d hz", SBT_1S / freqsbt);
534	callout_reset_sbt(&vrtc->callout, freqsbt, 0, vrtc_callout_handler,
535	    vrtc, 0);
536}
537
538static void
539vrtc_callout_handler(void *arg)
540{
541	struct vrtc *vrtc = arg;
542	sbintime_t freqsbt, basetime;
543	time_t rtctime;
544	int error;
545
546	VM_CTR0(vrtc->vm, "vrtc callout fired");
547
548	VRTC_LOCK(vrtc);
549	if (callout_pending(&vrtc->callout))	/* callout was reset */
550		goto done;
551
552	if (!callout_active(&vrtc->callout))	/* callout was stopped */
553		goto done;
554
555	callout_deactivate(&vrtc->callout);
556
557	KASSERT((vrtc->rtcdev.reg_b & RTCSB_ALL_INTRS) != 0,
558	    ("gratuitous vrtc callout"));
559
560	if (pintr_enabled(vrtc))
561		vrtc_set_reg_c(vrtc, vrtc->rtcdev.reg_c | RTCIR_PERIOD);
562
563	if (aintr_enabled(vrtc) || uintr_enabled(vrtc)) {
564		rtctime = vrtc_curtime(vrtc, &basetime);
565		error = vrtc_time_update(vrtc, rtctime, basetime);
566		KASSERT(error == 0, ("%s: vrtc_time_update error %d",
567		    __func__, error));
568	}
569
570	freqsbt = vrtc_freq(vrtc);
571	KASSERT(freqsbt != 0, ("%s: vrtc frequency cannot be zero", __func__));
572	vrtc_callout_reset(vrtc, freqsbt);
573done:
574	VRTC_UNLOCK(vrtc);
575}
576
577static __inline void
578vrtc_callout_check(struct vrtc *vrtc, sbintime_t freq)
579{
580	int active;
581
582	active = callout_active(&vrtc->callout) ? 1 : 0;
583	KASSERT((freq == 0 && !active) || (freq != 0 && active),
584	    ("vrtc callout %s with frequency %#lx",
585	    active ? "active" : "inactive", freq));
586}
587
588static void
589vrtc_set_reg_c(struct vrtc *vrtc, uint8_t newval)
590{
591	struct rtcdev *rtc;
592	int oldirqf, newirqf;
593	uint8_t oldval, changed;
594
595	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
596
597	rtc = &vrtc->rtcdev;
598	newval &= RTCIR_ALARM | RTCIR_PERIOD | RTCIR_UPDATE;
599
600	oldirqf = rtc->reg_c & RTCIR_INT;
601	if ((aintr_enabled(vrtc) && (newval & RTCIR_ALARM) != 0) ||
602	    (pintr_enabled(vrtc) && (newval & RTCIR_PERIOD) != 0) ||
603	    (uintr_enabled(vrtc) && (newval & RTCIR_UPDATE) != 0)) {
604		newirqf = RTCIR_INT;
605	} else {
606		newirqf = 0;
607	}
608
609	oldval = rtc->reg_c;
610	rtc->reg_c = newirqf | newval;
611	changed = oldval ^ rtc->reg_c;
612	if (changed) {
613		VM_CTR2(vrtc->vm, "RTC reg_c changed from %#x to %#x",
614		    oldval, rtc->reg_c);
615	}
616
617	if (!oldirqf && newirqf) {
618		VM_CTR1(vrtc->vm, "RTC irq %d asserted", RTC_IRQ);
619		vatpic_pulse_irq(vrtc->vm, RTC_IRQ);
620		vioapic_pulse_irq(vrtc->vm, RTC_IRQ);
621	} else if (oldirqf && !newirqf) {
622		VM_CTR1(vrtc->vm, "RTC irq %d deasserted", RTC_IRQ);
623	}
624}
625
626static int
627vrtc_set_reg_b(struct vrtc *vrtc, uint8_t newval)
628{
629	struct rtcdev *rtc;
630	sbintime_t oldfreq, newfreq, basetime;
631	time_t curtime, rtctime;
632	int error;
633	uint8_t oldval, changed;
634
635	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
636
637	rtc = &vrtc->rtcdev;
638	oldval = rtc->reg_b;
639	oldfreq = vrtc_freq(vrtc);
640
641	rtc->reg_b = newval;
642	changed = oldval ^ newval;
643	if (changed) {
644		VM_CTR2(vrtc->vm, "RTC reg_b changed from %#x to %#x",
645		    oldval, newval);
646	}
647
648	if (changed & RTCSB_HALT) {
649		if ((newval & RTCSB_HALT) == 0) {
650			rtctime = rtc_to_secs(vrtc);
651			basetime = sbinuptime();
652			if (rtctime == VRTC_BROKEN_TIME) {
653				if (rtc_flag_broken_time)
654					return (-1);
655			}
656		} else {
657			curtime = vrtc_curtime(vrtc, &basetime);
658			KASSERT(curtime == vrtc->base_rtctime, ("%s: mismatch "
659			    "between vrtc basetime (%#lx) and curtime (%#lx)",
660			    __func__, vrtc->base_rtctime, curtime));
661
662			/*
663			 * Force a refresh of the RTC date/time fields so
664			 * they reflect the time right before the guest set
665			 * the HALT bit.
666			 */
667			secs_to_rtc(curtime, vrtc, 1);
668
669			/*
670			 * Updates are halted so mark 'base_rtctime' to denote
671			 * that the RTC date/time is in flux.
672			 */
673			rtctime = VRTC_BROKEN_TIME;
674			rtc->reg_b &= ~RTCSB_UINTR;
675		}
676		error = vrtc_time_update(vrtc, rtctime, basetime);
677		KASSERT(error == 0, ("vrtc_time_update error %d", error));
678	}
679
680	/*
681	 * Side effect of changes to the interrupt enable bits.
682	 */
683	if (changed & RTCSB_ALL_INTRS)
684		vrtc_set_reg_c(vrtc, vrtc->rtcdev.reg_c);
685
686	/*
687	 * Change the callout frequency if it has changed.
688	 */
689	newfreq = vrtc_freq(vrtc);
690	if (newfreq != oldfreq)
691		vrtc_callout_reset(vrtc, newfreq);
692	else
693		vrtc_callout_check(vrtc, newfreq);
694
695	/*
696	 * The side effect of bits that control the RTC date/time format
697	 * is handled lazily when those fields are actually read.
698	 */
699	return (0);
700}
701
702static void
703vrtc_set_reg_a(struct vrtc *vrtc, uint8_t newval)
704{
705	sbintime_t oldfreq, newfreq;
706	uint8_t oldval, changed;
707
708	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
709
710	newval &= ~RTCSA_TUP;
711	oldval = vrtc->rtcdev.reg_a;
712	oldfreq = vrtc_freq(vrtc);
713
714	if (divider_enabled(oldval) && !divider_enabled(newval)) {
715		VM_CTR2(vrtc->vm, "RTC divider held in reset at %#lx/%#lx",
716		    vrtc->base_rtctime, vrtc->base_uptime);
717	} else if (!divider_enabled(oldval) && divider_enabled(newval)) {
718		/*
719		 * If the dividers are coming out of reset then update
720		 * 'base_uptime' before this happens. This is done to
721		 * maintain the illusion that the RTC date/time was frozen
722		 * while the dividers were disabled.
723		 */
724		vrtc->base_uptime = sbinuptime();
725		VM_CTR2(vrtc->vm, "RTC divider out of reset at %#lx/%#lx",
726		    vrtc->base_rtctime, vrtc->base_uptime);
727	} else {
728		/* NOTHING */
729	}
730
731	vrtc->rtcdev.reg_a = newval;
732	changed = oldval ^ newval;
733	if (changed) {
734		VM_CTR2(vrtc->vm, "RTC reg_a changed from %#x to %#x",
735		    oldval, newval);
736	}
737
738	/*
739	 * Side effect of changes to rate select and divider enable bits.
740	 */
741	newfreq = vrtc_freq(vrtc);
742	if (newfreq != oldfreq)
743		vrtc_callout_reset(vrtc, newfreq);
744	else
745		vrtc_callout_check(vrtc, newfreq);
746}
747
748int
749vrtc_set_time(struct vm *vm, time_t secs)
750{
751	struct vrtc *vrtc;
752	int error;
753
754	vrtc = vm_rtc(vm);
755	VRTC_LOCK(vrtc);
756	error = vrtc_time_update(vrtc, secs, sbinuptime());
757	VRTC_UNLOCK(vrtc);
758
759	if (error) {
760		VM_CTR2(vrtc->vm, "Error %d setting RTC time to %#lx", error,
761		    secs);
762	} else {
763		VM_CTR1(vrtc->vm, "RTC time set to %#lx", secs);
764	}
765
766	return (error);
767}
768
769time_t
770vrtc_get_time(struct vm *vm)
771{
772	struct vrtc *vrtc;
773	sbintime_t basetime;
774	time_t t;
775
776	vrtc = vm_rtc(vm);
777	VRTC_LOCK(vrtc);
778	t = vrtc_curtime(vrtc, &basetime);
779	VRTC_UNLOCK(vrtc);
780
781	return (t);
782}
783
784int
785vrtc_nvram_write(struct vm *vm, int offset, uint8_t value)
786{
787	struct vrtc *vrtc;
788	uint8_t *ptr;
789
790	vrtc = vm_rtc(vm);
791
792	/*
793	 * Don't allow writes to RTC control registers or the date/time fields.
794	 */
795	if (offset < offsetof(struct rtcdev, nvram[0]) ||
796	    offset == RTC_CENTURY || offset >= sizeof(struct rtcdev)) {
797		VM_CTR1(vrtc->vm, "RTC nvram write to invalid offset %d",
798		    offset);
799		return (EINVAL);
800	}
801
802	VRTC_LOCK(vrtc);
803	ptr = (uint8_t *)(&vrtc->rtcdev);
804	ptr[offset] = value;
805	VM_CTR2(vrtc->vm, "RTC nvram write %#x to offset %#x", value, offset);
806	VRTC_UNLOCK(vrtc);
807
808	return (0);
809}
810
811int
812vrtc_nvram_read(struct vm *vm, int offset, uint8_t *retval)
813{
814	struct vrtc *vrtc;
815	sbintime_t basetime;
816	time_t curtime;
817	uint8_t *ptr;
818
819	/*
820	 * Allow all offsets in the RTC to be read.
821	 */
822	if (offset < 0 || offset >= sizeof(struct rtcdev))
823		return (EINVAL);
824
825	vrtc = vm_rtc(vm);
826	VRTC_LOCK(vrtc);
827
828	/*
829	 * Update RTC date/time fields if necessary.
830	 */
831	if (offset < 10 || offset == RTC_CENTURY) {
832		curtime = vrtc_curtime(vrtc, &basetime);
833		secs_to_rtc(curtime, vrtc, 0);
834	}
835
836	ptr = (uint8_t *)(&vrtc->rtcdev);
837	*retval = ptr[offset];
838
839	VRTC_UNLOCK(vrtc);
840	return (0);
841}
842
843int
844vrtc_addr_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
845    uint32_t *val)
846{
847	struct vrtc *vrtc;
848
849	vrtc = vm_rtc(vm);
850
851	if (bytes != 1)
852		return (-1);
853
854	if (in) {
855		*val = 0xff;
856		return (0);
857	}
858
859	VRTC_LOCK(vrtc);
860	vrtc->addr = *val & 0x7f;
861	VRTC_UNLOCK(vrtc);
862
863	return (0);
864}
865
866int
867vrtc_data_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
868    uint32_t *val)
869{
870	struct vrtc *vrtc;
871	struct rtcdev *rtc;
872	sbintime_t basetime;
873	time_t curtime;
874	int error, offset;
875
876	vrtc = vm_rtc(vm);
877	rtc = &vrtc->rtcdev;
878
879	if (bytes != 1)
880		return (-1);
881
882	VRTC_LOCK(vrtc);
883	offset = vrtc->addr;
884	if (offset >= sizeof(struct rtcdev)) {
885		VRTC_UNLOCK(vrtc);
886		return (-1);
887	}
888
889	error = 0;
890	curtime = vrtc_curtime(vrtc, &basetime);
891	vrtc_time_update(vrtc, curtime, basetime);
892
893	/*
894	 * Update RTC date/time fields if necessary.
895	 *
896	 * This is not just for reads of the RTC. The side-effect of writing
897	 * the century byte requires other RTC date/time fields (e.g. sec)
898	 * to be updated here.
899	 */
900	if (offset < 10 || offset == RTC_CENTURY)
901		secs_to_rtc(curtime, vrtc, 0);
902
903	if (in) {
904		if (offset == 12) {
905			/*
906			 * XXX
907			 * reg_c interrupt flags are updated only if the
908			 * corresponding interrupt enable bit in reg_b is set.
909			 */
910			*val = vrtc->rtcdev.reg_c;
911			vrtc_set_reg_c(vrtc, 0);
912		} else {
913			*val = *((uint8_t *)rtc + offset);
914		}
915		VCPU_CTR2(vm, vcpuid, "Read value %#x from RTC offset %#x",
916		    *val, offset);
917	} else {
918		switch (offset) {
919		case 10:
920			VCPU_CTR1(vm, vcpuid, "RTC reg_a set to %#x", *val);
921			vrtc_set_reg_a(vrtc, *val);
922			break;
923		case 11:
924			VCPU_CTR1(vm, vcpuid, "RTC reg_b set to %#x", *val);
925			error = vrtc_set_reg_b(vrtc, *val);
926			break;
927		case 12:
928			VCPU_CTR1(vm, vcpuid, "RTC reg_c set to %#x (ignored)",
929			    *val);
930			break;
931		case 13:
932			VCPU_CTR1(vm, vcpuid, "RTC reg_d set to %#x (ignored)",
933			    *val);
934			break;
935		case 0:
936			/*
937			 * High order bit of 'seconds' is readonly.
938			 */
939			*val &= 0x7f;
940			/* FALLTHRU */
941		default:
942			VCPU_CTR2(vm, vcpuid, "RTC offset %#x set to %#x",
943			    offset, *val);
944			*((uint8_t *)rtc + offset) = *val;
945			break;
946		}
947
948		/*
949		 * XXX some guests (e.g. OpenBSD) write the century byte
950		 * outside of RTCSB_HALT so re-calculate the RTC date/time.
951		 */
952		if (offset == RTC_CENTURY && !rtc_halted(vrtc)) {
953			curtime = rtc_to_secs(vrtc);
954			error = vrtc_time_update(vrtc, curtime, sbinuptime());
955			KASSERT(!error, ("vrtc_time_update error %d", error));
956			if (curtime == VRTC_BROKEN_TIME && rtc_flag_broken_time)
957				error = -1;
958		}
959	}
960	VRTC_UNLOCK(vrtc);
961	return (error);
962}
963
964void
965vrtc_reset(struct vrtc *vrtc)
966{
967	struct rtcdev *rtc;
968
969	VRTC_LOCK(vrtc);
970
971	rtc = &vrtc->rtcdev;
972	vrtc_set_reg_b(vrtc, rtc->reg_b & ~(RTCSB_ALL_INTRS | RTCSB_SQWE));
973	vrtc_set_reg_c(vrtc, 0);
974	KASSERT(!callout_active(&vrtc->callout), ("rtc callout still active"));
975
976	VRTC_UNLOCK(vrtc);
977}
978
979struct vrtc *
980vrtc_init(struct vm *vm)
981{
982	struct vrtc *vrtc;
983	struct rtcdev *rtc;
984	time_t curtime;
985
986	vrtc = malloc(sizeof(struct vrtc), M_VRTC, M_WAITOK | M_ZERO);
987	vrtc->vm = vm;
988	mtx_init(&vrtc->mtx, "vrtc lock", NULL, MTX_DEF);
989	callout_init(&vrtc->callout, 1);
990
991	/* Allow dividers to keep time but disable everything else */
992	rtc = &vrtc->rtcdev;
993	rtc->reg_a = 0x20;
994	rtc->reg_b = RTCSB_24HR;
995	rtc->reg_c = 0;
996	rtc->reg_d = RTCSD_PWR;
997
998	/* Reset the index register to a safe value. */
999	vrtc->addr = RTC_STATUSD;
1000
1001	/*
1002	 * Initialize RTC time to 00:00:00 Jan 1, 1970.
1003	 */
1004	curtime = 0;
1005
1006	VRTC_LOCK(vrtc);
1007	vrtc->base_rtctime = VRTC_BROKEN_TIME;
1008	vrtc_time_update(vrtc, curtime, sbinuptime());
1009	secs_to_rtc(curtime, vrtc, 0);
1010	VRTC_UNLOCK(vrtc);
1011
1012	return (vrtc);
1013}
1014
1015void
1016vrtc_cleanup(struct vrtc *vrtc)
1017{
1018
1019	callout_drain(&vrtc->callout);
1020	free(vrtc, M_VRTC);
1021}
1022