xref: /illumos-gate/usr/src/uts/intel/io/vmm/io/vrtc.c (revision 0e34f8dd0e1614ee70140ee97784aed56852a423)
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 /*
30  * Copyright 2018 Joyent, Inc.
31  * Copyright 2023 Oxide Computer Company
32  */
33 
34 #include <sys/cdefs.h>
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 /*
54  * Virtual RTC: Fashioned after the MC146818
55  *
56  * Current limitations:
57  * - Clock divider will only run at 32768Hz (not 1.x or 4.x MHz)
58  * - Date-times prior to 1970-01-01 are not supported
59  * - If date-time held in CMOS is not valid (such as a nonsensical month/day)
60  *   then updates to the time (hours/minutes/seconds) will not occur, even if
61  *   they are enabled through the divider and flags.
62  */
63 
64 /* Register layout of the RTC */
65 struct rtcdev {
66 	uint8_t	sec;
67 	uint8_t	alarm_sec;
68 	uint8_t	min;
69 	uint8_t	alarm_min;
70 	uint8_t	hour;
71 	uint8_t	alarm_hour;
72 	uint8_t	day_of_week;
73 	uint8_t	day_of_month;
74 	uint8_t	month;
75 	uint8_t	year;
76 	uint8_t	reg_a;
77 	uint8_t	reg_b;
78 	uint8_t	reg_c;
79 	uint8_t	reg_d;
80 	uint8_t	nvram[36];
81 	uint8_t	century;
82 	uint8_t	nvram2[128 - 51];
83 } __packed;
84 CTASSERT(sizeof (struct rtcdev) == 128);
85 CTASSERT(offsetof(struct rtcdev, century) == RTC_CENTURY);
86 
87 struct vrtc {
88 	struct vm	*vm;
89 	kmutex_t	lock;
90 	struct callout	callout;
91 
92 	/*
93 	 * Address within the RTC to access when reading/writing from the data
94 	 * IO port.
95 	 */
96 	uint8_t		addr;
97 
98 	/*
99 	 * Time base for RTC functionality driven from the output of the
100 	 * (emulated) divider.  Holds the hrtime at the edge of the last update
101 	 * to seconds, be that an "official" update of the running RTC, the
102 	 * divider being enabled by the guest (and thus implying a start 500ms
103 	 * earlier), or the time being set by a userspace consumer.
104 	 */
105 	hrtime_t	base_clock;
106 
107 	/*
108 	 * Time for most recent periodic-timer-driven event.  Should be kept in
109 	 * phase with base_clock as it relates to edge boundaries of seconds.
110 	 */
111 	hrtime_t	last_period;
112 
113 	/*
114 	 * (UNIX) Time at the last base_clock reading.
115 	 *
116 	 * If an invalid date/time is specified in the RTC fields, this will
117 	 * hold VRTC_BROKEN_TIME to indicate to the rest of the vRTC logic that
118 	 * further updates will not occur on divider ticks (until the RTC fields
119 	 * are updated to hold a valid date/time).
120 	 */
121 	time_t		base_rtctime;
122 
123 	struct rtcdev	rtcdev;
124 };
125 
126 #define	VRTC_LOCK(vrtc)		mutex_enter(&((vrtc)->lock))
127 #define	VRTC_UNLOCK(vrtc)	mutex_exit(&((vrtc)->lock))
128 #define	VRTC_LOCKED(vrtc)	MUTEX_HELD(&((vrtc)->lock))
129 
130 /*
131  * RTC time is considered "broken" if:
132  * - RTC updates are halted by the guest
133  * - RTC date/time fields have invalid values
134  */
135 #define	VRTC_BROKEN_TIME	((time_t)-1)
136 
137 #define	RTC_IRQ			8
138 
139 #define	RTCSA_DIVIDER_MASK	0x70
140 #define	RTCSA_DIVIDER_32K	0x20
141 #define	RTCSA_PERIOD_MASK	0x0f
142 #define	RTCSB_BIN		0x04
143 #define	RTCSB_INTR_MASK		(RTCSB_UINTR | RTCSB_AINTR | RTCSB_PINTR)
144 #define	RTCSC_MASK	(RTCIR_UPDATE | RTCIR_ALARM | RTCIR_PERIOD | RTCIR_INT)
145 
146 /*
147  * Setting the two high bits in the alarm fields indicates a "don't care"
148  * condition, where that alarm field is to match against any value residing in
149  * its associated time field.
150  */
151 #define	ALARM_DONT_CARE(x)	(((x) & 0xc0) == 0xc0)
152 
153 /* The high bit of the hour field indicates PM when in 12-hour mode */
154 #define	HOUR_IS_PM		0x80
155 
156 #define	SEC_PER_DAY	(24 * 60 * 60)
157 
158 #define	ROUNDDOWN(x, y)	(((x)/(y))*(y))
159 
160 static void vrtc_regc_update(struct vrtc *, uint8_t);
161 static void vrtc_callout_reschedule(struct vrtc *);
162 
163 static __inline bool
rtc_field_datetime(uint8_t off)164 rtc_field_datetime(uint8_t off)
165 {
166 	switch (off) {
167 	case RTC_SEC:
168 	case RTC_MIN:
169 	case RTC_HRS:
170 	case RTC_WDAY:
171 	case RTC_DAY:
172 	case RTC_MONTH:
173 	case RTC_YEAR:
174 	case RTC_CENTURY:
175 		return (true);
176 	default:
177 		return (false);
178 	}
179 }
180 
181 static __inline bool
rtc_field_ondemand(uint8_t off)182 rtc_field_ondemand(uint8_t off)
183 {
184 	switch (off) {
185 	case RTC_STATUSA:
186 	case RTC_STATUSB:
187 	case RTC_INTR:
188 	case RTC_STATUSD:
189 		return (true);
190 	default:
191 		return (rtc_field_datetime(off));
192 	}
193 }
194 
195 static __inline bool
rtc_halted(const struct vrtc * vrtc)196 rtc_halted(const struct vrtc *vrtc)
197 {
198 	return ((vrtc->rtcdev.reg_b & RTCSB_HALT) != 0);
199 }
200 
201 static __inline bool
rega_divider_en(uint8_t rega)202 rega_divider_en(uint8_t rega)
203 {
204 	/*
205 	 * The RTC is counting only when dividers are not held in reset.
206 	 */
207 	return ((rega & RTCSA_DIVIDER_MASK) == RTCSA_DIVIDER_32K);
208 }
209 
210 static __inline hrtime_t
rega_period(uint8_t rega)211 rega_period(uint8_t rega)
212 {
213 	const uint_t sel = rega & RTCSA_PERIOD_MASK;
214 	const hrtime_t rate_period[16] = {
215 		0,
216 		NANOSEC / 256,
217 		NANOSEC / 128,
218 		NANOSEC / 8192,
219 		NANOSEC / 4096,
220 		NANOSEC / 2048,
221 		NANOSEC / 1024,
222 		NANOSEC / 512,
223 		NANOSEC / 256,
224 		NANOSEC / 128,
225 		NANOSEC / 64,
226 		NANOSEC / 32,
227 		NANOSEC / 16,
228 		NANOSEC / 8,
229 		NANOSEC / 4,
230 		NANOSEC / 2,
231 	};
232 
233 	return (rate_period[sel]);
234 }
235 
236 static __inline bool
vrtc_update_enabled(const struct vrtc * vrtc)237 vrtc_update_enabled(const struct vrtc *vrtc)
238 {
239 	/*
240 	 * RTC date/time can be updated only if:
241 	 * - divider is not held in reset
242 	 * - guest has not disabled updates
243 	 * - the date/time fields have valid contents
244 	 */
245 	if (!rega_divider_en(vrtc->rtcdev.reg_a))
246 		return (false);
247 
248 	if (rtc_halted(vrtc))
249 		return (false);
250 
251 	if (vrtc->base_rtctime == VRTC_BROKEN_TIME)
252 		return (false);
253 
254 	return (true);
255 }
256 
257 /*
258  * Calculate the current time held by the RTC.  If the RTC is running (divider
259  * enabled, and updates not halted) then this will account for any time has
260  * passed since the last update.
261  */
262 static time_t
vrtc_curtime(struct vrtc * vrtc,hrtime_t * basep,hrtime_t * phasep)263 vrtc_curtime(struct vrtc *vrtc, hrtime_t *basep, hrtime_t *phasep)
264 {
265 	time_t t = vrtc->base_rtctime;
266 	hrtime_t base = vrtc->base_clock;
267 	hrtime_t phase = 0;
268 
269 	ASSERT(VRTC_LOCKED(vrtc));
270 
271 	if (vrtc_update_enabled(vrtc)) {
272 		const hrtime_t delta = gethrtime() - vrtc->base_clock;
273 		const time_t sec = delta / NANOSEC;
274 
275 		ASSERT3S(delta, >=, 0);
276 
277 		t += sec;
278 		base += sec * NANOSEC;
279 		phase = delta % NANOSEC;
280 	}
281 	if (basep != NULL) {
282 		*basep = base;
283 	}
284 	if (phasep != NULL) {
285 		*phasep = phase;
286 	}
287 	return (t);
288 }
289 
290 /* Encode an RTC CMOS value, converting to BCD if necessary */
291 static __inline uint8_t
rtc_enc(const struct rtcdev * rtc,uint8_t val)292 rtc_enc(const struct rtcdev *rtc, uint8_t val)
293 {
294 	const uint8_t bin2bcd_data[] = {
295 		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
296 		0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
297 		0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
298 		0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
299 		0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
300 		0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
301 		0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
302 		0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
303 		0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
304 		0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99
305 	};
306 
307 	ASSERT3U(val, <, 100);
308 
309 	return ((rtc->reg_b & RTCSB_BIN) ? val : bin2bcd_data[val]);
310 }
311 
312 /*
313  * Write the date/time fields in the CMOS with the date represented by the
314  * internal RTC time (base_rtctime).  If the time is not valid, or updates of
315  * the RTC are disabled via register configuration (without force_update
316  * override), then the CMOS contents will not be changed.
317  */
318 static void
vrtc_time_to_cmos(struct vrtc * vrtc,bool force_update)319 vrtc_time_to_cmos(struct vrtc *vrtc, bool force_update)
320 {
321 	struct rtcdev *rtc = &vrtc->rtcdev;
322 	struct timespec ts = {
323 		.tv_sec = vrtc->base_rtctime,
324 		.tv_nsec = 0,
325 	};
326 
327 	ASSERT(VRTC_LOCKED(vrtc));
328 
329 	if (vrtc->base_rtctime < 0) {
330 		ASSERT3S(vrtc->base_rtctime, ==, VRTC_BROKEN_TIME);
331 		return;
332 	}
333 
334 	/*
335 	 * If the RTC is halted then the guest has "ownership" of the
336 	 * date/time fields. Don't update the RTC date/time fields in
337 	 * this case (unless forced).
338 	 */
339 	if (rtc_halted(vrtc) && !force_update) {
340 		return;
341 	}
342 
343 	struct clocktime ct;
344 	clock_ts_to_ct(&ts, &ct);
345 
346 	/*
347 	 * Check that output from clock_ts_to_ct() matches expectations.
348 	 * Although it closely resembles the requirements for the RTC CMOS
349 	 * fields, there are a few notable parts (day-of-week) which are
350 	 * different, and are thus subsequently adjusted for the CMOS output.
351 	 */
352 	ASSERT(ct.sec >= 0 && ct.sec <= 59);
353 	ASSERT(ct.min >= 0 && ct.min <= 59);
354 	ASSERT(ct.hour >= 0 && ct.hour <= 23);
355 	ASSERT(ct.dow >= 0 && ct.dow <= 6);
356 	ASSERT(ct.day >= 1 && ct.day <= 31);
357 	ASSERT(ct.mon >= 1 && ct.mon <= 12);
358 	ASSERT(ct.year >= POSIX_BASE_YEAR);
359 
360 	rtc->sec = rtc_enc(rtc, ct.sec);
361 	rtc->min = rtc_enc(rtc, ct.min);
362 
363 	int hour;
364 	if (rtc->reg_b & RTCSB_24HR) {
365 		hour = ct.hour;
366 	} else {
367 		/*
368 		 * Convert to the 12-hour format.
369 		 */
370 		switch (ct.hour) {
371 		case 0:			/* 12 AM */
372 		case 12:		/* 12 PM */
373 			hour = 12;
374 			break;
375 		default:
376 			/*
377 			 * The remaining 'ct.hour' values are interpreted as:
378 			 * [1  - 11] ->  1 - 11 AM
379 			 * [13 - 23] ->  1 - 11 PM
380 			 */
381 			hour = ct.hour % 12;
382 			break;
383 		}
384 	}
385 
386 	rtc->hour = rtc_enc(rtc, hour);
387 
388 	if ((rtc->reg_b & RTCSB_24HR) == 0 && ct.hour >= 12) {
389 		/* set MSB to indicate PM */
390 		rtc->hour |= HOUR_IS_PM;
391 	}
392 
393 	rtc->day_of_week = rtc_enc(rtc, ct.dow + 1);
394 	rtc->day_of_month = rtc_enc(rtc, ct.day);
395 	rtc->month = rtc_enc(rtc, ct.mon);
396 	rtc->year = rtc_enc(rtc, ct.year % 100);
397 	rtc->century = rtc_enc(rtc, ct.year / 100);
398 }
399 
400 /* Decode an RTC CMOS value, converting from BCD if necessary */
401 static uint8_t
rtc_dec(const struct rtcdev * rtc,uint8_t val,bool * errp)402 rtc_dec(const struct rtcdev *rtc, uint8_t val, bool *errp)
403 {
404 	if ((rtc->reg_b & RTCSB_BIN) == 0) {
405 		const uint8_t lower = val & 0xf;
406 		const uint8_t upper = val >> 4;
407 
408 		*errp = (lower > 9 || upper > 9);
409 
410 		/*
411 		 * Output will be bogus if value is out of range, so it is on
412 		 * the caller to properly check `errp`.
413 		 */
414 		return ((upper * 10) + lower);
415 	} else {
416 		*errp = false;
417 		return (val);
418 	}
419 }
420 
421 /* Parse hour format from CMOS, accounting for any BCD and 12/24hr encoding */
422 static uint8_t
rtc_parse_hour(const struct rtcdev * rtc,uint8_t hour,bool * errp)423 rtc_parse_hour(const struct rtcdev *rtc, uint8_t hour, bool *errp)
424 {
425 	bool pm = false;
426 
427 	if ((rtc->reg_b & RTCSB_24HR) == 0) {
428 		if ((hour & HOUR_IS_PM) != 0) {
429 			hour &= ~HOUR_IS_PM;
430 			pm = true;
431 		}
432 	}
433 	hour = rtc_dec(rtc, hour, errp);
434 
435 	if ((rtc->reg_b & RTCSB_24HR) == 0) {
436 		if (hour >= 1 && hour <= 12) {
437 			/*
438 			 * Convert from 12-hour format to internal 24-hour
439 			 * representation as follows:
440 			 *
441 			 *    12-hour format		ct.hour
442 			 *	12	AM		0
443 			 *	1 - 11	AM		1 - 11
444 			 *	12	PM		12
445 			 *	1 - 11	PM		13 - 23
446 			 */
447 			if (hour == 12) {
448 				hour = 0;
449 			}
450 			if (pm) {
451 				hour += 12;
452 			}
453 		} else {
454 			/* invalid RTC 12-hour format */
455 			*errp = true;
456 		}
457 	}
458 
459 	if (hour > 23) {
460 		*errp = true;
461 	}
462 
463 	return (hour);
464 }
465 
466 /* Check if alarm fields in CMOS are valid. */
467 static bool
vrtc_alarm_valid(const struct vrtc * vrtc)468 vrtc_alarm_valid(const struct vrtc *vrtc)
469 {
470 	const struct rtcdev *rtc = &vrtc->rtcdev;
471 	bool err;
472 	uint8_t val;
473 
474 	ASSERT(VRTC_LOCKED(vrtc));
475 
476 	/*
477 	 * For seconds, minutes, and hours fields of the alarm configuration,
478 	 * check that they can match against valid times, either by matching any
479 	 * value via the "don't care" mode, or holding a valid time component.
480 	 */
481 
482 	val = rtc->sec;
483 	if (!ALARM_DONT_CARE(val)) {
484 		val = rtc_dec(rtc, val, &err);
485 		if (err || val > 59) {
486 			return (false);
487 		}
488 	}
489 
490 	val = rtc->min;
491 	if (!ALARM_DONT_CARE(val)) {
492 		val = rtc_dec(rtc, val, &err);
493 		if (err || val > 59) {
494 			return (false);
495 		}
496 	}
497 
498 	val = rtc->hour;
499 	if (!ALARM_DONT_CARE(val)) {
500 		(void) rtc_parse_hour(rtc, val, &err);
501 		if (err) {
502 			return (false);
503 		}
504 	}
505 
506 	/*
507 	 * The alarm fields hold a valid time representation, taking into
508 	 * consideration any potential "don't care" directives.
509 	 */
510 	return (true);
511 }
512 
513 /*
514  * Read the date/time fields from the CMOS and attempt to convert it to a valid
515  * UNIX timestamp.  VRTC_BROKEN_TIME will be emitted if those fields represent
516  * an invalid date.
517  *
518  * The day-of-week field is ignored for the purposes of validation since certain
519  * guests do not make use of it.
520  */
521 static time_t
vrtc_cmos_to_secs(struct vrtc * vrtc)522 vrtc_cmos_to_secs(struct vrtc *vrtc)
523 {
524 	struct rtcdev *rtc = &vrtc->rtcdev;
525 	struct clocktime ct = { 0 };
526 	bool err;
527 
528 	ASSERT(VRTC_LOCKED(vrtc));
529 
530 	ct.sec = rtc_dec(rtc, rtc->sec, &err);
531 	if (err || ct.sec > 59) {
532 		/* invalid RTC seconds */
533 		goto fail;
534 	}
535 
536 	ct.min = rtc_dec(rtc, rtc->min, &err);
537 	if (err || ct.min > 59) {
538 		/* invalid RTC minutes */
539 		goto fail;
540 	}
541 
542 	ct.hour = rtc_parse_hour(rtc, rtc->hour, &err);
543 	if (err) {
544 		/* invalid RTC hour */
545 		goto fail;
546 	}
547 
548 	/*
549 	 * Ignore 'rtc->dow' because some guests like Linux don't bother
550 	 * setting it at all while others like OpenBSD/i386 set it incorrectly.
551 	 *
552 	 * clock_ct_to_ts() does not depend on 'ct.dow' anyways so ignore it.
553 	 */
554 	ct.dow = -1;
555 
556 	ct.day = rtc_dec(rtc, rtc->day_of_month, &err);
557 	if (err || ct.day < 1 || ct.day > 31) {
558 		/* invalid RTC day-of-month */
559 		goto fail;
560 	}
561 
562 	ct.mon = rtc_dec(rtc, rtc->month, &err);
563 	if (err || ct.mon < 1 || ct.mon > 12) {
564 		/* invalid RTC month */
565 		goto fail;
566 	}
567 
568 	const uint_t year = rtc_dec(rtc, rtc->year, &err);
569 	if (err || year > 99) {
570 		/* invalid RTC year */
571 		goto fail;
572 	}
573 
574 	const uint_t century = rtc_dec(rtc, rtc->century, &err);
575 	ct.year = century * 100 + year;
576 	if (err || ct.year < POSIX_BASE_YEAR) {
577 		/* invalid RTC century */
578 		goto fail;
579 	}
580 
581 	struct timespec ts;
582 	if (clock_ct_to_ts(&ct, &ts) != 0 || ts.tv_sec < 0) {
583 		/* invalid RTC clocktime */
584 		goto fail;
585 	}
586 	return (ts.tv_sec);		/* success */
587 
588 fail:
589 	/*
590 	 * Stop updating the RTC if the date/time fields programmed by
591 	 * the guest are invalid.
592 	 */
593 	return (VRTC_BROKEN_TIME);
594 }
595 
596 /*
597  * If the periodic timer is enabled, check if enough time has passed for it to
598  * generate an event.
599  */
600 static void
vrtc_periodic_update(struct vrtc * vrtc)601 vrtc_periodic_update(struct vrtc *vrtc)
602 {
603 	struct rtcdev *rtc = &vrtc->rtcdev;
604 
605 	ASSERT(VRTC_LOCKED(vrtc));
606 
607 	/*
608 	 * If the divider is disabled, or periodic interrupts are not
609 	 * configured, then no further work is required.
610 	 */
611 	const hrtime_t period = rega_period(rtc->reg_a);
612 	if (!rega_divider_en(rtc->reg_a) || period == 0) {
613 		return;
614 	}
615 
616 	/*
617 	 * Have we crossed the edge of a period-sized time interval since the
618 	 * last periodic event?
619 	 */
620 	hrtime_t since_last = gethrtime() - vrtc->last_period;
621 	if (since_last > period) {
622 		vrtc_regc_update(vrtc, RTCIR_PERIOD);
623 		vrtc->last_period += ROUNDDOWN(since_last, period);
624 	}
625 }
626 
627 /*
628  * Update the internal contents of the RTC.  This processes any events which may
629  * have been generated by the passage of time (update/periodic/alarm), resulting
630  * in updates to register-C.  As part of that, it updates the internal time
631  * representation of the RTC, but is not required to render those changes (if
632  * any) to the CMOS memory.  A separate call to vrtc_time_to_cmos() is needed if
633  * those fields are about to be accessed.
634  */
635 static void
vrtc_update(struct vrtc * vrtc,uint8_t off)636 vrtc_update(struct vrtc *vrtc, uint8_t off)
637 {
638 	struct rtcdev *rtc = &vrtc->rtcdev;
639 
640 	ASSERT(VRTC_LOCKED(vrtc));
641 
642 	/*
643 	 * If CMOS offset of interest is not one which is updated on-demand,
644 	 * then no update processing is required.
645 	 */
646 	if (!rtc_field_ondemand(off)) {
647 		return;
648 	}
649 
650 	/*
651 	 * If the divider output is disabled, no events will be generated, and
652 	 * the time will not be updated.
653 	 */
654 	if (!rega_divider_en(rtc->reg_a)) {
655 		return;
656 	}
657 
658 	/* Check for any periodic timer events requiring injection. */
659 	vrtc_periodic_update(vrtc);
660 
661 	if (vrtc->base_rtctime == VRTC_BROKEN_TIME) {
662 		/*
663 		 * If the RTC is halted, or the time stored in CMOS is invalid,
664 		 * then neither alarm checks nor updates to the time stored in
665 		 * CMOS are performed.
666 		 */
667 		return;
668 	}
669 
670 	/*
671 	 * Calculate the new time and its corresponding second-granularity clock
672 	 * edge from the divider for base_clock.
673 	 */
674 	hrtime_t base_clock;
675 	const time_t newtime = vrtc_curtime(vrtc, &base_clock, NULL);
676 	if (vrtc->base_rtctime >= newtime) {
677 		/* Nothing more to do if the actual time is unchanged */
678 		return;
679 	}
680 	vrtc->base_clock = base_clock;
681 
682 	if (!vrtc_alarm_valid(vrtc) || (rtc->reg_c & RTCIR_ALARM) != 0) {
683 		/*
684 		 * If no valid alarm is configured, or the alarm event is
685 		 * already pending, there is no need to match the RTC time
686 		 * against it, since any additional assertion will be redundant
687 		 * until the flag is read/cleared.
688 		 */
689 		vrtc->base_rtctime = newtime;
690 	} else if ((newtime - vrtc->base_rtctime) >= SEC_PER_DAY) {
691 		/*
692 		 * If 24 hours (or more) has elapsed since the last update, the
693 		 * configured alarm is certain to fire.  Rather than spending
694 		 * considerable effort in the full matching logic in order to
695 		 * determine this certainty, just apply it now as a shortcut.
696 		 */
697 		vrtc_regc_update(vrtc, RTCIR_ALARM);
698 		vrtc->base_rtctime = newtime;
699 	} else {
700 		/*
701 		 * Check if any of the times (down to the second) between the
702 		 * old time and the new match against a configured alarm
703 		 * condition.
704 		 *
705 		 * This is not insignificant effort and could stand to be
706 		 * optimized at some point in the future.
707 		 */
708 		const uint8_t a_sec = rtc->alarm_sec;
709 		const uint8_t a_min = rtc->alarm_min;
710 		const uint8_t a_hour = rtc->alarm_hour;
711 		do {
712 			vrtc->base_rtctime++;
713 			vrtc_time_to_cmos(vrtc, false);
714 
715 			if ((ALARM_DONT_CARE(a_sec) || a_sec == rtc->sec) &&
716 			    (ALARM_DONT_CARE(a_min) || a_min == rtc->min) &&
717 			    (ALARM_DONT_CARE(a_hour) || a_hour == rtc->hour)) {
718 				vrtc_regc_update(vrtc, RTCIR_ALARM);
719 				/*
720 				 * Once the alarm triggers during this check, we
721 				 * can skip to the end, since subsequent firings
722 				 * would be redundant until the guest can
723 				 * read/clear the event in register-C.
724 				 */
725 				vrtc->base_rtctime = newtime;
726 			}
727 		} while (vrtc->base_rtctime != newtime);
728 	}
729 
730 	/* Reflect that the time underwent an update */
731 	vrtc_regc_update(vrtc, RTCIR_UPDATE);
732 }
733 
734 static void
vrtc_callout_handler(void * arg)735 vrtc_callout_handler(void *arg)
736 {
737 	struct vrtc *vrtc = arg;
738 
739 	VRTC_LOCK(vrtc);
740 	if (callout_pending(&vrtc->callout)) {
741 		/* callout was reset */
742 	} else if (!callout_active(&vrtc->callout)) {
743 		/* callout was stopped */
744 	} else {
745 		callout_deactivate(&vrtc->callout);
746 
747 		/* Perform the actual update and reschedule (if needed) */
748 		vrtc_update(vrtc, RTC_INTR);
749 		vrtc_callout_reschedule(vrtc);
750 	}
751 	VRTC_UNLOCK(vrtc);
752 }
753 
754 static void
vrtc_callout_reschedule(struct vrtc * vrtc)755 vrtc_callout_reschedule(struct vrtc *vrtc)
756 {
757 	struct rtcdev *rtc = &vrtc->rtcdev;
758 
759 	ASSERT(VRTC_LOCKED(vrtc));
760 
761 	hrtime_t period = 0;
762 	if ((rtc->reg_b & RTCSB_PINTR) != 0) {
763 		/*
764 		 * Calculate the next event edge using the periodic timer, since
765 		 * it will be more granular (2Hz or faster) than the 1Hz used by
766 		 * the alarm and update interrupts, and still in phase.
767 		 */
768 		period = rega_period(rtc->reg_a);
769 	}
770 	if (period == 0 && vrtc_update_enabled(vrtc)) {
771 		/*
772 		 * If RTC updates are enabled, there is potential for update or
773 		 * alarm interrupts on 1Hz intervals.
774 		 */
775 		period = NANOSEC;
776 	}
777 
778 	/*
779 	 * RTC callouts are only required if interrupts are enabled, since all
780 	 * other side effects of time moving forward (such as setting of the
781 	 * event bits in register-C) can be conjured on-demand when those fields
782 	 * are read by the guest.  The same is true when an interrupt has been
783 	 * asserted and not yet handled.
784 	 */
785 	const bool intr_enabled = (rtc->reg_b & RTCSB_INTR_MASK) != 0;
786 	const bool intr_asserted = (rtc->reg_c & RTCIR_INT) != 0;
787 	if (period != 0 && intr_enabled && !intr_asserted) {
788 		/*
789 		 * Find the next edge of the specified period interval,
790 		 * referenced against the phase of base_clock.
791 		 */
792 		const hrtime_t delta = gethrtime() + period - vrtc->base_clock;
793 		const hrtime_t next =
794 		    ROUNDDOWN(delta, period) + vrtc->base_clock;
795 
796 		callout_reset_hrtime(&vrtc->callout, next, vrtc_callout_handler,
797 		    vrtc, C_ABSOLUTE);
798 	} else {
799 		if (callout_active(&vrtc->callout)) {
800 			callout_stop(&vrtc->callout);
801 		}
802 	}
803 }
804 
805 /*
806  * We can take some shortcuts in the register-B/register-C math since the
807  * interrupt-enable bits match their corresponding interrupt-present bits.
808  */
809 CTASSERT(RTCIR_UPDATE == RTCSB_UINTR);
810 CTASSERT(RTCIR_ALARM == RTCSB_AINTR);
811 CTASSERT(RTCIR_PERIOD == RTCSB_PINTR);
812 
813 /*
814  * Update the contents of register-C either due to newly asserted events, or
815  * altered interrupt-enable flags.
816  */
817 static void
vrtc_regc_update(struct vrtc * vrtc,uint8_t events)818 vrtc_regc_update(struct vrtc *vrtc, uint8_t events)
819 {
820 	struct rtcdev *rtc = &vrtc->rtcdev;
821 
822 	ASSERT(VRTC_LOCKED(vrtc));
823 	ASSERT0(events & ~(RTCSB_INTR_MASK));
824 
825 	/*
826 	 * Regardless of which interrupt enable flags are set in register-B, the
827 	 * corresponding event flags are always set in register-C.
828 	 */
829 	rtc->reg_c |= events;
830 
831 	const bool oldirq = (rtc->reg_c & RTCIR_INT) != 0;
832 	if ((rtc->reg_b & RTCSB_INTR_MASK & rtc->reg_c) != 0) {
833 		rtc->reg_c |= RTCIR_INT;
834 	}
835 	const bool newirq = (rtc->reg_c & RTCIR_INT) != 0;
836 
837 	/*
838 	 * Although this should probably be asserting level-triggered interrupt,
839 	 * the original logic from bhyve is event-triggered.  This may warrant
840 	 * additional consideration at some point.
841 	 */
842 	if (!oldirq && newirq) {
843 		/* IRQ asserted */
844 		(void) vatpic_pulse_irq(vrtc->vm, RTC_IRQ);
845 		(void) vioapic_pulse_irq(vrtc->vm, RTC_IRQ);
846 	} else if (oldirq && !newirq) {
847 		/* IRQ de-asserted */
848 	}
849 }
850 
851 /*
852  * Emulate a read of register-C, emitting the contained value and clearing its
853  * contents for subsequent actions.
854  */
855 static uint8_t
vrtc_regc_read(struct vrtc * vrtc)856 vrtc_regc_read(struct vrtc *vrtc)
857 {
858 	struct rtcdev *rtc = &vrtc->rtcdev;
859 
860 	ASSERT(VRTC_LOCKED(vrtc));
861 
862 	/* Clear the IRQ flag, and any asserted events */
863 	const uint8_t val = rtc->reg_c;
864 	rtc->reg_c = 0;
865 
866 	/*
867 	 * Since callout scheduling is suppressed when the IRQ flag is asserted,
868 	 * it may need to be re-scheduled when the flag is read/cleared.
869 	 */
870 	if ((val & RTCIR_INT) != 0) {
871 		vrtc_callout_reschedule(vrtc);
872 	}
873 
874 	return (val);
875 }
876 
877 static void
vrtc_regb_write(struct vrtc * vrtc,uint8_t newval)878 vrtc_regb_write(struct vrtc *vrtc, uint8_t newval)
879 {
880 	struct rtcdev *rtc = &vrtc->rtcdev;
881 
882 	ASSERT(VRTC_LOCKED(vrtc));
883 
884 	uint8_t changed = rtc->reg_b ^ newval;
885 	rtc->reg_b = newval;
886 
887 	if (changed & RTCSB_HALT) {
888 		if ((newval & RTCSB_HALT) == 0) {
889 			/*
890 			 * RTC is coming out of a halted state.
891 			 *
892 			 * Push the base time (the clock from the divider)
893 			 * forward to the nearest second boundary so it may
894 			 * resume updates from the value set in the CMOS.
895 			 */
896 			vrtc->base_rtctime = vrtc_cmos_to_secs(vrtc);
897 
898 			/*
899 			 * Account for any time which has passed if the divider
900 			 * was left running while the RTC was in the halted
901 			 * state.  Any whole seconds which elapsed while the
902 			 * device was in such a state must be discarded.
903 			 *
904 			 * If this was not done, the RTC would play "catch-up"
905 			 * since the last update as recorded in `base_clock`.
906 			 * The phase of that clock is preserved, even if the
907 			 * time itself is discarded.
908 			 */
909 			if (rega_divider_en(vrtc->rtcdev.reg_a)) {
910 				const hrtime_t delta =
911 				    gethrtime() - vrtc->base_clock;
912 
913 				if (delta > NANOSEC) {
914 					vrtc->base_clock += delta / NANOSEC;
915 				}
916 			} else {
917 				/*
918 				 * If the divider is not running, then all of
919 				 * this will be taken care of if/when it is
920 				 * re-enabled by the guest.
921 				 */
922 			}
923 		} else {
924 			/*
925 			 * Force a refresh of the RTC date/time fields so
926 			 * they reflect the time right before the guest set
927 			 * the HALT bit.
928 			 */
929 			vrtc_update(vrtc, RTC_STATUSB);
930 			vrtc_time_to_cmos(vrtc, true);
931 
932 			/*
933 			 * Updates are halted so mark 'base_rtctime' to denote
934 			 * that the RTC date/time is in flux.
935 			 *
936 			 * Since the HALT/RUN flag does not effect the actual
937 			 * phase of the clock emitted from the emulated divider,
938 			 * the base time will remain unchanged
939 			 */
940 			vrtc->base_rtctime = VRTC_BROKEN_TIME;
941 
942 			/*
943 			 * Per the specification, the UINTR bit must be cleared
944 			 * if the HALT bit is set.
945 			 */
946 			if ((rtc->reg_b & RTCSB_UINTR) != 0) {
947 				rtc->reg_b &= ~RTCSB_UINTR;
948 				changed |= RTCSB_UINTR;
949 			}
950 		}
951 	}
952 
953 	/* Side effect of changes to the interrupt enable bits.  */
954 	if (changed & RTCSB_INTR_MASK) {
955 		vrtc_regc_update(vrtc, 0);
956 	}
957 
958 	vrtc_callout_reschedule(vrtc);
959 
960 	/*
961 	 * The side effect of bits that control the RTC date/time format
962 	 * is handled lazily when those fields are actually read.
963 	 */
964 }
965 
966 static void
vrtc_rega_write(struct vrtc * vrtc,uint8_t newval)967 vrtc_rega_write(struct vrtc *vrtc, uint8_t newval)
968 {
969 	ASSERT(VRTC_LOCKED(vrtc));
970 
971 	const hrtime_t now = gethrtime();
972 	const uint8_t oldval = vrtc->rtcdev.reg_a;
973 	bool divider_restarted = false;
974 
975 	if (rega_divider_en(oldval) && !rega_divider_en(newval)) {
976 		/* RTC divider held in reset */
977 	} else if (!rega_divider_en(oldval) && rega_divider_en(newval)) {
978 		/*
979 		 * Divider is coming out of reset.  Updates of the reported time
980 		 * (if enabled) are expected to begin 500ms from now.
981 		 */
982 		vrtc->base_rtctime = vrtc_cmos_to_secs(vrtc);
983 		vrtc->base_clock = now - (NANOSEC / 2);
984 		divider_restarted = true;
985 	}
986 
987 	/*
988 	 * If the frequency of the periodic timer was altered, or the divider
989 	 * itself was just brought out of reset, we must re-calculate
990 	 * 'last_period' in order to determine the next edge when the periodic
991 	 * timer would fire.
992 	 */
993 	const hrtime_t period_old = rega_period(oldval);
994 	const hrtime_t period_new = rega_period(newval);
995 	if (period_old != period_new || divider_restarted) {
996 		if (period_new != 0) {
997 			/*
998 			 * Since the periodic timer is derived from additional
999 			 * division applied to the output of the main divider,
1000 			 * we determine the last edge based on the most recent
1001 			 * time update.
1002 			 */
1003 			const hrtime_t since_last = now - vrtc->base_clock;
1004 			vrtc->last_period = vrtc->base_clock;
1005 			vrtc->last_period += ROUNDDOWN(since_last, period_new);
1006 		} else {
1007 			/*
1008 			 * The timing of the edge does not matter if the
1009 			 * periodic timer is disabled
1010 			 */
1011 			vrtc->last_period = now;
1012 		}
1013 	}
1014 
1015 	/*
1016 	 * We never present the time-update bit as a device, nor is the consumer
1017 	 * allowed to set it during a write.
1018 	 */
1019 	vrtc->rtcdev.reg_a = newval & ~RTCSA_TUP;
1020 
1021 	vrtc_callout_reschedule(vrtc);
1022 }
1023 
1024 int
vrtc_set_time(struct vm * vm,const timespec_t * ts)1025 vrtc_set_time(struct vm *vm, const timespec_t *ts)
1026 {
1027 	struct vrtc *vrtc = vm_rtc(vm);
1028 
1029 	if (ts->tv_sec < 0 || ts->tv_nsec >= NANOSEC) {
1030 		/*
1031 		 * Times before the 1970 epoch, or with nonsensical nanosecond
1032 		 * counts are not supported
1033 		 */
1034 		return (EINVAL);
1035 	}
1036 
1037 	VRTC_LOCK(vrtc);
1038 	vrtc->base_rtctime = ts->tv_sec;
1039 	vrtc->base_clock = gethrtime() - ts->tv_nsec;
1040 	vrtc->last_period = vrtc->base_clock;
1041 	if (!vm_is_paused(vrtc->vm)) {
1042 		vrtc_callout_reschedule(vrtc);
1043 	}
1044 	VRTC_UNLOCK(vrtc);
1045 
1046 	return (0);
1047 }
1048 
1049 void
vrtc_get_time(struct vm * vm,timespec_t * ts)1050 vrtc_get_time(struct vm *vm, timespec_t *ts)
1051 {
1052 	struct vrtc *vrtc = vm_rtc(vm);
1053 	hrtime_t phase;
1054 
1055 	VRTC_LOCK(vrtc);
1056 	ts->tv_sec = vrtc_curtime(vrtc, NULL, &phase);
1057 	ts->tv_nsec = phase;
1058 	VRTC_UNLOCK(vrtc);
1059 }
1060 
1061 int
vrtc_nvram_write(struct vm * vm,int offset,uint8_t value)1062 vrtc_nvram_write(struct vm *vm, int offset, uint8_t value)
1063 {
1064 	struct vrtc *vrtc = vm_rtc(vm);
1065 	uint8_t *rtc_raw = (uint8_t *)&vrtc->rtcdev;
1066 
1067 	/* Write offset must be valid */
1068 	if (offset < 0 || offset >= sizeof (struct rtcdev)) {
1069 		return (EINVAL);
1070 	}
1071 
1072 	/* Disallow writes to RTC control registers or the date/time fields */
1073 	if (rtc_field_ondemand(offset)) {
1074 		return (EINVAL);
1075 	}
1076 
1077 	VRTC_LOCK(vrtc);
1078 	rtc_raw[offset] = value;
1079 	VRTC_UNLOCK(vrtc);
1080 
1081 	return (0);
1082 }
1083 
1084 int
vrtc_nvram_read(struct vm * vm,int offset,uint8_t * retval)1085 vrtc_nvram_read(struct vm *vm, int offset, uint8_t *retval)
1086 {
1087 	struct vrtc *vrtc = vm_rtc(vm);
1088 	const uint8_t *rtc_raw = (uint8_t *)&vrtc->rtcdev;
1089 
1090 	/* Read offset must be valid */
1091 	if (offset < 0 || offset >= sizeof (struct rtcdev)) {
1092 		return (EINVAL);
1093 	}
1094 
1095 	VRTC_LOCK(vrtc);
1096 
1097 	vrtc_update(vrtc, offset);
1098 	/* Render out the updated date/time if it is being accessed */
1099 	if (rtc_field_datetime(offset)) {
1100 		vrtc_time_to_cmos(vrtc, false);
1101 	}
1102 	*retval = rtc_raw[offset];
1103 
1104 	VRTC_UNLOCK(vrtc);
1105 
1106 	return (0);
1107 }
1108 
1109 int
vrtc_addr_handler(void * arg,bool in,uint16_t port,uint8_t bytes,uint32_t * val)1110 vrtc_addr_handler(void *arg, bool in, uint16_t port, uint8_t bytes,
1111     uint32_t *val)
1112 {
1113 	struct vrtc *vrtc = arg;
1114 
1115 	if (bytes != 1) {
1116 		return (-1);
1117 	}
1118 
1119 	if (in) {
1120 		*val = 0xff;
1121 		return (0);
1122 	}
1123 
1124 	VRTC_LOCK(vrtc);
1125 	vrtc->addr = *val & 0x7f;
1126 	VRTC_UNLOCK(vrtc);
1127 
1128 	return (0);
1129 }
1130 
1131 static uint8_t
vrtc_read(struct vrtc * vrtc,uint8_t offset)1132 vrtc_read(struct vrtc *vrtc, uint8_t offset)
1133 {
1134 	const uint8_t *rtc_raw = (uint8_t *)&vrtc->rtcdev;
1135 
1136 	ASSERT(VRTC_LOCKED(vrtc));
1137 	ASSERT(offset < sizeof (struct rtcdev));
1138 
1139 	switch (offset) {
1140 	case RTC_INTR:
1141 		return (vrtc_regc_read(vrtc));
1142 	default:
1143 		/*
1144 		 * Everything else can be read from the updated-on-demand data
1145 		 * stored in the emulated CMOS space.
1146 		 */
1147 		return (rtc_raw[offset]);
1148 	}
1149 }
1150 
1151 static int
vrtc_write(struct vrtc * vrtc,uint8_t offset,uint8_t val)1152 vrtc_write(struct vrtc *vrtc, uint8_t offset, uint8_t val)
1153 {
1154 	uint8_t *rtc_raw = (uint8_t *)&vrtc->rtcdev;
1155 
1156 	ASSERT(VRTC_LOCKED(vrtc));
1157 	if (offset >= sizeof (struct rtcdev))
1158 		return (-1);
1159 
1160 	switch (offset) {
1161 	case RTC_STATUSA:
1162 		vrtc_rega_write(vrtc, val);
1163 		break;
1164 	case RTC_STATUSB:
1165 		vrtc_regb_write(vrtc, val);
1166 		break;
1167 	case RTC_INTR:
1168 		/* Ignored write to register-C */
1169 		break;
1170 	case RTC_STATUSD:
1171 		/* Ignored write to register-D */
1172 		break;
1173 	case RTC_SEC:
1174 		/* High order bit of 'seconds' is read-only.  */
1175 		rtc_raw[offset] = val & 0x7f;
1176 		break;
1177 	default:
1178 		rtc_raw[offset] = val;
1179 		break;
1180 	}
1181 
1182 	/*
1183 	 * Some guests may write to date/time fields (such as OpenBSD writing
1184 	 * the century byte) without first pausing updates with RTCSB_HALT.
1185 	 *
1186 	 * Keep our internal representation of the time updated should such
1187 	 * writes occur.
1188 	 */
1189 	if (rtc_field_datetime(offset) && !rtc_halted(vrtc)) {
1190 		vrtc->base_rtctime = vrtc_cmos_to_secs(vrtc);
1191 	}
1192 	return (0);
1193 }
1194 
1195 int
vrtc_data_handler(void * arg,bool in,uint16_t port,uint8_t bytes,uint32_t * val)1196 vrtc_data_handler(void *arg, bool in, uint16_t port, uint8_t bytes,
1197     uint32_t *val)
1198 {
1199 	struct vrtc *vrtc = arg;
1200 	int ret = -1;
1201 
1202 	if (bytes != 1) {
1203 		return (ret);
1204 	}
1205 
1206 	VRTC_LOCK(vrtc);
1207 	const uint8_t offset = vrtc->addr;
1208 	if (offset < sizeof (struct rtcdev)) {
1209 		ret = 0;
1210 
1211 		/* Ensure internal state of RTC is updated */
1212 		vrtc_update(vrtc, offset);
1213 
1214 		/*
1215 		 * Update RTC date/time CMOS fields, if necessary.
1216 		 *
1217 		 * While the necessity for reads is obvious, the need for it
1218 		 * during writes is slightly more subtle: A write to one of the
1219 		 * date/time fields will requiring (re)parsing them all in
1220 		 * order to determine the new working date/time for the RTC.
1221 		 */
1222 		if (rtc_field_datetime(offset)) {
1223 			vrtc_time_to_cmos(vrtc, false);
1224 		}
1225 
1226 		if (in) {
1227 			*val = vrtc_read(vrtc, offset);
1228 		} else {
1229 			ret = vrtc_write(vrtc, offset, *val);
1230 		}
1231 	}
1232 	VRTC_UNLOCK(vrtc);
1233 	return (ret);
1234 }
1235 
1236 void
vrtc_reset(struct vrtc * vrtc)1237 vrtc_reset(struct vrtc *vrtc)
1238 {
1239 	struct rtcdev *rtc = &vrtc->rtcdev;
1240 
1241 	VRTC_LOCK(vrtc);
1242 
1243 	vrtc_regb_write(vrtc, rtc->reg_b & ~(RTCSB_INTR_MASK | RTCSB_SQWE));
1244 	rtc->reg_c = 0;
1245 	ASSERT(!callout_active(&vrtc->callout));
1246 
1247 	VRTC_UNLOCK(vrtc);
1248 }
1249 
1250 struct vrtc *
vrtc_init(struct vm * vm)1251 vrtc_init(struct vm *vm)
1252 {
1253 	struct vrtc *vrtc;
1254 	struct rtcdev *rtc;
1255 
1256 	vrtc = kmem_zalloc(sizeof (struct vrtc), KM_SLEEP);
1257 	vrtc->vm = vm;
1258 	mutex_init(&vrtc->lock, NULL, MUTEX_ADAPTIVE, NULL);
1259 	callout_init(&vrtc->callout, 1);
1260 
1261 	/* Allow dividers to keep time but disable everything else */
1262 	rtc = &vrtc->rtcdev;
1263 	rtc->reg_a = RTCSA_DIVIDER_32K;
1264 	rtc->reg_b = RTCSB_24HR;
1265 	rtc->reg_c = 0;
1266 	rtc->reg_d = RTCSD_PWR;
1267 
1268 	/* Reset the index register to a safe value. */
1269 	vrtc->addr = RTC_STATUSD;
1270 
1271 	VRTC_LOCK(vrtc);
1272 	/* Initialize RTC time to 00:00:00 1 January, 1970.  */
1273 	vrtc->base_rtctime = 0;
1274 	vrtc->base_clock = gethrtime();
1275 	vrtc->last_period = vrtc->base_clock;
1276 	vrtc_time_to_cmos(vrtc, false);
1277 	VRTC_UNLOCK(vrtc);
1278 
1279 	return (vrtc);
1280 }
1281 
1282 void
vrtc_cleanup(struct vrtc * vrtc)1283 vrtc_cleanup(struct vrtc *vrtc)
1284 {
1285 	callout_drain(&vrtc->callout);
1286 	mutex_destroy(&vrtc->lock);
1287 	kmem_free(vrtc, sizeof (*vrtc));
1288 }
1289 
1290 void
vrtc_localize_resources(struct vrtc * vrtc)1291 vrtc_localize_resources(struct vrtc *vrtc)
1292 {
1293 	vmm_glue_callout_localize(&vrtc->callout);
1294 }
1295 
1296 void
vrtc_pause(struct vrtc * vrtc)1297 vrtc_pause(struct vrtc *vrtc)
1298 {
1299 	VRTC_LOCK(vrtc);
1300 	callout_stop(&vrtc->callout);
1301 	VRTC_UNLOCK(vrtc);
1302 }
1303 
1304 void
vrtc_resume(struct vrtc * vrtc)1305 vrtc_resume(struct vrtc *vrtc)
1306 {
1307 	VRTC_LOCK(vrtc);
1308 	ASSERT(!callout_active(&vrtc->callout));
1309 	vrtc_callout_reschedule(vrtc);
1310 	VRTC_UNLOCK(vrtc);
1311 }
1312 
1313 static int
vrtc_data_read(void * datap,const vmm_data_req_t * req)1314 vrtc_data_read(void *datap, const vmm_data_req_t *req)
1315 {
1316 	VERIFY3U(req->vdr_class, ==, VDC_RTC);
1317 	VERIFY3U(req->vdr_version, ==, 2);
1318 	VERIFY3U(req->vdr_len, >=, sizeof (struct vdi_rtc_v2));
1319 
1320 	struct vrtc *vrtc = datap;
1321 	struct vdi_rtc_v2 *out = req->vdr_data;
1322 
1323 	VRTC_LOCK(vrtc);
1324 
1325 	out->vr_addr = vrtc->addr;
1326 	out->vr_base_clock = vm_normalize_hrtime(vrtc->vm, vrtc->base_clock);
1327 	out->vr_last_period = vm_normalize_hrtime(vrtc->vm, vrtc->last_period);
1328 	bcopy(&vrtc->rtcdev, out->vr_content, sizeof (out->vr_content));
1329 
1330 	VRTC_UNLOCK(vrtc);
1331 
1332 	return (0);
1333 }
1334 
1335 static int
vrtc_data_write(void * datap,const vmm_data_req_t * req)1336 vrtc_data_write(void *datap, const vmm_data_req_t *req)
1337 {
1338 	VERIFY3U(req->vdr_class, ==, VDC_RTC);
1339 	VERIFY3U(req->vdr_version, ==, 2);
1340 	VERIFY3U(req->vdr_len, >=, sizeof (struct vdi_rtc_v2));
1341 
1342 	struct vrtc *vrtc = datap;
1343 	const struct vdi_rtc_v2 *src = req->vdr_data;
1344 
1345 	const hrtime_t base_clock =
1346 	    vm_denormalize_hrtime(vrtc->vm, src->vr_base_clock);
1347 	const hrtime_t last_period =
1348 	    vm_denormalize_hrtime(vrtc->vm, src->vr_last_period);
1349 
1350 	const hrtime_t now = gethrtime();
1351 	if (base_clock > now || last_period > now) {
1352 		/*
1353 		 * Neither the base clock nor the last periodic event edge
1354 		 * should be in the future, since they should trail (or at most
1355 		 * equal) the current time.
1356 		 */
1357 		return (EINVAL);
1358 	}
1359 
1360 	/*
1361 	 * The phase of last_period could be checked against that of base_clock,
1362 	 * but for now, any shenanigans there will go unhandled.
1363 	 */
1364 
1365 	VRTC_LOCK(vrtc);
1366 
1367 	vrtc->base_clock = base_clock;
1368 	bcopy(src->vr_content, &vrtc->rtcdev, sizeof (vrtc->rtcdev));
1369 	vrtc->addr = src->vr_addr;
1370 
1371 	vrtc->rtcdev.reg_a &= ~RTCSA_TUP;
1372 	/* register B needs requires no masking */
1373 	vrtc->rtcdev.reg_c &= RTCSC_MASK;
1374 	vrtc->rtcdev.reg_d = RTCSD_PWR;
1375 
1376 	/* Set internal time based on what is stored in CMOS */
1377 	vrtc->base_rtctime = vrtc_cmos_to_secs(vrtc);
1378 	/* Using the specified divider edge timing */
1379 	vrtc->base_clock = base_clock;
1380 	vrtc->last_period = last_period;
1381 
1382 	if (!vm_is_paused(vrtc->vm)) {
1383 		vrtc_callout_reschedule(vrtc);
1384 	}
1385 
1386 	VRTC_UNLOCK(vrtc);
1387 	return (0);
1388 }
1389 
1390 static const vmm_data_version_entry_t rtc_v2 = {
1391 	.vdve_class = VDC_RTC,
1392 	.vdve_version = 2,
1393 	.vdve_len_expect = sizeof (struct vdi_rtc_v2),
1394 	.vdve_readf = vrtc_data_read,
1395 	.vdve_writef = vrtc_data_write,
1396 };
1397 VMM_DATA_VERSION(rtc_v2);
1398