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