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