xref: /freebsd/sys/amd64/vmm/io/vlapic.c (revision 2f513db7)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright (c) 2019 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following 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 NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/lock.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/mutex.h>
40 #include <sys/systm.h>
41 #include <sys/smp.h>
42 
43 #include <x86/specialreg.h>
44 #include <x86/apicreg.h>
45 
46 #include <machine/clock.h>
47 #include <machine/smp.h>
48 
49 #include <machine/vmm.h>
50 
51 #include "vmm_lapic.h"
52 #include "vmm_ktr.h"
53 #include "vmm_stat.h"
54 
55 #include "vlapic.h"
56 #include "vlapic_priv.h"
57 #include "vioapic.h"
58 
59 #define	PRIO(x)			((x) >> 4)
60 
61 #define VLAPIC_VERSION		(16)
62 
63 #define	x2apic(vlapic)	(((vlapic)->msr_apicbase & APICBASE_X2APIC) ? 1 : 0)
64 
65 /*
66  * The 'vlapic->timer_mtx' is used to provide mutual exclusion between the
67  * vlapic_callout_handler() and vcpu accesses to:
68  * - timer_freq_bt, timer_period_bt, timer_fire_bt
69  * - timer LVT register
70  */
71 #define	VLAPIC_TIMER_LOCK(vlapic)	mtx_lock_spin(&((vlapic)->timer_mtx))
72 #define	VLAPIC_TIMER_UNLOCK(vlapic)	mtx_unlock_spin(&((vlapic)->timer_mtx))
73 #define	VLAPIC_TIMER_LOCKED(vlapic)	mtx_owned(&((vlapic)->timer_mtx))
74 
75 /*
76  * APIC timer frequency:
77  * - arbitrary but chosen to be in the ballpark of contemporary hardware.
78  * - power-of-two to avoid loss of precision when converted to a bintime.
79  */
80 #define VLAPIC_BUS_FREQ		(128 * 1024 * 1024)
81 
82 static void vlapic_set_error(struct vlapic *, uint32_t, bool);
83 
84 static __inline uint32_t
85 vlapic_get_id(struct vlapic *vlapic)
86 {
87 
88 	if (x2apic(vlapic))
89 		return (vlapic->vcpuid);
90 	else
91 		return (vlapic->vcpuid << 24);
92 }
93 
94 static uint32_t
95 x2apic_ldr(struct vlapic *vlapic)
96 {
97 	int apicid;
98 	uint32_t ldr;
99 
100 	apicid = vlapic_get_id(vlapic);
101 	ldr = 1 << (apicid & 0xf);
102 	ldr |= (apicid & 0xffff0) << 12;
103 	return (ldr);
104 }
105 
106 void
107 vlapic_dfr_write_handler(struct vlapic *vlapic)
108 {
109 	struct LAPIC *lapic;
110 
111 	lapic = vlapic->apic_page;
112 	if (x2apic(vlapic)) {
113 		VM_CTR1(vlapic->vm, "ignoring write to DFR in x2apic mode: %#x",
114 		    lapic->dfr);
115 		lapic->dfr = 0;
116 		return;
117 	}
118 
119 	lapic->dfr &= APIC_DFR_MODEL_MASK;
120 	lapic->dfr |= APIC_DFR_RESERVED;
121 
122 	if ((lapic->dfr & APIC_DFR_MODEL_MASK) == APIC_DFR_MODEL_FLAT)
123 		VLAPIC_CTR0(vlapic, "vlapic DFR in Flat Model");
124 	else if ((lapic->dfr & APIC_DFR_MODEL_MASK) == APIC_DFR_MODEL_CLUSTER)
125 		VLAPIC_CTR0(vlapic, "vlapic DFR in Cluster Model");
126 	else
127 		VLAPIC_CTR1(vlapic, "DFR in Unknown Model %#x", lapic->dfr);
128 }
129 
130 void
131 vlapic_ldr_write_handler(struct vlapic *vlapic)
132 {
133 	struct LAPIC *lapic;
134 
135 	lapic = vlapic->apic_page;
136 
137 	/* LDR is read-only in x2apic mode */
138 	if (x2apic(vlapic)) {
139 		VLAPIC_CTR1(vlapic, "ignoring write to LDR in x2apic mode: %#x",
140 		    lapic->ldr);
141 		lapic->ldr = x2apic_ldr(vlapic);
142 	} else {
143 		lapic->ldr &= ~APIC_LDR_RESERVED;
144 		VLAPIC_CTR1(vlapic, "vlapic LDR set to %#x", lapic->ldr);
145 	}
146 }
147 
148 void
149 vlapic_id_write_handler(struct vlapic *vlapic)
150 {
151 	struct LAPIC *lapic;
152 
153 	/*
154 	 * We don't allow the ID register to be modified so reset it back to
155 	 * its default value.
156 	 */
157 	lapic = vlapic->apic_page;
158 	lapic->id = vlapic_get_id(vlapic);
159 }
160 
161 static int
162 vlapic_timer_divisor(uint32_t dcr)
163 {
164 	switch (dcr & 0xB) {
165 	case APIC_TDCR_1:
166 		return (1);
167 	case APIC_TDCR_2:
168 		return (2);
169 	case APIC_TDCR_4:
170 		return (4);
171 	case APIC_TDCR_8:
172 		return (8);
173 	case APIC_TDCR_16:
174 		return (16);
175 	case APIC_TDCR_32:
176 		return (32);
177 	case APIC_TDCR_64:
178 		return (64);
179 	case APIC_TDCR_128:
180 		return (128);
181 	default:
182 		panic("vlapic_timer_divisor: invalid dcr 0x%08x", dcr);
183 	}
184 }
185 
186 #if 0
187 static inline void
188 vlapic_dump_lvt(uint32_t offset, uint32_t *lvt)
189 {
190 	printf("Offset %x: lvt %08x (V:%02x DS:%x M:%x)\n", offset,
191 	    *lvt, *lvt & APIC_LVTT_VECTOR, *lvt & APIC_LVTT_DS,
192 	    *lvt & APIC_LVTT_M);
193 }
194 #endif
195 
196 static uint32_t
197 vlapic_get_ccr(struct vlapic *vlapic)
198 {
199 	struct bintime bt_now, bt_rem;
200 	struct LAPIC *lapic;
201 	uint32_t ccr;
202 
203 	ccr = 0;
204 	lapic = vlapic->apic_page;
205 
206 	VLAPIC_TIMER_LOCK(vlapic);
207 	if (callout_active(&vlapic->callout)) {
208 		/*
209 		 * If the timer is scheduled to expire in the future then
210 		 * compute the value of 'ccr' based on the remaining time.
211 		 */
212 		binuptime(&bt_now);
213 		if (bintime_cmp(&vlapic->timer_fire_bt, &bt_now, >)) {
214 			bt_rem = vlapic->timer_fire_bt;
215 			bintime_sub(&bt_rem, &bt_now);
216 			ccr += bt_rem.sec * BT2FREQ(&vlapic->timer_freq_bt);
217 			ccr += bt_rem.frac / vlapic->timer_freq_bt.frac;
218 		}
219 	}
220 	KASSERT(ccr <= lapic->icr_timer, ("vlapic_get_ccr: invalid ccr %#x, "
221 	    "icr_timer is %#x", ccr, lapic->icr_timer));
222 	VLAPIC_CTR2(vlapic, "vlapic ccr_timer = %#x, icr_timer = %#x",
223 	    ccr, lapic->icr_timer);
224 	VLAPIC_TIMER_UNLOCK(vlapic);
225 	return (ccr);
226 }
227 
228 void
229 vlapic_dcr_write_handler(struct vlapic *vlapic)
230 {
231 	struct LAPIC *lapic;
232 	int divisor;
233 
234 	lapic = vlapic->apic_page;
235 	VLAPIC_TIMER_LOCK(vlapic);
236 
237 	divisor = vlapic_timer_divisor(lapic->dcr_timer);
238 	VLAPIC_CTR2(vlapic, "vlapic dcr_timer=%#x, divisor=%d",
239 	    lapic->dcr_timer, divisor);
240 
241 	/*
242 	 * Update the timer frequency and the timer period.
243 	 *
244 	 * XXX changes to the frequency divider will not take effect until
245 	 * the timer is reloaded.
246 	 */
247 	FREQ2BT(VLAPIC_BUS_FREQ / divisor, &vlapic->timer_freq_bt);
248 	vlapic->timer_period_bt = vlapic->timer_freq_bt;
249 	bintime_mul(&vlapic->timer_period_bt, lapic->icr_timer);
250 
251 	VLAPIC_TIMER_UNLOCK(vlapic);
252 }
253 
254 void
255 vlapic_esr_write_handler(struct vlapic *vlapic)
256 {
257 	struct LAPIC *lapic;
258 
259 	lapic = vlapic->apic_page;
260 	lapic->esr = vlapic->esr_pending;
261 	vlapic->esr_pending = 0;
262 }
263 
264 int
265 vlapic_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
266 {
267 	struct LAPIC *lapic;
268 	uint32_t *irrptr, *tmrptr, mask;
269 	int idx;
270 
271 	KASSERT(vector >= 0 && vector < 256, ("invalid vector %d", vector));
272 
273 	lapic = vlapic->apic_page;
274 	if (!(lapic->svr & APIC_SVR_ENABLE)) {
275 		VLAPIC_CTR1(vlapic, "vlapic is software disabled, ignoring "
276 		    "interrupt %d", vector);
277 		return (0);
278 	}
279 
280 	if (vector < 16) {
281 		vlapic_set_error(vlapic, APIC_ESR_RECEIVE_ILLEGAL_VECTOR,
282 		    false);
283 		VLAPIC_CTR1(vlapic, "vlapic ignoring interrupt to vector %d",
284 		    vector);
285 		return (1);
286 	}
287 
288 	if (vlapic->ops.set_intr_ready)
289 		return ((*vlapic->ops.set_intr_ready)(vlapic, vector, level));
290 
291 	idx = (vector / 32) * 4;
292 	mask = 1 << (vector % 32);
293 
294 	irrptr = &lapic->irr0;
295 	atomic_set_int(&irrptr[idx], mask);
296 
297 	/*
298 	 * Verify that the trigger-mode of the interrupt matches with
299 	 * the vlapic TMR registers.
300 	 */
301 	tmrptr = &lapic->tmr0;
302 	if ((tmrptr[idx] & mask) != (level ? mask : 0)) {
303 		VLAPIC_CTR3(vlapic, "vlapic TMR[%d] is 0x%08x but "
304 		    "interrupt is %s-triggered", idx / 4, tmrptr[idx],
305 		    level ? "level" : "edge");
306 	}
307 
308 	VLAPIC_CTR_IRR(vlapic, "vlapic_set_intr_ready");
309 	return (1);
310 }
311 
312 static __inline uint32_t *
313 vlapic_get_lvtptr(struct vlapic *vlapic, uint32_t offset)
314 {
315 	struct LAPIC	*lapic = vlapic->apic_page;
316 	int 		 i;
317 
318 	switch (offset) {
319 	case APIC_OFFSET_CMCI_LVT:
320 		return (&lapic->lvt_cmci);
321 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
322 		i = (offset - APIC_OFFSET_TIMER_LVT) >> 2;
323 		return ((&lapic->lvt_timer) + i);
324 	default:
325 		panic("vlapic_get_lvt: invalid LVT\n");
326 	}
327 }
328 
329 static __inline int
330 lvt_off_to_idx(uint32_t offset)
331 {
332 	int index;
333 
334 	switch (offset) {
335 	case APIC_OFFSET_CMCI_LVT:
336 		index = APIC_LVT_CMCI;
337 		break;
338 	case APIC_OFFSET_TIMER_LVT:
339 		index = APIC_LVT_TIMER;
340 		break;
341 	case APIC_OFFSET_THERM_LVT:
342 		index = APIC_LVT_THERMAL;
343 		break;
344 	case APIC_OFFSET_PERF_LVT:
345 		index = APIC_LVT_PMC;
346 		break;
347 	case APIC_OFFSET_LINT0_LVT:
348 		index = APIC_LVT_LINT0;
349 		break;
350 	case APIC_OFFSET_LINT1_LVT:
351 		index = APIC_LVT_LINT1;
352 		break;
353 	case APIC_OFFSET_ERROR_LVT:
354 		index = APIC_LVT_ERROR;
355 		break;
356 	default:
357 		index = -1;
358 		break;
359 	}
360 	KASSERT(index >= 0 && index <= VLAPIC_MAXLVT_INDEX, ("lvt_off_to_idx: "
361 	    "invalid lvt index %d for offset %#x", index, offset));
362 
363 	return (index);
364 }
365 
366 static __inline uint32_t
367 vlapic_get_lvt(struct vlapic *vlapic, uint32_t offset)
368 {
369 	int idx;
370 	uint32_t val;
371 
372 	idx = lvt_off_to_idx(offset);
373 	val = atomic_load_acq_32(&vlapic->lvt_last[idx]);
374 	return (val);
375 }
376 
377 void
378 vlapic_lvt_write_handler(struct vlapic *vlapic, uint32_t offset)
379 {
380 	uint32_t *lvtptr, mask, val;
381 	struct LAPIC *lapic;
382 	int idx;
383 
384 	lapic = vlapic->apic_page;
385 	lvtptr = vlapic_get_lvtptr(vlapic, offset);
386 	val = *lvtptr;
387 	idx = lvt_off_to_idx(offset);
388 
389 	if (!(lapic->svr & APIC_SVR_ENABLE))
390 		val |= APIC_LVT_M;
391 	mask = APIC_LVT_M | APIC_LVT_DS | APIC_LVT_VECTOR;
392 	switch (offset) {
393 	case APIC_OFFSET_TIMER_LVT:
394 		mask |= APIC_LVTT_TM;
395 		break;
396 	case APIC_OFFSET_ERROR_LVT:
397 		break;
398 	case APIC_OFFSET_LINT0_LVT:
399 	case APIC_OFFSET_LINT1_LVT:
400 		mask |= APIC_LVT_TM | APIC_LVT_RIRR | APIC_LVT_IIPP;
401 		/* FALLTHROUGH */
402 	default:
403 		mask |= APIC_LVT_DM;
404 		break;
405 	}
406 	val &= mask;
407 	*lvtptr = val;
408 	atomic_store_rel_32(&vlapic->lvt_last[idx], val);
409 }
410 
411 static void
412 vlapic_mask_lvts(struct vlapic *vlapic)
413 {
414 	struct LAPIC *lapic = vlapic->apic_page;
415 
416 	lapic->lvt_cmci |= APIC_LVT_M;
417 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_CMCI_LVT);
418 
419 	lapic->lvt_timer |= APIC_LVT_M;
420 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_TIMER_LVT);
421 
422 	lapic->lvt_thermal |= APIC_LVT_M;
423 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_THERM_LVT);
424 
425 	lapic->lvt_pcint |= APIC_LVT_M;
426 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_PERF_LVT);
427 
428 	lapic->lvt_lint0 |= APIC_LVT_M;
429 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_LINT0_LVT);
430 
431 	lapic->lvt_lint1 |= APIC_LVT_M;
432 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_LINT1_LVT);
433 
434 	lapic->lvt_error |= APIC_LVT_M;
435 	vlapic_lvt_write_handler(vlapic, APIC_OFFSET_ERROR_LVT);
436 }
437 
438 static int
439 vlapic_fire_lvt(struct vlapic *vlapic, u_int lvt)
440 {
441 	uint32_t mode, reg, vec;
442 
443 	reg = atomic_load_acq_32(&vlapic->lvt_last[lvt]);
444 
445 	if (reg & APIC_LVT_M)
446 		return (0);
447 	vec = reg & APIC_LVT_VECTOR;
448 	mode = reg & APIC_LVT_DM;
449 
450 	switch (mode) {
451 	case APIC_LVT_DM_FIXED:
452 		if (vec < 16) {
453 			vlapic_set_error(vlapic, APIC_ESR_SEND_ILLEGAL_VECTOR,
454 			    lvt == APIC_LVT_ERROR);
455 			return (0);
456 		}
457 		if (vlapic_set_intr_ready(vlapic, vec, false))
458 			vcpu_notify_event(vlapic->vm, vlapic->vcpuid, true);
459 		break;
460 	case APIC_LVT_DM_NMI:
461 		vm_inject_nmi(vlapic->vm, vlapic->vcpuid);
462 		break;
463 	case APIC_LVT_DM_EXTINT:
464 		vm_inject_extint(vlapic->vm, vlapic->vcpuid);
465 		break;
466 	default:
467 		// Other modes ignored
468 		return (0);
469 	}
470 	return (1);
471 }
472 
473 #if 1
474 static void
475 dump_isrvec_stk(struct vlapic *vlapic)
476 {
477 	int i;
478 	uint32_t *isrptr;
479 
480 	isrptr = &vlapic->apic_page->isr0;
481 	for (i = 0; i < 8; i++)
482 		printf("ISR%d 0x%08x\n", i, isrptr[i * 4]);
483 
484 	for (i = 0; i <= vlapic->isrvec_stk_top; i++)
485 		printf("isrvec_stk[%d] = %d\n", i, vlapic->isrvec_stk[i]);
486 }
487 #endif
488 
489 /*
490  * Algorithm adopted from section "Interrupt, Task and Processor Priority"
491  * in Intel Architecture Manual Vol 3a.
492  */
493 static void
494 vlapic_update_ppr(struct vlapic *vlapic)
495 {
496 	int isrvec, tpr, ppr;
497 
498 	/*
499 	 * Note that the value on the stack at index 0 is always 0.
500 	 *
501 	 * This is a placeholder for the value of ISRV when none of the
502 	 * bits is set in the ISRx registers.
503 	 */
504 	isrvec = vlapic->isrvec_stk[vlapic->isrvec_stk_top];
505 	tpr = vlapic->apic_page->tpr;
506 
507 #if 1
508 	{
509 		int i, lastprio, curprio, vector, idx;
510 		uint32_t *isrptr;
511 
512 		if (vlapic->isrvec_stk_top == 0 && isrvec != 0)
513 			panic("isrvec_stk is corrupted: %d", isrvec);
514 
515 		/*
516 		 * Make sure that the priority of the nested interrupts is
517 		 * always increasing.
518 		 */
519 		lastprio = -1;
520 		for (i = 1; i <= vlapic->isrvec_stk_top; i++) {
521 			curprio = PRIO(vlapic->isrvec_stk[i]);
522 			if (curprio <= lastprio) {
523 				dump_isrvec_stk(vlapic);
524 				panic("isrvec_stk does not satisfy invariant");
525 			}
526 			lastprio = curprio;
527 		}
528 
529 		/*
530 		 * Make sure that each bit set in the ISRx registers has a
531 		 * corresponding entry on the isrvec stack.
532 		 */
533 		i = 1;
534 		isrptr = &vlapic->apic_page->isr0;
535 		for (vector = 0; vector < 256; vector++) {
536 			idx = (vector / 32) * 4;
537 			if (isrptr[idx] & (1 << (vector % 32))) {
538 				if (i > vlapic->isrvec_stk_top ||
539 				    vlapic->isrvec_stk[i] != vector) {
540 					dump_isrvec_stk(vlapic);
541 					panic("ISR and isrvec_stk out of sync");
542 				}
543 				i++;
544 			}
545 		}
546 	}
547 #endif
548 
549 	if (PRIO(tpr) >= PRIO(isrvec))
550 		ppr = tpr;
551 	else
552 		ppr = isrvec & 0xf0;
553 
554 	vlapic->apic_page->ppr = ppr;
555 	VLAPIC_CTR1(vlapic, "vlapic_update_ppr 0x%02x", ppr);
556 }
557 
558 static VMM_STAT(VLAPIC_GRATUITOUS_EOI, "EOI without any in-service interrupt");
559 
560 static void
561 vlapic_process_eoi(struct vlapic *vlapic)
562 {
563 	struct LAPIC	*lapic = vlapic->apic_page;
564 	uint32_t	*isrptr, *tmrptr;
565 	int		i, idx, bitpos, vector;
566 
567 	isrptr = &lapic->isr0;
568 	tmrptr = &lapic->tmr0;
569 
570 	for (i = 7; i >= 0; i--) {
571 		idx = i * 4;
572 		bitpos = fls(isrptr[idx]);
573 		if (bitpos-- != 0) {
574 			if (vlapic->isrvec_stk_top <= 0) {
575 				panic("invalid vlapic isrvec_stk_top %d",
576 				      vlapic->isrvec_stk_top);
577 			}
578 			isrptr[idx] &= ~(1 << bitpos);
579 			vector = i * 32 + bitpos;
580 			VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "EOI vector %d",
581 			    vector);
582 			VLAPIC_CTR_ISR(vlapic, "vlapic_process_eoi");
583 			vlapic->isrvec_stk_top--;
584 			vlapic_update_ppr(vlapic);
585 			if ((tmrptr[idx] & (1 << bitpos)) != 0) {
586 				vioapic_process_eoi(vlapic->vm, vlapic->vcpuid,
587 				    vector);
588 			}
589 			return;
590 		}
591 	}
592 	VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "Gratuitous EOI");
593 	vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_GRATUITOUS_EOI, 1);
594 }
595 
596 static __inline int
597 vlapic_get_lvt_field(uint32_t lvt, uint32_t mask)
598 {
599 
600 	return (lvt & mask);
601 }
602 
603 static __inline int
604 vlapic_periodic_timer(struct vlapic *vlapic)
605 {
606 	uint32_t lvt;
607 
608 	lvt = vlapic_get_lvt(vlapic, APIC_OFFSET_TIMER_LVT);
609 
610 	return (vlapic_get_lvt_field(lvt, APIC_LVTT_TM_PERIODIC));
611 }
612 
613 static VMM_STAT(VLAPIC_INTR_ERROR, "error interrupts generated by vlapic");
614 
615 static void
616 vlapic_set_error(struct vlapic *vlapic, uint32_t mask, bool lvt_error)
617 {
618 
619 	vlapic->esr_pending |= mask;
620 
621 	/*
622 	 * Avoid infinite recursion if the error LVT itself is configured with
623 	 * an illegal vector.
624 	 */
625 	if (lvt_error)
626 		return;
627 
628 	if (vlapic_fire_lvt(vlapic, APIC_LVT_ERROR)) {
629 		vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_ERROR, 1);
630 	}
631 }
632 
633 static VMM_STAT(VLAPIC_INTR_TIMER, "timer interrupts generated by vlapic");
634 
635 static void
636 vlapic_fire_timer(struct vlapic *vlapic)
637 {
638 
639 	KASSERT(VLAPIC_TIMER_LOCKED(vlapic), ("vlapic_fire_timer not locked"));
640 
641 	if (vlapic_fire_lvt(vlapic, APIC_LVT_TIMER)) {
642 		VLAPIC_CTR0(vlapic, "vlapic timer fired");
643 		vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_TIMER, 1);
644 	}
645 }
646 
647 static VMM_STAT(VLAPIC_INTR_CMC,
648     "corrected machine check interrupts generated by vlapic");
649 
650 void
651 vlapic_fire_cmci(struct vlapic *vlapic)
652 {
653 
654 	if (vlapic_fire_lvt(vlapic, APIC_LVT_CMCI)) {
655 		vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_CMC, 1);
656 	}
657 }
658 
659 static VMM_STAT_ARRAY(LVTS_TRIGGERRED, VLAPIC_MAXLVT_INDEX + 1,
660     "lvts triggered");
661 
662 int
663 vlapic_trigger_lvt(struct vlapic *vlapic, int vector)
664 {
665 
666 	if (vlapic_enabled(vlapic) == false) {
667 		/*
668 		 * When the local APIC is global/hardware disabled,
669 		 * LINT[1:0] pins are configured as INTR and NMI pins,
670 		 * respectively.
671 		*/
672 		switch (vector) {
673 			case APIC_LVT_LINT0:
674 				vm_inject_extint(vlapic->vm, vlapic->vcpuid);
675 				break;
676 			case APIC_LVT_LINT1:
677 				vm_inject_nmi(vlapic->vm, vlapic->vcpuid);
678 				break;
679 			default:
680 				break;
681 		}
682 		return (0);
683 	}
684 
685 	switch (vector) {
686 	case APIC_LVT_LINT0:
687 	case APIC_LVT_LINT1:
688 	case APIC_LVT_TIMER:
689 	case APIC_LVT_ERROR:
690 	case APIC_LVT_PMC:
691 	case APIC_LVT_THERMAL:
692 	case APIC_LVT_CMCI:
693 		if (vlapic_fire_lvt(vlapic, vector)) {
694 			vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid,
695 			    LVTS_TRIGGERRED, vector, 1);
696 		}
697 		break;
698 	default:
699 		return (EINVAL);
700 	}
701 	return (0);
702 }
703 
704 static void
705 vlapic_callout_handler(void *arg)
706 {
707 	struct vlapic *vlapic;
708 	struct bintime bt, btnow;
709 	sbintime_t rem_sbt;
710 
711 	vlapic = arg;
712 
713 	VLAPIC_TIMER_LOCK(vlapic);
714 	if (callout_pending(&vlapic->callout))	/* callout was reset */
715 		goto done;
716 
717 	if (!callout_active(&vlapic->callout))	/* callout was stopped */
718 		goto done;
719 
720 	callout_deactivate(&vlapic->callout);
721 
722 	vlapic_fire_timer(vlapic);
723 
724 	if (vlapic_periodic_timer(vlapic)) {
725 		binuptime(&btnow);
726 		KASSERT(bintime_cmp(&btnow, &vlapic->timer_fire_bt, >=),
727 		    ("vlapic callout at %#lx.%#lx, expected at %#lx.#%lx",
728 		    btnow.sec, btnow.frac, vlapic->timer_fire_bt.sec,
729 		    vlapic->timer_fire_bt.frac));
730 
731 		/*
732 		 * Compute the delta between when the timer was supposed to
733 		 * fire and the present time.
734 		 */
735 		bt = btnow;
736 		bintime_sub(&bt, &vlapic->timer_fire_bt);
737 
738 		rem_sbt = bttosbt(vlapic->timer_period_bt);
739 		if (bintime_cmp(&bt, &vlapic->timer_period_bt, <)) {
740 			/*
741 			 * Adjust the time until the next countdown downward
742 			 * to account for the lost time.
743 			 */
744 			rem_sbt -= bttosbt(bt);
745 		} else {
746 			/*
747 			 * If the delta is greater than the timer period then
748 			 * just reset our time base instead of trying to catch
749 			 * up.
750 			 */
751 			vlapic->timer_fire_bt = btnow;
752 			VLAPIC_CTR2(vlapic, "vlapic timer lagging by %lu "
753 			    "usecs, period is %lu usecs - resetting time base",
754 			    bttosbt(bt) / SBT_1US,
755 			    bttosbt(vlapic->timer_period_bt) / SBT_1US);
756 		}
757 
758 		bintime_add(&vlapic->timer_fire_bt, &vlapic->timer_period_bt);
759 		callout_reset_sbt(&vlapic->callout, rem_sbt, 0,
760 		    vlapic_callout_handler, vlapic, 0);
761 	}
762 done:
763 	VLAPIC_TIMER_UNLOCK(vlapic);
764 }
765 
766 void
767 vlapic_icrtmr_write_handler(struct vlapic *vlapic)
768 {
769 	struct LAPIC *lapic;
770 	sbintime_t sbt;
771 	uint32_t icr_timer;
772 
773 	VLAPIC_TIMER_LOCK(vlapic);
774 
775 	lapic = vlapic->apic_page;
776 	icr_timer = lapic->icr_timer;
777 
778 	vlapic->timer_period_bt = vlapic->timer_freq_bt;
779 	bintime_mul(&vlapic->timer_period_bt, icr_timer);
780 
781 	if (icr_timer != 0) {
782 		binuptime(&vlapic->timer_fire_bt);
783 		bintime_add(&vlapic->timer_fire_bt, &vlapic->timer_period_bt);
784 
785 		sbt = bttosbt(vlapic->timer_period_bt);
786 		callout_reset_sbt(&vlapic->callout, sbt, 0,
787 		    vlapic_callout_handler, vlapic, 0);
788 	} else
789 		callout_stop(&vlapic->callout);
790 
791 	VLAPIC_TIMER_UNLOCK(vlapic);
792 }
793 
794 /*
795  * This function populates 'dmask' with the set of vcpus that match the
796  * addressing specified by the (dest, phys, lowprio) tuple.
797  *
798  * 'x2apic_dest' specifies whether 'dest' is interpreted as x2APIC (32-bit)
799  * or xAPIC (8-bit) destination field.
800  */
801 static void
802 vlapic_calcdest(struct vm *vm, cpuset_t *dmask, uint32_t dest, bool phys,
803     bool lowprio, bool x2apic_dest)
804 {
805 	struct vlapic *vlapic;
806 	uint32_t dfr, ldr, ldest, cluster;
807 	uint32_t mda_flat_ldest, mda_cluster_ldest, mda_ldest, mda_cluster_id;
808 	cpuset_t amask;
809 	int vcpuid;
810 
811 	if ((x2apic_dest && dest == 0xffffffff) ||
812 	    (!x2apic_dest && dest == 0xff)) {
813 		/*
814 		 * Broadcast in both logical and physical modes.
815 		 */
816 		*dmask = vm_active_cpus(vm);
817 		return;
818 	}
819 
820 	if (phys) {
821 		/*
822 		 * Physical mode: destination is APIC ID.
823 		 */
824 		CPU_ZERO(dmask);
825 		vcpuid = vm_apicid2vcpuid(vm, dest);
826 		amask = vm_active_cpus(vm);
827 		if (vcpuid < vm_get_maxcpus(vm) && CPU_ISSET(vcpuid, &amask))
828 			CPU_SET(vcpuid, dmask);
829 	} else {
830 		/*
831 		 * In the "Flat Model" the MDA is interpreted as an 8-bit wide
832 		 * bitmask. This model is only available in the xAPIC mode.
833 		 */
834 		mda_flat_ldest = dest & 0xff;
835 
836 		/*
837 		 * In the "Cluster Model" the MDA is used to identify a
838 		 * specific cluster and a set of APICs in that cluster.
839 		 */
840 		if (x2apic_dest) {
841 			mda_cluster_id = dest >> 16;
842 			mda_cluster_ldest = dest & 0xffff;
843 		} else {
844 			mda_cluster_id = (dest >> 4) & 0xf;
845 			mda_cluster_ldest = dest & 0xf;
846 		}
847 
848 		/*
849 		 * Logical mode: match each APIC that has a bit set
850 		 * in its LDR that matches a bit in the ldest.
851 		 */
852 		CPU_ZERO(dmask);
853 		amask = vm_active_cpus(vm);
854 		while ((vcpuid = CPU_FFS(&amask)) != 0) {
855 			vcpuid--;
856 			CPU_CLR(vcpuid, &amask);
857 
858 			vlapic = vm_lapic(vm, vcpuid);
859 			dfr = vlapic->apic_page->dfr;
860 			ldr = vlapic->apic_page->ldr;
861 
862 			if ((dfr & APIC_DFR_MODEL_MASK) ==
863 			    APIC_DFR_MODEL_FLAT) {
864 				ldest = ldr >> 24;
865 				mda_ldest = mda_flat_ldest;
866 			} else if ((dfr & APIC_DFR_MODEL_MASK) ==
867 			    APIC_DFR_MODEL_CLUSTER) {
868 				if (x2apic(vlapic)) {
869 					cluster = ldr >> 16;
870 					ldest = ldr & 0xffff;
871 				} else {
872 					cluster = ldr >> 28;
873 					ldest = (ldr >> 24) & 0xf;
874 				}
875 				if (cluster != mda_cluster_id)
876 					continue;
877 				mda_ldest = mda_cluster_ldest;
878 			} else {
879 				/*
880 				 * Guest has configured a bad logical
881 				 * model for this vcpu - skip it.
882 				 */
883 				VLAPIC_CTR1(vlapic, "vlapic has bad logical "
884 				    "model %x - cannot deliver interrupt", dfr);
885 				continue;
886 			}
887 
888 			if ((mda_ldest & ldest) != 0) {
889 				CPU_SET(vcpuid, dmask);
890 				if (lowprio)
891 					break;
892 			}
893 		}
894 	}
895 }
896 
897 static VMM_STAT_ARRAY(IPIS_SENT, VM_MAXCPU, "ipis sent to vcpu");
898 
899 static void
900 vlapic_set_tpr(struct vlapic *vlapic, uint8_t val)
901 {
902 	struct LAPIC *lapic = vlapic->apic_page;
903 
904 	if (lapic->tpr != val) {
905 		VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vlapic TPR changed "
906 		    "from %#x to %#x", lapic->tpr, val);
907 		lapic->tpr = val;
908 		vlapic_update_ppr(vlapic);
909 	}
910 }
911 
912 static uint8_t
913 vlapic_get_tpr(struct vlapic *vlapic)
914 {
915 	struct LAPIC *lapic = vlapic->apic_page;
916 
917 	return (lapic->tpr);
918 }
919 
920 void
921 vlapic_set_cr8(struct vlapic *vlapic, uint64_t val)
922 {
923 	uint8_t tpr;
924 
925 	if (val & ~0xf) {
926 		vm_inject_gp(vlapic->vm, vlapic->vcpuid);
927 		return;
928 	}
929 
930 	tpr = val << 4;
931 	vlapic_set_tpr(vlapic, tpr);
932 }
933 
934 uint64_t
935 vlapic_get_cr8(struct vlapic *vlapic)
936 {
937 	uint8_t tpr;
938 
939 	tpr = vlapic_get_tpr(vlapic);
940 	return (tpr >> 4);
941 }
942 
943 int
944 vlapic_icrlo_write_handler(struct vlapic *vlapic, bool *retu)
945 {
946 	int i;
947 	bool phys;
948 	cpuset_t dmask;
949 	uint64_t icrval;
950 	uint32_t dest, vec, mode;
951 	struct vlapic *vlapic2;
952 	struct vm_exit *vmexit;
953 	struct LAPIC *lapic;
954 	uint16_t maxcpus;
955 
956 	lapic = vlapic->apic_page;
957 	lapic->icr_lo &= ~APIC_DELSTAT_PEND;
958 	icrval = ((uint64_t)lapic->icr_hi << 32) | lapic->icr_lo;
959 
960 	if (x2apic(vlapic))
961 		dest = icrval >> 32;
962 	else
963 		dest = icrval >> (32 + 24);
964 	vec = icrval & APIC_VECTOR_MASK;
965 	mode = icrval & APIC_DELMODE_MASK;
966 
967 	if (mode == APIC_DELMODE_FIXED && vec < 16) {
968 		vlapic_set_error(vlapic, APIC_ESR_SEND_ILLEGAL_VECTOR, false);
969 		VLAPIC_CTR1(vlapic, "Ignoring invalid IPI %d", vec);
970 		return (0);
971 	}
972 
973 	VLAPIC_CTR2(vlapic, "icrlo 0x%016lx triggered ipi %d", icrval, vec);
974 
975 	if (mode == APIC_DELMODE_FIXED || mode == APIC_DELMODE_NMI) {
976 		switch (icrval & APIC_DEST_MASK) {
977 		case APIC_DEST_DESTFLD:
978 			phys = ((icrval & APIC_DESTMODE_LOG) == 0);
979 			vlapic_calcdest(vlapic->vm, &dmask, dest, phys, false,
980 			    x2apic(vlapic));
981 			break;
982 		case APIC_DEST_SELF:
983 			CPU_SETOF(vlapic->vcpuid, &dmask);
984 			break;
985 		case APIC_DEST_ALLISELF:
986 			dmask = vm_active_cpus(vlapic->vm);
987 			break;
988 		case APIC_DEST_ALLESELF:
989 			dmask = vm_active_cpus(vlapic->vm);
990 			CPU_CLR(vlapic->vcpuid, &dmask);
991 			break;
992 		default:
993 			CPU_ZERO(&dmask);	/* satisfy gcc */
994 			break;
995 		}
996 
997 		while ((i = CPU_FFS(&dmask)) != 0) {
998 			i--;
999 			CPU_CLR(i, &dmask);
1000 			if (mode == APIC_DELMODE_FIXED) {
1001 				lapic_intr_edge(vlapic->vm, i, vec);
1002 				vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid,
1003 						    IPIS_SENT, i, 1);
1004 				VLAPIC_CTR2(vlapic, "vlapic sending ipi %d "
1005 				    "to vcpuid %d", vec, i);
1006 			} else {
1007 				vm_inject_nmi(vlapic->vm, i);
1008 				VLAPIC_CTR1(vlapic, "vlapic sending ipi nmi "
1009 				    "to vcpuid %d", i);
1010 			}
1011 		}
1012 
1013 		return (0);	/* handled completely in the kernel */
1014 	}
1015 
1016 	maxcpus = vm_get_maxcpus(vlapic->vm);
1017 	if (mode == APIC_DELMODE_INIT) {
1018 		if ((icrval & APIC_LEVEL_MASK) == APIC_LEVEL_DEASSERT)
1019 			return (0);
1020 
1021 		if (vlapic->vcpuid == 0 && dest != 0 && dest < maxcpus) {
1022 			vlapic2 = vm_lapic(vlapic->vm, dest);
1023 
1024 			/* move from INIT to waiting-for-SIPI state */
1025 			if (vlapic2->boot_state == BS_INIT) {
1026 				vlapic2->boot_state = BS_SIPI;
1027 			}
1028 
1029 			return (0);
1030 		}
1031 	}
1032 
1033 	if (mode == APIC_DELMODE_STARTUP) {
1034 		if (vlapic->vcpuid == 0 && dest != 0 && dest < maxcpus) {
1035 			vlapic2 = vm_lapic(vlapic->vm, dest);
1036 
1037 			/*
1038 			 * Ignore SIPIs in any state other than wait-for-SIPI
1039 			 */
1040 			if (vlapic2->boot_state != BS_SIPI)
1041 				return (0);
1042 
1043 			vlapic2->boot_state = BS_RUNNING;
1044 
1045 			*retu = true;
1046 			vmexit = vm_exitinfo(vlapic->vm, vlapic->vcpuid);
1047 			vmexit->exitcode = VM_EXITCODE_SPINUP_AP;
1048 			vmexit->u.spinup_ap.vcpu = dest;
1049 			vmexit->u.spinup_ap.rip = vec << PAGE_SHIFT;
1050 
1051 			return (0);
1052 		}
1053 	}
1054 
1055 	/*
1056 	 * This will cause a return to userland.
1057 	 */
1058 	return (1);
1059 }
1060 
1061 void
1062 vlapic_self_ipi_handler(struct vlapic *vlapic, uint64_t val)
1063 {
1064 	int vec;
1065 
1066 	KASSERT(x2apic(vlapic), ("SELF_IPI does not exist in xAPIC mode"));
1067 
1068 	vec = val & 0xff;
1069 	lapic_intr_edge(vlapic->vm, vlapic->vcpuid, vec);
1070 	vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid, IPIS_SENT,
1071 	    vlapic->vcpuid, 1);
1072 	VLAPIC_CTR1(vlapic, "vlapic self-ipi %d", vec);
1073 }
1074 
1075 int
1076 vlapic_pending_intr(struct vlapic *vlapic, int *vecptr)
1077 {
1078 	struct LAPIC	*lapic = vlapic->apic_page;
1079 	int	  	 idx, i, bitpos, vector;
1080 	uint32_t	*irrptr, val;
1081 
1082 	if (vlapic->ops.pending_intr)
1083 		return ((*vlapic->ops.pending_intr)(vlapic, vecptr));
1084 
1085 	irrptr = &lapic->irr0;
1086 
1087 	for (i = 7; i >= 0; i--) {
1088 		idx = i * 4;
1089 		val = atomic_load_acq_int(&irrptr[idx]);
1090 		bitpos = fls(val);
1091 		if (bitpos != 0) {
1092 			vector = i * 32 + (bitpos - 1);
1093 			if (PRIO(vector) > PRIO(lapic->ppr)) {
1094 				VLAPIC_CTR1(vlapic, "pending intr %d", vector);
1095 				if (vecptr != NULL)
1096 					*vecptr = vector;
1097 				return (1);
1098 			} else
1099 				break;
1100 		}
1101 	}
1102 	return (0);
1103 }
1104 
1105 void
1106 vlapic_intr_accepted(struct vlapic *vlapic, int vector)
1107 {
1108 	struct LAPIC	*lapic = vlapic->apic_page;
1109 	uint32_t	*irrptr, *isrptr;
1110 	int		idx, stk_top;
1111 
1112 	if (vlapic->ops.intr_accepted)
1113 		return ((*vlapic->ops.intr_accepted)(vlapic, vector));
1114 
1115 	/*
1116 	 * clear the ready bit for vector being accepted in irr
1117 	 * and set the vector as in service in isr.
1118 	 */
1119 	idx = (vector / 32) * 4;
1120 
1121 	irrptr = &lapic->irr0;
1122 	atomic_clear_int(&irrptr[idx], 1 << (vector % 32));
1123 	VLAPIC_CTR_IRR(vlapic, "vlapic_intr_accepted");
1124 
1125 	isrptr = &lapic->isr0;
1126 	isrptr[idx] |= 1 << (vector % 32);
1127 	VLAPIC_CTR_ISR(vlapic, "vlapic_intr_accepted");
1128 
1129 	/*
1130 	 * Update the PPR
1131 	 */
1132 	vlapic->isrvec_stk_top++;
1133 
1134 	stk_top = vlapic->isrvec_stk_top;
1135 	if (stk_top >= ISRVEC_STK_SIZE)
1136 		panic("isrvec_stk_top overflow %d", stk_top);
1137 
1138 	vlapic->isrvec_stk[stk_top] = vector;
1139 	vlapic_update_ppr(vlapic);
1140 }
1141 
1142 void
1143 vlapic_svr_write_handler(struct vlapic *vlapic)
1144 {
1145 	struct LAPIC *lapic;
1146 	uint32_t old, new, changed;
1147 
1148 	lapic = vlapic->apic_page;
1149 
1150 	new = lapic->svr;
1151 	old = vlapic->svr_last;
1152 	vlapic->svr_last = new;
1153 
1154 	changed = old ^ new;
1155 	if ((changed & APIC_SVR_ENABLE) != 0) {
1156 		if ((new & APIC_SVR_ENABLE) == 0) {
1157 			/*
1158 			 * The apic is now disabled so stop the apic timer
1159 			 * and mask all the LVT entries.
1160 			 */
1161 			VLAPIC_CTR0(vlapic, "vlapic is software-disabled");
1162 			VLAPIC_TIMER_LOCK(vlapic);
1163 			callout_stop(&vlapic->callout);
1164 			VLAPIC_TIMER_UNLOCK(vlapic);
1165 			vlapic_mask_lvts(vlapic);
1166 		} else {
1167 			/*
1168 			 * The apic is now enabled so restart the apic timer
1169 			 * if it is configured in periodic mode.
1170 			 */
1171 			VLAPIC_CTR0(vlapic, "vlapic is software-enabled");
1172 			if (vlapic_periodic_timer(vlapic))
1173 				vlapic_icrtmr_write_handler(vlapic);
1174 		}
1175 	}
1176 }
1177 
1178 int
1179 vlapic_read(struct vlapic *vlapic, int mmio_access, uint64_t offset,
1180     uint64_t *data, bool *retu)
1181 {
1182 	struct LAPIC	*lapic = vlapic->apic_page;
1183 	uint32_t	*reg;
1184 	int		 i;
1185 
1186 	/* Ignore MMIO accesses in x2APIC mode */
1187 	if (x2apic(vlapic) && mmio_access) {
1188 		VLAPIC_CTR1(vlapic, "MMIO read from offset %#lx in x2APIC mode",
1189 		    offset);
1190 		*data = 0;
1191 		goto done;
1192 	}
1193 
1194 	if (!x2apic(vlapic) && !mmio_access) {
1195 		/*
1196 		 * XXX Generate GP fault for MSR accesses in xAPIC mode
1197 		 */
1198 		VLAPIC_CTR1(vlapic, "x2APIC MSR read from offset %#lx in "
1199 		    "xAPIC mode", offset);
1200 		*data = 0;
1201 		goto done;
1202 	}
1203 
1204 	if (offset > sizeof(*lapic)) {
1205 		*data = 0;
1206 		goto done;
1207 	}
1208 
1209 	offset &= ~3;
1210 	switch(offset)
1211 	{
1212 		case APIC_OFFSET_ID:
1213 			*data = lapic->id;
1214 			break;
1215 		case APIC_OFFSET_VER:
1216 			*data = lapic->version;
1217 			break;
1218 		case APIC_OFFSET_TPR:
1219 			*data = vlapic_get_tpr(vlapic);
1220 			break;
1221 		case APIC_OFFSET_APR:
1222 			*data = lapic->apr;
1223 			break;
1224 		case APIC_OFFSET_PPR:
1225 			*data = lapic->ppr;
1226 			break;
1227 		case APIC_OFFSET_EOI:
1228 			*data = lapic->eoi;
1229 			break;
1230 		case APIC_OFFSET_LDR:
1231 			*data = lapic->ldr;
1232 			break;
1233 		case APIC_OFFSET_DFR:
1234 			*data = lapic->dfr;
1235 			break;
1236 		case APIC_OFFSET_SVR:
1237 			*data = lapic->svr;
1238 			break;
1239 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1240 			i = (offset - APIC_OFFSET_ISR0) >> 2;
1241 			reg = &lapic->isr0;
1242 			*data = *(reg + i);
1243 			break;
1244 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1245 			i = (offset - APIC_OFFSET_TMR0) >> 2;
1246 			reg = &lapic->tmr0;
1247 			*data = *(reg + i);
1248 			break;
1249 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1250 			i = (offset - APIC_OFFSET_IRR0) >> 2;
1251 			reg = &lapic->irr0;
1252 			*data = atomic_load_acq_int(reg + i);
1253 			break;
1254 		case APIC_OFFSET_ESR:
1255 			*data = lapic->esr;
1256 			break;
1257 		case APIC_OFFSET_ICR_LOW:
1258 			*data = lapic->icr_lo;
1259 			if (x2apic(vlapic))
1260 				*data |= (uint64_t)lapic->icr_hi << 32;
1261 			break;
1262 		case APIC_OFFSET_ICR_HI:
1263 			*data = lapic->icr_hi;
1264 			break;
1265 		case APIC_OFFSET_CMCI_LVT:
1266 		case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1267 			*data = vlapic_get_lvt(vlapic, offset);
1268 #ifdef INVARIANTS
1269 			reg = vlapic_get_lvtptr(vlapic, offset);
1270 			KASSERT(*data == *reg, ("inconsistent lvt value at "
1271 			    "offset %#lx: %#lx/%#x", offset, *data, *reg));
1272 #endif
1273 			break;
1274 		case APIC_OFFSET_TIMER_ICR:
1275 			*data = lapic->icr_timer;
1276 			break;
1277 		case APIC_OFFSET_TIMER_CCR:
1278 			*data = vlapic_get_ccr(vlapic);
1279 			break;
1280 		case APIC_OFFSET_TIMER_DCR:
1281 			*data = lapic->dcr_timer;
1282 			break;
1283 		case APIC_OFFSET_SELF_IPI:
1284 			/*
1285 			 * XXX generate a GP fault if vlapic is in x2apic mode
1286 			 */
1287 			*data = 0;
1288 			break;
1289 		case APIC_OFFSET_RRR:
1290 		default:
1291 			*data = 0;
1292 			break;
1293 	}
1294 done:
1295 	VLAPIC_CTR2(vlapic, "vlapic read offset %#x, data %#lx", offset, *data);
1296 	return 0;
1297 }
1298 
1299 int
1300 vlapic_write(struct vlapic *vlapic, int mmio_access, uint64_t offset,
1301     uint64_t data, bool *retu)
1302 {
1303 	struct LAPIC	*lapic = vlapic->apic_page;
1304 	uint32_t	*regptr;
1305 	int		retval;
1306 
1307 	KASSERT((offset & 0xf) == 0 && offset < PAGE_SIZE,
1308 	    ("vlapic_write: invalid offset %#lx", offset));
1309 
1310 	VLAPIC_CTR2(vlapic, "vlapic write offset %#lx, data %#lx",
1311 	    offset, data);
1312 
1313 	if (offset > sizeof(*lapic))
1314 		return (0);
1315 
1316 	/* Ignore MMIO accesses in x2APIC mode */
1317 	if (x2apic(vlapic) && mmio_access) {
1318 		VLAPIC_CTR2(vlapic, "MMIO write of %#lx to offset %#lx "
1319 		    "in x2APIC mode", data, offset);
1320 		return (0);
1321 	}
1322 
1323 	/*
1324 	 * XXX Generate GP fault for MSR accesses in xAPIC mode
1325 	 */
1326 	if (!x2apic(vlapic) && !mmio_access) {
1327 		VLAPIC_CTR2(vlapic, "x2APIC MSR write of %#lx to offset %#lx "
1328 		    "in xAPIC mode", data, offset);
1329 		return (0);
1330 	}
1331 
1332 	retval = 0;
1333 	switch(offset)
1334 	{
1335 		case APIC_OFFSET_ID:
1336 			lapic->id = data;
1337 			vlapic_id_write_handler(vlapic);
1338 			break;
1339 		case APIC_OFFSET_TPR:
1340 			vlapic_set_tpr(vlapic, data & 0xff);
1341 			break;
1342 		case APIC_OFFSET_EOI:
1343 			vlapic_process_eoi(vlapic);
1344 			break;
1345 		case APIC_OFFSET_LDR:
1346 			lapic->ldr = data;
1347 			vlapic_ldr_write_handler(vlapic);
1348 			break;
1349 		case APIC_OFFSET_DFR:
1350 			lapic->dfr = data;
1351 			vlapic_dfr_write_handler(vlapic);
1352 			break;
1353 		case APIC_OFFSET_SVR:
1354 			lapic->svr = data;
1355 			vlapic_svr_write_handler(vlapic);
1356 			break;
1357 		case APIC_OFFSET_ICR_LOW:
1358 			lapic->icr_lo = data;
1359 			if (x2apic(vlapic))
1360 				lapic->icr_hi = data >> 32;
1361 			retval = vlapic_icrlo_write_handler(vlapic, retu);
1362 			break;
1363 		case APIC_OFFSET_ICR_HI:
1364 			lapic->icr_hi = data;
1365 			break;
1366 		case APIC_OFFSET_CMCI_LVT:
1367 		case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1368 			regptr = vlapic_get_lvtptr(vlapic, offset);
1369 			*regptr = data;
1370 			vlapic_lvt_write_handler(vlapic, offset);
1371 			break;
1372 		case APIC_OFFSET_TIMER_ICR:
1373 			lapic->icr_timer = data;
1374 			vlapic_icrtmr_write_handler(vlapic);
1375 			break;
1376 
1377 		case APIC_OFFSET_TIMER_DCR:
1378 			lapic->dcr_timer = data;
1379 			vlapic_dcr_write_handler(vlapic);
1380 			break;
1381 
1382 		case APIC_OFFSET_ESR:
1383 			vlapic_esr_write_handler(vlapic);
1384 			break;
1385 
1386 		case APIC_OFFSET_SELF_IPI:
1387 			if (x2apic(vlapic))
1388 				vlapic_self_ipi_handler(vlapic, data);
1389 			break;
1390 
1391 		case APIC_OFFSET_VER:
1392 		case APIC_OFFSET_APR:
1393 		case APIC_OFFSET_PPR:
1394 		case APIC_OFFSET_RRR:
1395 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1396 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1397 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1398 		case APIC_OFFSET_TIMER_CCR:
1399 		default:
1400 			// Read only.
1401 			break;
1402 	}
1403 
1404 	return (retval);
1405 }
1406 
1407 static void
1408 vlapic_reset(struct vlapic *vlapic)
1409 {
1410 	struct LAPIC *lapic;
1411 
1412 	lapic = vlapic->apic_page;
1413 	bzero(lapic, sizeof(struct LAPIC));
1414 
1415 	lapic->id = vlapic_get_id(vlapic);
1416 	lapic->version = VLAPIC_VERSION;
1417 	lapic->version |= (VLAPIC_MAXLVT_INDEX << MAXLVTSHIFT);
1418 	lapic->dfr = 0xffffffff;
1419 	lapic->svr = APIC_SVR_VECTOR;
1420 	vlapic_mask_lvts(vlapic);
1421 	vlapic_reset_tmr(vlapic);
1422 
1423 	lapic->dcr_timer = 0;
1424 	vlapic_dcr_write_handler(vlapic);
1425 
1426 	if (vlapic->vcpuid == 0)
1427 		vlapic->boot_state = BS_RUNNING;	/* BSP */
1428 	else
1429 		vlapic->boot_state = BS_INIT;		/* AP */
1430 
1431 	vlapic->svr_last = lapic->svr;
1432 }
1433 
1434 void
1435 vlapic_init(struct vlapic *vlapic)
1436 {
1437 	KASSERT(vlapic->vm != NULL, ("vlapic_init: vm is not initialized"));
1438 	KASSERT(vlapic->vcpuid >= 0 &&
1439 	    vlapic->vcpuid < vm_get_maxcpus(vlapic->vm),
1440 	    ("vlapic_init: vcpuid is not initialized"));
1441 	KASSERT(vlapic->apic_page != NULL, ("vlapic_init: apic_page is not "
1442 	    "initialized"));
1443 
1444 	/*
1445 	 * If the vlapic is configured in x2apic mode then it will be
1446 	 * accessed in the critical section via the MSR emulation code.
1447 	 *
1448 	 * Therefore the timer mutex must be a spinlock because blockable
1449 	 * mutexes cannot be acquired in a critical section.
1450 	 */
1451 	mtx_init(&vlapic->timer_mtx, "vlapic timer mtx", NULL, MTX_SPIN);
1452 	callout_init(&vlapic->callout, 1);
1453 
1454 	vlapic->msr_apicbase = DEFAULT_APIC_BASE | APICBASE_ENABLED;
1455 
1456 	if (vlapic->vcpuid == 0)
1457 		vlapic->msr_apicbase |= APICBASE_BSP;
1458 
1459 	vlapic_reset(vlapic);
1460 }
1461 
1462 void
1463 vlapic_cleanup(struct vlapic *vlapic)
1464 {
1465 
1466 	callout_drain(&vlapic->callout);
1467 }
1468 
1469 uint64_t
1470 vlapic_get_apicbase(struct vlapic *vlapic)
1471 {
1472 
1473 	return (vlapic->msr_apicbase);
1474 }
1475 
1476 int
1477 vlapic_set_apicbase(struct vlapic *vlapic, uint64_t new)
1478 {
1479 
1480 	if (vlapic->msr_apicbase != new) {
1481 		VLAPIC_CTR2(vlapic, "Changing APIC_BASE MSR from %#lx to %#lx "
1482 		    "not supported", vlapic->msr_apicbase, new);
1483 		return (-1);
1484 	}
1485 
1486 	return (0);
1487 }
1488 
1489 void
1490 vlapic_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1491 {
1492 	struct vlapic *vlapic;
1493 	struct LAPIC *lapic;
1494 
1495 	vlapic = vm_lapic(vm, vcpuid);
1496 
1497 	if (state == X2APIC_DISABLED)
1498 		vlapic->msr_apicbase &= ~APICBASE_X2APIC;
1499 	else
1500 		vlapic->msr_apicbase |= APICBASE_X2APIC;
1501 
1502 	/*
1503 	 * Reset the local APIC registers whose values are mode-dependent.
1504 	 *
1505 	 * XXX this works because the APIC mode can be changed only at vcpu
1506 	 * initialization time.
1507 	 */
1508 	lapic = vlapic->apic_page;
1509 	lapic->id = vlapic_get_id(vlapic);
1510 	if (x2apic(vlapic)) {
1511 		lapic->ldr = x2apic_ldr(vlapic);
1512 		lapic->dfr = 0;
1513 	} else {
1514 		lapic->ldr = 0;
1515 		lapic->dfr = 0xffffffff;
1516 	}
1517 
1518 	if (state == X2APIC_ENABLED) {
1519 		if (vlapic->ops.enable_x2apic_mode)
1520 			(*vlapic->ops.enable_x2apic_mode)(vlapic);
1521 	}
1522 }
1523 
1524 void
1525 vlapic_deliver_intr(struct vm *vm, bool level, uint32_t dest, bool phys,
1526     int delmode, int vec)
1527 {
1528 	bool lowprio;
1529 	int vcpuid;
1530 	cpuset_t dmask;
1531 
1532 	if (delmode != IOART_DELFIXED &&
1533 	    delmode != IOART_DELLOPRI &&
1534 	    delmode != IOART_DELEXINT) {
1535 		VM_CTR1(vm, "vlapic intr invalid delmode %#x", delmode);
1536 		return;
1537 	}
1538 	lowprio = (delmode == IOART_DELLOPRI);
1539 
1540 	/*
1541 	 * We don't provide any virtual interrupt redirection hardware so
1542 	 * all interrupts originating from the ioapic or MSI specify the
1543 	 * 'dest' in the legacy xAPIC format.
1544 	 */
1545 	vlapic_calcdest(vm, &dmask, dest, phys, lowprio, false);
1546 
1547 	while ((vcpuid = CPU_FFS(&dmask)) != 0) {
1548 		vcpuid--;
1549 		CPU_CLR(vcpuid, &dmask);
1550 		if (delmode == IOART_DELEXINT) {
1551 			vm_inject_extint(vm, vcpuid);
1552 		} else {
1553 			lapic_set_intr(vm, vcpuid, vec, level);
1554 		}
1555 	}
1556 }
1557 
1558 void
1559 vlapic_post_intr(struct vlapic *vlapic, int hostcpu, int ipinum)
1560 {
1561 	/*
1562 	 * Post an interrupt to the vcpu currently running on 'hostcpu'.
1563 	 *
1564 	 * This is done by leveraging features like Posted Interrupts (Intel)
1565 	 * Doorbell MSR (AMD AVIC) that avoid a VM exit.
1566 	 *
1567 	 * If neither of these features are available then fallback to
1568 	 * sending an IPI to 'hostcpu'.
1569 	 */
1570 	if (vlapic->ops.post_intr)
1571 		(*vlapic->ops.post_intr)(vlapic, hostcpu);
1572 	else
1573 		ipi_cpu(hostcpu, ipinum);
1574 }
1575 
1576 bool
1577 vlapic_enabled(struct vlapic *vlapic)
1578 {
1579 	struct LAPIC *lapic = vlapic->apic_page;
1580 
1581 	if ((vlapic->msr_apicbase & APICBASE_ENABLED) != 0 &&
1582 	    (lapic->svr & APIC_SVR_ENABLE) != 0)
1583 		return (true);
1584 	else
1585 		return (false);
1586 }
1587 
1588 static void
1589 vlapic_set_tmr(struct vlapic *vlapic, int vector, bool level)
1590 {
1591 	struct LAPIC *lapic;
1592 	uint32_t *tmrptr, mask;
1593 	int idx;
1594 
1595 	lapic = vlapic->apic_page;
1596 	tmrptr = &lapic->tmr0;
1597 	idx = (vector / 32) * 4;
1598 	mask = 1 << (vector % 32);
1599 	if (level)
1600 		tmrptr[idx] |= mask;
1601 	else
1602 		tmrptr[idx] &= ~mask;
1603 
1604 	if (vlapic->ops.set_tmr != NULL)
1605 		(*vlapic->ops.set_tmr)(vlapic, vector, level);
1606 }
1607 
1608 void
1609 vlapic_reset_tmr(struct vlapic *vlapic)
1610 {
1611 	int vector;
1612 
1613 	VLAPIC_CTR0(vlapic, "vlapic resetting all vectors to edge-triggered");
1614 
1615 	for (vector = 0; vector <= 255; vector++)
1616 		vlapic_set_tmr(vlapic, vector, false);
1617 }
1618 
1619 void
1620 vlapic_set_tmr_level(struct vlapic *vlapic, uint32_t dest, bool phys,
1621     int delmode, int vector)
1622 {
1623 	cpuset_t dmask;
1624 	bool lowprio;
1625 
1626 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
1627 
1628 	/*
1629 	 * A level trigger is valid only for fixed and lowprio delivery modes.
1630 	 */
1631 	if (delmode != APIC_DELMODE_FIXED && delmode != APIC_DELMODE_LOWPRIO) {
1632 		VLAPIC_CTR1(vlapic, "Ignoring level trigger-mode for "
1633 		    "delivery-mode %d", delmode);
1634 		return;
1635 	}
1636 
1637 	lowprio = (delmode == APIC_DELMODE_LOWPRIO);
1638 	vlapic_calcdest(vlapic->vm, &dmask, dest, phys, lowprio, false);
1639 
1640 	if (!CPU_ISSET(vlapic->vcpuid, &dmask))
1641 		return;
1642 
1643 	VLAPIC_CTR1(vlapic, "vector %d set to level-triggered", vector);
1644 	vlapic_set_tmr(vlapic, vector, true);
1645 }
1646