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