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