xref: /freebsd/sys/amd64/vmm/io/vrtc.c (revision 130d950cafcd29c6a32cf5357bf600dcd9c1d998)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2014, Neel Natu (neel@freebsd.org)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/queue.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/clock.h>
40 #include <sys/sysctl.h>
41 
42 #include <machine/vmm.h>
43 
44 #include <isa/rtc.h>
45 
46 #include "vmm_ktr.h"
47 #include "vatpic.h"
48 #include "vioapic.h"
49 #include "vrtc.h"
50 
51 /* Register layout of the RTC */
52 struct rtcdev {
53 	uint8_t	sec;
54 	uint8_t	alarm_sec;
55 	uint8_t	min;
56 	uint8_t	alarm_min;
57 	uint8_t	hour;
58 	uint8_t	alarm_hour;
59 	uint8_t	day_of_week;
60 	uint8_t	day_of_month;
61 	uint8_t	month;
62 	uint8_t	year;
63 	uint8_t	reg_a;
64 	uint8_t	reg_b;
65 	uint8_t	reg_c;
66 	uint8_t	reg_d;
67 	uint8_t	nvram[36];
68 	uint8_t	century;
69 	uint8_t	nvram2[128 - 51];
70 } __packed;
71 CTASSERT(sizeof(struct rtcdev) == 128);
72 CTASSERT(offsetof(struct rtcdev, century) == RTC_CENTURY);
73 
74 struct vrtc {
75 	struct vm	*vm;
76 	struct mtx	mtx;
77 	struct callout	callout;
78 	u_int		addr;		/* RTC register to read or write */
79 	sbintime_t	base_uptime;
80 	time_t		base_rtctime;
81 	struct rtcdev	rtcdev;
82 };
83 
84 #define	VRTC_LOCK(vrtc)		mtx_lock(&((vrtc)->mtx))
85 #define	VRTC_UNLOCK(vrtc)	mtx_unlock(&((vrtc)->mtx))
86 #define	VRTC_LOCKED(vrtc)	mtx_owned(&((vrtc)->mtx))
87 
88 /*
89  * RTC time is considered "broken" if:
90  * - RTC updates are halted by the guest
91  * - RTC date/time fields have invalid values
92  */
93 #define	VRTC_BROKEN_TIME	((time_t)-1)
94 
95 #define	RTC_IRQ			8
96 #define	RTCSB_BIN		0x04
97 #define	RTCSB_ALL_INTRS		(RTCSB_UINTR | RTCSB_AINTR | RTCSB_PINTR)
98 #define	rtc_halted(vrtc)	((vrtc->rtcdev.reg_b & RTCSB_HALT) != 0)
99 #define	aintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_AINTR) != 0)
100 #define	pintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_PINTR) != 0)
101 #define	uintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_UINTR) != 0)
102 
103 static void vrtc_callout_handler(void *arg);
104 static void vrtc_set_reg_c(struct vrtc *vrtc, uint8_t newval);
105 
106 static MALLOC_DEFINE(M_VRTC, "vrtc", "bhyve virtual rtc");
107 
108 SYSCTL_DECL(_hw_vmm);
109 SYSCTL_NODE(_hw_vmm, OID_AUTO, vrtc, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
110     NULL);
111 
112 static int rtc_flag_broken_time = 1;
113 SYSCTL_INT(_hw_vmm_vrtc, OID_AUTO, flag_broken_time, CTLFLAG_RDTUN,
114     &rtc_flag_broken_time, 0, "Stop guest when invalid RTC time is detected");
115 
116 static __inline bool
117 divider_enabled(int reg_a)
118 {
119 	/*
120 	 * The RTC is counting only when dividers are not held in reset.
121 	 */
122 	return ((reg_a & 0x70) == 0x20);
123 }
124 
125 static __inline bool
126 update_enabled(struct vrtc *vrtc)
127 {
128 	/*
129 	 * RTC date/time can be updated only if:
130 	 * - divider is not held in reset
131 	 * - guest has not disabled updates
132 	 * - the date/time fields have valid contents
133 	 */
134 	if (!divider_enabled(vrtc->rtcdev.reg_a))
135 		return (false);
136 
137 	if (rtc_halted(vrtc))
138 		return (false);
139 
140 	if (vrtc->base_rtctime == VRTC_BROKEN_TIME)
141 		return (false);
142 
143 	return (true);
144 }
145 
146 static time_t
147 vrtc_curtime(struct vrtc *vrtc, sbintime_t *basetime)
148 {
149 	sbintime_t now, delta;
150 	time_t t, secs;
151 
152 	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
153 
154 	t = vrtc->base_rtctime;
155 	*basetime = vrtc->base_uptime;
156 	if (update_enabled(vrtc)) {
157 		now = sbinuptime();
158 		delta = now - vrtc->base_uptime;
159 		KASSERT(delta >= 0, ("vrtc_curtime: uptime went backwards: "
160 		    "%#lx to %#lx", vrtc->base_uptime, now));
161 		secs = delta / SBT_1S;
162 		t += secs;
163 		*basetime += secs * SBT_1S;
164 	}
165 	return (t);
166 }
167 
168 static __inline uint8_t
169 rtcset(struct rtcdev *rtc, int val)
170 {
171 
172 	KASSERT(val >= 0 && val < 100, ("%s: invalid bin2bcd index %d",
173 	    __func__, val));
174 
175 	return ((rtc->reg_b & RTCSB_BIN) ? val : bin2bcd_data[val]);
176 }
177 
178 static void
179 secs_to_rtc(time_t rtctime, struct vrtc *vrtc, int force_update)
180 {
181 	struct clocktime ct;
182 	struct timespec ts;
183 	struct rtcdev *rtc;
184 	int hour;
185 
186 	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
187 
188 	if (rtctime < 0) {
189 		KASSERT(rtctime == VRTC_BROKEN_TIME,
190 		    ("%s: invalid vrtc time %#lx", __func__, rtctime));
191 		return;
192 	}
193 
194 	/*
195 	 * If the RTC is halted then the guest has "ownership" of the
196 	 * date/time fields. Don't update the RTC date/time fields in
197 	 * this case (unless forced).
198 	 */
199 	if (rtc_halted(vrtc) && !force_update)
200 		return;
201 
202 	ts.tv_sec = rtctime;
203 	ts.tv_nsec = 0;
204 	clock_ts_to_ct(&ts, &ct);
205 
206 	KASSERT(ct.sec >= 0 && ct.sec <= 59, ("invalid clocktime sec %d",
207 	    ct.sec));
208 	KASSERT(ct.min >= 0 && ct.min <= 59, ("invalid clocktime min %d",
209 	    ct.min));
210 	KASSERT(ct.hour >= 0 && ct.hour <= 23, ("invalid clocktime hour %d",
211 	    ct.hour));
212 	KASSERT(ct.dow >= 0 && ct.dow <= 6, ("invalid clocktime wday %d",
213 	    ct.dow));
214 	KASSERT(ct.day >= 1 && ct.day <= 31, ("invalid clocktime mday %d",
215 	    ct.day));
216 	KASSERT(ct.mon >= 1 && ct.mon <= 12, ("invalid clocktime month %d",
217 	    ct.mon));
218 	KASSERT(ct.year >= POSIX_BASE_YEAR, ("invalid clocktime year %d",
219 	    ct.year));
220 
221 	rtc = &vrtc->rtcdev;
222 	rtc->sec = rtcset(rtc, ct.sec);
223 	rtc->min = rtcset(rtc, ct.min);
224 
225 	if (rtc->reg_b & RTCSB_24HR) {
226 		hour = ct.hour;
227 	} else {
228 		/*
229 		 * Convert to the 12-hour format.
230 		 */
231 		switch (ct.hour) {
232 		case 0:			/* 12 AM */
233 		case 12:		/* 12 PM */
234 			hour = 12;
235 			break;
236 		default:
237 			/*
238 			 * The remaining 'ct.hour' values are interpreted as:
239 			 * [1  - 11] ->  1 - 11 AM
240 			 * [13 - 23] ->  1 - 11 PM
241 			 */
242 			hour = ct.hour % 12;
243 			break;
244 		}
245 	}
246 
247 	rtc->hour = rtcset(rtc, hour);
248 
249 	if ((rtc->reg_b & RTCSB_24HR) == 0 && ct.hour >= 12)
250 		rtc->hour |= 0x80;	    /* set MSB to indicate PM */
251 
252 	rtc->day_of_week = rtcset(rtc, ct.dow + 1);
253 	rtc->day_of_month = rtcset(rtc, ct.day);
254 	rtc->month = rtcset(rtc, ct.mon);
255 	rtc->year = rtcset(rtc, ct.year % 100);
256 	rtc->century = rtcset(rtc, ct.year / 100);
257 }
258 
259 static int
260 rtcget(struct rtcdev *rtc, int val, int *retval)
261 {
262 	uint8_t upper, lower;
263 
264 	if (rtc->reg_b & RTCSB_BIN) {
265 		*retval = val;
266 		return (0);
267 	}
268 
269 	lower = val & 0xf;
270 	upper = (val >> 4) & 0xf;
271 
272 	if (lower > 9 || upper > 9)
273 		return (-1);
274 
275 	*retval = upper * 10 + lower;
276 	return (0);
277 }
278 
279 static time_t
280 rtc_to_secs(struct vrtc *vrtc)
281 {
282 	struct clocktime ct;
283 	struct timespec ts;
284 	struct rtcdev *rtc;
285 	struct vm *vm;
286 	int century, error, hour, pm, year;
287 
288 	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
289 
290 	vm = vrtc->vm;
291 	rtc = &vrtc->rtcdev;
292 
293 	bzero(&ct, sizeof(struct clocktime));
294 
295 	error = rtcget(rtc, rtc->sec, &ct.sec);
296 	if (error || ct.sec < 0 || ct.sec > 59) {
297 		VM_CTR2(vm, "Invalid RTC sec %#x/%d", rtc->sec, ct.sec);
298 		goto fail;
299 	}
300 
301 	error = rtcget(rtc, rtc->min, &ct.min);
302 	if (error || ct.min < 0 || ct.min > 59) {
303 		VM_CTR2(vm, "Invalid RTC min %#x/%d", rtc->min, ct.min);
304 		goto fail;
305 	}
306 
307 	pm = 0;
308 	hour = rtc->hour;
309 	if ((rtc->reg_b & RTCSB_24HR) == 0) {
310 		if (hour & 0x80) {
311 			hour &= ~0x80;
312 			pm = 1;
313 		}
314 	}
315 	error = rtcget(rtc, hour, &ct.hour);
316 	if ((rtc->reg_b & RTCSB_24HR) == 0) {
317 		if (ct.hour >= 1 && ct.hour <= 12) {
318 			/*
319 			 * Convert from 12-hour format to internal 24-hour
320 			 * representation as follows:
321 			 *
322 			 *    12-hour format		ct.hour
323 			 *	12	AM		0
324 			 *	1 - 11	AM		1 - 11
325 			 *	12	PM		12
326 			 *	1 - 11	PM		13 - 23
327 			 */
328 			if (ct.hour == 12)
329 				ct.hour = 0;
330 			if (pm)
331 				ct.hour += 12;
332 		} else {
333 			VM_CTR2(vm, "Invalid RTC 12-hour format %#x/%d",
334 			    rtc->hour, ct.hour);
335 			goto fail;
336 		}
337 	}
338 
339 	if (error || ct.hour < 0 || ct.hour > 23) {
340 		VM_CTR2(vm, "Invalid RTC hour %#x/%d", rtc->hour, ct.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 		VM_CTR2(vm, "Invalid RTC mday %#x/%d", rtc->day_of_month,
355 		    ct.day);
356 		goto fail;
357 	}
358 
359 	error = rtcget(rtc, rtc->month, &ct.mon);
360 	if (error || ct.mon < 1 || ct.mon > 12) {
361 		VM_CTR2(vm, "Invalid RTC month %#x/%d", rtc->month, ct.mon);
362 		goto fail;
363 	}
364 
365 	error = rtcget(rtc, rtc->year, &year);
366 	if (error || year < 0 || year > 99) {
367 		VM_CTR2(vm, "Invalid RTC year %#x/%d", rtc->year, year);
368 		goto fail;
369 	}
370 
371 	error = rtcget(rtc, rtc->century, &century);
372 	ct.year = century * 100 + year;
373 	if (error || ct.year < POSIX_BASE_YEAR) {
374 		VM_CTR2(vm, "Invalid RTC century %#x/%d", rtc->century,
375 		    ct.year);
376 		goto fail;
377 	}
378 
379 	error = clock_ct_to_ts(&ct, &ts);
380 	if (error || ts.tv_sec < 0) {
381 		VM_CTR3(vm, "Invalid RTC clocktime.date %04d-%02d-%02d",
382 		    ct.year, ct.mon, ct.day);
383 		VM_CTR3(vm, "Invalid RTC clocktime.time %02d:%02d:%02d",
384 		    ct.hour, ct.min, ct.sec);
385 		goto fail;
386 	}
387 	return (ts.tv_sec);		/* success */
388 fail:
389 	/*
390 	 * Stop updating the RTC if the date/time fields programmed by
391 	 * the guest are invalid.
392 	 */
393 	VM_CTR0(vrtc->vm, "Invalid RTC date/time programming detected");
394 	return (VRTC_BROKEN_TIME);
395 }
396 
397 static int
398 vrtc_time_update(struct vrtc *vrtc, time_t newtime, sbintime_t newbase)
399 {
400 	struct rtcdev *rtc;
401 	sbintime_t oldbase;
402 	time_t oldtime;
403 	uint8_t alarm_sec, alarm_min, alarm_hour;
404 
405 	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
406 
407 	rtc = &vrtc->rtcdev;
408 	alarm_sec = rtc->alarm_sec;
409 	alarm_min = rtc->alarm_min;
410 	alarm_hour = rtc->alarm_hour;
411 
412 	oldtime = vrtc->base_rtctime;
413 	VM_CTR2(vrtc->vm, "Updating RTC secs from %#lx to %#lx",
414 	    oldtime, newtime);
415 
416 	oldbase = vrtc->base_uptime;
417 	VM_CTR2(vrtc->vm, "Updating RTC base uptime from %#lx to %#lx",
418 	    oldbase, 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;
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;
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;
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, int vcpuid, bool in, int port, int bytes,
846     uint32_t *val)
847 {
848 	struct vrtc *vrtc;
849 
850 	vrtc = vm_rtc(vm);
851 
852 	if (bytes != 1)
853 		return (-1);
854 
855 	if (in) {
856 		*val = 0xff;
857 		return (0);
858 	}
859 
860 	VRTC_LOCK(vrtc);
861 	vrtc->addr = *val & 0x7f;
862 	VRTC_UNLOCK(vrtc);
863 
864 	return (0);
865 }
866 
867 int
868 vrtc_data_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
869     uint32_t *val)
870 {
871 	struct vrtc *vrtc;
872 	struct rtcdev *rtc;
873 	sbintime_t basetime;
874 	time_t curtime;
875 	int error, offset;
876 
877 	vrtc = vm_rtc(vm);
878 	rtc = &vrtc->rtcdev;
879 
880 	if (bytes != 1)
881 		return (-1);
882 
883 	VRTC_LOCK(vrtc);
884 	offset = vrtc->addr;
885 	if (offset >= sizeof(struct rtcdev)) {
886 		VRTC_UNLOCK(vrtc);
887 		return (-1);
888 	}
889 
890 	error = 0;
891 	curtime = vrtc_curtime(vrtc, &basetime);
892 	vrtc_time_update(vrtc, curtime, basetime);
893 
894 	/*
895 	 * Update RTC date/time fields if necessary.
896 	 *
897 	 * This is not just for reads of the RTC. The side-effect of writing
898 	 * the century byte requires other RTC date/time fields (e.g. sec)
899 	 * to be updated here.
900 	 */
901 	if (offset < 10 || offset == RTC_CENTURY)
902 		secs_to_rtc(curtime, vrtc, 0);
903 
904 	if (in) {
905 		if (offset == 12) {
906 			/*
907 			 * XXX
908 			 * reg_c interrupt flags are updated only if the
909 			 * corresponding interrupt enable bit in reg_b is set.
910 			 */
911 			*val = vrtc->rtcdev.reg_c;
912 			vrtc_set_reg_c(vrtc, 0);
913 		} else {
914 			*val = *((uint8_t *)rtc + offset);
915 		}
916 		VCPU_CTR2(vm, vcpuid, "Read value %#x from RTC offset %#x",
917 		    *val, offset);
918 	} else {
919 		switch (offset) {
920 		case 10:
921 			VCPU_CTR1(vm, vcpuid, "RTC reg_a set to %#x", *val);
922 			vrtc_set_reg_a(vrtc, *val);
923 			break;
924 		case 11:
925 			VCPU_CTR1(vm, vcpuid, "RTC reg_b set to %#x", *val);
926 			error = vrtc_set_reg_b(vrtc, *val);
927 			break;
928 		case 12:
929 			VCPU_CTR1(vm, vcpuid, "RTC reg_c set to %#x (ignored)",
930 			    *val);
931 			break;
932 		case 13:
933 			VCPU_CTR1(vm, vcpuid, "RTC reg_d set to %#x (ignored)",
934 			    *val);
935 			break;
936 		case 0:
937 			/*
938 			 * High order bit of 'seconds' is readonly.
939 			 */
940 			*val &= 0x7f;
941 			/* FALLTHRU */
942 		default:
943 			VCPU_CTR2(vm, vcpuid, "RTC offset %#x set to %#x",
944 			    offset, *val);
945 			*((uint8_t *)rtc + offset) = *val;
946 			break;
947 		}
948 
949 		/*
950 		 * XXX some guests (e.g. OpenBSD) write the century byte
951 		 * outside of RTCSB_HALT so re-calculate the RTC date/time.
952 		 */
953 		if (offset == RTC_CENTURY && !rtc_halted(vrtc)) {
954 			curtime = rtc_to_secs(vrtc);
955 			error = vrtc_time_update(vrtc, curtime, sbinuptime());
956 			KASSERT(!error, ("vrtc_time_update error %d", error));
957 			if (curtime == VRTC_BROKEN_TIME && rtc_flag_broken_time)
958 				error = -1;
959 		}
960 	}
961 	VRTC_UNLOCK(vrtc);
962 	return (error);
963 }
964 
965 void
966 vrtc_reset(struct vrtc *vrtc)
967 {
968 	struct rtcdev *rtc;
969 
970 	VRTC_LOCK(vrtc);
971 
972 	rtc = &vrtc->rtcdev;
973 	vrtc_set_reg_b(vrtc, rtc->reg_b & ~(RTCSB_ALL_INTRS | RTCSB_SQWE));
974 	vrtc_set_reg_c(vrtc, 0);
975 	KASSERT(!callout_active(&vrtc->callout), ("rtc callout still active"));
976 
977 	VRTC_UNLOCK(vrtc);
978 }
979 
980 struct vrtc *
981 vrtc_init(struct vm *vm)
982 {
983 	struct vrtc *vrtc;
984 	struct rtcdev *rtc;
985 	time_t curtime;
986 
987 	vrtc = malloc(sizeof(struct vrtc), M_VRTC, M_WAITOK | M_ZERO);
988 	vrtc->vm = vm;
989 	mtx_init(&vrtc->mtx, "vrtc lock", NULL, MTX_DEF);
990 	callout_init(&vrtc->callout, 1);
991 
992 	/* Allow dividers to keep time but disable everything else */
993 	rtc = &vrtc->rtcdev;
994 	rtc->reg_a = 0x20;
995 	rtc->reg_b = RTCSB_24HR;
996 	rtc->reg_c = 0;
997 	rtc->reg_d = RTCSD_PWR;
998 
999 	/* Reset the index register to a safe value. */
1000 	vrtc->addr = RTC_STATUSD;
1001 
1002 	/*
1003 	 * Initialize RTC time to 00:00:00 Jan 1, 1970.
1004 	 */
1005 	curtime = 0;
1006 
1007 	VRTC_LOCK(vrtc);
1008 	vrtc->base_rtctime = VRTC_BROKEN_TIME;
1009 	vrtc_time_update(vrtc, curtime, sbinuptime());
1010 	secs_to_rtc(curtime, vrtc, 0);
1011 	VRTC_UNLOCK(vrtc);
1012 
1013 	return (vrtc);
1014 }
1015 
1016 void
1017 vrtc_cleanup(struct vrtc *vrtc)
1018 {
1019 
1020 	callout_drain(&vrtc->callout);
1021 	free(vrtc, M_VRTC);
1022 }
1023