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