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