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