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