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