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