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