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