vrtc.c revision 284899
1/*-
2 * Copyright (c) 2014, Neel Natu (neel@freebsd.org)
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice unmodified, this list of conditions, and the following
10 *    disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: stable/10/sys/amd64/vmm/io/vrtc.c 284899 2015-06-28 01:21:55Z neel $");
29
30#include <sys/param.h>
31#include <sys/systm.h>
32#include <sys/queue.h>
33#include <sys/cpuset.h>
34#include <sys/kernel.h>
35#include <sys/malloc.h>
36#include <sys/lock.h>
37#include <sys/mutex.h>
38#include <sys/clock.h>
39#include <sys/sysctl.h>
40
41#include <machine/vmm.h>
42
43#include <isa/rtc.h>
44
45#include "vmm_ktr.h"
46#include "vatpic.h"
47#include "vioapic.h"
48#include "vrtc.h"
49
50/* Register layout of the RTC */
51struct rtcdev {
52	uint8_t	sec;
53	uint8_t	alarm_sec;
54	uint8_t	min;
55	uint8_t	alarm_min;
56	uint8_t	hour;
57	uint8_t	alarm_hour;
58	uint8_t	day_of_week;
59	uint8_t	day_of_month;
60	uint8_t	month;
61	uint8_t	year;
62	uint8_t	reg_a;
63	uint8_t	reg_b;
64	uint8_t	reg_c;
65	uint8_t	reg_d;
66	uint8_t	nvram[36];
67	uint8_t	century;
68	uint8_t	nvram2[128 - 51];
69} __packed;
70CTASSERT(sizeof(struct rtcdev) == 128);
71CTASSERT(offsetof(struct rtcdev, century) == RTC_CENTURY);
72
73struct vrtc {
74	struct vm	*vm;
75	struct mtx	mtx;
76	struct callout	callout;
77	u_int		addr;		/* RTC register to read or write */
78	sbintime_t	base_uptime;
79	time_t		base_rtctime;
80	struct rtcdev	rtcdev;
81};
82
83#define	VRTC_LOCK(vrtc)		mtx_lock(&((vrtc)->mtx))
84#define	VRTC_UNLOCK(vrtc)	mtx_unlock(&((vrtc)->mtx))
85#define	VRTC_LOCKED(vrtc)	mtx_owned(&((vrtc)->mtx))
86
87/*
88 * RTC time is considered "broken" if:
89 * - RTC updates are halted by the guest
90 * - RTC date/time fields have invalid values
91 */
92#define	VRTC_BROKEN_TIME	((time_t)-1)
93
94#define	RTC_IRQ			8
95#define	RTCSB_BIN		0x04
96#define	RTCSB_ALL_INTRS		(RTCSB_UINTR | RTCSB_AINTR | RTCSB_PINTR)
97#define	rtc_halted(vrtc)	((vrtc->rtcdev.reg_b & RTCSB_HALT) != 0)
98#define	aintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_AINTR) != 0)
99#define	pintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_PINTR) != 0)
100#define	uintr_enabled(vrtc)	(((vrtc)->rtcdev.reg_b & RTCSB_UINTR) != 0)
101
102static void vrtc_callout_handler(void *arg);
103static void vrtc_set_reg_c(struct vrtc *vrtc, uint8_t newval);
104
105static MALLOC_DEFINE(M_VRTC, "vrtc", "bhyve virtual rtc");
106
107SYSCTL_DECL(_hw_vmm);
108SYSCTL_NODE(_hw_vmm, OID_AUTO, vrtc, CTLFLAG_RW, NULL, NULL);
109
110static int rtc_flag_broken_time = 1;
111SYSCTL_INT(_hw_vmm_vrtc, OID_AUTO, flag_broken_time, CTLFLAG_RDTUN,
112    &rtc_flag_broken_time, 0, "Stop guest when invalid RTC time is detected");
113
114static __inline bool
115divider_enabled(int reg_a)
116{
117	/*
118	 * The RTC is counting only when dividers are not held in reset.
119	 */
120	return ((reg_a & 0x70) == 0x20);
121}
122
123static __inline bool
124update_enabled(struct vrtc *vrtc)
125{
126	/*
127	 * RTC date/time can be updated only if:
128	 * - divider is not held in reset
129	 * - guest has not disabled updates
130	 * - the date/time fields have valid contents
131	 */
132	if (!divider_enabled(vrtc->rtcdev.reg_a))
133		return (false);
134
135	if (rtc_halted(vrtc))
136		return (false);
137
138	if (vrtc->base_rtctime == VRTC_BROKEN_TIME)
139		return (false);
140
141	return (true);
142}
143
144static time_t
145vrtc_curtime(struct vrtc *vrtc)
146{
147	sbintime_t now, delta;
148	time_t t;
149
150	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
151
152	t = vrtc->base_rtctime;
153	if (update_enabled(vrtc)) {
154		now = sbinuptime();
155		delta = now - vrtc->base_uptime;
156		KASSERT(delta >= 0, ("vrtc_curtime: uptime went backwards: "
157		    "%#lx to %#lx", vrtc->base_uptime, now));
158		t += delta / SBT_1S;
159	}
160	return (t);
161}
162
163static __inline uint8_t
164rtcset(struct rtcdev *rtc, int val)
165{
166
167	KASSERT(val >= 0 && val < 100, ("%s: invalid bin2bcd index %d",
168	    __func__, val));
169
170	return ((rtc->reg_b & RTCSB_BIN) ? val : bin2bcd_data[val]);
171}
172
173static void
174secs_to_rtc(time_t rtctime, struct vrtc *vrtc, int force_update)
175{
176	struct clocktime ct;
177	struct timespec ts;
178	struct rtcdev *rtc;
179	int hour;
180
181	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
182
183	if (rtctime < 0) {
184		KASSERT(rtctime == VRTC_BROKEN_TIME,
185		    ("%s: invalid vrtc time %#lx", __func__, rtctime));
186		return;
187	}
188
189	/*
190	 * If the RTC is halted then the guest has "ownership" of the
191	 * date/time fields. Don't update the RTC date/time fields in
192	 * this case (unless forced).
193	 */
194	if (rtc_halted(vrtc) && !force_update)
195		return;
196
197	ts.tv_sec = rtctime;
198	ts.tv_nsec = 0;
199	clock_ts_to_ct(&ts, &ct);
200
201	KASSERT(ct.sec >= 0 && ct.sec <= 59, ("invalid clocktime sec %d",
202	    ct.sec));
203	KASSERT(ct.min >= 0 && ct.min <= 59, ("invalid clocktime min %d",
204	    ct.min));
205	KASSERT(ct.hour >= 0 && ct.hour <= 23, ("invalid clocktime hour %d",
206	    ct.hour));
207	KASSERT(ct.dow >= 0 && ct.dow <= 6, ("invalid clocktime wday %d",
208	    ct.dow));
209	KASSERT(ct.day >= 1 && ct.day <= 31, ("invalid clocktime mday %d",
210	    ct.day));
211	KASSERT(ct.mon >= 1 && ct.mon <= 12, ("invalid clocktime month %d",
212	    ct.mon));
213	KASSERT(ct.year >= POSIX_BASE_YEAR, ("invalid clocktime year %d",
214	    ct.year));
215
216	rtc = &vrtc->rtcdev;
217	rtc->sec = rtcset(rtc, ct.sec);
218	rtc->min = rtcset(rtc, ct.min);
219
220	if (rtc->reg_b & RTCSB_24HR) {
221		hour = ct.hour;
222	} else {
223		/*
224		 * Convert to the 12-hour format.
225		 */
226		switch (ct.hour) {
227		case 0:			/* 12 AM */
228		case 12:		/* 12 PM */
229			hour = 12;
230			break;
231		default:
232			/*
233			 * The remaining 'ct.hour' values are interpreted as:
234			 * [1  - 11] ->  1 - 11 AM
235			 * [13 - 23] ->  1 - 11 PM
236			 */
237			hour = ct.hour % 12;
238			break;
239		}
240	}
241
242	rtc->hour = rtcset(rtc, hour);
243
244	if ((rtc->reg_b & RTCSB_24HR) == 0 && ct.hour >= 12)
245		rtc->hour |= 0x80;	    /* set MSB to indicate PM */
246
247	rtc->day_of_week = rtcset(rtc, ct.dow + 1);
248	rtc->day_of_month = rtcset(rtc, ct.day);
249	rtc->month = rtcset(rtc, ct.mon);
250	rtc->year = rtcset(rtc, ct.year % 100);
251	rtc->century = rtcset(rtc, ct.year / 100);
252}
253
254static int
255rtcget(struct rtcdev *rtc, int val, int *retval)
256{
257	uint8_t upper, lower;
258
259	if (rtc->reg_b & RTCSB_BIN) {
260		*retval = val;
261		return (0);
262	}
263
264	lower = val & 0xf;
265	upper = (val >> 4) & 0xf;
266
267	if (lower > 9 || upper > 9)
268		return (-1);
269
270	*retval = upper * 10 + lower;
271	return (0);
272}
273
274static time_t
275rtc_to_secs(struct vrtc *vrtc)
276{
277	struct clocktime ct;
278	struct timespec ts;
279	struct rtcdev *rtc;
280	struct vm *vm;
281	int century, error, hour, pm, year;
282
283	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
284
285	vm = vrtc->vm;
286	rtc = &vrtc->rtcdev;
287
288	bzero(&ct, sizeof(struct clocktime));
289
290	error = rtcget(rtc, rtc->sec, &ct.sec);
291	if (error || ct.sec < 0 || ct.sec > 59) {
292		VM_CTR2(vm, "Invalid RTC sec %#x/%d", rtc->sec, ct.sec);
293		goto fail;
294	}
295
296	error = rtcget(rtc, rtc->min, &ct.min);
297	if (error || ct.min < 0 || ct.min > 59) {
298		VM_CTR2(vm, "Invalid RTC min %#x/%d", rtc->min, ct.min);
299		goto fail;
300	}
301
302	pm = 0;
303	hour = rtc->hour;
304	if ((rtc->reg_b & RTCSB_24HR) == 0) {
305		if (hour & 0x80) {
306			hour &= ~0x80;
307			pm = 1;
308		}
309	}
310	error = rtcget(rtc, hour, &ct.hour);
311	if ((rtc->reg_b & RTCSB_24HR) == 0) {
312		if (ct.hour >= 1 && ct.hour <= 12) {
313			/*
314			 * Convert from 12-hour format to internal 24-hour
315			 * representation as follows:
316			 *
317			 *    12-hour format		ct.hour
318			 *	12	AM		0
319			 *	1 - 11	AM		1 - 11
320			 *	12	PM		12
321			 *	1 - 11	PM		13 - 23
322			 */
323			if (ct.hour == 12)
324				ct.hour = 0;
325			if (pm)
326				ct.hour += 12;
327		} else {
328			VM_CTR2(vm, "Invalid RTC 12-hour format %#x/%d",
329			    rtc->hour, ct.hour);
330			goto fail;
331		}
332	}
333
334	if (error || ct.hour < 0 || ct.hour > 23) {
335		VM_CTR2(vm, "Invalid RTC hour %#x/%d", rtc->hour, ct.hour);
336		goto fail;
337	}
338
339	/*
340	 * Ignore 'rtc->dow' because some guests like Linux don't bother
341	 * setting it at all while others like OpenBSD/i386 set it incorrectly.
342	 *
343	 * clock_ct_to_ts() does not depend on 'ct.dow' anyways so ignore it.
344	 */
345	ct.dow = -1;
346
347	error = rtcget(rtc, rtc->day_of_month, &ct.day);
348	if (error || ct.day < 1 || ct.day > 31) {
349		VM_CTR2(vm, "Invalid RTC mday %#x/%d", rtc->day_of_month,
350		    ct.day);
351		goto fail;
352	}
353
354	error = rtcget(rtc, rtc->month, &ct.mon);
355	if (error || ct.mon < 1 || ct.mon > 12) {
356		VM_CTR2(vm, "Invalid RTC month %#x/%d", rtc->month, ct.mon);
357		goto fail;
358	}
359
360	error = rtcget(rtc, rtc->year, &year);
361	if (error || year < 0 || year > 99) {
362		VM_CTR2(vm, "Invalid RTC year %#x/%d", rtc->year, year);
363		goto fail;
364	}
365
366	error = rtcget(rtc, rtc->century, &century);
367	ct.year = century * 100 + year;
368	if (error || ct.year < POSIX_BASE_YEAR) {
369		VM_CTR2(vm, "Invalid RTC century %#x/%d", rtc->century,
370		    ct.year);
371		goto fail;
372	}
373
374	error = clock_ct_to_ts(&ct, &ts);
375	if (error || ts.tv_sec < 0) {
376		VM_CTR3(vm, "Invalid RTC clocktime.date %04d-%02d-%02d",
377		    ct.year, ct.mon, ct.day);
378		VM_CTR3(vm, "Invalid RTC clocktime.time %02d:%02d:%02d",
379		    ct.hour, ct.min, ct.sec);
380		goto fail;
381	}
382	return (ts.tv_sec);		/* success */
383fail:
384	/*
385	 * Stop updating the RTC if the date/time fields programmed by
386	 * the guest are invalid.
387	 */
388	VM_CTR0(vrtc->vm, "Invalid RTC date/time programming detected");
389	return (VRTC_BROKEN_TIME);
390}
391
392static int
393vrtc_time_update(struct vrtc *vrtc, time_t newtime)
394{
395	struct rtcdev *rtc;
396	time_t oldtime;
397	uint8_t alarm_sec, alarm_min, alarm_hour;
398
399	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
400
401	rtc = &vrtc->rtcdev;
402	alarm_sec = rtc->alarm_sec;
403	alarm_min = rtc->alarm_min;
404	alarm_hour = rtc->alarm_hour;
405
406	oldtime = vrtc->base_rtctime;
407	VM_CTR2(vrtc->vm, "Updating RTC time from %#lx to %#lx",
408	    oldtime, newtime);
409
410	if (newtime == oldtime)
411		return (0);
412
413	/*
414	 * If 'newtime' indicates that RTC updates are disabled then just
415	 * record that and return. There is no need to do alarm interrupt
416	 * processing or update 'base_uptime' in this case.
417	 */
418	if (newtime == VRTC_BROKEN_TIME) {
419		vrtc->base_rtctime = VRTC_BROKEN_TIME;
420		return (0);
421	}
422
423	/*
424	 * Return an error if RTC updates are halted by the guest.
425	 */
426	if (rtc_halted(vrtc)) {
427		VM_CTR0(vrtc->vm, "RTC update halted by guest");
428		return (EBUSY);
429	}
430
431	do {
432		/*
433		 * If the alarm interrupt is enabled and 'oldtime' is valid
434		 * then visit all the seconds between 'oldtime' and 'newtime'
435		 * to check for the alarm condition.
436		 *
437		 * Otherwise move the RTC time forward directly to 'newtime'.
438		 */
439		if (aintr_enabled(vrtc) && oldtime != VRTC_BROKEN_TIME)
440			vrtc->base_rtctime++;
441		else
442			vrtc->base_rtctime = newtime;
443
444		if (aintr_enabled(vrtc)) {
445			/*
446			 * Update the RTC date/time fields before checking
447			 * if the alarm conditions are satisfied.
448			 */
449			secs_to_rtc(vrtc->base_rtctime, vrtc, 0);
450
451			if ((alarm_sec >= 0xC0 || alarm_sec == rtc->sec) &&
452			    (alarm_min >= 0xC0 || alarm_min == rtc->min) &&
453			    (alarm_hour >= 0xC0 || alarm_hour == rtc->hour)) {
454				vrtc_set_reg_c(vrtc, rtc->reg_c | RTCIR_ALARM);
455			}
456		}
457	} while (vrtc->base_rtctime != newtime);
458
459	if (uintr_enabled(vrtc))
460		vrtc_set_reg_c(vrtc, rtc->reg_c | RTCIR_UPDATE);
461
462	vrtc->base_uptime = sbinuptime();
463
464	return (0);
465}
466
467static sbintime_t
468vrtc_freq(struct vrtc *vrtc)
469{
470	int ratesel;
471
472	static sbintime_t pf[16] = {
473		0,
474		SBT_1S / 256,
475		SBT_1S / 128,
476		SBT_1S / 8192,
477		SBT_1S / 4096,
478		SBT_1S / 2048,
479		SBT_1S / 1024,
480		SBT_1S / 512,
481		SBT_1S / 256,
482		SBT_1S / 128,
483		SBT_1S / 64,
484		SBT_1S / 32,
485		SBT_1S / 16,
486		SBT_1S / 8,
487		SBT_1S / 4,
488		SBT_1S / 2,
489	};
490
491	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
492
493	/*
494	 * If both periodic and alarm interrupts are enabled then use the
495	 * periodic frequency to drive the callout. The minimum periodic
496	 * frequency (2 Hz) is higher than the alarm frequency (1 Hz) so
497	 * piggyback the alarm on top of it. The same argument applies to
498	 * the update interrupt.
499	 */
500	if (pintr_enabled(vrtc) && divider_enabled(vrtc->rtcdev.reg_a)) {
501		ratesel = vrtc->rtcdev.reg_a & 0xf;
502		return (pf[ratesel]);
503	} else if (aintr_enabled(vrtc) && update_enabled(vrtc)) {
504		return (SBT_1S);
505	} else if (uintr_enabled(vrtc) && update_enabled(vrtc)) {
506		return (SBT_1S);
507	} else {
508		return (0);
509	}
510}
511
512static void
513vrtc_callout_reset(struct vrtc *vrtc, sbintime_t freqsbt)
514{
515
516	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
517
518	if (freqsbt == 0) {
519		if (callout_active(&vrtc->callout)) {
520			VM_CTR0(vrtc->vm, "RTC callout stopped");
521			callout_stop(&vrtc->callout);
522		}
523		return;
524	}
525	VM_CTR1(vrtc->vm, "RTC callout frequency %d hz", SBT_1S / freqsbt);
526	callout_reset_sbt(&vrtc->callout, freqsbt, 0, vrtc_callout_handler,
527	    vrtc, 0);
528}
529
530static void
531vrtc_callout_handler(void *arg)
532{
533	struct vrtc *vrtc = arg;
534	sbintime_t freqsbt;
535	time_t rtctime;
536	int error;
537
538	VM_CTR0(vrtc->vm, "vrtc callout fired");
539
540	VRTC_LOCK(vrtc);
541	if (callout_pending(&vrtc->callout))	/* callout was reset */
542		goto done;
543
544	if (!callout_active(&vrtc->callout))	/* callout was stopped */
545		goto done;
546
547	callout_deactivate(&vrtc->callout);
548
549	KASSERT((vrtc->rtcdev.reg_b & RTCSB_ALL_INTRS) != 0,
550	    ("gratuitous vrtc callout"));
551
552	if (pintr_enabled(vrtc))
553		vrtc_set_reg_c(vrtc, vrtc->rtcdev.reg_c | RTCIR_PERIOD);
554
555	if (aintr_enabled(vrtc) || uintr_enabled(vrtc)) {
556		rtctime = vrtc_curtime(vrtc);
557		error = vrtc_time_update(vrtc, rtctime);
558		KASSERT(error == 0, ("%s: vrtc_time_update error %d",
559		    __func__, error));
560	}
561
562	freqsbt = vrtc_freq(vrtc);
563	KASSERT(freqsbt != 0, ("%s: vrtc frequency cannot be zero", __func__));
564	vrtc_callout_reset(vrtc, freqsbt);
565done:
566	VRTC_UNLOCK(vrtc);
567}
568
569static __inline void
570vrtc_callout_check(struct vrtc *vrtc, sbintime_t freq)
571{
572	int active;
573
574	active = callout_active(&vrtc->callout) ? 1 : 0;
575	KASSERT((freq == 0 && !active) || (freq != 0 && active),
576	    ("vrtc callout %s with frequency %#lx",
577	    active ? "active" : "inactive", freq));
578}
579
580static void
581vrtc_set_reg_c(struct vrtc *vrtc, uint8_t newval)
582{
583	struct rtcdev *rtc;
584	int oldirqf, newirqf;
585	uint8_t oldval, changed;
586
587	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
588
589	rtc = &vrtc->rtcdev;
590	newval &= RTCIR_ALARM | RTCIR_PERIOD | RTCIR_UPDATE;
591
592	oldirqf = rtc->reg_c & RTCIR_INT;
593	if ((aintr_enabled(vrtc) && (newval & RTCIR_ALARM) != 0) ||
594	    (pintr_enabled(vrtc) && (newval & RTCIR_PERIOD) != 0) ||
595	    (uintr_enabled(vrtc) && (newval & RTCIR_UPDATE) != 0)) {
596		newirqf = RTCIR_INT;
597	} else {
598		newirqf = 0;
599	}
600
601	oldval = rtc->reg_c;
602	rtc->reg_c = newirqf | newval;
603	changed = oldval ^ rtc->reg_c;
604	if (changed) {
605		VM_CTR2(vrtc->vm, "RTC reg_c changed from %#x to %#x",
606		    oldval, rtc->reg_c);
607	}
608
609	if (!oldirqf && newirqf) {
610		VM_CTR1(vrtc->vm, "RTC irq %d asserted", RTC_IRQ);
611		vatpic_pulse_irq(vrtc->vm, RTC_IRQ);
612		vioapic_pulse_irq(vrtc->vm, RTC_IRQ);
613	} else if (oldirqf && !newirqf) {
614		VM_CTR1(vrtc->vm, "RTC irq %d deasserted", RTC_IRQ);
615	}
616}
617
618static int
619vrtc_set_reg_b(struct vrtc *vrtc, uint8_t newval)
620{
621	struct rtcdev *rtc;
622	sbintime_t oldfreq, newfreq;
623	time_t curtime, rtctime;
624	int error;
625	uint8_t oldval, changed;
626
627	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
628
629	rtc = &vrtc->rtcdev;
630	oldval = rtc->reg_b;
631	oldfreq = vrtc_freq(vrtc);
632
633	rtc->reg_b = newval;
634	changed = oldval ^ newval;
635	if (changed) {
636		VM_CTR2(vrtc->vm, "RTC reg_b changed from %#x to %#x",
637		    oldval, newval);
638	}
639
640	if (changed & RTCSB_HALT) {
641		if ((newval & RTCSB_HALT) == 0) {
642			rtctime = rtc_to_secs(vrtc);
643			if (rtctime == VRTC_BROKEN_TIME) {
644				if (rtc_flag_broken_time)
645					return (-1);
646			}
647		} else {
648			curtime = vrtc_curtime(vrtc);
649			KASSERT(curtime == vrtc->base_rtctime, ("%s: mismatch "
650			    "between vrtc basetime (%#lx) and curtime (%#lx)",
651			    __func__, vrtc->base_rtctime, curtime));
652
653			/*
654			 * Force a refresh of the RTC date/time fields so
655			 * they reflect the time right before the guest set
656			 * the HALT bit.
657			 */
658			secs_to_rtc(curtime, vrtc, 1);
659
660			/*
661			 * Updates are halted so mark 'base_rtctime' to denote
662			 * that the RTC date/time is in flux.
663			 */
664			rtctime = VRTC_BROKEN_TIME;
665			rtc->reg_b &= ~RTCSB_UINTR;
666		}
667		error = vrtc_time_update(vrtc, rtctime);
668		KASSERT(error == 0, ("vrtc_time_update error %d", error));
669	}
670
671	/*
672	 * Side effect of changes to the interrupt enable bits.
673	 */
674	if (changed & RTCSB_ALL_INTRS)
675		vrtc_set_reg_c(vrtc, vrtc->rtcdev.reg_c);
676
677	/*
678	 * Change the callout frequency if it has changed.
679	 */
680	newfreq = vrtc_freq(vrtc);
681	if (newfreq != oldfreq)
682		vrtc_callout_reset(vrtc, newfreq);
683	else
684		vrtc_callout_check(vrtc, newfreq);
685
686	/*
687	 * The side effect of bits that control the RTC date/time format
688	 * is handled lazily when those fields are actually read.
689	 */
690	return (0);
691}
692
693static void
694vrtc_set_reg_a(struct vrtc *vrtc, uint8_t newval)
695{
696	sbintime_t oldfreq, newfreq;
697	uint8_t oldval, changed;
698
699	KASSERT(VRTC_LOCKED(vrtc), ("%s: vrtc not locked", __func__));
700
701	newval &= ~RTCSA_TUP;
702	oldval = vrtc->rtcdev.reg_a;
703	oldfreq = vrtc_freq(vrtc);
704
705	if (divider_enabled(oldval) && !divider_enabled(newval)) {
706		VM_CTR2(vrtc->vm, "RTC divider held in reset at %#lx/%#lx",
707		    vrtc->base_rtctime, vrtc->base_uptime);
708	} else if (!divider_enabled(oldval) && divider_enabled(newval)) {
709		/*
710		 * If the dividers are coming out of reset then update
711		 * 'base_uptime' before this happens. This is done to
712		 * maintain the illusion that the RTC date/time was frozen
713		 * while the dividers were disabled.
714		 */
715		vrtc->base_uptime = sbinuptime();
716		VM_CTR2(vrtc->vm, "RTC divider out of reset at %#lx/%#lx",
717		    vrtc->base_rtctime, vrtc->base_uptime);
718	} else {
719		/* NOTHING */
720	}
721
722	vrtc->rtcdev.reg_a = newval;
723	changed = oldval ^ newval;
724	if (changed) {
725		VM_CTR2(vrtc->vm, "RTC reg_a changed from %#x to %#x",
726		    oldval, newval);
727	}
728
729	/*
730	 * Side effect of changes to rate select and divider enable bits.
731	 */
732	newfreq = vrtc_freq(vrtc);
733	if (newfreq != oldfreq)
734		vrtc_callout_reset(vrtc, newfreq);
735	else
736		vrtc_callout_check(vrtc, newfreq);
737}
738
739int
740vrtc_set_time(struct vm *vm, time_t secs)
741{
742	struct vrtc *vrtc;
743	int error;
744
745	vrtc = vm_rtc(vm);
746	VRTC_LOCK(vrtc);
747	error = vrtc_time_update(vrtc, secs);
748	VRTC_UNLOCK(vrtc);
749
750	if (error) {
751		VM_CTR2(vrtc->vm, "Error %d setting RTC time to %#lx", error,
752		    secs);
753	} else {
754		VM_CTR1(vrtc->vm, "RTC time set to %#lx", secs);
755	}
756
757	return (error);
758}
759
760time_t
761vrtc_get_time(struct vm *vm)
762{
763	struct vrtc *vrtc;
764	time_t t;
765
766	vrtc = vm_rtc(vm);
767	VRTC_LOCK(vrtc);
768	t = vrtc_curtime(vrtc);
769	VRTC_UNLOCK(vrtc);
770
771	return (t);
772}
773
774int
775vrtc_nvram_write(struct vm *vm, int offset, uint8_t value)
776{
777	struct vrtc *vrtc;
778	uint8_t *ptr;
779
780	vrtc = vm_rtc(vm);
781
782	/*
783	 * Don't allow writes to RTC control registers or the date/time fields.
784	 */
785	if (offset < offsetof(struct rtcdev, nvram[0]) ||
786	    offset == RTC_CENTURY || offset >= sizeof(struct rtcdev)) {
787		VM_CTR1(vrtc->vm, "RTC nvram write to invalid offset %d",
788		    offset);
789		return (EINVAL);
790	}
791
792	VRTC_LOCK(vrtc);
793	ptr = (uint8_t *)(&vrtc->rtcdev);
794	ptr[offset] = value;
795	VM_CTR2(vrtc->vm, "RTC nvram write %#x to offset %#x", value, offset);
796	VRTC_UNLOCK(vrtc);
797
798	return (0);
799}
800
801int
802vrtc_nvram_read(struct vm *vm, int offset, uint8_t *retval)
803{
804	struct vrtc *vrtc;
805	time_t curtime;
806	uint8_t *ptr;
807
808	/*
809	 * Allow all offsets in the RTC to be read.
810	 */
811	if (offset < 0 || offset >= sizeof(struct rtcdev))
812		return (EINVAL);
813
814	vrtc = vm_rtc(vm);
815	VRTC_LOCK(vrtc);
816
817	/*
818	 * Update RTC date/time fields if necessary.
819	 */
820	if (offset < 10 || offset == RTC_CENTURY) {
821		curtime = vrtc_curtime(vrtc);
822		secs_to_rtc(curtime, vrtc, 0);
823	}
824
825	ptr = (uint8_t *)(&vrtc->rtcdev);
826	*retval = ptr[offset];
827
828	VRTC_UNLOCK(vrtc);
829	return (0);
830}
831
832int
833vrtc_addr_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
834    uint32_t *val)
835{
836	struct vrtc *vrtc;
837
838	vrtc = vm_rtc(vm);
839
840	if (bytes != 1)
841		return (-1);
842
843	if (in) {
844		*val = 0xff;
845		return (0);
846	}
847
848	VRTC_LOCK(vrtc);
849	vrtc->addr = *val & 0x7f;
850	VRTC_UNLOCK(vrtc);
851
852	return (0);
853}
854
855int
856vrtc_data_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
857    uint32_t *val)
858{
859	struct vrtc *vrtc;
860	struct rtcdev *rtc;
861	time_t curtime;
862	int error, offset;
863
864	vrtc = vm_rtc(vm);
865	rtc = &vrtc->rtcdev;
866
867	if (bytes != 1)
868		return (-1);
869
870	VRTC_LOCK(vrtc);
871	offset = vrtc->addr;
872	if (offset >= sizeof(struct rtcdev)) {
873		VRTC_UNLOCK(vrtc);
874		return (-1);
875	}
876
877	error = 0;
878	curtime = vrtc_curtime(vrtc);
879	vrtc_time_update(vrtc, curtime);
880
881	/*
882	 * Update RTC date/time fields if necessary.
883	 *
884	 * This is not just for reads of the RTC. The side-effect of writing
885	 * the century byte requires other RTC date/time fields (e.g. sec)
886	 * to be updated here.
887	 */
888	if (offset < 10 || offset == RTC_CENTURY)
889		secs_to_rtc(curtime, vrtc, 0);
890
891	if (in) {
892		if (offset == 12) {
893			/*
894			 * XXX
895			 * reg_c interrupt flags are updated only if the
896			 * corresponding interrupt enable bit in reg_b is set.
897			 */
898			*val = vrtc->rtcdev.reg_c;
899			vrtc_set_reg_c(vrtc, 0);
900		} else {
901			*val = *((uint8_t *)rtc + offset);
902		}
903		VCPU_CTR2(vm, vcpuid, "Read value %#x from RTC offset %#x",
904		    *val, offset);
905	} else {
906		switch (offset) {
907		case 10:
908			VCPU_CTR1(vm, vcpuid, "RTC reg_a set to %#x", *val);
909			vrtc_set_reg_a(vrtc, *val);
910			break;
911		case 11:
912			VCPU_CTR1(vm, vcpuid, "RTC reg_b set to %#x", *val);
913			error = vrtc_set_reg_b(vrtc, *val);
914			break;
915		case 12:
916			VCPU_CTR1(vm, vcpuid, "RTC reg_c set to %#x (ignored)",
917			    *val);
918			break;
919		case 13:
920			VCPU_CTR1(vm, vcpuid, "RTC reg_d set to %#x (ignored)",
921			    *val);
922			break;
923		case 0:
924			/*
925			 * High order bit of 'seconds' is readonly.
926			 */
927			*val &= 0x7f;
928			/* FALLTHRU */
929		default:
930			VCPU_CTR2(vm, vcpuid, "RTC offset %#x set to %#x",
931			    offset, *val);
932			*((uint8_t *)rtc + offset) = *val;
933			break;
934		}
935
936		/*
937		 * XXX some guests (e.g. OpenBSD) write the century byte
938		 * outside of RTCSB_HALT so re-calculate the RTC date/time.
939		 */
940		if (offset == RTC_CENTURY && !rtc_halted(vrtc)) {
941			curtime = rtc_to_secs(vrtc);
942			error = vrtc_time_update(vrtc, curtime);
943			KASSERT(!error, ("vrtc_time_update error %d", error));
944			if (curtime == VRTC_BROKEN_TIME && rtc_flag_broken_time)
945				error = -1;
946		}
947	}
948	VRTC_UNLOCK(vrtc);
949	return (error);
950}
951
952void
953vrtc_reset(struct vrtc *vrtc)
954{
955	struct rtcdev *rtc;
956
957	VRTC_LOCK(vrtc);
958
959	rtc = &vrtc->rtcdev;
960	vrtc_set_reg_b(vrtc, rtc->reg_b & ~(RTCSB_ALL_INTRS | RTCSB_SQWE));
961	vrtc_set_reg_c(vrtc, 0);
962	KASSERT(!callout_active(&vrtc->callout), ("rtc callout still active"));
963
964	VRTC_UNLOCK(vrtc);
965}
966
967struct vrtc *
968vrtc_init(struct vm *vm)
969{
970	struct vrtc *vrtc;
971	struct rtcdev *rtc;
972	time_t curtime;
973
974	vrtc = malloc(sizeof(struct vrtc), M_VRTC, M_WAITOK | M_ZERO);
975	vrtc->vm = vm;
976	mtx_init(&vrtc->mtx, "vrtc lock", NULL, MTX_DEF);
977	callout_init(&vrtc->callout, 1);
978
979	/* Allow dividers to keep time but disable everything else */
980	rtc = &vrtc->rtcdev;
981	rtc->reg_a = 0x20;
982	rtc->reg_b = RTCSB_24HR;
983	rtc->reg_c = 0;
984	rtc->reg_d = RTCSD_PWR;
985
986	/* Reset the index register to a safe value. */
987	vrtc->addr = RTC_STATUSD;
988
989	/*
990	 * Initialize RTC time to 00:00:00 Jan 1, 1970.
991	 */
992	curtime = 0;
993
994	VRTC_LOCK(vrtc);
995	vrtc->base_rtctime = VRTC_BROKEN_TIME;
996	vrtc_time_update(vrtc, curtime);
997	secs_to_rtc(curtime, vrtc, 0);
998	VRTC_UNLOCK(vrtc);
999
1000	return (vrtc);
1001}
1002
1003void
1004vrtc_cleanup(struct vrtc *vrtc)
1005{
1006
1007	callout_drain(&vrtc->callout);
1008	free(vrtc, M_VRTC);
1009}
1010