xref: /freebsd/sys/amd64/vmm/amd/svm.c (revision b37f6c9805edb4b89f0a8c2b78f78a3dcfc0647b)
1 /*-
2  * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
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$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/smp.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/pcpu.h>
36 #include <sys/proc.h>
37 #include <sys/sysctl.h>
38 
39 #include <vm/vm.h>
40 #include <vm/pmap.h>
41 
42 #include <machine/cpufunc.h>
43 #include <machine/psl.h>
44 #include <machine/md_var.h>
45 #include <machine/specialreg.h>
46 #include <machine/smp.h>
47 #include <machine/vmm.h>
48 #include <machine/vmm_dev.h>
49 #include <machine/vmm_instruction_emul.h>
50 
51 #include "vmm_lapic.h"
52 #include "vmm_stat.h"
53 #include "vmm_ktr.h"
54 #include "vmm_ioport.h"
55 #include "vatpic.h"
56 #include "vlapic.h"
57 #include "vlapic_priv.h"
58 
59 #include "x86.h"
60 #include "vmcb.h"
61 #include "svm.h"
62 #include "svm_softc.h"
63 #include "svm_msr.h"
64 #include "npt.h"
65 
66 SYSCTL_DECL(_hw_vmm);
67 SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
68 
69 /*
70  * SVM CPUID function 0x8000_000A, edx bit decoding.
71  */
72 #define AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
73 #define AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
74 #define AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
75 #define AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
76 #define AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
77 #define AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
78 #define AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
79 #define AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
80 #define AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
81 #define AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
82 #define	AMD_CPUID_SVM_AVIC		BIT(13)	/* AVIC present */
83 
84 #define	VMCB_CACHE_DEFAULT	(VMCB_CACHE_ASID 	|	\
85 				VMCB_CACHE_IOPM		|	\
86 				VMCB_CACHE_I		|	\
87 				VMCB_CACHE_TPR		|	\
88 				VMCB_CACHE_CR2		|	\
89 				VMCB_CACHE_CR		|	\
90 				VMCB_CACHE_DR		|	\
91 				VMCB_CACHE_DT		|	\
92 				VMCB_CACHE_SEG		|	\
93 				VMCB_CACHE_NP)
94 
95 static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
96 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
97     0, NULL);
98 
99 static MALLOC_DEFINE(M_SVM, "svm", "svm");
100 static MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
101 
102 /* Per-CPU context area. */
103 extern struct pcpu __pcpu[];
104 
105 static uint32_t svm_feature = ~0U;	/* AMD SVM features. */
106 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RDTUN, &svm_feature, 0,
107     "SVM features advertised by CPUID.8000000AH:EDX");
108 
109 static int disable_npf_assist;
110 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
111     &disable_npf_assist, 0, NULL);
112 
113 /* Maximum ASIDs supported by the processor */
114 static uint32_t nasid;
115 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RDTUN, &nasid, 0,
116     "Number of ASIDs supported by this processor");
117 
118 /* Current ASID generation for each host cpu */
119 static struct asid asid[MAXCPU];
120 
121 /*
122  * SVM host state saved area of size 4KB for each core.
123  */
124 static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
125 
126 static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
127 static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
128 static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
129 
130 static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
131 
132 static __inline int
133 flush_by_asid(void)
134 {
135 
136 	return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
137 }
138 
139 static __inline int
140 decode_assist(void)
141 {
142 
143 	return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
144 }
145 
146 static void
147 svm_disable(void *arg __unused)
148 {
149 	uint64_t efer;
150 
151 	efer = rdmsr(MSR_EFER);
152 	efer &= ~EFER_SVM;
153 	wrmsr(MSR_EFER, efer);
154 }
155 
156 /*
157  * Disable SVM on all CPUs.
158  */
159 static int
160 svm_cleanup(void)
161 {
162 
163 	smp_rendezvous(NULL, svm_disable, NULL, NULL);
164 	return (0);
165 }
166 
167 /*
168  * Verify that all the features required by bhyve are available.
169  */
170 static int
171 check_svm_features(void)
172 {
173 	u_int regs[4];
174 
175 	/* CPUID Fn8000_000A is for SVM */
176 	do_cpuid(0x8000000A, regs);
177 	svm_feature &= regs[3];
178 
179 	/*
180 	 * The number of ASIDs can be configured to be less than what is
181 	 * supported by the hardware but not more.
182 	 */
183 	if (nasid == 0 || nasid > regs[1])
184 		nasid = regs[1];
185 	KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
186 
187 	/* bhyve requires the Nested Paging feature */
188 	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
189 		printf("SVM: Nested Paging feature not available.\n");
190 		return (ENXIO);
191 	}
192 
193 	/* bhyve requires the NRIP Save feature */
194 	if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
195 		printf("SVM: NRIP Save feature not available.\n");
196 		return (ENXIO);
197 	}
198 
199 	return (0);
200 }
201 
202 static void
203 svm_enable(void *arg __unused)
204 {
205 	uint64_t efer;
206 
207 	efer = rdmsr(MSR_EFER);
208 	efer |= EFER_SVM;
209 	wrmsr(MSR_EFER, efer);
210 
211 	wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
212 }
213 
214 /*
215  * Return 1 if SVM is enabled on this processor and 0 otherwise.
216  */
217 static int
218 svm_available(void)
219 {
220 	uint64_t msr;
221 
222 	/* Section 15.4 Enabling SVM from APM2. */
223 	if ((amd_feature2 & AMDID2_SVM) == 0) {
224 		printf("SVM: not available.\n");
225 		return (0);
226 	}
227 
228 	msr = rdmsr(MSR_VM_CR);
229 	if ((msr & VM_CR_SVMDIS) != 0) {
230 		printf("SVM: disabled by BIOS.\n");
231 		return (0);
232 	}
233 
234 	return (1);
235 }
236 
237 static int
238 svm_init(int ipinum)
239 {
240 	int error, cpu;
241 
242 	if (!svm_available())
243 		return (ENXIO);
244 
245 	error = check_svm_features();
246 	if (error)
247 		return (error);
248 
249 	vmcb_clean &= VMCB_CACHE_DEFAULT;
250 
251 	for (cpu = 0; cpu < MAXCPU; cpu++) {
252 		/*
253 		 * Initialize the host ASIDs to their "highest" valid values.
254 		 *
255 		 * The next ASID allocation will rollover both 'gen' and 'num'
256 		 * and start off the sequence at {1,1}.
257 		 */
258 		asid[cpu].gen = ~0UL;
259 		asid[cpu].num = nasid - 1;
260 	}
261 
262 	svm_msr_init();
263 	svm_npt_init(ipinum);
264 
265 	/* Enable SVM on all CPUs */
266 	smp_rendezvous(NULL, svm_enable, NULL, NULL);
267 
268 	return (0);
269 }
270 
271 static void
272 svm_restore(void)
273 {
274 
275 	svm_enable(NULL);
276 }
277 
278 /* Pentium compatible MSRs */
279 #define MSR_PENTIUM_START 	0
280 #define MSR_PENTIUM_END 	0x1FFF
281 /* AMD 6th generation and Intel compatible MSRs */
282 #define MSR_AMD6TH_START 	0xC0000000UL
283 #define MSR_AMD6TH_END 		0xC0001FFFUL
284 /* AMD 7th and 8th generation compatible MSRs */
285 #define MSR_AMD7TH_START 	0xC0010000UL
286 #define MSR_AMD7TH_END 		0xC0011FFFUL
287 
288 /*
289  * Get the index and bit position for a MSR in permission bitmap.
290  * Two bits are used for each MSR: lower bit for read and higher bit for write.
291  */
292 static int
293 svm_msr_index(uint64_t msr, int *index, int *bit)
294 {
295 	uint32_t base, off;
296 
297 	*index = -1;
298 	*bit = (msr % 4) * 2;
299 	base = 0;
300 
301 	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
302 		*index = msr / 4;
303 		return (0);
304 	}
305 
306 	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
307 	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
308 		off = (msr - MSR_AMD6TH_START);
309 		*index = (off + base) / 4;
310 		return (0);
311 	}
312 
313 	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
314 	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
315 		off = (msr - MSR_AMD7TH_START);
316 		*index = (off + base) / 4;
317 		return (0);
318 	}
319 
320 	return (EINVAL);
321 }
322 
323 /*
324  * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
325  */
326 static void
327 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
328 {
329 	int index, bit, error;
330 
331 	error = svm_msr_index(msr, &index, &bit);
332 	KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
333 	KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
334 	    ("%s: invalid index %d for msr %#lx", __func__, index, msr));
335 	KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
336 	    "msr %#lx", __func__, bit, msr));
337 
338 	if (read)
339 		perm_bitmap[index] &= ~(1UL << bit);
340 
341 	if (write)
342 		perm_bitmap[index] &= ~(2UL << bit);
343 }
344 
345 static void
346 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
347 {
348 
349 	svm_msr_perm(perm_bitmap, msr, true, true);
350 }
351 
352 static void
353 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
354 {
355 
356 	svm_msr_perm(perm_bitmap, msr, true, false);
357 }
358 
359 static __inline int
360 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
361 {
362 	struct vmcb_ctrl *ctrl;
363 
364 	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
365 
366 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
367 	return (ctrl->intercept[idx] & bitmask ? 1 : 0);
368 }
369 
370 static __inline void
371 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
372     int enabled)
373 {
374 	struct vmcb_ctrl *ctrl;
375 	uint32_t oldval;
376 
377 	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
378 
379 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
380 	oldval = ctrl->intercept[idx];
381 
382 	if (enabled)
383 		ctrl->intercept[idx] |= bitmask;
384 	else
385 		ctrl->intercept[idx] &= ~bitmask;
386 
387 	if (ctrl->intercept[idx] != oldval) {
388 		svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
389 		VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
390 		    "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
391 	}
392 }
393 
394 static __inline void
395 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
396 {
397 
398 	svm_set_intercept(sc, vcpu, off, bitmask, 0);
399 }
400 
401 static __inline void
402 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
403 {
404 
405 	svm_set_intercept(sc, vcpu, off, bitmask, 1);
406 }
407 
408 static void
409 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
410     uint64_t msrpm_base_pa, uint64_t np_pml4)
411 {
412 	struct vmcb_ctrl *ctrl;
413 	struct vmcb_state *state;
414 	uint32_t mask;
415 	int n;
416 
417 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
418 	state = svm_get_vmcb_state(sc, vcpu);
419 
420 	ctrl->iopm_base_pa = iopm_base_pa;
421 	ctrl->msrpm_base_pa = msrpm_base_pa;
422 
423 	/* Enable nested paging */
424 	ctrl->np_enable = 1;
425 	ctrl->n_cr3 = np_pml4;
426 
427 	/*
428 	 * Intercept accesses to the control registers that are not shadowed
429 	 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
430 	 */
431 	for (n = 0; n < 16; n++) {
432 		mask = (BIT(n) << 16) | BIT(n);
433 		if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
434 			svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
435 		else
436 			svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
437 	}
438 
439 
440 	/*
441 	 * Intercept everything when tracing guest exceptions otherwise
442 	 * just intercept machine check exception.
443 	 */
444 	if (vcpu_trace_exceptions(sc->vm, vcpu)) {
445 		for (n = 0; n < 32; n++) {
446 			/*
447 			 * Skip unimplemented vectors in the exception bitmap.
448 			 */
449 			if (n == 2 || n == 9) {
450 				continue;
451 			}
452 			svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
453 		}
454 	} else {
455 		svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
456 	}
457 
458 	/* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
459 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
460 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
461 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
462 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
463 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
464 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
465 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
466 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
467 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
468 	    VMCB_INTCPT_FERR_FREEZE);
469 
470 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
471 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
472 
473 	/*
474 	 * From section "Canonicalization and Consistency Checks" in APMv2
475 	 * the VMRUN intercept bit must be set to pass the consistency check.
476 	 */
477 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
478 
479 	/*
480 	 * The ASID will be set to a non-zero value just before VMRUN.
481 	 */
482 	ctrl->asid = 0;
483 
484 	/*
485 	 * Section 15.21.1, Interrupt Masking in EFLAGS
486 	 * Section 15.21.2, Virtualizing APIC.TPR
487 	 *
488 	 * This must be set for %rflag and %cr8 isolation of guest and host.
489 	 */
490 	ctrl->v_intr_masking = 1;
491 
492 	/* Enable Last Branch Record aka LBR for debugging */
493 	ctrl->lbr_virt_en = 1;
494 	state->dbgctl = BIT(0);
495 
496 	/* EFER_SVM must always be set when the guest is executing */
497 	state->efer = EFER_SVM;
498 
499 	/* Set up the PAT to power-on state */
500 	state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK)	|
501 	    PAT_VALUE(1, PAT_WRITE_THROUGH)	|
502 	    PAT_VALUE(2, PAT_UNCACHED)		|
503 	    PAT_VALUE(3, PAT_UNCACHEABLE)	|
504 	    PAT_VALUE(4, PAT_WRITE_BACK)	|
505 	    PAT_VALUE(5, PAT_WRITE_THROUGH)	|
506 	    PAT_VALUE(6, PAT_UNCACHED)		|
507 	    PAT_VALUE(7, PAT_UNCACHEABLE);
508 
509 	/* Set up DR6/7 to power-on state */
510 	state->dr6 = 0xffff0ff0;
511 	state->dr7 = 0x400;
512 }
513 
514 /*
515  * Initialize a virtual machine.
516  */
517 static void *
518 svm_vminit(struct vm *vm, pmap_t pmap)
519 {
520 	struct svm_softc *svm_sc;
521 	struct svm_vcpu *vcpu;
522 	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
523 	int i;
524 
525 	svm_sc = malloc(sizeof (*svm_sc), M_SVM, M_WAITOK | M_ZERO);
526 	if (((uintptr_t)svm_sc & PAGE_MASK) != 0)
527 		panic("malloc of svm_softc not aligned on page boundary");
528 
529 	svm_sc->msr_bitmap = contigmalloc(SVM_MSR_BITMAP_SIZE, M_SVM,
530 	    M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
531 	if (svm_sc->msr_bitmap == NULL)
532 		panic("contigmalloc of SVM MSR bitmap failed");
533 	svm_sc->iopm_bitmap = contigmalloc(SVM_IO_BITMAP_SIZE, M_SVM,
534 	    M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
535 	if (svm_sc->iopm_bitmap == NULL)
536 		panic("contigmalloc of SVM IO bitmap failed");
537 
538 	svm_sc->vm = vm;
539 	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
540 
541 	/*
542 	 * Intercept read and write accesses to all MSRs.
543 	 */
544 	memset(svm_sc->msr_bitmap, 0xFF, SVM_MSR_BITMAP_SIZE);
545 
546 	/*
547 	 * Access to the following MSRs is redirected to the VMCB when the
548 	 * guest is executing. Therefore it is safe to allow the guest to
549 	 * read/write these MSRs directly without hypervisor involvement.
550 	 */
551 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
552 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
553 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
554 
555 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
556 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
557 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
558 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
559 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
560 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
561 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
562 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
563 
564 	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
565 
566 	/*
567 	 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
568 	 */
569 	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
570 
571 	/* Intercept access to all I/O ports. */
572 	memset(svm_sc->iopm_bitmap, 0xFF, SVM_IO_BITMAP_SIZE);
573 
574 	iopm_pa = vtophys(svm_sc->iopm_bitmap);
575 	msrpm_pa = vtophys(svm_sc->msr_bitmap);
576 	pml4_pa = svm_sc->nptp;
577 	for (i = 0; i < VM_MAXCPU; i++) {
578 		vcpu = svm_get_vcpu(svm_sc, i);
579 		vcpu->nextrip = ~0;
580 		vcpu->lastcpu = NOCPU;
581 		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
582 		vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
583 		svm_msr_guest_init(svm_sc, i);
584 	}
585 	return (svm_sc);
586 }
587 
588 /*
589  * Collateral for a generic SVM VM-exit.
590  */
591 static void
592 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
593 {
594 
595 	vme->exitcode = VM_EXITCODE_SVM;
596 	vme->u.svm.exitcode = code;
597 	vme->u.svm.exitinfo1 = info1;
598 	vme->u.svm.exitinfo2 = info2;
599 }
600 
601 static int
602 svm_cpl(struct vmcb_state *state)
603 {
604 
605 	/*
606 	 * From APMv2:
607 	 *   "Retrieve the CPL from the CPL field in the VMCB, not
608 	 *    from any segment DPL"
609 	 */
610 	return (state->cpl);
611 }
612 
613 static enum vm_cpu_mode
614 svm_vcpu_mode(struct vmcb *vmcb)
615 {
616 	struct vmcb_segment seg;
617 	struct vmcb_state *state;
618 	int error;
619 
620 	state = &vmcb->state;
621 
622 	if (state->efer & EFER_LMA) {
623 		error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
624 		KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
625 		    error));
626 
627 		/*
628 		 * Section 4.8.1 for APM2, check if Code Segment has
629 		 * Long attribute set in descriptor.
630 		 */
631 		if (seg.attrib & VMCB_CS_ATTRIB_L)
632 			return (CPU_MODE_64BIT);
633 		else
634 			return (CPU_MODE_COMPATIBILITY);
635 	} else  if (state->cr0 & CR0_PE) {
636 		return (CPU_MODE_PROTECTED);
637 	} else {
638 		return (CPU_MODE_REAL);
639 	}
640 }
641 
642 static enum vm_paging_mode
643 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
644 {
645 
646 	if ((cr0 & CR0_PG) == 0)
647 		return (PAGING_MODE_FLAT);
648 	if ((cr4 & CR4_PAE) == 0)
649 		return (PAGING_MODE_32);
650 	if (efer & EFER_LME)
651 		return (PAGING_MODE_64);
652 	else
653 		return (PAGING_MODE_PAE);
654 }
655 
656 /*
657  * ins/outs utility routines
658  */
659 static uint64_t
660 svm_inout_str_index(struct svm_regctx *regs, int in)
661 {
662 	uint64_t val;
663 
664 	val = in ? regs->sctx_rdi : regs->sctx_rsi;
665 
666 	return (val);
667 }
668 
669 static uint64_t
670 svm_inout_str_count(struct svm_regctx *regs, int rep)
671 {
672 	uint64_t val;
673 
674 	val = rep ? regs->sctx_rcx : 1;
675 
676 	return (val);
677 }
678 
679 static void
680 svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
681     int in, struct vm_inout_str *vis)
682 {
683 	int error, s;
684 
685 	if (in) {
686 		vis->seg_name = VM_REG_GUEST_ES;
687 	} else {
688 		/* The segment field has standard encoding */
689 		s = (info1 >> 10) & 0x7;
690 		vis->seg_name = vm_segment_name(s);
691 	}
692 
693 	error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
694 	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
695 }
696 
697 static int
698 svm_inout_str_addrsize(uint64_t info1)
699 {
700         uint32_t size;
701 
702         size = (info1 >> 7) & 0x7;
703         switch (size) {
704         case 1:
705                 return (2);     /* 16 bit */
706         case 2:
707                 return (4);     /* 32 bit */
708         case 4:
709                 return (8);     /* 64 bit */
710         default:
711                 panic("%s: invalid size encoding %d", __func__, size);
712         }
713 }
714 
715 static void
716 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
717 {
718 	struct vmcb_state *state;
719 
720 	state = &vmcb->state;
721 	paging->cr3 = state->cr3;
722 	paging->cpl = svm_cpl(state);
723 	paging->cpu_mode = svm_vcpu_mode(vmcb);
724 	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
725 	    state->efer);
726 }
727 
728 #define	UNHANDLED 0
729 
730 /*
731  * Handle guest I/O intercept.
732  */
733 static int
734 svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
735 {
736 	struct vmcb_ctrl *ctrl;
737 	struct vmcb_state *state;
738 	struct svm_regctx *regs;
739 	struct vm_inout_str *vis;
740 	uint64_t info1;
741 	int inout_string;
742 
743 	state = svm_get_vmcb_state(svm_sc, vcpu);
744 	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
745 	regs  = svm_get_guest_regctx(svm_sc, vcpu);
746 
747 	info1 = ctrl->exitinfo1;
748 	inout_string = info1 & BIT(2) ? 1 : 0;
749 
750 	/*
751 	 * The effective segment number in EXITINFO1[12:10] is populated
752 	 * only if the processor has the DecodeAssist capability.
753 	 *
754 	 * XXX this is not specified explicitly in APMv2 but can be verified
755 	 * empirically.
756 	 */
757 	if (inout_string && !decode_assist())
758 		return (UNHANDLED);
759 
760 	vmexit->exitcode 	= VM_EXITCODE_INOUT;
761 	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
762 	vmexit->u.inout.string 	= inout_string;
763 	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
764 	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
765 	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
766 	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
767 
768 	if (inout_string) {
769 		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
770 		vis = &vmexit->u.inout_str;
771 		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
772 		vis->rflags = state->rflags;
773 		vis->cr0 = state->cr0;
774 		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
775 		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
776 		vis->addrsize = svm_inout_str_addrsize(info1);
777 		svm_inout_str_seginfo(svm_sc, vcpu, info1,
778 		    vmexit->u.inout.in, vis);
779 	}
780 
781 	return (UNHANDLED);
782 }
783 
784 static int
785 npf_fault_type(uint64_t exitinfo1)
786 {
787 
788 	if (exitinfo1 & VMCB_NPF_INFO1_W)
789 		return (VM_PROT_WRITE);
790 	else if (exitinfo1 & VMCB_NPF_INFO1_ID)
791 		return (VM_PROT_EXECUTE);
792 	else
793 		return (VM_PROT_READ);
794 }
795 
796 static bool
797 svm_npf_emul_fault(uint64_t exitinfo1)
798 {
799 
800 	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
801 		return (false);
802 	}
803 
804 	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
805 		return (false);
806 	}
807 
808 	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
809 		return (false);
810 	}
811 
812 	return (true);
813 }
814 
815 static void
816 svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
817 {
818 	struct vm_guest_paging *paging;
819 	struct vmcb_segment seg;
820 	struct vmcb_ctrl *ctrl;
821 	char *inst_bytes;
822 	int error, inst_len;
823 
824 	ctrl = &vmcb->ctrl;
825 	paging = &vmexit->u.inst_emul.paging;
826 
827 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
828 	vmexit->u.inst_emul.gpa = gpa;
829 	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
830 	svm_paging_info(vmcb, paging);
831 
832 	error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
833 	KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
834 
835 	switch(paging->cpu_mode) {
836 	case CPU_MODE_REAL:
837 		vmexit->u.inst_emul.cs_base = seg.base;
838 		vmexit->u.inst_emul.cs_d = 0;
839 		break;
840 	case CPU_MODE_PROTECTED:
841 	case CPU_MODE_COMPATIBILITY:
842 		vmexit->u.inst_emul.cs_base = seg.base;
843 
844 		/*
845 		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
846 		 */
847 		vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
848 		    1 : 0;
849 		break;
850 	default:
851 		vmexit->u.inst_emul.cs_base = 0;
852 		vmexit->u.inst_emul.cs_d = 0;
853 		break;
854 	}
855 
856 	/*
857 	 * Copy the instruction bytes into 'vie' if available.
858 	 */
859 	if (decode_assist() && !disable_npf_assist) {
860 		inst_len = ctrl->inst_len;
861 		inst_bytes = ctrl->inst_bytes;
862 	} else {
863 		inst_len = 0;
864 		inst_bytes = NULL;
865 	}
866 	vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
867 }
868 
869 #ifdef KTR
870 static const char *
871 intrtype_to_str(int intr_type)
872 {
873 	switch (intr_type) {
874 	case VMCB_EVENTINJ_TYPE_INTR:
875 		return ("hwintr");
876 	case VMCB_EVENTINJ_TYPE_NMI:
877 		return ("nmi");
878 	case VMCB_EVENTINJ_TYPE_INTn:
879 		return ("swintr");
880 	case VMCB_EVENTINJ_TYPE_EXCEPTION:
881 		return ("exception");
882 	default:
883 		panic("%s: unknown intr_type %d", __func__, intr_type);
884 	}
885 }
886 #endif
887 
888 /*
889  * Inject an event to vcpu as described in section 15.20, "Event injection".
890  */
891 static void
892 svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
893 		 uint32_t error, bool ec_valid)
894 {
895 	struct vmcb_ctrl *ctrl;
896 
897 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
898 
899 	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
900 	    ("%s: event already pending %#lx", __func__, ctrl->eventinj));
901 
902 	KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
903 	    __func__, vector));
904 
905 	switch (intr_type) {
906 	case VMCB_EVENTINJ_TYPE_INTR:
907 	case VMCB_EVENTINJ_TYPE_NMI:
908 	case VMCB_EVENTINJ_TYPE_INTn:
909 		break;
910 	case VMCB_EVENTINJ_TYPE_EXCEPTION:
911 		if (vector >= 0 && vector <= 31 && vector != 2)
912 			break;
913 		/* FALLTHROUGH */
914 	default:
915 		panic("%s: invalid intr_type/vector: %d/%d", __func__,
916 		    intr_type, vector);
917 	}
918 	ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
919 	if (ec_valid) {
920 		ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
921 		ctrl->eventinj |= (uint64_t)error << 32;
922 		VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
923 		    intrtype_to_str(intr_type), vector, error);
924 	} else {
925 		VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
926 		    intrtype_to_str(intr_type), vector);
927 	}
928 }
929 
930 static void
931 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
932 {
933 	struct vm *vm;
934 	struct vlapic *vlapic;
935 	struct vmcb_ctrl *ctrl;
936 	int pending;
937 
938 	vm = sc->vm;
939 	vlapic = vm_lapic(vm, vcpu);
940 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
941 
942 	/* Update %cr8 in the emulated vlapic */
943 	vlapic_set_cr8(vlapic, ctrl->v_tpr);
944 
945 	/*
946 	 * If V_IRQ indicates that the interrupt injection attempted on then
947 	 * last VMRUN was successful then update the vlapic accordingly.
948 	 */
949 	if (ctrl->v_intr_vector != 0) {
950 		pending = ctrl->v_irq;
951 		KASSERT(ctrl->v_intr_vector >= 16, ("%s: invalid "
952 		    "v_intr_vector %d", __func__, ctrl->v_intr_vector));
953 		KASSERT(!ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
954 		VCPU_CTR2(vm, vcpu, "v_intr_vector %d %s", ctrl->v_intr_vector,
955 		    pending ? "pending" : "accepted");
956 		if (!pending)
957 			vlapic_intr_accepted(vlapic, ctrl->v_intr_vector);
958 	}
959 }
960 
961 static void
962 svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
963 {
964 	struct vmcb_ctrl *ctrl;
965 	uint64_t intinfo;
966 
967 	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
968 	intinfo = ctrl->exitintinfo;
969 	if (!VMCB_EXITINTINFO_VALID(intinfo))
970 		return;
971 
972 	/*
973 	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
974 	 *
975 	 * If a #VMEXIT happened during event delivery then record the event
976 	 * that was being delivered.
977 	 */
978 	VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
979 		intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
980 	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
981 	vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
982 }
983 
984 static __inline int
985 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
986 {
987 
988 	return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
989 	    VMCB_INTCPT_VINTR));
990 }
991 
992 static __inline void
993 enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
994 {
995 	struct vmcb_ctrl *ctrl;
996 
997 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
998 
999 	if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
1000 		KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
1001 		KASSERT(vintr_intercept_enabled(sc, vcpu),
1002 		    ("%s: vintr intercept should be enabled", __func__));
1003 		return;
1004 	}
1005 
1006 	VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
1007 	ctrl->v_irq = 1;
1008 	ctrl->v_ign_tpr = 1;
1009 	ctrl->v_intr_vector = 0;
1010 	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1011 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1012 }
1013 
1014 static __inline void
1015 disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
1016 {
1017 	struct vmcb_ctrl *ctrl;
1018 
1019 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1020 
1021 	if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
1022 		KASSERT(!vintr_intercept_enabled(sc, vcpu),
1023 		    ("%s: vintr intercept should be disabled", __func__));
1024 		return;
1025 	}
1026 
1027 #ifdef KTR
1028 	if (ctrl->v_intr_vector == 0)
1029 		VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
1030 	else
1031 		VCPU_CTR0(sc->vm, vcpu, "Clearing V_IRQ interrupt injection");
1032 #endif
1033 	ctrl->v_irq = 0;
1034 	ctrl->v_intr_vector = 0;
1035 	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1036 	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1037 }
1038 
1039 static int
1040 svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1041 {
1042 	struct vmcb_ctrl *ctrl;
1043 	int oldval, newval;
1044 
1045 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1046 	oldval = ctrl->intr_shadow;
1047 	newval = val ? 1 : 0;
1048 	if (newval != oldval) {
1049 		ctrl->intr_shadow = newval;
1050 		VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1051 	}
1052 	return (0);
1053 }
1054 
1055 static int
1056 svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1057 {
1058 	struct vmcb_ctrl *ctrl;
1059 
1060 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1061 	*val = ctrl->intr_shadow;
1062 	return (0);
1063 }
1064 
1065 /*
1066  * Once an NMI is injected it blocks delivery of further NMIs until the handler
1067  * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1068  * to track when the vcpu is done handling the NMI.
1069  */
1070 static int
1071 nmi_blocked(struct svm_softc *sc, int vcpu)
1072 {
1073 	int blocked;
1074 
1075 	blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1076 	    VMCB_INTCPT_IRET);
1077 	return (blocked);
1078 }
1079 
1080 static void
1081 enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1082 {
1083 
1084 	KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1085 	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1086 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1087 }
1088 
1089 static void
1090 clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1091 {
1092 	int error;
1093 
1094 	KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1095 	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1096 	/*
1097 	 * When the IRET intercept is cleared the vcpu will attempt to execute
1098 	 * the "iret" when it runs next. However, it is possible to inject
1099 	 * another NMI into the vcpu before the "iret" has actually executed.
1100 	 *
1101 	 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1102 	 * it will trap back into the hypervisor. If an NMI is pending for
1103 	 * the vcpu it will be injected into the guest.
1104 	 *
1105 	 * XXX this needs to be fixed
1106 	 */
1107 	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1108 
1109 	/*
1110 	 * Set 'intr_shadow' to prevent an NMI from being injected on the
1111 	 * immediate VMRUN.
1112 	 */
1113 	error = svm_modify_intr_shadow(sc, vcpu, 1);
1114 	KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1115 }
1116 
1117 #define	EFER_MBZ_BITS	0xFFFFFFFFFFFF0200UL
1118 
1119 static int
1120 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval, bool *retu)
1121 {
1122 	struct vm_exit *vme;
1123 	struct vmcb_state *state;
1124 	uint64_t changed, lma, oldval;
1125 	int error;
1126 
1127 	state = svm_get_vmcb_state(sc, vcpu);
1128 
1129 	oldval = state->efer;
1130 	VCPU_CTR2(sc->vm, vcpu, "wrmsr(efer) %#lx/%#lx", oldval, newval);
1131 
1132 	newval &= ~0xFE;		/* clear the Read-As-Zero (RAZ) bits */
1133 	changed = oldval ^ newval;
1134 
1135 	if (newval & EFER_MBZ_BITS)
1136 		goto gpf;
1137 
1138 	/* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1139 	if (changed & EFER_LME) {
1140 		if (state->cr0 & CR0_PG)
1141 			goto gpf;
1142 	}
1143 
1144 	/* EFER.LMA = EFER.LME & CR0.PG */
1145 	if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0)
1146 		lma = EFER_LMA;
1147 	else
1148 		lma = 0;
1149 
1150 	if ((newval & EFER_LMA) != lma)
1151 		goto gpf;
1152 
1153 	if (newval & EFER_NXE) {
1154 		if (!vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE))
1155 			goto gpf;
1156 	}
1157 
1158 	/*
1159 	 * XXX bhyve does not enforce segment limits in 64-bit mode. Until
1160 	 * this is fixed flag guest attempt to set EFER_LMSLE as an error.
1161 	 */
1162 	if (newval & EFER_LMSLE) {
1163 		vme = vm_exitinfo(sc->vm, vcpu);
1164 		vm_exit_svm(vme, VMCB_EXIT_MSR, 1, 0);
1165 		*retu = true;
1166 		return (0);
1167 	}
1168 
1169 	if (newval & EFER_FFXSR) {
1170 		if (!vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR))
1171 			goto gpf;
1172 	}
1173 
1174 	if (newval & EFER_TCE) {
1175 		if (!vm_cpuid_capability(sc->vm, vcpu, VCC_TCE))
1176 			goto gpf;
1177 	}
1178 
1179 	error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1180 	KASSERT(error == 0, ("%s: error %d updating efer", __func__, error));
1181 	return (0);
1182 gpf:
1183 	vm_inject_gp(sc->vm, vcpu);
1184 	return (0);
1185 }
1186 
1187 static int
1188 emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1189     bool *retu)
1190 {
1191 	int error;
1192 
1193 	if (lapic_msr(num))
1194 		error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1195 	else if (num == MSR_EFER)
1196 		error = svm_write_efer(sc, vcpu, val, retu);
1197 	else
1198 		error = svm_wrmsr(sc, vcpu, num, val, retu);
1199 
1200 	return (error);
1201 }
1202 
1203 static int
1204 emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1205 {
1206 	struct vmcb_state *state;
1207 	struct svm_regctx *ctx;
1208 	uint64_t result;
1209 	int error;
1210 
1211 	if (lapic_msr(num))
1212 		error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1213 	else
1214 		error = svm_rdmsr(sc, vcpu, num, &result, retu);
1215 
1216 	if (error == 0) {
1217 		state = svm_get_vmcb_state(sc, vcpu);
1218 		ctx = svm_get_guest_regctx(sc, vcpu);
1219 		state->rax = result & 0xffffffff;
1220 		ctx->sctx_rdx = result >> 32;
1221 	}
1222 
1223 	return (error);
1224 }
1225 
1226 #ifdef KTR
1227 static const char *
1228 exit_reason_to_str(uint64_t reason)
1229 {
1230 	static char reasonbuf[32];
1231 
1232 	switch (reason) {
1233 	case VMCB_EXIT_INVALID:
1234 		return ("invalvmcb");
1235 	case VMCB_EXIT_SHUTDOWN:
1236 		return ("shutdown");
1237 	case VMCB_EXIT_NPF:
1238 		return ("nptfault");
1239 	case VMCB_EXIT_PAUSE:
1240 		return ("pause");
1241 	case VMCB_EXIT_HLT:
1242 		return ("hlt");
1243 	case VMCB_EXIT_CPUID:
1244 		return ("cpuid");
1245 	case VMCB_EXIT_IO:
1246 		return ("inout");
1247 	case VMCB_EXIT_MC:
1248 		return ("mchk");
1249 	case VMCB_EXIT_INTR:
1250 		return ("extintr");
1251 	case VMCB_EXIT_NMI:
1252 		return ("nmi");
1253 	case VMCB_EXIT_VINTR:
1254 		return ("vintr");
1255 	case VMCB_EXIT_MSR:
1256 		return ("msr");
1257 	case VMCB_EXIT_IRET:
1258 		return ("iret");
1259 	case VMCB_EXIT_MONITOR:
1260 		return ("monitor");
1261 	case VMCB_EXIT_MWAIT:
1262 		return ("mwait");
1263 	default:
1264 		snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1265 		return (reasonbuf);
1266 	}
1267 }
1268 #endif	/* KTR */
1269 
1270 /*
1271  * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1272  * that are due to instruction intercepts as well as MSR and IOIO intercepts
1273  * and exceptions caused by INT3, INTO and BOUND instructions.
1274  *
1275  * Return 1 if the nRIP is valid and 0 otherwise.
1276  */
1277 static int
1278 nrip_valid(uint64_t exitcode)
1279 {
1280 	switch (exitcode) {
1281 	case 0x00 ... 0x0F:	/* read of CR0 through CR15 */
1282 	case 0x10 ... 0x1F:	/* write of CR0 through CR15 */
1283 	case 0x20 ... 0x2F:	/* read of DR0 through DR15 */
1284 	case 0x30 ... 0x3F:	/* write of DR0 through DR15 */
1285 	case 0x43:		/* INT3 */
1286 	case 0x44:		/* INTO */
1287 	case 0x45:		/* BOUND */
1288 	case 0x65 ... 0x7C:	/* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1289 	case 0x80 ... 0x8D:	/* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1290 		return (1);
1291 	default:
1292 		return (0);
1293 	}
1294 }
1295 
1296 static int
1297 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1298 {
1299 	struct vmcb *vmcb;
1300 	struct vmcb_state *state;
1301 	struct vmcb_ctrl *ctrl;
1302 	struct svm_regctx *ctx;
1303 	uint64_t code, info1, info2, val;
1304 	uint32_t eax, ecx, edx;
1305 	int error, errcode_valid, handled, idtvec, reflect;
1306 	bool retu;
1307 
1308 	ctx = svm_get_guest_regctx(svm_sc, vcpu);
1309 	vmcb = svm_get_vmcb(svm_sc, vcpu);
1310 	state = &vmcb->state;
1311 	ctrl = &vmcb->ctrl;
1312 
1313 	handled = 0;
1314 	code = ctrl->exitcode;
1315 	info1 = ctrl->exitinfo1;
1316 	info2 = ctrl->exitinfo2;
1317 
1318 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1319 	vmexit->rip = state->rip;
1320 	vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1321 
1322 	vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1323 
1324 	/*
1325 	 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1326 	 * in an inconsistent state and can trigger assertions that would
1327 	 * never happen otherwise.
1328 	 */
1329 	if (code == VMCB_EXIT_INVALID) {
1330 		vm_exit_svm(vmexit, code, info1, info2);
1331 		return (0);
1332 	}
1333 
1334 	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1335 	    "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1336 
1337 	KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1338 	    ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1339 	    vmexit->inst_length, code, info1, info2));
1340 
1341 	svm_update_virqinfo(svm_sc, vcpu);
1342 	svm_save_intinfo(svm_sc, vcpu);
1343 
1344 	switch (code) {
1345 	case VMCB_EXIT_IRET:
1346 		/*
1347 		 * Restart execution at "iret" but with the intercept cleared.
1348 		 */
1349 		vmexit->inst_length = 0;
1350 		clear_nmi_blocking(svm_sc, vcpu);
1351 		handled = 1;
1352 		break;
1353 	case VMCB_EXIT_VINTR:	/* interrupt window exiting */
1354 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1355 		handled = 1;
1356 		break;
1357 	case VMCB_EXIT_INTR:	/* external interrupt */
1358 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1359 		handled = 1;
1360 		break;
1361 	case VMCB_EXIT_NMI:	/* external NMI */
1362 		handled = 1;
1363 		break;
1364 	case 0x40 ... 0x5F:
1365 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1366 		reflect = 1;
1367 		idtvec = code - 0x40;
1368 		switch (idtvec) {
1369 		case IDT_MC:
1370 			/*
1371 			 * Call the machine check handler by hand. Also don't
1372 			 * reflect the machine check back into the guest.
1373 			 */
1374 			reflect = 0;
1375 			VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1376 			__asm __volatile("int $18");
1377 			break;
1378 		case IDT_PF:
1379 			error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1380 			    info2);
1381 			KASSERT(error == 0, ("%s: error %d updating cr2",
1382 			    __func__, error));
1383 			/* fallthru */
1384 		case IDT_NP:
1385 		case IDT_SS:
1386 		case IDT_GP:
1387 		case IDT_AC:
1388 		case IDT_TS:
1389 			errcode_valid = 1;
1390 			break;
1391 
1392 		case IDT_DF:
1393 			errcode_valid = 1;
1394 			info1 = 0;
1395 			break;
1396 
1397 		case IDT_BP:
1398 		case IDT_OF:
1399 		case IDT_BR:
1400 			/*
1401 			 * The 'nrip' field is populated for INT3, INTO and
1402 			 * BOUND exceptions and this also implies that
1403 			 * 'inst_length' is non-zero.
1404 			 *
1405 			 * Reset 'inst_length' to zero so the guest %rip at
1406 			 * event injection is identical to what it was when
1407 			 * the exception originally happened.
1408 			 */
1409 			VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1410 			    "to zero before injecting exception %d",
1411 			    vmexit->inst_length, idtvec);
1412 			vmexit->inst_length = 0;
1413 			/* fallthru */
1414 		default:
1415 			errcode_valid = 0;
1416 			info1 = 0;
1417 			break;
1418 		}
1419 		KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1420 		    "when reflecting exception %d into guest",
1421 		    vmexit->inst_length, idtvec));
1422 
1423 		if (reflect) {
1424 			/* Reflect the exception back into the guest */
1425 			VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1426 			    "%d/%#x into the guest", idtvec, (int)info1);
1427 			error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1428 			    errcode_valid, info1, 0);
1429 			KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1430 			    __func__, error));
1431 		}
1432 		handled = 1;
1433 		break;
1434 	case VMCB_EXIT_MSR:	/* MSR access. */
1435 		eax = state->rax;
1436 		ecx = ctx->sctx_rcx;
1437 		edx = ctx->sctx_rdx;
1438 		retu = false;
1439 
1440 		if (info1) {
1441 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1442 			val = (uint64_t)edx << 32 | eax;
1443 			VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1444 			    ecx, val);
1445 			if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1446 				vmexit->exitcode = VM_EXITCODE_WRMSR;
1447 				vmexit->u.msr.code = ecx;
1448 				vmexit->u.msr.wval = val;
1449 			} else if (!retu) {
1450 				handled = 1;
1451 			} else {
1452 				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1453 				    ("emulate_wrmsr retu with bogus exitcode"));
1454 			}
1455 		} else {
1456 			VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1457 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1458 			if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1459 				vmexit->exitcode = VM_EXITCODE_RDMSR;
1460 				vmexit->u.msr.code = ecx;
1461 			} else if (!retu) {
1462 				handled = 1;
1463 			} else {
1464 				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1465 				    ("emulate_rdmsr retu with bogus exitcode"));
1466 			}
1467 		}
1468 		break;
1469 	case VMCB_EXIT_IO:
1470 		handled = svm_handle_io(svm_sc, vcpu, vmexit);
1471 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1472 		break;
1473 	case VMCB_EXIT_CPUID:
1474 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1475 		handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1476 		    (uint32_t *)&state->rax,
1477 		    (uint32_t *)&ctx->sctx_rbx,
1478 		    (uint32_t *)&ctx->sctx_rcx,
1479 		    (uint32_t *)&ctx->sctx_rdx);
1480 		break;
1481 	case VMCB_EXIT_HLT:
1482 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1483 		vmexit->exitcode = VM_EXITCODE_HLT;
1484 		vmexit->u.hlt.rflags = state->rflags;
1485 		break;
1486 	case VMCB_EXIT_PAUSE:
1487 		vmexit->exitcode = VM_EXITCODE_PAUSE;
1488 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1489 		break;
1490 	case VMCB_EXIT_NPF:
1491 		/* EXITINFO2 contains the faulting guest physical address */
1492 		if (info1 & VMCB_NPF_INFO1_RSV) {
1493 			VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1494 			    "reserved bits set: info1(%#lx) info2(%#lx)",
1495 			    info1, info2);
1496 		} else if (vm_mem_allocated(svm_sc->vm, vcpu, info2)) {
1497 			vmexit->exitcode = VM_EXITCODE_PAGING;
1498 			vmexit->u.paging.gpa = info2;
1499 			vmexit->u.paging.fault_type = npf_fault_type(info1);
1500 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1501 			VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1502 			    "on gpa %#lx/%#lx at rip %#lx",
1503 			    info2, info1, state->rip);
1504 		} else if (svm_npf_emul_fault(info1)) {
1505 			svm_handle_inst_emul(vmcb, info2, vmexit);
1506 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1507 			VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1508 			    "for gpa %#lx/%#lx at rip %#lx",
1509 			    info2, info1, state->rip);
1510 		}
1511 		break;
1512 	case VMCB_EXIT_MONITOR:
1513 		vmexit->exitcode = VM_EXITCODE_MONITOR;
1514 		break;
1515 	case VMCB_EXIT_MWAIT:
1516 		vmexit->exitcode = VM_EXITCODE_MWAIT;
1517 		break;
1518 	default:
1519 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1520 		break;
1521 	}
1522 
1523 	VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1524 	    handled ? "handled" : "unhandled", exit_reason_to_str(code),
1525 	    vmexit->rip, vmexit->inst_length);
1526 
1527 	if (handled) {
1528 		vmexit->rip += vmexit->inst_length;
1529 		vmexit->inst_length = 0;
1530 		state->rip = vmexit->rip;
1531 	} else {
1532 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1533 			/*
1534 			 * If this VM exit was not claimed by anybody then
1535 			 * treat it as a generic SVM exit.
1536 			 */
1537 			vm_exit_svm(vmexit, code, info1, info2);
1538 		} else {
1539 			/*
1540 			 * The exitcode and collateral have been populated.
1541 			 * The VM exit will be processed further in userland.
1542 			 */
1543 		}
1544 	}
1545 	return (handled);
1546 }
1547 
1548 static void
1549 svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1550 {
1551 	uint64_t intinfo;
1552 
1553 	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1554 		return;
1555 
1556 	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1557 	    "valid: %#lx", __func__, intinfo));
1558 
1559 	svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1560 		VMCB_EXITINTINFO_VECTOR(intinfo),
1561 		VMCB_EXITINTINFO_EC(intinfo),
1562 		VMCB_EXITINTINFO_EC_VALID(intinfo));
1563 	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1564 	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1565 }
1566 
1567 /*
1568  * Inject event to virtual cpu.
1569  */
1570 static void
1571 svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1572 {
1573 	struct vmcb_ctrl *ctrl;
1574 	struct vmcb_state *state;
1575 	struct svm_vcpu *vcpustate;
1576 	uint8_t v_tpr;
1577 	int vector, need_intr_window, pending_apic_vector;
1578 
1579 	state = svm_get_vmcb_state(sc, vcpu);
1580 	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1581 	vcpustate = svm_get_vcpu(sc, vcpu);
1582 
1583 	need_intr_window = 0;
1584 	pending_apic_vector = 0;
1585 
1586 	if (vcpustate->nextrip != state->rip) {
1587 		ctrl->intr_shadow = 0;
1588 		VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1589 		    "cleared due to rip change: %#lx/%#lx",
1590 		    vcpustate->nextrip, state->rip);
1591 	}
1592 
1593 	/*
1594 	 * Inject pending events or exceptions for this vcpu.
1595 	 *
1596 	 * An event might be pending because the previous #VMEXIT happened
1597 	 * during event delivery (i.e. ctrl->exitintinfo).
1598 	 *
1599 	 * An event might also be pending because an exception was injected
1600 	 * by the hypervisor (e.g. #PF during instruction emulation).
1601 	 */
1602 	svm_inj_intinfo(sc, vcpu);
1603 
1604 	/* NMI event has priority over interrupts. */
1605 	if (vm_nmi_pending(sc->vm, vcpu)) {
1606 		if (nmi_blocked(sc, vcpu)) {
1607 			/*
1608 			 * Can't inject another NMI if the guest has not
1609 			 * yet executed an "iret" after the last NMI.
1610 			 */
1611 			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1612 			    "to NMI-blocking");
1613 		} else if (ctrl->intr_shadow) {
1614 			/*
1615 			 * Can't inject an NMI if the vcpu is in an intr_shadow.
1616 			 */
1617 			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1618 			    "interrupt shadow");
1619 			need_intr_window = 1;
1620 			goto done;
1621 		} else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1622 			/*
1623 			 * If there is already an exception/interrupt pending
1624 			 * then defer the NMI until after that.
1625 			 */
1626 			VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1627 			    "eventinj %#lx", ctrl->eventinj);
1628 
1629 			/*
1630 			 * Use self-IPI to trigger a VM-exit as soon as
1631 			 * possible after the event injection is completed.
1632 			 *
1633 			 * This works only if the external interrupt exiting
1634 			 * is at a lower priority than the event injection.
1635 			 *
1636 			 * Although not explicitly specified in APMv2 the
1637 			 * relative priorities were verified empirically.
1638 			 */
1639 			ipi_cpu(curcpu, IPI_AST);	/* XXX vmm_ipinum? */
1640 		} else {
1641 			vm_nmi_clear(sc->vm, vcpu);
1642 
1643 			/* Inject NMI, vector number is not used */
1644 			svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1645 			    IDT_NMI, 0, false);
1646 
1647 			/* virtual NMI blocking is now in effect */
1648 			enable_nmi_blocking(sc, vcpu);
1649 
1650 			VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1651 		}
1652 	}
1653 
1654 	if (!vm_extint_pending(sc->vm, vcpu)) {
1655 		/*
1656 		 * APIC interrupts are delivered using the V_IRQ offload.
1657 		 *
1658 		 * The primary benefit is that the hypervisor doesn't need to
1659 		 * deal with the various conditions that inhibit interrupts.
1660 		 * It also means that TPR changes via CR8 will be handled
1661 		 * without any hypervisor involvement.
1662 		 *
1663 		 * Note that the APIC vector must remain pending in the vIRR
1664 		 * until it is confirmed that it was delivered to the guest.
1665 		 * This can be confirmed based on the value of V_IRQ at the
1666 		 * next #VMEXIT (1 = pending, 0 = delivered).
1667 		 *
1668 		 * Also note that it is possible that another higher priority
1669 		 * vector can become pending before this vector is delivered
1670 		 * to the guest. This is alright because vcpu_notify_event()
1671 		 * will send an IPI and force the vcpu to trap back into the
1672 		 * hypervisor. The higher priority vector will be injected on
1673 		 * the next VMRUN.
1674 		 */
1675 		if (vlapic_pending_intr(vlapic, &vector)) {
1676 			KASSERT(vector >= 16 && vector <= 255,
1677 			    ("invalid vector %d from local APIC", vector));
1678 			pending_apic_vector = vector;
1679 		}
1680 		goto done;
1681 	}
1682 
1683 	/* Ask the legacy pic for a vector to inject */
1684 	vatpic_pending_intr(sc->vm, &vector);
1685 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d from INTR",
1686 	    vector));
1687 
1688 	/*
1689 	 * If the guest has disabled interrupts or is in an interrupt shadow
1690 	 * then we cannot inject the pending interrupt.
1691 	 */
1692 	if ((state->rflags & PSL_I) == 0) {
1693 		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1694 		    "rflags %#lx", vector, state->rflags);
1695 		need_intr_window = 1;
1696 		goto done;
1697 	}
1698 
1699 	if (ctrl->intr_shadow) {
1700 		VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1701 		    "interrupt shadow", vector);
1702 		need_intr_window = 1;
1703 		goto done;
1704 	}
1705 
1706 	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1707 		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1708 		    "eventinj %#lx", vector, ctrl->eventinj);
1709 		need_intr_window = 1;
1710 		goto done;
1711 	}
1712 
1713 	/*
1714 	 * Legacy PIC interrupts are delivered via the event injection
1715 	 * mechanism.
1716 	 */
1717 	svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1718 
1719 	vm_extint_clear(sc->vm, vcpu);
1720 	vatpic_intr_accepted(sc->vm, vector);
1721 
1722 	/*
1723 	 * Force a VM-exit as soon as the vcpu is ready to accept another
1724 	 * interrupt. This is done because the PIC might have another vector
1725 	 * that it wants to inject. Also, if the APIC has a pending interrupt
1726 	 * that was preempted by the ExtInt then it allows us to inject the
1727 	 * APIC vector as soon as possible.
1728 	 */
1729 	need_intr_window = 1;
1730 done:
1731 	/*
1732 	 * The guest can modify the TPR by writing to %CR8. In guest mode
1733 	 * the processor reflects this write to V_TPR without hypervisor
1734 	 * intervention.
1735 	 *
1736 	 * The guest can also modify the TPR by writing to it via the memory
1737 	 * mapped APIC page. In this case, the write will be emulated by the
1738 	 * hypervisor. For this reason V_TPR must be updated before every
1739 	 * VMRUN.
1740 	 */
1741 	v_tpr = vlapic_get_cr8(vlapic);
1742 	KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1743 	if (ctrl->v_tpr != v_tpr) {
1744 		VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1745 		    ctrl->v_tpr, v_tpr);
1746 		ctrl->v_tpr = v_tpr;
1747 		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1748 	}
1749 
1750 	if (pending_apic_vector) {
1751 		/*
1752 		 * If an APIC vector is being injected then interrupt window
1753 		 * exiting is not possible on this VMRUN.
1754 		 */
1755 		KASSERT(!need_intr_window, ("intr_window exiting impossible"));
1756 		VCPU_CTR1(sc->vm, vcpu, "Injecting vector %d using V_IRQ",
1757 		    pending_apic_vector);
1758 
1759 		ctrl->v_irq = 1;
1760 		ctrl->v_ign_tpr = 0;
1761 		ctrl->v_intr_vector = pending_apic_vector;
1762 		ctrl->v_intr_prio = pending_apic_vector >> 4;
1763 		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1764 	} else if (need_intr_window) {
1765 		/*
1766 		 * We use V_IRQ in conjunction with the VINTR intercept to
1767 		 * trap into the hypervisor as soon as a virtual interrupt
1768 		 * can be delivered.
1769 		 *
1770 		 * Since injected events are not subject to intercept checks
1771 		 * we need to ensure that the V_IRQ is not actually going to
1772 		 * be delivered on VM entry. The KASSERT below enforces this.
1773 		 */
1774 		KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1775 		    (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1776 		    ("Bogus intr_window_exiting: eventinj (%#lx), "
1777 		    "intr_shadow (%u), rflags (%#lx)",
1778 		    ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1779 		enable_intr_window_exiting(sc, vcpu);
1780 	} else {
1781 		disable_intr_window_exiting(sc, vcpu);
1782 	}
1783 }
1784 
1785 static __inline void
1786 restore_host_tss(void)
1787 {
1788 	struct system_segment_descriptor *tss_sd;
1789 
1790 	/*
1791 	 * The TSS descriptor was in use prior to launching the guest so it
1792 	 * has been marked busy.
1793 	 *
1794 	 * 'ltr' requires the descriptor to be marked available so change the
1795 	 * type to "64-bit available TSS".
1796 	 */
1797 	tss_sd = PCPU_GET(tss);
1798 	tss_sd->sd_type = SDT_SYSTSS;
1799 	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1800 }
1801 
1802 static void
1803 check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1804 {
1805 	struct svm_vcpu *vcpustate;
1806 	struct vmcb_ctrl *ctrl;
1807 	long eptgen;
1808 	bool alloc_asid;
1809 
1810 	KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1811 	    "active on cpu %u", __func__, thiscpu));
1812 
1813 	vcpustate = svm_get_vcpu(sc, vcpuid);
1814 	ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1815 
1816 	/*
1817 	 * The TLB entries associated with the vcpu's ASID are not valid
1818 	 * if either of the following conditions is true:
1819 	 *
1820 	 * 1. The vcpu's ASID generation is different than the host cpu's
1821 	 *    ASID generation. This happens when the vcpu migrates to a new
1822 	 *    host cpu. It can also happen when the number of vcpus executing
1823 	 *    on a host cpu is greater than the number of ASIDs available.
1824 	 *
1825 	 * 2. The pmap generation number is different than the value cached in
1826 	 *    the 'vcpustate'. This happens when the host invalidates pages
1827 	 *    belonging to the guest.
1828 	 *
1829 	 *	asidgen		eptgen	      Action
1830 	 *	mismatch	mismatch
1831 	 *	   0		   0		(a)
1832 	 *	   0		   1		(b1) or (b2)
1833 	 *	   1		   0		(c)
1834 	 *	   1		   1		(d)
1835 	 *
1836 	 * (a) There is no mismatch in eptgen or ASID generation and therefore
1837 	 *     no further action is needed.
1838 	 *
1839 	 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1840 	 *      retained and the TLB entries associated with this ASID
1841 	 *      are flushed by VMRUN.
1842 	 *
1843 	 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1844 	 *      allocated.
1845 	 *
1846 	 * (c) A new ASID is allocated.
1847 	 *
1848 	 * (d) A new ASID is allocated.
1849 	 */
1850 
1851 	alloc_asid = false;
1852 	eptgen = pmap->pm_eptgen;
1853 	ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1854 
1855 	if (vcpustate->asid.gen != asid[thiscpu].gen) {
1856 		alloc_asid = true;	/* (c) and (d) */
1857 	} else if (vcpustate->eptgen != eptgen) {
1858 		if (flush_by_asid())
1859 			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;	/* (b1) */
1860 		else
1861 			alloc_asid = true;			/* (b2) */
1862 	} else {
1863 		/*
1864 		 * This is the common case (a).
1865 		 */
1866 		KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1867 		KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1868 		    ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1869 	}
1870 
1871 	if (alloc_asid) {
1872 		if (++asid[thiscpu].num >= nasid) {
1873 			asid[thiscpu].num = 1;
1874 			if (++asid[thiscpu].gen == 0)
1875 				asid[thiscpu].gen = 1;
1876 			/*
1877 			 * If this cpu does not support "flush-by-asid"
1878 			 * then flush the entire TLB on a generation
1879 			 * bump. Subsequent ASID allocation in this
1880 			 * generation can be done without a TLB flush.
1881 			 */
1882 			if (!flush_by_asid())
1883 				ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1884 		}
1885 		vcpustate->asid.gen = asid[thiscpu].gen;
1886 		vcpustate->asid.num = asid[thiscpu].num;
1887 
1888 		ctrl->asid = vcpustate->asid.num;
1889 		svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1890 		/*
1891 		 * If this cpu supports "flush-by-asid" then the TLB
1892 		 * was not flushed after the generation bump. The TLB
1893 		 * is flushed selectively after every new ASID allocation.
1894 		 */
1895 		if (flush_by_asid())
1896 			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1897 	}
1898 	vcpustate->eptgen = eptgen;
1899 
1900 	KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1901 	KASSERT(ctrl->asid == vcpustate->asid.num,
1902 	    ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1903 }
1904 
1905 static __inline void
1906 disable_gintr(void)
1907 {
1908 
1909 	__asm __volatile("clgi");
1910 }
1911 
1912 static __inline void
1913 enable_gintr(void)
1914 {
1915 
1916         __asm __volatile("stgi");
1917 }
1918 
1919 static __inline void
1920 svm_dr_enter_guest(struct svm_regctx *gctx)
1921 {
1922 
1923 	/* Save host control debug registers. */
1924 	gctx->host_dr7 = rdr7();
1925 	gctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
1926 
1927 	/*
1928 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
1929 	 * exceptions in the host based on the guest DRx values.  The
1930 	 * guest DR6, DR7, and DEBUGCTL are saved/restored in the
1931 	 * VMCB.
1932 	 */
1933 	load_dr7(0);
1934 	wrmsr(MSR_DEBUGCTLMSR, 0);
1935 
1936 	/* Save host debug registers. */
1937 	gctx->host_dr0 = rdr0();
1938 	gctx->host_dr1 = rdr1();
1939 	gctx->host_dr2 = rdr2();
1940 	gctx->host_dr3 = rdr3();
1941 	gctx->host_dr6 = rdr6();
1942 
1943 	/* Restore guest debug registers. */
1944 	load_dr0(gctx->sctx_dr0);
1945 	load_dr1(gctx->sctx_dr1);
1946 	load_dr2(gctx->sctx_dr2);
1947 	load_dr3(gctx->sctx_dr3);
1948 }
1949 
1950 static __inline void
1951 svm_dr_leave_guest(struct svm_regctx *gctx)
1952 {
1953 
1954 	/* Save guest debug registers. */
1955 	gctx->sctx_dr0 = rdr0();
1956 	gctx->sctx_dr1 = rdr1();
1957 	gctx->sctx_dr2 = rdr2();
1958 	gctx->sctx_dr3 = rdr3();
1959 
1960 	/*
1961 	 * Restore host debug registers.  Restore DR7 and DEBUGCTL
1962 	 * last.
1963 	 */
1964 	load_dr0(gctx->host_dr0);
1965 	load_dr1(gctx->host_dr1);
1966 	load_dr2(gctx->host_dr2);
1967 	load_dr3(gctx->host_dr3);
1968 	load_dr6(gctx->host_dr6);
1969 	wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
1970 	load_dr7(gctx->host_dr7);
1971 }
1972 
1973 /*
1974  * Start vcpu with specified RIP.
1975  */
1976 static int
1977 svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1978 	struct vm_eventinfo *evinfo)
1979 {
1980 	struct svm_regctx *gctx;
1981 	struct svm_softc *svm_sc;
1982 	struct svm_vcpu *vcpustate;
1983 	struct vmcb_state *state;
1984 	struct vmcb_ctrl *ctrl;
1985 	struct vm_exit *vmexit;
1986 	struct vlapic *vlapic;
1987 	struct vm *vm;
1988 	uint64_t vmcb_pa;
1989 	int handled;
1990 
1991 	svm_sc = arg;
1992 	vm = svm_sc->vm;
1993 
1994 	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1995 	state = svm_get_vmcb_state(svm_sc, vcpu);
1996 	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1997 	vmexit = vm_exitinfo(vm, vcpu);
1998 	vlapic = vm_lapic(vm, vcpu);
1999 
2000 	gctx = svm_get_guest_regctx(svm_sc, vcpu);
2001 	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
2002 
2003 	if (vcpustate->lastcpu != curcpu) {
2004 		/*
2005 		 * Force new ASID allocation by invalidating the generation.
2006 		 */
2007 		vcpustate->asid.gen = 0;
2008 
2009 		/*
2010 		 * Invalidate the VMCB state cache by marking all fields dirty.
2011 		 */
2012 		svm_set_dirty(svm_sc, vcpu, 0xffffffff);
2013 
2014 		/*
2015 		 * XXX
2016 		 * Setting 'vcpustate->lastcpu' here is bit premature because
2017 		 * we may return from this function without actually executing
2018 		 * the VMRUN  instruction. This could happen if a rendezvous
2019 		 * or an AST is pending on the first time through the loop.
2020 		 *
2021 		 * This works for now but any new side-effects of vcpu
2022 		 * migration should take this case into account.
2023 		 */
2024 		vcpustate->lastcpu = curcpu;
2025 		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
2026 	}
2027 
2028 	svm_msr_guest_enter(svm_sc, vcpu);
2029 
2030 	/* Update Guest RIP */
2031 	state->rip = rip;
2032 
2033 	do {
2034 		/*
2035 		 * Disable global interrupts to guarantee atomicity during
2036 		 * loading of guest state. This includes not only the state
2037 		 * loaded by the "vmrun" instruction but also software state
2038 		 * maintained by the hypervisor: suspended and rendezvous
2039 		 * state, NPT generation number, vlapic interrupts etc.
2040 		 */
2041 		disable_gintr();
2042 
2043 		if (vcpu_suspended(evinfo)) {
2044 			enable_gintr();
2045 			vm_exit_suspended(vm, vcpu, state->rip);
2046 			break;
2047 		}
2048 
2049 		if (vcpu_rendezvous_pending(evinfo)) {
2050 			enable_gintr();
2051 			vm_exit_rendezvous(vm, vcpu, state->rip);
2052 			break;
2053 		}
2054 
2055 		if (vcpu_reqidle(evinfo)) {
2056 			enable_gintr();
2057 			vm_exit_reqidle(vm, vcpu, state->rip);
2058 			break;
2059 		}
2060 
2061 		/* We are asked to give the cpu by scheduler. */
2062 		if (vcpu_should_yield(vm, vcpu)) {
2063 			enable_gintr();
2064 			vm_exit_astpending(vm, vcpu, state->rip);
2065 			break;
2066 		}
2067 
2068 		svm_inj_interrupts(svm_sc, vcpu, vlapic);
2069 
2070 		/* Activate the nested pmap on 'curcpu' */
2071 		CPU_SET_ATOMIC_ACQ(curcpu, &pmap->pm_active);
2072 
2073 		/*
2074 		 * Check the pmap generation and the ASID generation to
2075 		 * ensure that the vcpu does not use stale TLB mappings.
2076 		 */
2077 		check_asid(svm_sc, vcpu, pmap, curcpu);
2078 
2079 		ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
2080 		vcpustate->dirty = 0;
2081 		VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
2082 
2083 		/* Launch Virtual Machine. */
2084 		VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
2085 		svm_dr_enter_guest(gctx);
2086 		svm_launch(vmcb_pa, gctx, &__pcpu[curcpu]);
2087 		svm_dr_leave_guest(gctx);
2088 
2089 		CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
2090 
2091 		/*
2092 		 * The host GDTR and IDTR is saved by VMRUN and restored
2093 		 * automatically on #VMEXIT. However, the host TSS needs
2094 		 * to be restored explicitly.
2095 		 */
2096 		restore_host_tss();
2097 
2098 		/* #VMEXIT disables interrupts so re-enable them here. */
2099 		enable_gintr();
2100 
2101 		/* Update 'nextrip' */
2102 		vcpustate->nextrip = state->rip;
2103 
2104 		/* Handle #VMEXIT and if required return to user space. */
2105 		handled = svm_vmexit(svm_sc, vcpu, vmexit);
2106 	} while (handled);
2107 
2108 	svm_msr_guest_exit(svm_sc, vcpu);
2109 
2110 	return (0);
2111 }
2112 
2113 static void
2114 svm_vmcleanup(void *arg)
2115 {
2116 	struct svm_softc *sc = arg;
2117 
2118 	contigfree(sc->iopm_bitmap, SVM_IO_BITMAP_SIZE, M_SVM);
2119 	contigfree(sc->msr_bitmap, SVM_MSR_BITMAP_SIZE, M_SVM);
2120 	free(sc, M_SVM);
2121 }
2122 
2123 static register_t *
2124 swctx_regptr(struct svm_regctx *regctx, int reg)
2125 {
2126 
2127 	switch (reg) {
2128 	case VM_REG_GUEST_RBX:
2129 		return (&regctx->sctx_rbx);
2130 	case VM_REG_GUEST_RCX:
2131 		return (&regctx->sctx_rcx);
2132 	case VM_REG_GUEST_RDX:
2133 		return (&regctx->sctx_rdx);
2134 	case VM_REG_GUEST_RDI:
2135 		return (&regctx->sctx_rdi);
2136 	case VM_REG_GUEST_RSI:
2137 		return (&regctx->sctx_rsi);
2138 	case VM_REG_GUEST_RBP:
2139 		return (&regctx->sctx_rbp);
2140 	case VM_REG_GUEST_R8:
2141 		return (&regctx->sctx_r8);
2142 	case VM_REG_GUEST_R9:
2143 		return (&regctx->sctx_r9);
2144 	case VM_REG_GUEST_R10:
2145 		return (&regctx->sctx_r10);
2146 	case VM_REG_GUEST_R11:
2147 		return (&regctx->sctx_r11);
2148 	case VM_REG_GUEST_R12:
2149 		return (&regctx->sctx_r12);
2150 	case VM_REG_GUEST_R13:
2151 		return (&regctx->sctx_r13);
2152 	case VM_REG_GUEST_R14:
2153 		return (&regctx->sctx_r14);
2154 	case VM_REG_GUEST_R15:
2155 		return (&regctx->sctx_r15);
2156 	case VM_REG_GUEST_DR0:
2157 		return (&regctx->sctx_dr0);
2158 	case VM_REG_GUEST_DR1:
2159 		return (&regctx->sctx_dr1);
2160 	case VM_REG_GUEST_DR2:
2161 		return (&regctx->sctx_dr2);
2162 	case VM_REG_GUEST_DR3:
2163 		return (&regctx->sctx_dr3);
2164 	default:
2165 		return (NULL);
2166 	}
2167 }
2168 
2169 static int
2170 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2171 {
2172 	struct svm_softc *svm_sc;
2173 	register_t *reg;
2174 
2175 	svm_sc = arg;
2176 
2177 	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2178 		return (svm_get_intr_shadow(svm_sc, vcpu, val));
2179 	}
2180 
2181 	if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2182 		return (0);
2183 	}
2184 
2185 	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2186 
2187 	if (reg != NULL) {
2188 		*val = *reg;
2189 		return (0);
2190 	}
2191 
2192 	VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2193 	return (EINVAL);
2194 }
2195 
2196 static int
2197 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2198 {
2199 	struct svm_softc *svm_sc;
2200 	register_t *reg;
2201 
2202 	svm_sc = arg;
2203 
2204 	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2205 		return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2206 	}
2207 
2208 	if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2209 		return (0);
2210 	}
2211 
2212 	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2213 
2214 	if (reg != NULL) {
2215 		*reg = val;
2216 		return (0);
2217 	}
2218 
2219 	/*
2220 	 * XXX deal with CR3 and invalidate TLB entries tagged with the
2221 	 * vcpu's ASID. This needs to be treated differently depending on
2222 	 * whether 'running' is true/false.
2223 	 */
2224 
2225 	VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2226 	return (EINVAL);
2227 }
2228 
2229 static int
2230 svm_setcap(void *arg, int vcpu, int type, int val)
2231 {
2232 	struct svm_softc *sc;
2233 	int error;
2234 
2235 	sc = arg;
2236 	error = 0;
2237 	switch (type) {
2238 	case VM_CAP_HALT_EXIT:
2239 		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2240 		    VMCB_INTCPT_HLT, val);
2241 		break;
2242 	case VM_CAP_PAUSE_EXIT:
2243 		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2244 		    VMCB_INTCPT_PAUSE, val);
2245 		break;
2246 	case VM_CAP_UNRESTRICTED_GUEST:
2247 		/* Unrestricted guest execution cannot be disabled in SVM */
2248 		if (val == 0)
2249 			error = EINVAL;
2250 		break;
2251 	default:
2252 		error = ENOENT;
2253 		break;
2254 	}
2255 	return (error);
2256 }
2257 
2258 static int
2259 svm_getcap(void *arg, int vcpu, int type, int *retval)
2260 {
2261 	struct svm_softc *sc;
2262 	int error;
2263 
2264 	sc = arg;
2265 	error = 0;
2266 
2267 	switch (type) {
2268 	case VM_CAP_HALT_EXIT:
2269 		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2270 		    VMCB_INTCPT_HLT);
2271 		break;
2272 	case VM_CAP_PAUSE_EXIT:
2273 		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2274 		    VMCB_INTCPT_PAUSE);
2275 		break;
2276 	case VM_CAP_UNRESTRICTED_GUEST:
2277 		*retval = 1;	/* unrestricted guest is always enabled */
2278 		break;
2279 	default:
2280 		error = ENOENT;
2281 		break;
2282 	}
2283 	return (error);
2284 }
2285 
2286 static struct vlapic *
2287 svm_vlapic_init(void *arg, int vcpuid)
2288 {
2289 	struct svm_softc *svm_sc;
2290 	struct vlapic *vlapic;
2291 
2292 	svm_sc = arg;
2293 	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2294 	vlapic->vm = svm_sc->vm;
2295 	vlapic->vcpuid = vcpuid;
2296 	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2297 
2298 	vlapic_init(vlapic);
2299 
2300 	return (vlapic);
2301 }
2302 
2303 static void
2304 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2305 {
2306 
2307         vlapic_cleanup(vlapic);
2308         free(vlapic, M_SVM_VLAPIC);
2309 }
2310 
2311 struct vmm_ops vmm_ops_amd = {
2312 	svm_init,
2313 	svm_cleanup,
2314 	svm_restore,
2315 	svm_vminit,
2316 	svm_vmrun,
2317 	svm_vmcleanup,
2318 	svm_getreg,
2319 	svm_setreg,
2320 	vmcb_getdesc,
2321 	vmcb_setdesc,
2322 	svm_getcap,
2323 	svm_setcap,
2324 	svm_npt_alloc,
2325 	svm_npt_free,
2326 	svm_vlapic_init,
2327 	svm_vlapic_cleanup
2328 };
2329