xref: /illumos-gate/usr/src/uts/intel/io/vmm/amd/svm.c (revision a4955f4fa65e38d70c07d38e657a9aff43fa155f)
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 /*
30  * This file and its contents are supplied under the terms of the
31  * Common Development and Distribution License ("CDDL"), version 1.0.
32  * You may only use this file in accordance with the terms of version
33  * 1.0 of the CDDL.
34  *
35  * A full copy of the text of the CDDL should have accompanied this
36  * source.  A copy of the CDDL is also available via the Internet at
37  * http://www.illumos.org/license/CDDL.
38  *
39  * Copyright 2018 Joyent, Inc.
40  * Copyright 2022 Oxide Computer Company
41  */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/kmem.h>
50 #include <sys/pcpu.h>
51 #include <sys/proc.h>
52 #include <sys/sysctl.h>
53 
54 #include <sys/x86_archext.h>
55 #include <sys/trap.h>
56 
57 #include <machine/cpufunc.h>
58 #include <machine/psl.h>
59 #include <machine/md_var.h>
60 #include <machine/reg.h>
61 #include <machine/specialreg.h>
62 #include <machine/vmm.h>
63 #include <machine/vmm_dev.h>
64 #include <sys/vmm_instruction_emul.h>
65 #include <sys/vmm_vm.h>
66 #include <sys/vmm_kernel.h>
67 
68 #include "vmm_lapic.h"
69 #include "vmm_stat.h"
70 #include "vmm_ioport.h"
71 #include "vatpic.h"
72 #include "vlapic.h"
73 #include "vlapic_priv.h"
74 
75 #include "vmcb.h"
76 #include "svm.h"
77 #include "svm_softc.h"
78 #include "svm_msr.h"
79 
80 SYSCTL_DECL(_hw_vmm);
81 SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
82     NULL);
83 
84 /*
85  * SVM CPUID function 0x8000_000A, edx bit decoding.
86  */
87 #define	AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
88 #define	AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
89 #define	AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
90 #define	AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
91 #define	AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
92 #define	AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
93 #define	AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
94 #define	AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
95 #define	AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
96 #define	AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
97 #define	AMD_CPUID_SVM_AVIC		BIT(13)	/* AVIC present */
98 
99 #define	VMCB_CACHE_DEFAULT	(VMCB_CACHE_ASID	|	\
100 				VMCB_CACHE_IOPM		|	\
101 				VMCB_CACHE_I		|	\
102 				VMCB_CACHE_TPR		|	\
103 				VMCB_CACHE_CR2		|	\
104 				VMCB_CACHE_CR		|	\
105 				VMCB_CACHE_DR		|	\
106 				VMCB_CACHE_DT		|	\
107 				VMCB_CACHE_SEG		|	\
108 				VMCB_CACHE_NP)
109 
110 static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
111 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
112     0, NULL);
113 
114 /* SVM features advertised by CPUID.8000000AH:EDX */
115 static uint32_t svm_feature = ~0U;	/* AMD SVM features. */
116 
117 static int disable_npf_assist;
118 
119 static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
120 static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
121 static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
122 
123 static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
124 static int svm_getreg(void *arg, int vcpu, int ident, uint64_t *val);
125 static void flush_asid(struct svm_softc *sc, int vcpuid);
126 
127 static __inline bool
128 flush_by_asid(void)
129 {
130 	return ((svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID) != 0);
131 }
132 
133 static __inline bool
134 decode_assist(void)
135 {
136 	return ((svm_feature & AMD_CPUID_SVM_DECODE_ASSIST) != 0);
137 }
138 
139 static int
140 svm_cleanup(void)
141 {
142 	/* This is taken care of by the hma registration */
143 	return (0);
144 }
145 
146 static int
147 svm_init(void)
148 {
149 	vmcb_clean &= VMCB_CACHE_DEFAULT;
150 
151 	svm_msr_init();
152 
153 	return (0);
154 }
155 
156 static void
157 svm_restore(void)
158 {
159 	/* No-op on illumos */
160 }
161 
162 /* Pentium compatible MSRs */
163 #define	MSR_PENTIUM_START	0
164 #define	MSR_PENTIUM_END		0x1FFF
165 /* AMD 6th generation and Intel compatible MSRs */
166 #define	MSR_AMD6TH_START	0xC0000000UL
167 #define	MSR_AMD6TH_END		0xC0001FFFUL
168 /* AMD 7th and 8th generation compatible MSRs */
169 #define	MSR_AMD7TH_START	0xC0010000UL
170 #define	MSR_AMD7TH_END		0xC0011FFFUL
171 
172 /*
173  * Get the index and bit position for a MSR in permission bitmap.
174  * Two bits are used for each MSR: lower bit for read and higher bit for write.
175  */
176 static int
177 svm_msr_index(uint64_t msr, int *index, int *bit)
178 {
179 	uint32_t base, off;
180 
181 	*index = -1;
182 	*bit = (msr % 4) * 2;
183 	base = 0;
184 
185 	if (msr <= MSR_PENTIUM_END) {
186 		*index = msr / 4;
187 		return (0);
188 	}
189 
190 	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
191 	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
192 		off = (msr - MSR_AMD6TH_START);
193 		*index = (off + base) / 4;
194 		return (0);
195 	}
196 
197 	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
198 	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
199 		off = (msr - MSR_AMD7TH_START);
200 		*index = (off + base) / 4;
201 		return (0);
202 	}
203 
204 	return (EINVAL);
205 }
206 
207 /*
208  * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
209  */
210 static void
211 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
212 {
213 	int index, bit, error;
214 
215 	error = svm_msr_index(msr, &index, &bit);
216 	KASSERT(error == 0, ("%s: invalid msr %lx", __func__, msr));
217 	KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
218 	    ("%s: invalid index %d for msr %lx", __func__, index, msr));
219 	KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
220 	    "msr %lx", __func__, bit, msr));
221 
222 	if (read)
223 		perm_bitmap[index] &= ~(1UL << bit);
224 
225 	if (write)
226 		perm_bitmap[index] &= ~(2UL << bit);
227 }
228 
229 static void
230 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
231 {
232 
233 	svm_msr_perm(perm_bitmap, msr, true, true);
234 }
235 
236 static void
237 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
238 {
239 
240 	svm_msr_perm(perm_bitmap, msr, true, false);
241 }
242 
243 static __inline int
244 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
245 {
246 	struct vmcb_ctrl *ctrl;
247 
248 	KASSERT(idx >= 0 && idx < 5, ("invalid intercept index %d", idx));
249 
250 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
251 	return (ctrl->intercept[idx] & bitmask ? 1 : 0);
252 }
253 
254 static __inline void
255 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
256     int enabled)
257 {
258 	struct vmcb_ctrl *ctrl;
259 	uint32_t oldval;
260 
261 	KASSERT(idx >= 0 && idx < 5, ("invalid intercept index %d", idx));
262 
263 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
264 	oldval = ctrl->intercept[idx];
265 
266 	if (enabled)
267 		ctrl->intercept[idx] |= bitmask;
268 	else
269 		ctrl->intercept[idx] &= ~bitmask;
270 
271 	if (ctrl->intercept[idx] != oldval) {
272 		svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
273 	}
274 }
275 
276 static __inline void
277 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
278 {
279 
280 	svm_set_intercept(sc, vcpu, off, bitmask, 0);
281 }
282 
283 static __inline void
284 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
285 {
286 
287 	svm_set_intercept(sc, vcpu, off, bitmask, 1);
288 }
289 
290 static void
291 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
292     uint64_t msrpm_base_pa, uint64_t np_pml4)
293 {
294 	struct vmcb_ctrl *ctrl;
295 	struct vmcb_state *state;
296 	uint32_t mask;
297 	int n;
298 
299 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
300 	state = svm_get_vmcb_state(sc, vcpu);
301 
302 	ctrl->iopm_base_pa = iopm_base_pa;
303 	ctrl->msrpm_base_pa = msrpm_base_pa;
304 
305 	/* Enable nested paging */
306 	ctrl->np_ctrl = NP_ENABLE;
307 	ctrl->n_cr3 = np_pml4;
308 
309 	/*
310 	 * Intercept accesses to the control registers that are not shadowed
311 	 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
312 	 */
313 	for (n = 0; n < 16; n++) {
314 		mask = (BIT(n) << 16) | BIT(n);
315 		if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
316 			svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
317 		else
318 			svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
319 	}
320 
321 	/*
322 	 * Selectively intercept writes to %cr0.  This triggers on operations
323 	 * which would change bits other than TS or MP.
324 	 */
325 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
326 	    VMCB_INTCPT_CR0_WRITE);
327 
328 	/*
329 	 * Intercept everything when tracing guest exceptions otherwise
330 	 * just intercept machine check exception.
331 	 */
332 	if (vcpu_trace_exceptions(sc->vm, vcpu)) {
333 		for (n = 0; n < 32; n++) {
334 			/*
335 			 * Skip unimplemented vectors in the exception bitmap.
336 			 */
337 			if (n == 2 || n == 9) {
338 				continue;
339 			}
340 			svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
341 		}
342 	} else {
343 		svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
344 	}
345 
346 	/* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
347 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
348 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
349 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
350 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
351 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
352 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
353 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
354 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
355 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
356 	    VMCB_INTCPT_FERR_FREEZE);
357 
358 	/* Enable exit-on-hlt by default */
359 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_HLT);
360 
361 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
362 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
363 
364 	/* Intercept privileged invalidation instructions. */
365 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INVD);
366 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INVLPGA);
367 
368 	/*
369 	 * Intercept all virtualization-related instructions.
370 	 *
371 	 * From section "Canonicalization and Consistency Checks" in APMv2
372 	 * the VMRUN intercept bit must be set to pass the consistency check.
373 	 */
374 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
375 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMMCALL);
376 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMLOAD);
377 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMSAVE);
378 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_STGI);
379 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_CLGI);
380 	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_SKINIT);
381 	if (vcpu_trap_wbinvd(sc->vm, vcpu) != 0) {
382 		svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT,
383 		    VMCB_INTCPT_WBINVD);
384 	}
385 
386 	/*
387 	 * The ASID will be set to a non-zero value just before VMRUN.
388 	 */
389 	ctrl->asid = 0;
390 
391 	/*
392 	 * Section 15.21.1, Interrupt Masking in EFLAGS
393 	 * Section 15.21.2, Virtualizing APIC.TPR
394 	 *
395 	 * This must be set for %rflag and %cr8 isolation of guest and host.
396 	 */
397 	ctrl->v_intr_ctrl |= V_INTR_MASKING;
398 
399 	/* Enable Last Branch Record aka LBR for debugging */
400 	ctrl->misc_ctrl |= LBR_VIRT_ENABLE;
401 	state->dbgctl = BIT(0);
402 
403 	/* EFER_SVM must always be set when the guest is executing */
404 	state->efer = EFER_SVM;
405 
406 	/* Set up the PAT to power-on state */
407 	state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK)	|
408 	    PAT_VALUE(1, PAT_WRITE_THROUGH)	|
409 	    PAT_VALUE(2, PAT_UNCACHED)		|
410 	    PAT_VALUE(3, PAT_UNCACHEABLE)	|
411 	    PAT_VALUE(4, PAT_WRITE_BACK)	|
412 	    PAT_VALUE(5, PAT_WRITE_THROUGH)	|
413 	    PAT_VALUE(6, PAT_UNCACHED)		|
414 	    PAT_VALUE(7, PAT_UNCACHEABLE);
415 
416 	/* Set up DR6/7 to power-on state */
417 	state->dr6 = DBREG_DR6_RESERVED1;
418 	state->dr7 = DBREG_DR7_RESERVED1;
419 }
420 
421 /*
422  * Initialize a virtual machine.
423  */
424 static void *
425 svm_vminit(struct vm *vm)
426 {
427 	struct svm_softc *svm_sc;
428 	struct svm_vcpu *vcpu;
429 	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
430 	int i;
431 	uint16_t maxcpus;
432 
433 	svm_sc = kmem_zalloc(sizeof (*svm_sc), KM_SLEEP);
434 	VERIFY3U(((uintptr_t)svm_sc & PAGE_MASK),  ==,  0);
435 
436 	svm_sc->msr_bitmap = vmm_contig_alloc(SVM_MSR_BITMAP_SIZE);
437 	if (svm_sc->msr_bitmap == NULL)
438 		panic("contigmalloc of SVM MSR bitmap failed");
439 	svm_sc->iopm_bitmap = vmm_contig_alloc(SVM_IO_BITMAP_SIZE);
440 	if (svm_sc->iopm_bitmap == NULL)
441 		panic("contigmalloc of SVM IO bitmap failed");
442 
443 	svm_sc->vm = vm;
444 	svm_sc->nptp = vmspace_table_root(vm_get_vmspace(vm));
445 
446 	/*
447 	 * Intercept read and write accesses to all MSRs.
448 	 */
449 	memset(svm_sc->msr_bitmap, 0xFF, SVM_MSR_BITMAP_SIZE);
450 
451 	/*
452 	 * Access to the following MSRs is redirected to the VMCB when the
453 	 * guest is executing. Therefore it is safe to allow the guest to
454 	 * read/write these MSRs directly without hypervisor involvement.
455 	 */
456 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
457 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
458 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
459 
460 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
461 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
462 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
463 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
464 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
465 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
466 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
467 	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
468 
469 	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
470 
471 	/*
472 	 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
473 	 */
474 	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
475 
476 	/* Intercept access to all I/O ports. */
477 	memset(svm_sc->iopm_bitmap, 0xFF, SVM_IO_BITMAP_SIZE);
478 
479 	iopm_pa = vtophys(svm_sc->iopm_bitmap);
480 	msrpm_pa = vtophys(svm_sc->msr_bitmap);
481 	pml4_pa = svm_sc->nptp;
482 	maxcpus = vm_get_maxcpus(svm_sc->vm);
483 	for (i = 0; i < maxcpus; i++) {
484 		vcpu = svm_get_vcpu(svm_sc, i);
485 		vcpu->nextrip = ~0;
486 		vcpu->lastcpu = NOCPU;
487 		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
488 		vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
489 		svm_msr_guest_init(svm_sc, i);
490 	}
491 	return (svm_sc);
492 }
493 
494 /*
495  * Collateral for a generic SVM VM-exit.
496  */
497 static void
498 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
499 {
500 
501 	vme->exitcode = VM_EXITCODE_SVM;
502 	vme->u.svm.exitcode = code;
503 	vme->u.svm.exitinfo1 = info1;
504 	vme->u.svm.exitinfo2 = info2;
505 }
506 
507 static int
508 svm_cpl(struct vmcb_state *state)
509 {
510 
511 	/*
512 	 * From APMv2:
513 	 *   "Retrieve the CPL from the CPL field in the VMCB, not
514 	 *    from any segment DPL"
515 	 */
516 	return (state->cpl);
517 }
518 
519 static enum vm_cpu_mode
520 svm_vcpu_mode(struct vmcb *vmcb)
521 {
522 	struct vmcb_state *state;
523 
524 	state = &vmcb->state;
525 
526 	if (state->efer & EFER_LMA) {
527 		struct vmcb_segment *seg;
528 
529 		/*
530 		 * Section 4.8.1 for APM2, check if Code Segment has
531 		 * Long attribute set in descriptor.
532 		 */
533 		seg = vmcb_segptr(vmcb, VM_REG_GUEST_CS);
534 		if (seg->attrib & VMCB_CS_ATTRIB_L)
535 			return (CPU_MODE_64BIT);
536 		else
537 			return (CPU_MODE_COMPATIBILITY);
538 	} else  if (state->cr0 & CR0_PE) {
539 		return (CPU_MODE_PROTECTED);
540 	} else {
541 		return (CPU_MODE_REAL);
542 	}
543 }
544 
545 static enum vm_paging_mode
546 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
547 {
548 
549 	if ((cr0 & CR0_PG) == 0)
550 		return (PAGING_MODE_FLAT);
551 	if ((cr4 & CR4_PAE) == 0)
552 		return (PAGING_MODE_32);
553 	if (efer & EFER_LME)
554 		return (PAGING_MODE_64);
555 	else
556 		return (PAGING_MODE_PAE);
557 }
558 
559 /*
560  * ins/outs utility routines
561  */
562 
563 static void
564 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
565 {
566 	struct vmcb_state *state;
567 
568 	state = &vmcb->state;
569 	paging->cr3 = state->cr3;
570 	paging->cpl = svm_cpl(state);
571 	paging->cpu_mode = svm_vcpu_mode(vmcb);
572 	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
573 	    state->efer);
574 }
575 
576 #define	UNHANDLED 0
577 
578 /*
579  * Handle guest I/O intercept.
580  */
581 static int
582 svm_handle_inout(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
583 {
584 	struct vmcb_ctrl *ctrl;
585 	struct vmcb_state *state;
586 	struct vm_inout *inout;
587 	struct vie *vie;
588 	uint64_t info1;
589 	struct vm_guest_paging paging;
590 
591 	state = svm_get_vmcb_state(svm_sc, vcpu);
592 	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
593 	inout = &vmexit->u.inout;
594 	info1 = ctrl->exitinfo1;
595 
596 	inout->bytes = (info1 >> 4) & 0x7;
597 	inout->flags = 0;
598 	inout->flags |= (info1 & BIT(0)) ? INOUT_IN : 0;
599 	inout->flags |= (info1 & BIT(3)) ? INOUT_REP : 0;
600 	inout->flags |= (info1 & BIT(2)) ? INOUT_STR : 0;
601 	inout->port = (uint16_t)(info1 >> 16);
602 	inout->eax = (uint32_t)(state->rax);
603 
604 	if ((inout->flags & INOUT_STR) != 0) {
605 		/*
606 		 * The effective segment number in EXITINFO1[12:10] is populated
607 		 * only if the processor has the DecodeAssist capability.
608 		 *
609 		 * This is not specified explicitly in APMv2 but can be verified
610 		 * empirically.
611 		 */
612 		if (!decode_assist()) {
613 			/*
614 			 * Without decoding assistance, force the task of
615 			 * emulating the ins/outs on userspace.
616 			 */
617 			vmexit->exitcode = VM_EXITCODE_INST_EMUL;
618 			bzero(&vmexit->u.inst_emul,
619 			    sizeof (vmexit->u.inst_emul));
620 			return (UNHANDLED);
621 		}
622 
623 		/*
624 		 * Bits 7-9 encode the address size of ins/outs operations where
625 		 * the 1/2/4 values correspond to 16/32/64 bit sizes.
626 		 */
627 		inout->addrsize = 2 * ((info1 >> 7) & 0x7);
628 		VERIFY(inout->addrsize == 2 || inout->addrsize == 4 ||
629 		    inout->addrsize == 8);
630 
631 		if (inout->flags & INOUT_IN) {
632 			/*
633 			 * For INS instructions, %es (encoded as 0) is the
634 			 * implied segment for the operation.
635 			 */
636 			inout->segment = 0;
637 		} else {
638 			/*
639 			 * Bits 10-12 encode the segment for OUTS.
640 			 * This value follows the standard x86 segment order.
641 			 */
642 			inout->segment = (info1 >> 10) & 0x7;
643 		}
644 	}
645 
646 	vmexit->exitcode = VM_EXITCODE_INOUT;
647 	svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &paging);
648 	vie = vm_vie_ctx(svm_sc->vm, vcpu);
649 	vie_init_inout(vie, inout, vmexit->inst_length, &paging);
650 
651 	/* The in/out emulation will handle advancing %rip */
652 	vmexit->inst_length = 0;
653 
654 	return (UNHANDLED);
655 }
656 
657 static int
658 npf_fault_type(uint64_t exitinfo1)
659 {
660 
661 	if (exitinfo1 & VMCB_NPF_INFO1_W)
662 		return (PROT_WRITE);
663 	else if (exitinfo1 & VMCB_NPF_INFO1_ID)
664 		return (PROT_EXEC);
665 	else
666 		return (PROT_READ);
667 }
668 
669 static bool
670 svm_npf_emul_fault(uint64_t exitinfo1)
671 {
672 	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
673 		return (false);
674 	}
675 
676 	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
677 		return (false);
678 	}
679 
680 	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
681 		return (false);
682 	}
683 
684 	return (true);
685 }
686 
687 static void
688 svm_handle_mmio_emul(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit,
689     uint64_t gpa)
690 {
691 	struct vmcb_ctrl *ctrl;
692 	struct vmcb *vmcb;
693 	struct vie *vie;
694 	struct vm_guest_paging paging;
695 	struct vmcb_segment *seg;
696 	char *inst_bytes = NULL;
697 	uint8_t inst_len = 0;
698 
699 	vmcb = svm_get_vmcb(svm_sc, vcpu);
700 	ctrl = &vmcb->ctrl;
701 
702 	vmexit->exitcode = VM_EXITCODE_MMIO_EMUL;
703 	vmexit->u.mmio_emul.gpa = gpa;
704 	vmexit->u.mmio_emul.gla = VIE_INVALID_GLA;
705 	svm_paging_info(vmcb, &paging);
706 
707 	switch (paging.cpu_mode) {
708 	case CPU_MODE_REAL:
709 		seg = vmcb_segptr(vmcb, VM_REG_GUEST_CS);
710 		vmexit->u.mmio_emul.cs_base = seg->base;
711 		vmexit->u.mmio_emul.cs_d = 0;
712 		break;
713 	case CPU_MODE_PROTECTED:
714 	case CPU_MODE_COMPATIBILITY:
715 		seg = vmcb_segptr(vmcb, VM_REG_GUEST_CS);
716 		vmexit->u.mmio_emul.cs_base = seg->base;
717 
718 		/*
719 		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
720 		 */
721 		vmexit->u.mmio_emul.cs_d = (seg->attrib & VMCB_CS_ATTRIB_D) ?
722 		    1 : 0;
723 		break;
724 	default:
725 		vmexit->u.mmio_emul.cs_base = 0;
726 		vmexit->u.mmio_emul.cs_d = 0;
727 		break;
728 	}
729 
730 	/*
731 	 * Copy the instruction bytes into 'vie' if available.
732 	 */
733 	if (decode_assist() && !disable_npf_assist) {
734 		inst_len = ctrl->inst_len;
735 		inst_bytes = (char *)ctrl->inst_bytes;
736 	}
737 	vie = vm_vie_ctx(svm_sc->vm, vcpu);
738 	vie_init_mmio(vie, inst_bytes, inst_len, &paging, gpa);
739 }
740 
741 /*
742  * Do not allow CD, NW, or invalid high bits to be asserted in the value of cr0
743  * which is live in the guest.  They are visible via the shadow instead.
744  */
745 #define	SVM_CR0_MASK	~(CR0_CD | CR0_NW | 0xffffffff00000000)
746 
747 static void
748 svm_set_cr0(struct svm_softc *svm_sc, int vcpu, uint64_t val, bool guest_write)
749 {
750 	struct vmcb_state *state;
751 	struct svm_regctx *regctx;
752 	uint64_t masked, old, diff;
753 
754 	state = svm_get_vmcb_state(svm_sc, vcpu);
755 	regctx = svm_get_guest_regctx(svm_sc, vcpu);
756 
757 	old = state->cr0 | (regctx->sctx_cr0_shadow & ~SVM_CR0_MASK);
758 	diff = old ^ val;
759 
760 	/* No further work needed if register contents remain the same */
761 	if (diff == 0) {
762 		return;
763 	}
764 
765 	/* Flush the TLB if the paging or write-protect bits are changing */
766 	if ((diff & CR0_PG) != 0 || (diff & CR0_WP) != 0) {
767 		flush_asid(svm_sc, vcpu);
768 	}
769 
770 	/*
771 	 * If the change in %cr0 is due to a guest action (via interception)
772 	 * then other CPU state updates may be required.
773 	 */
774 	if (guest_write) {
775 		if ((diff & CR0_PG) != 0) {
776 			uint64_t efer = state->efer;
777 
778 			/* Keep the long-mode state in EFER in sync */
779 			if ((val & CR0_PG) != 0 && (efer & EFER_LME) != 0) {
780 				state->efer |= EFER_LMA;
781 			}
782 			if ((val & CR0_PG) == 0 && (efer & EFER_LME) != 0) {
783 				state->efer &= ~EFER_LMA;
784 			}
785 		}
786 	}
787 
788 	masked = val & SVM_CR0_MASK;
789 	regctx->sctx_cr0_shadow = val;
790 	state->cr0 = masked;
791 	svm_set_dirty(svm_sc, vcpu, VMCB_CACHE_CR);
792 
793 	if ((masked ^ val) != 0) {
794 		/*
795 		 * The guest has set bits in %cr0 which we are masking out and
796 		 * exposing via shadow.
797 		 *
798 		 * We must intercept %cr0 reads in order to make the shadowed
799 		 * view available to the guest.
800 		 *
801 		 * Writes to %cr0 must also be intercepted (unconditionally,
802 		 * unlike the VMCB_INTCPT_CR0_WRITE mechanism) so we can catch
803 		 * if/when the guest clears those shadowed bits.
804 		 */
805 		svm_enable_intercept(svm_sc, vcpu, VMCB_CR_INTCPT,
806 		    BIT(0) | BIT(16));
807 	} else {
808 		/*
809 		 * When no bits remain in %cr0 which require shadowing, the
810 		 * unconditional intercept of reads/writes to %cr0 can be
811 		 * disabled.
812 		 *
813 		 * The selective write intercept (VMCB_INTCPT_CR0_WRITE) remains
814 		 * in place so we can be notified of operations which change
815 		 * bits other than TS or MP.
816 		 */
817 		svm_disable_intercept(svm_sc, vcpu, VMCB_CR_INTCPT,
818 		    BIT(0) | BIT(16));
819 	}
820 	svm_set_dirty(svm_sc, vcpu, VMCB_CACHE_I);
821 }
822 
823 static void
824 svm_get_cr0(struct svm_softc *svm_sc, int vcpu, uint64_t *val)
825 {
826 	struct vmcb *vmcb;
827 	struct svm_regctx *regctx;
828 
829 	vmcb = svm_get_vmcb(svm_sc, vcpu);
830 	regctx = svm_get_guest_regctx(svm_sc, vcpu);
831 
832 	/*
833 	 * Include the %cr0 bits which exist only in the shadow along with those
834 	 * in the running vCPU state.
835 	 */
836 	*val = vmcb->state.cr0 | (regctx->sctx_cr0_shadow & ~SVM_CR0_MASK);
837 }
838 
839 static void
840 svm_handle_cr0_read(struct svm_softc *svm_sc, int vcpu, enum vm_reg_name reg)
841 {
842 	uint64_t val;
843 	int err __maybe_unused;
844 
845 	svm_get_cr0(svm_sc, vcpu, &val);
846 	err = svm_setreg(svm_sc, vcpu, reg, val);
847 	ASSERT(err == 0);
848 }
849 
850 static void
851 svm_handle_cr0_write(struct svm_softc *svm_sc, int vcpu, enum vm_reg_name reg)
852 {
853 	struct vmcb_state *state;
854 	uint64_t val;
855 	int err __maybe_unused;
856 
857 	state = svm_get_vmcb_state(svm_sc, vcpu);
858 
859 	err = svm_getreg(svm_sc, vcpu, reg, &val);
860 	ASSERT(err == 0);
861 
862 	if ((val & CR0_NW) != 0 && (val & CR0_CD) == 0) {
863 		/* NW without CD is nonsensical */
864 		vm_inject_gp(svm_sc->vm, vcpu);
865 		return;
866 	}
867 	if ((val & CR0_PG) != 0 && (val & CR0_PE) == 0) {
868 		/* PG requires PE */
869 		vm_inject_gp(svm_sc->vm, vcpu);
870 		return;
871 	}
872 	if ((state->cr0 & CR0_PG) == 0 && (val & CR0_PG) != 0) {
873 		/* When enabling paging, PAE must be enabled if LME is. */
874 		if ((state->efer & EFER_LME) != 0 &&
875 		    (state->cr4 & CR4_PAE) == 0) {
876 			vm_inject_gp(svm_sc->vm, vcpu);
877 			return;
878 		}
879 	}
880 
881 	svm_set_cr0(svm_sc, vcpu, val, true);
882 }
883 
884 static void
885 svm_inst_emul_other(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
886 {
887 	struct vie *vie;
888 	struct vm_guest_paging paging;
889 
890 	/* Let the instruction emulation (hopefully in-kernel) handle it */
891 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
892 	bzero(&vmexit->u.inst_emul, sizeof (vmexit->u.inst_emul));
893 	vie = vm_vie_ctx(svm_sc->vm, vcpu);
894 	svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &paging);
895 	vie_init_other(vie, &paging);
896 
897 	/* The instruction emulation will handle advancing %rip */
898 	vmexit->inst_length = 0;
899 }
900 
901 static void
902 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
903 {
904 	struct vm *vm;
905 	struct vlapic *vlapic;
906 	struct vmcb_ctrl *ctrl;
907 
908 	vm = sc->vm;
909 	vlapic = vm_lapic(vm, vcpu);
910 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
911 
912 	/* Update %cr8 in the emulated vlapic */
913 	vlapic_set_cr8(vlapic, ctrl->v_tpr);
914 
915 	/* Virtual interrupt injection is not used. */
916 	KASSERT(ctrl->v_intr_vector == 0, ("%s: invalid "
917 	    "v_intr_vector %d", __func__, ctrl->v_intr_vector));
918 }
919 
920 CTASSERT(VMCB_EVENTINJ_TYPE_INTR	== VM_INTINFO_HWINTR);
921 CTASSERT(VMCB_EVENTINJ_TYPE_NMI		== VM_INTINFO_NMI);
922 CTASSERT(VMCB_EVENTINJ_TYPE_EXCEPTION	== VM_INTINFO_HWEXCP);
923 CTASSERT(VMCB_EVENTINJ_TYPE_INTn	== VM_INTINFO_SWINTR);
924 CTASSERT(VMCB_EVENTINJ_EC_VALID		== VM_INTINFO_DEL_ERRCODE);
925 CTASSERT(VMCB_EVENTINJ_VALID		== VM_INTINFO_VALID);
926 
927 static void
928 svm_save_exitintinfo(struct svm_softc *svm_sc, int vcpu)
929 {
930 	struct vmcb_ctrl *ctrl;
931 	uint64_t intinfo;
932 	int err;
933 
934 	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
935 	intinfo = ctrl->exitintinfo;
936 	if (!VMCB_EXITINTINFO_VALID(intinfo))
937 		return;
938 
939 	/*
940 	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
941 	 *
942 	 * If a #VMEXIT happened during event delivery then record the event
943 	 * that was being delivered.
944 	 */
945 	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
946 	/*
947 	 * Relies on match between VMCB exitintinfo format and bhyve-generic
948 	 * format, which is ensured by CTASSERTs above.
949 	 */
950 	err = vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
951 	VERIFY0(err);
952 }
953 
954 static __inline int
955 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
956 {
957 
958 	return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
959 	    VMCB_INTCPT_VINTR));
960 }
961 
962 static void
963 svm_enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
964 {
965 	struct vmcb_ctrl *ctrl;
966 	struct vmcb_state *state;
967 
968 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
969 	state = svm_get_vmcb_state(sc, vcpu);
970 
971 	if ((ctrl->v_irq & V_IRQ) != 0 && ctrl->v_intr_vector == 0) {
972 		KASSERT(ctrl->v_intr_prio & V_IGN_TPR,
973 		    ("%s: invalid v_ign_tpr", __func__));
974 		KASSERT(vintr_intercept_enabled(sc, vcpu),
975 		    ("%s: vintr intercept should be enabled", __func__));
976 		return;
977 	}
978 
979 	/*
980 	 * We use V_IRQ in conjunction with the VINTR intercept to trap into the
981 	 * hypervisor as soon as a virtual interrupt can be delivered.
982 	 *
983 	 * Since injected events are not subject to intercept checks we need to
984 	 * ensure that the V_IRQ is not actually going to be delivered on VM
985 	 * entry.
986 	 */
987 	VERIFY((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
988 	    (state->rflags & PSL_I) == 0 || ctrl->intr_shadow);
989 
990 	ctrl->v_irq |= V_IRQ;
991 	ctrl->v_intr_prio |= V_IGN_TPR;
992 	ctrl->v_intr_vector = 0;
993 	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
994 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
995 }
996 
997 static void
998 svm_disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
999 {
1000 	struct vmcb_ctrl *ctrl;
1001 
1002 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1003 
1004 	if ((ctrl->v_irq & V_IRQ) == 0 && ctrl->v_intr_vector == 0) {
1005 		KASSERT(!vintr_intercept_enabled(sc, vcpu),
1006 		    ("%s: vintr intercept should be disabled", __func__));
1007 		return;
1008 	}
1009 
1010 	ctrl->v_irq &= ~V_IRQ;
1011 	ctrl->v_intr_vector = 0;
1012 	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1013 	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1014 }
1015 
1016 /*
1017  * Once an NMI is injected it blocks delivery of further NMIs until the handler
1018  * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1019  * to track when the vcpu is done handling the NMI.
1020  */
1021 static int
1022 svm_nmi_blocked(struct svm_softc *sc, int vcpu)
1023 {
1024 	return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1025 	    VMCB_INTCPT_IRET));
1026 }
1027 
1028 static void
1029 svm_clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1030 {
1031 	struct vmcb_ctrl *ctrl;
1032 
1033 	KASSERT(svm_nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1034 	/*
1035 	 * When the IRET intercept is cleared the vcpu will attempt to execute
1036 	 * the "iret" when it runs next. However, it is possible to inject
1037 	 * another NMI into the vcpu before the "iret" has actually executed.
1038 	 *
1039 	 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1040 	 * it will trap back into the hypervisor. If an NMI is pending for
1041 	 * the vcpu it will be injected into the guest.
1042 	 *
1043 	 * XXX this needs to be fixed
1044 	 */
1045 	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1046 
1047 	/*
1048 	 * Set an interrupt shadow to prevent an NMI from being immediately
1049 	 * injected on the next VMRUN.
1050 	 */
1051 	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1052 	ctrl->intr_shadow = 1;
1053 }
1054 
1055 static void
1056 svm_inject_event(struct vmcb_ctrl *ctrl, uint64_t info)
1057 {
1058 	ASSERT(VM_INTINFO_PENDING(info));
1059 
1060 	uint8_t vector = VM_INTINFO_VECTOR(info);
1061 	uint32_t type = VM_INTINFO_TYPE(info);
1062 
1063 	/*
1064 	 * Correct behavior depends on bhyve intinfo event types lining up with
1065 	 * those defined by AMD for event injection in the VMCB.  The CTASSERTs
1066 	 * above svm_save_exitintinfo() ensure it.
1067 	 */
1068 	switch (type) {
1069 	case VM_INTINFO_NMI:
1070 		/* Ensure vector for injected event matches its type (NMI) */
1071 		vector = IDT_NMI;
1072 		break;
1073 	case VM_INTINFO_HWINTR:
1074 	case VM_INTINFO_SWINTR:
1075 		break;
1076 	case VM_INTINFO_HWEXCP:
1077 		if (vector == IDT_NMI) {
1078 			/*
1079 			 * NMIs are expected to be injected with
1080 			 * VMCB_EVENTINJ_TYPE_NMI, rather than as an exception
1081 			 * with the NMI vector.
1082 			 */
1083 			type = VM_INTINFO_NMI;
1084 		}
1085 		VERIFY(vector < 32);
1086 		break;
1087 	default:
1088 		/*
1089 		 * Since there is not strong validation for injected event types
1090 		 * at this point, fall back to software interrupt for those we
1091 		 * do not recognized.
1092 		 */
1093 		type = VM_INTINFO_SWINTR;
1094 		break;
1095 	}
1096 
1097 	ctrl->eventinj = VMCB_EVENTINJ_VALID | type | vector;
1098 	if (VM_INTINFO_HAS_ERRCODE(info)) {
1099 		ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
1100 		ctrl->eventinj |= (uint64_t)VM_INTINFO_ERRCODE(info) << 32;
1101 	}
1102 }
1103 
1104 static void
1105 svm_inject_nmi(struct svm_softc *sc, int vcpu)
1106 {
1107 	struct vmcb_ctrl *ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1108 
1109 	ASSERT(!svm_nmi_blocked(sc, vcpu));
1110 
1111 	ctrl->eventinj = VMCB_EVENTINJ_VALID | VMCB_EVENTINJ_TYPE_NMI;
1112 	vm_nmi_clear(sc->vm, vcpu);
1113 
1114 	/*
1115 	 * Virtual NMI blocking is now in effect.
1116 	 *
1117 	 * Not only does this block a subsequent NMI injection from taking
1118 	 * place, it also configures an intercept on the IRET so we can track
1119 	 * when the next injection can take place.
1120 	 */
1121 	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1122 }
1123 
1124 static void
1125 svm_inject_irq(struct svm_softc *sc, int vcpu, int vector)
1126 {
1127 	struct vmcb_ctrl *ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1128 
1129 	ASSERT(vector >= 0 && vector <= 255);
1130 
1131 	ctrl->eventinj = VMCB_EVENTINJ_VALID | vector;
1132 }
1133 
1134 #define	EFER_MBZ_BITS	0xFFFFFFFFFFFF0200UL
1135 
1136 static vm_msr_result_t
1137 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval)
1138 {
1139 	struct vmcb_state *state = svm_get_vmcb_state(sc, vcpu);
1140 	uint64_t lma;
1141 	int error;
1142 
1143 	newval &= ~0xFE;		/* clear the Read-As-Zero (RAZ) bits */
1144 
1145 	if (newval & EFER_MBZ_BITS) {
1146 		return (VMR_GP);
1147 	}
1148 
1149 	/* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1150 	const uint64_t changed = state->efer ^ newval;
1151 	if (changed & EFER_LME) {
1152 		if (state->cr0 & CR0_PG) {
1153 			return (VMR_GP);
1154 		}
1155 	}
1156 
1157 	/* EFER.LMA = EFER.LME & CR0.PG */
1158 	if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0) {
1159 		lma = EFER_LMA;
1160 	} else {
1161 		lma = 0;
1162 	}
1163 	if ((newval & EFER_LMA) != lma) {
1164 		return (VMR_GP);
1165 	}
1166 
1167 	if ((newval & EFER_NXE) != 0 &&
1168 	    !vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE)) {
1169 		return (VMR_GP);
1170 	}
1171 	if ((newval & EFER_FFXSR) != 0 &&
1172 	    !vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR)) {
1173 		return (VMR_GP);
1174 	}
1175 	if ((newval & EFER_TCE) != 0 &&
1176 	    !vm_cpuid_capability(sc->vm, vcpu, VCC_TCE)) {
1177 		return (VMR_GP);
1178 	}
1179 
1180 	/*
1181 	 * Until bhyve has proper support for long-mode segment limits, just
1182 	 * toss a #GP at the guest if they attempt to use it.
1183 	 */
1184 	if (newval & EFER_LMSLE) {
1185 		return (VMR_GP);
1186 	}
1187 
1188 	error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1189 	VERIFY0(error);
1190 	return (VMR_OK);
1191 }
1192 
1193 static int
1194 svm_handle_msr(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit,
1195     bool is_wrmsr)
1196 {
1197 	struct vmcb_state *state = svm_get_vmcb_state(svm_sc, vcpu);
1198 	struct svm_regctx *ctx = svm_get_guest_regctx(svm_sc, vcpu);
1199 	const uint32_t ecx = ctx->sctx_rcx;
1200 	vm_msr_result_t res;
1201 	uint64_t val = 0;
1202 
1203 	if (is_wrmsr) {
1204 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1205 		val = ctx->sctx_rdx << 32 | (uint32_t)state->rax;
1206 
1207 		if (vlapic_owned_msr(ecx)) {
1208 			struct vlapic *vlapic = vm_lapic(svm_sc->vm, vcpu);
1209 
1210 			res = vlapic_wrmsr(vlapic, ecx, val);
1211 		} else if (ecx == MSR_EFER) {
1212 			res = svm_write_efer(svm_sc, vcpu, val);
1213 		} else {
1214 			res = svm_wrmsr(svm_sc, vcpu, ecx, val);
1215 		}
1216 	} else {
1217 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1218 
1219 		if (vlapic_owned_msr(ecx)) {
1220 			struct vlapic *vlapic = vm_lapic(svm_sc->vm, vcpu);
1221 
1222 			res = vlapic_rdmsr(vlapic, ecx, &val);
1223 		} else {
1224 			res = svm_rdmsr(svm_sc, vcpu, ecx, &val);
1225 		}
1226 	}
1227 
1228 	switch (res) {
1229 	case VMR_OK:
1230 		/* Store rdmsr result in the appropriate registers */
1231 		if (!is_wrmsr) {
1232 			state->rax = (uint32_t)val;
1233 			ctx->sctx_rdx = val >> 32;
1234 		}
1235 		return (1);
1236 	case VMR_GP:
1237 		vm_inject_gp(svm_sc->vm, vcpu);
1238 		return (1);
1239 	case VMR_UNHANLDED:
1240 		vmexit->exitcode = is_wrmsr ?
1241 		    VM_EXITCODE_WRMSR : VM_EXITCODE_RDMSR;
1242 		vmexit->u.msr.code = ecx;
1243 		vmexit->u.msr.wval = val;
1244 		return (0);
1245 	default:
1246 		panic("unexpected msr result %u\n", res);
1247 	}
1248 }
1249 
1250 /*
1251  * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1252  * that are due to instruction intercepts as well as MSR and IOIO intercepts
1253  * and exceptions caused by INT3, INTO and BOUND instructions.
1254  *
1255  * Return 1 if the nRIP is valid and 0 otherwise.
1256  */
1257 static int
1258 nrip_valid(uint64_t exitcode)
1259 {
1260 	switch (exitcode) {
1261 	case 0x00 ... 0x0F:	/* read of CR0 through CR15 */
1262 	case 0x10 ... 0x1F:	/* write of CR0 through CR15 */
1263 	case 0x20 ... 0x2F:	/* read of DR0 through DR15 */
1264 	case 0x30 ... 0x3F:	/* write of DR0 through DR15 */
1265 	case 0x43:		/* INT3 */
1266 	case 0x44:		/* INTO */
1267 	case 0x45:		/* BOUND */
1268 	case 0x65 ... 0x7C:	/* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1269 	case 0x80 ... 0x8D:	/* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1270 		return (1);
1271 	default:
1272 		return (0);
1273 	}
1274 }
1275 
1276 static int
1277 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1278 {
1279 	struct vmcb *vmcb;
1280 	struct vmcb_state *state;
1281 	struct vmcb_ctrl *ctrl;
1282 	struct svm_regctx *ctx;
1283 	uint64_t code, info1, info2;
1284 	int handled;
1285 
1286 	ctx = svm_get_guest_regctx(svm_sc, vcpu);
1287 	vmcb = svm_get_vmcb(svm_sc, vcpu);
1288 	state = &vmcb->state;
1289 	ctrl = &vmcb->ctrl;
1290 
1291 	handled = 0;
1292 	code = ctrl->exitcode;
1293 	info1 = ctrl->exitinfo1;
1294 	info2 = ctrl->exitinfo2;
1295 
1296 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1297 	vmexit->rip = state->rip;
1298 	vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1299 
1300 	vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1301 
1302 	/*
1303 	 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1304 	 * in an inconsistent state and can trigger assertions that would
1305 	 * never happen otherwise.
1306 	 */
1307 	if (code == VMCB_EXIT_INVALID) {
1308 		vm_exit_svm(vmexit, code, info1, info2);
1309 		return (0);
1310 	}
1311 
1312 	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1313 	    "injection valid bit is set %lx", __func__, ctrl->eventinj));
1314 
1315 	KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1316 	    ("invalid inst_length %d: code (%lx), info1 (%lx), info2 (%lx)",
1317 	    vmexit->inst_length, code, info1, info2));
1318 
1319 	svm_update_virqinfo(svm_sc, vcpu);
1320 	svm_save_exitintinfo(svm_sc, vcpu);
1321 
1322 	switch (code) {
1323 	case VMCB_EXIT_CR0_READ:
1324 		if (VMCB_CRx_INFO1_VALID(info1) != 0) {
1325 			svm_handle_cr0_read(svm_sc, vcpu,
1326 			    vie_regnum_map(VMCB_CRx_INFO1_GPR(info1)));
1327 			handled = 1;
1328 		} else {
1329 			/*
1330 			 * If SMSW is used to read the contents of %cr0, then
1331 			 * the VALID bit will not be set in `info1`, since the
1332 			 * handling is different from the mov-to-reg case.
1333 			 *
1334 			 * Punt to the instruction emulation to handle it.
1335 			 */
1336 			svm_inst_emul_other(svm_sc, vcpu, vmexit);
1337 		}
1338 		break;
1339 	case VMCB_EXIT_CR0_WRITE:
1340 	case VMCB_EXIT_CR0_SEL_WRITE:
1341 		if (VMCB_CRx_INFO1_VALID(info1) != 0) {
1342 			svm_handle_cr0_write(svm_sc, vcpu,
1343 			    vie_regnum_map(VMCB_CRx_INFO1_GPR(info1)));
1344 			handled = 1;
1345 		} else {
1346 			/*
1347 			 * Writes to %cr0 without VALID being set in `info1` are
1348 			 * initiated by the LMSW and CLTS instructions.  While
1349 			 * LMSW (like SMSW) sees little use in modern OSes and
1350 			 * bootloaders, CLTS is still used for handling FPU
1351 			 * state transitions.
1352 			 *
1353 			 * Punt to the instruction emulation to handle them.
1354 			 */
1355 			svm_inst_emul_other(svm_sc, vcpu, vmexit);
1356 		}
1357 		break;
1358 	case VMCB_EXIT_IRET:
1359 		/*
1360 		 * Restart execution at "iret" but with the intercept cleared.
1361 		 */
1362 		vmexit->inst_length = 0;
1363 		svm_clear_nmi_blocking(svm_sc, vcpu);
1364 		handled = 1;
1365 		break;
1366 	case VMCB_EXIT_VINTR:	/* interrupt window exiting */
1367 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1368 		svm_disable_intr_window_exiting(svm_sc, vcpu);
1369 		handled = 1;
1370 		break;
1371 	case VMCB_EXIT_INTR:	/* external interrupt */
1372 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1373 		handled = 1;
1374 		break;
1375 	case VMCB_EXIT_NMI:
1376 	case VMCB_EXIT_SMI:
1377 	case VMCB_EXIT_INIT:
1378 		/*
1379 		 * For external NMI/SMI and physical INIT interrupts, simply
1380 		 * continue execution, as those host events will be handled by
1381 		 * the physical CPU.
1382 		 */
1383 		handled = 1;
1384 		break;
1385 	case VMCB_EXIT_EXCP0 ... VMCB_EXIT_EXCP31: {
1386 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1387 
1388 		const uint8_t idtvec = code - VMCB_EXIT_EXCP0;
1389 		uint32_t errcode = 0;
1390 		bool reflect = true;
1391 		bool errcode_valid = false;
1392 
1393 		switch (idtvec) {
1394 		case IDT_MC:
1395 			/* The host will handle the MCE itself. */
1396 			reflect = false;
1397 			vmm_call_trap(T_MCE);
1398 			break;
1399 		case IDT_PF:
1400 			VERIFY0(svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1401 			    info2));
1402 			/* fallthru */
1403 		case IDT_NP:
1404 		case IDT_SS:
1405 		case IDT_GP:
1406 		case IDT_AC:
1407 		case IDT_TS:
1408 			errcode_valid = true;
1409 			errcode = info1;
1410 			break;
1411 
1412 		case IDT_DF:
1413 			errcode_valid = true;
1414 			break;
1415 
1416 		case IDT_BP:
1417 		case IDT_OF:
1418 		case IDT_BR:
1419 			/*
1420 			 * The 'nrip' field is populated for INT3, INTO and
1421 			 * BOUND exceptions and this also implies that
1422 			 * 'inst_length' is non-zero.
1423 			 *
1424 			 * Reset 'inst_length' to zero so the guest %rip at
1425 			 * event injection is identical to what it was when
1426 			 * the exception originally happened.
1427 			 */
1428 			vmexit->inst_length = 0;
1429 			/* fallthru */
1430 		default:
1431 			errcode_valid = false;
1432 			break;
1433 		}
1434 		VERIFY0(vmexit->inst_length);
1435 
1436 		if (reflect) {
1437 			/* Reflect the exception back into the guest */
1438 			VERIFY0(vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1439 			    errcode_valid, errcode, false));
1440 		}
1441 		handled = 1;
1442 		break;
1443 		}
1444 	case VMCB_EXIT_MSR:
1445 		handled = svm_handle_msr(svm_sc, vcpu, vmexit, info1 != 0);
1446 		break;
1447 	case VMCB_EXIT_IO:
1448 		handled = svm_handle_inout(svm_sc, vcpu, vmexit);
1449 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1450 		break;
1451 	case VMCB_EXIT_SHUTDOWN:
1452 		(void) vm_suspend(svm_sc->vm, VM_SUSPEND_TRIPLEFAULT);
1453 		handled = 1;
1454 		break;
1455 	case VMCB_EXIT_INVLPGA:
1456 		/* privileged invalidation instructions */
1457 		vm_inject_ud(svm_sc->vm, vcpu);
1458 		handled = 1;
1459 		break;
1460 	case VMCB_EXIT_VMRUN:
1461 	case VMCB_EXIT_VMLOAD:
1462 	case VMCB_EXIT_VMSAVE:
1463 	case VMCB_EXIT_STGI:
1464 	case VMCB_EXIT_CLGI:
1465 	case VMCB_EXIT_SKINIT:
1466 		/* privileged vmm instructions */
1467 		vm_inject_ud(svm_sc->vm, vcpu);
1468 		handled = 1;
1469 		break;
1470 	case VMCB_EXIT_INVD:
1471 	case VMCB_EXIT_WBINVD:
1472 		/* ignore exit */
1473 		handled = 1;
1474 		break;
1475 	case VMCB_EXIT_VMMCALL:
1476 		/* No handlers make use of VMMCALL for now */
1477 		vm_inject_ud(svm_sc->vm, vcpu);
1478 		handled = 1;
1479 		break;
1480 	case VMCB_EXIT_CPUID:
1481 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1482 		vcpu_emulate_cpuid(svm_sc->vm, vcpu, &state->rax,
1483 		    &ctx->sctx_rbx, &ctx->sctx_rcx, &ctx->sctx_rdx);
1484 		handled = 1;
1485 		break;
1486 	case VMCB_EXIT_HLT:
1487 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1488 		vmexit->exitcode = VM_EXITCODE_HLT;
1489 		vmexit->u.hlt.rflags = state->rflags;
1490 		break;
1491 	case VMCB_EXIT_PAUSE:
1492 		vmexit->exitcode = VM_EXITCODE_PAUSE;
1493 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1494 		break;
1495 	case VMCB_EXIT_NPF:
1496 		/* EXITINFO2 contains the faulting guest physical address */
1497 		if (info1 & VMCB_NPF_INFO1_RSV) {
1498 			/* nested fault with reserved bits set */
1499 		} else if (vm_mem_allocated(svm_sc->vm, vcpu, info2)) {
1500 			vmexit->exitcode = VM_EXITCODE_PAGING;
1501 			vmexit->u.paging.gpa = info2;
1502 			vmexit->u.paging.fault_type = npf_fault_type(info1);
1503 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1504 		} else if (svm_npf_emul_fault(info1)) {
1505 			svm_handle_mmio_emul(svm_sc, vcpu, vmexit, info2);
1506 			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_MMIO_EMUL, 1);
1507 		}
1508 		break;
1509 	case VMCB_EXIT_MONITOR:
1510 		vmexit->exitcode = VM_EXITCODE_MONITOR;
1511 		break;
1512 	case VMCB_EXIT_MWAIT:
1513 		vmexit->exitcode = VM_EXITCODE_MWAIT;
1514 		break;
1515 	default:
1516 		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1517 		break;
1518 	}
1519 
1520 	DTRACE_PROBE3(vmm__vexit, int, vcpu, uint64_t, vmexit->rip, uint32_t,
1521 	    code);
1522 
1523 	if (handled) {
1524 		vmexit->rip += vmexit->inst_length;
1525 		vmexit->inst_length = 0;
1526 		state->rip = vmexit->rip;
1527 	} else {
1528 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1529 			/*
1530 			 * If this VM exit was not claimed by anybody then
1531 			 * treat it as a generic SVM exit.
1532 			 */
1533 			vm_exit_svm(vmexit, code, info1, info2);
1534 		} else {
1535 			/*
1536 			 * The exitcode and collateral have been populated.
1537 			 * The VM exit will be processed further in userland.
1538 			 */
1539 		}
1540 	}
1541 	return (handled);
1542 }
1543 
1544 /*
1545  * Inject exceptions, NMIs, and ExtINTs.
1546  *
1547  * The logic behind these are complicated and may involve mutex contention, so
1548  * the injection is performed without the protection of host CPU interrupts
1549  * being disabled.  This means a racing notification could be "lost",
1550  * necessitating a later call to svm_inject_recheck() to close that window
1551  * of opportunity.
1552  */
1553 static enum event_inject_state
1554 svm_inject_events(struct svm_softc *sc, int vcpu)
1555 {
1556 	struct vmcb_ctrl *ctrl;
1557 	struct vmcb_state *state;
1558 	struct svm_vcpu *vcpustate;
1559 	uint64_t intinfo;
1560 	enum event_inject_state ev_state;
1561 
1562 	state = svm_get_vmcb_state(sc, vcpu);
1563 	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1564 	vcpustate = svm_get_vcpu(sc, vcpu);
1565 	ev_state = EIS_CAN_INJECT;
1566 
1567 	/* Clear any interrupt shadow if guest %rip has changed */
1568 	if (vcpustate->nextrip != state->rip) {
1569 		ctrl->intr_shadow = 0;
1570 	}
1571 
1572 	/*
1573 	 * An event is already pending for injection.  This can occur when the
1574 	 * vCPU exits prior to VM entry (like for an AST).
1575 	 */
1576 	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1577 		return (EIS_EV_EXISTING | EIS_REQ_EXIT);
1578 	}
1579 
1580 	/*
1581 	 * Inject pending events or exceptions for this vcpu.
1582 	 *
1583 	 * An event might be pending because the previous #VMEXIT happened
1584 	 * during event delivery (i.e. ctrl->exitintinfo).
1585 	 *
1586 	 * An event might also be pending because an exception was injected
1587 	 * by the hypervisor (e.g. #PF during instruction emulation).
1588 	 */
1589 	if (vm_entry_intinfo(sc->vm, vcpu, &intinfo)) {
1590 		svm_inject_event(ctrl, intinfo);
1591 		vmm_stat_incr(sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1592 		ev_state = EIS_EV_INJECTED;
1593 	}
1594 
1595 	/* NMI event has priority over interrupts. */
1596 	if (vm_nmi_pending(sc->vm, vcpu) && !svm_nmi_blocked(sc, vcpu)) {
1597 		if (ev_state == EIS_CAN_INJECT) {
1598 			/* Can't inject NMI if vcpu is in an intr_shadow. */
1599 			if (ctrl->intr_shadow) {
1600 				return (EIS_GI_BLOCK);
1601 			}
1602 
1603 			svm_inject_nmi(sc, vcpu);
1604 			ev_state = EIS_EV_INJECTED;
1605 		} else {
1606 			return (ev_state | EIS_REQ_EXIT);
1607 		}
1608 	}
1609 
1610 	if (vm_extint_pending(sc->vm, vcpu)) {
1611 		int vector;
1612 
1613 		if (ev_state != EIS_CAN_INJECT) {
1614 			return (ev_state | EIS_REQ_EXIT);
1615 		}
1616 
1617 		/*
1618 		 * If the guest has disabled interrupts or is in an interrupt
1619 		 * shadow then we cannot inject the pending interrupt.
1620 		 */
1621 		if ((state->rflags & PSL_I) == 0 || ctrl->intr_shadow) {
1622 			return (EIS_GI_BLOCK);
1623 		}
1624 
1625 		/* Ask the legacy pic for a vector to inject */
1626 		vatpic_pending_intr(sc->vm, &vector);
1627 		KASSERT(vector >= 0 && vector <= 255,
1628 		    ("invalid vector %d from INTR", vector));
1629 
1630 		svm_inject_irq(sc, vcpu, vector);
1631 		vm_extint_clear(sc->vm, vcpu);
1632 		vatpic_intr_accepted(sc->vm, vector);
1633 		ev_state = EIS_EV_INJECTED;
1634 	}
1635 
1636 	return (ev_state);
1637 }
1638 
1639 /*
1640  * Synchronize vLAPIC state and inject any interrupts pending on it.
1641  *
1642  * This is done with host CPU interrupts disabled so notification IPIs will be
1643  * queued on the host APIC and recognized when entering SVM guest context.
1644  */
1645 static enum event_inject_state
1646 svm_inject_vlapic(struct svm_softc *sc, int vcpu, struct vlapic *vlapic,
1647     enum event_inject_state ev_state)
1648 {
1649 	struct vmcb_ctrl *ctrl;
1650 	struct vmcb_state *state;
1651 	int vector;
1652 	uint8_t v_tpr;
1653 
1654 	state = svm_get_vmcb_state(sc, vcpu);
1655 	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1656 
1657 	/*
1658 	 * The guest can modify the TPR by writing to %cr8. In guest mode the
1659 	 * CPU reflects this write to V_TPR without hypervisor intervention.
1660 	 *
1661 	 * The guest can also modify the TPR by writing to it via the memory
1662 	 * mapped APIC page. In this case, the write will be emulated by the
1663 	 * hypervisor. For this reason V_TPR must be updated before every
1664 	 * VMRUN.
1665 	 */
1666 	v_tpr = vlapic_get_cr8(vlapic);
1667 	KASSERT(v_tpr <= 15, ("invalid v_tpr %x", v_tpr));
1668 	if (ctrl->v_tpr != v_tpr) {
1669 		ctrl->v_tpr = v_tpr;
1670 		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1671 	}
1672 
1673 	/* If an event cannot otherwise be injected, we are done for now */
1674 	if (ev_state != EIS_CAN_INJECT) {
1675 		return (ev_state);
1676 	}
1677 
1678 	if (!vlapic_pending_intr(vlapic, &vector)) {
1679 		return (EIS_CAN_INJECT);
1680 	}
1681 	KASSERT(vector >= 16 && vector <= 255,
1682 	    ("invalid vector %d from local APIC", vector));
1683 
1684 	/*
1685 	 * If the guest has disabled interrupts or is in an interrupt shadow
1686 	 * then we cannot inject the pending interrupt.
1687 	 */
1688 	if ((state->rflags & PSL_I) == 0 || ctrl->intr_shadow) {
1689 		return (EIS_GI_BLOCK);
1690 	}
1691 
1692 	svm_inject_irq(sc, vcpu, vector);
1693 	vlapic_intr_accepted(vlapic, vector);
1694 	return (EIS_EV_INJECTED);
1695 }
1696 
1697 /*
1698  * Re-check for events to be injected.
1699  *
1700  * Once host CPU interrupts are disabled, check for the presence of any events
1701  * which require injection processing.  If an exit is required upon injection,
1702  * or once the guest becomes interruptable, that will be configured too.
1703  */
1704 static bool
1705 svm_inject_recheck(struct svm_softc *sc, int vcpu,
1706     enum event_inject_state ev_state)
1707 {
1708 	struct vmcb_ctrl *ctrl;
1709 
1710 	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1711 
1712 	if (ev_state == EIS_CAN_INJECT) {
1713 		/*
1714 		 * An active interrupt shadow would preclude us from injecting
1715 		 * any events picked up during a re-check.
1716 		 */
1717 		if (ctrl->intr_shadow != 0) {
1718 			return (false);
1719 		}
1720 
1721 		if (vm_nmi_pending(sc->vm, vcpu) &&
1722 		    !svm_nmi_blocked(sc, vcpu)) {
1723 			/* queued NMI not blocked by NMI-window-exiting */
1724 			return (true);
1725 		}
1726 		if (vm_extint_pending(sc->vm, vcpu)) {
1727 			/* queued ExtINT not blocked by existing injection */
1728 			return (true);
1729 		}
1730 	} else {
1731 		if ((ev_state & EIS_REQ_EXIT) != 0) {
1732 			/*
1733 			 * Use a self-IPI to force an immediate exit after
1734 			 * event injection has occurred.
1735 			 */
1736 			poke_cpu(CPU->cpu_id);
1737 		} else {
1738 			/*
1739 			 * If any event is being injected, an exit immediately
1740 			 * upon becoming interruptable again will allow pending
1741 			 * or newly queued events to be injected in a timely
1742 			 * manner.
1743 			 */
1744 			svm_enable_intr_window_exiting(sc, vcpu);
1745 		}
1746 	}
1747 	return (false);
1748 }
1749 
1750 
1751 static void
1752 check_asid(struct svm_softc *sc, int vcpuid, uint_t thiscpu, uint64_t nptgen)
1753 {
1754 	struct svm_vcpu *vcpustate = svm_get_vcpu(sc, vcpuid);
1755 	struct vmcb_ctrl *ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1756 	uint8_t flush;
1757 
1758 	flush = hma_svm_asid_update(&vcpustate->hma_asid, flush_by_asid(),
1759 	    vcpustate->nptgen != nptgen);
1760 
1761 	if (flush != VMCB_TLB_FLUSH_NOTHING) {
1762 		ctrl->asid = vcpustate->hma_asid.hsa_asid;
1763 		svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1764 	}
1765 	ctrl->tlb_ctrl = flush;
1766 	vcpustate->nptgen = nptgen;
1767 }
1768 
1769 static void
1770 flush_asid(struct svm_softc *sc, int vcpuid)
1771 {
1772 	struct svm_vcpu *vcpustate = svm_get_vcpu(sc, vcpuid);
1773 	struct vmcb_ctrl *ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1774 	uint8_t flush;
1775 
1776 	flush = hma_svm_asid_update(&vcpustate->hma_asid, flush_by_asid(),
1777 	    true);
1778 
1779 	ASSERT(flush != VMCB_TLB_FLUSH_NOTHING);
1780 	ctrl->asid = vcpustate->hma_asid.hsa_asid;
1781 	ctrl->tlb_ctrl = flush;
1782 	svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1783 	/*
1784 	 * A potential future optimization: We could choose to update the nptgen
1785 	 * associated with the vCPU, since any pending nptgen change requiring a
1786 	 * flush will be satisfied by the one which has just now been queued.
1787 	 */
1788 }
1789 
1790 static __inline void
1791 disable_gintr(void)
1792 {
1793 	__asm __volatile("clgi");
1794 }
1795 
1796 static __inline void
1797 enable_gintr(void)
1798 {
1799 	__asm __volatile("stgi");
1800 }
1801 
1802 static __inline void
1803 svm_dr_enter_guest(struct svm_regctx *gctx)
1804 {
1805 
1806 	/* Save host control debug registers. */
1807 	gctx->host_dr7 = rdr7();
1808 	gctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
1809 
1810 	/*
1811 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
1812 	 * exceptions in the host based on the guest DRx values.  The
1813 	 * guest DR6, DR7, and DEBUGCTL are saved/restored in the
1814 	 * VMCB.
1815 	 */
1816 	load_dr7(0);
1817 	wrmsr(MSR_DEBUGCTLMSR, 0);
1818 
1819 	/* Save host debug registers. */
1820 	gctx->host_dr0 = rdr0();
1821 	gctx->host_dr1 = rdr1();
1822 	gctx->host_dr2 = rdr2();
1823 	gctx->host_dr3 = rdr3();
1824 	gctx->host_dr6 = rdr6();
1825 
1826 	/* Restore guest debug registers. */
1827 	load_dr0(gctx->sctx_dr0);
1828 	load_dr1(gctx->sctx_dr1);
1829 	load_dr2(gctx->sctx_dr2);
1830 	load_dr3(gctx->sctx_dr3);
1831 }
1832 
1833 static __inline void
1834 svm_dr_leave_guest(struct svm_regctx *gctx)
1835 {
1836 
1837 	/* Save guest debug registers. */
1838 	gctx->sctx_dr0 = rdr0();
1839 	gctx->sctx_dr1 = rdr1();
1840 	gctx->sctx_dr2 = rdr2();
1841 	gctx->sctx_dr3 = rdr3();
1842 
1843 	/*
1844 	 * Restore host debug registers.  Restore DR7 and DEBUGCTL
1845 	 * last.
1846 	 */
1847 	load_dr0(gctx->host_dr0);
1848 	load_dr1(gctx->host_dr1);
1849 	load_dr2(gctx->host_dr2);
1850 	load_dr3(gctx->host_dr3);
1851 	load_dr6(gctx->host_dr6);
1852 	wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
1853 	load_dr7(gctx->host_dr7);
1854 }
1855 
1856 static void
1857 svm_apply_tsc_adjust(struct svm_softc *svm_sc, int vcpuid)
1858 {
1859 	const uint64_t offset = vcpu_tsc_offset(svm_sc->vm, vcpuid, true);
1860 	struct vmcb_ctrl *ctrl = svm_get_vmcb_ctrl(svm_sc, vcpuid);
1861 
1862 	if (ctrl->tsc_offset != offset) {
1863 		ctrl->tsc_offset = offset;
1864 		svm_set_dirty(svm_sc, vcpuid, VMCB_CACHE_I);
1865 	}
1866 }
1867 
1868 
1869 /*
1870  * Start vcpu with specified RIP.
1871  */
1872 static int
1873 svm_vmrun(void *arg, int vcpu, uint64_t rip)
1874 {
1875 	struct svm_regctx *gctx;
1876 	struct svm_softc *svm_sc;
1877 	struct svm_vcpu *vcpustate;
1878 	struct vmcb_state *state;
1879 	struct vmcb_ctrl *ctrl;
1880 	struct vm_exit *vmexit;
1881 	struct vlapic *vlapic;
1882 	vm_client_t *vmc;
1883 	struct vm *vm;
1884 	uint64_t vmcb_pa;
1885 	int handled;
1886 	uint16_t ldt_sel;
1887 
1888 	svm_sc = arg;
1889 	vm = svm_sc->vm;
1890 
1891 	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1892 	state = svm_get_vmcb_state(svm_sc, vcpu);
1893 	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1894 	vmexit = vm_exitinfo(vm, vcpu);
1895 	vlapic = vm_lapic(vm, vcpu);
1896 	vmc = vm_get_vmclient(vm, vcpu);
1897 
1898 	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1899 	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1900 
1901 	if (vcpustate->lastcpu != curcpu) {
1902 		/*
1903 		 * Force new ASID allocation by invalidating the generation.
1904 		 */
1905 		vcpustate->hma_asid.hsa_gen = 0;
1906 
1907 		/*
1908 		 * Invalidate the VMCB state cache by marking all fields dirty.
1909 		 */
1910 		svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1911 
1912 		/*
1913 		 * XXX
1914 		 * Setting 'vcpustate->lastcpu' here is bit premature because
1915 		 * we may return from this function without actually executing
1916 		 * the VMRUN  instruction. This could happen if an AST or yield
1917 		 * condition is pending on the first time through the loop.
1918 		 *
1919 		 * This works for now but any new side-effects of vcpu
1920 		 * migration should take this case into account.
1921 		 */
1922 		vcpustate->lastcpu = curcpu;
1923 		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1924 	}
1925 
1926 	svm_apply_tsc_adjust(svm_sc, vcpu);
1927 
1928 	svm_msr_guest_enter(svm_sc, vcpu);
1929 
1930 	VERIFY(!vcpustate->loaded && curthread->t_preempt != 0);
1931 	vcpustate->loaded = B_TRUE;
1932 
1933 	/* Update Guest RIP */
1934 	state->rip = rip;
1935 
1936 	do {
1937 		enum event_inject_state inject_state;
1938 		uint64_t nptgen;
1939 
1940 		/*
1941 		 * Initial event injection is complex and may involve mutex
1942 		 * contention, so it must be performed with global interrupts
1943 		 * still enabled.
1944 		 */
1945 		inject_state = svm_inject_events(svm_sc, vcpu);
1946 		handled = 0;
1947 
1948 		/*
1949 		 * Disable global interrupts to guarantee atomicity during
1950 		 * loading of guest state. This includes not only the state
1951 		 * loaded by the "vmrun" instruction but also software state
1952 		 * maintained by the hypervisor: suspended and rendezvous
1953 		 * state, NPT generation number, vlapic interrupts etc.
1954 		 */
1955 		disable_gintr();
1956 
1957 		/*
1958 		 * Synchronizing and injecting vlapic state is lock-free and is
1959 		 * safe (and prudent) to perform with interrupts disabled.
1960 		 */
1961 		inject_state = svm_inject_vlapic(svm_sc, vcpu, vlapic,
1962 		    inject_state);
1963 
1964 		/*
1965 		 * Check for vCPU bail-out conditions.  This must be done after
1966 		 * svm_inject_events() to detect a triple-fault condition.
1967 		 */
1968 		if (vcpu_entry_bailout_checks(vm, vcpu, state->rip)) {
1969 			enable_gintr();
1970 			break;
1971 		}
1972 
1973 		if (vcpu_run_state_pending(vm, vcpu)) {
1974 			enable_gintr();
1975 			vm_exit_run_state(vm, vcpu, state->rip);
1976 			break;
1977 		}
1978 
1979 		/*
1980 		 * If subsequent activity queued events which require injection
1981 		 * handling, take another lap to handle them.
1982 		 */
1983 		if (svm_inject_recheck(svm_sc, vcpu, inject_state)) {
1984 			enable_gintr();
1985 			handled = 1;
1986 			continue;
1987 		}
1988 
1989 		/*
1990 		 * #VMEXIT resumes the host with the guest LDTR, so
1991 		 * save the current LDT selector so it can be restored
1992 		 * after an exit.  The userspace hypervisor probably
1993 		 * doesn't use a LDT, but save and restore it to be
1994 		 * safe.
1995 		 */
1996 		ldt_sel = sldt();
1997 
1998 		/*
1999 		 * Check the vmspace and ASID generations to ensure that the
2000 		 * vcpu does not use stale TLB mappings.
2001 		 */
2002 		nptgen = vmc_table_enter(vmc);
2003 		check_asid(svm_sc, vcpu, curcpu, nptgen);
2004 
2005 		ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
2006 		vcpustate->dirty = 0;
2007 
2008 		/* Launch Virtual Machine. */
2009 		vcpu_ustate_change(vm, vcpu, VU_RUN);
2010 		svm_dr_enter_guest(gctx);
2011 		svm_launch(vmcb_pa, gctx, get_pcpu());
2012 		svm_dr_leave_guest(gctx);
2013 		vcpu_ustate_change(vm, vcpu, VU_EMU_KERN);
2014 
2015 		/* Restore host LDTR. */
2016 		lldt(ldt_sel);
2017 
2018 		/* #VMEXIT disables interrupts so re-enable them here. */
2019 		enable_gintr();
2020 
2021 		vmc_table_exit(vmc);
2022 
2023 		/* Update 'nextrip' */
2024 		vcpustate->nextrip = state->rip;
2025 
2026 		/* Handle #VMEXIT and if required return to user space. */
2027 		handled = svm_vmexit(svm_sc, vcpu, vmexit);
2028 	} while (handled);
2029 
2030 	svm_msr_guest_exit(svm_sc, vcpu);
2031 
2032 	VERIFY(vcpustate->loaded && curthread->t_preempt != 0);
2033 	vcpustate->loaded = B_FALSE;
2034 
2035 	return (0);
2036 }
2037 
2038 static void
2039 svm_vmcleanup(void *arg)
2040 {
2041 	struct svm_softc *sc = arg;
2042 
2043 	vmm_contig_free(sc->iopm_bitmap, SVM_IO_BITMAP_SIZE);
2044 	vmm_contig_free(sc->msr_bitmap, SVM_MSR_BITMAP_SIZE);
2045 	kmem_free(sc, sizeof (*sc));
2046 }
2047 
2048 static uint64_t *
2049 swctx_regptr(struct svm_regctx *regctx, int reg)
2050 {
2051 	switch (reg) {
2052 	case VM_REG_GUEST_RBX:
2053 		return (&regctx->sctx_rbx);
2054 	case VM_REG_GUEST_RCX:
2055 		return (&regctx->sctx_rcx);
2056 	case VM_REG_GUEST_RDX:
2057 		return (&regctx->sctx_rdx);
2058 	case VM_REG_GUEST_RDI:
2059 		return (&regctx->sctx_rdi);
2060 	case VM_REG_GUEST_RSI:
2061 		return (&regctx->sctx_rsi);
2062 	case VM_REG_GUEST_RBP:
2063 		return (&regctx->sctx_rbp);
2064 	case VM_REG_GUEST_R8:
2065 		return (&regctx->sctx_r8);
2066 	case VM_REG_GUEST_R9:
2067 		return (&regctx->sctx_r9);
2068 	case VM_REG_GUEST_R10:
2069 		return (&regctx->sctx_r10);
2070 	case VM_REG_GUEST_R11:
2071 		return (&regctx->sctx_r11);
2072 	case VM_REG_GUEST_R12:
2073 		return (&regctx->sctx_r12);
2074 	case VM_REG_GUEST_R13:
2075 		return (&regctx->sctx_r13);
2076 	case VM_REG_GUEST_R14:
2077 		return (&regctx->sctx_r14);
2078 	case VM_REG_GUEST_R15:
2079 		return (&regctx->sctx_r15);
2080 	case VM_REG_GUEST_DR0:
2081 		return (&regctx->sctx_dr0);
2082 	case VM_REG_GUEST_DR1:
2083 		return (&regctx->sctx_dr1);
2084 	case VM_REG_GUEST_DR2:
2085 		return (&regctx->sctx_dr2);
2086 	case VM_REG_GUEST_DR3:
2087 		return (&regctx->sctx_dr3);
2088 	default:
2089 		return (NULL);
2090 	}
2091 }
2092 
2093 static int
2094 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2095 {
2096 	struct svm_softc *sc;
2097 	struct vmcb *vmcb;
2098 	uint64_t *regp;
2099 	uint64_t *fieldp;
2100 	struct vmcb_segment *seg;
2101 
2102 	sc = arg;
2103 	vmcb = svm_get_vmcb(sc, vcpu);
2104 
2105 	regp = swctx_regptr(svm_get_guest_regctx(sc, vcpu), ident);
2106 	if (regp != NULL) {
2107 		*val = *regp;
2108 		return (0);
2109 	}
2110 
2111 	switch (ident) {
2112 	case VM_REG_GUEST_INTR_SHADOW:
2113 		*val = (vmcb->ctrl.intr_shadow != 0) ? 1 : 0;
2114 		break;
2115 
2116 	case VM_REG_GUEST_CR0:
2117 		svm_get_cr0(sc, vcpu, val);
2118 		break;
2119 	case VM_REG_GUEST_CR2:
2120 	case VM_REG_GUEST_CR3:
2121 	case VM_REG_GUEST_CR4:
2122 	case VM_REG_GUEST_DR6:
2123 	case VM_REG_GUEST_DR7:
2124 	case VM_REG_GUEST_EFER:
2125 	case VM_REG_GUEST_RAX:
2126 	case VM_REG_GUEST_RFLAGS:
2127 	case VM_REG_GUEST_RIP:
2128 	case VM_REG_GUEST_RSP:
2129 		fieldp = vmcb_regptr(vmcb, ident, NULL);
2130 		*val = *fieldp;
2131 		break;
2132 
2133 	case VM_REG_GUEST_CS:
2134 	case VM_REG_GUEST_DS:
2135 	case VM_REG_GUEST_ES:
2136 	case VM_REG_GUEST_FS:
2137 	case VM_REG_GUEST_GS:
2138 	case VM_REG_GUEST_SS:
2139 	case VM_REG_GUEST_LDTR:
2140 	case VM_REG_GUEST_TR:
2141 		seg = vmcb_segptr(vmcb, ident);
2142 		*val = seg->selector;
2143 		break;
2144 
2145 	case VM_REG_GUEST_GDTR:
2146 	case VM_REG_GUEST_IDTR:
2147 		/* GDTR and IDTR don't have segment selectors */
2148 		return (EINVAL);
2149 
2150 	case VM_REG_GUEST_PDPTE0:
2151 	case VM_REG_GUEST_PDPTE1:
2152 	case VM_REG_GUEST_PDPTE2:
2153 	case VM_REG_GUEST_PDPTE3:
2154 		/*
2155 		 * Unlike VMX, where the PDPTEs are explicitly cached as part of
2156 		 * several well-defined events related to paging (such as
2157 		 * loading %cr3), SVM walks the PDPEs (their PDPTE) as part of
2158 		 * nested paging lookups.  This makes these registers
2159 		 * effectively irrelevant on SVM.
2160 		 *
2161 		 * Rather than tossing an error, emit zeroed values so casual
2162 		 * consumers do not need to be as careful about that difference.
2163 		 */
2164 		*val = 0;
2165 		break;
2166 
2167 	default:
2168 		return (EINVAL);
2169 	}
2170 
2171 	return (0);
2172 }
2173 
2174 static int
2175 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2176 {
2177 	struct svm_softc *sc;
2178 	struct vmcb *vmcb;
2179 	uint64_t *regp;
2180 	uint64_t *fieldp;
2181 	uint32_t dirty;
2182 	struct vmcb_segment *seg;
2183 
2184 	sc = arg;
2185 	vmcb = svm_get_vmcb(sc, vcpu);
2186 
2187 	regp = swctx_regptr(svm_get_guest_regctx(sc, vcpu), ident);
2188 	if (regp != NULL) {
2189 		*regp = val;
2190 		return (0);
2191 	}
2192 
2193 	dirty = VMCB_CACHE_NONE;
2194 	switch (ident) {
2195 	case VM_REG_GUEST_INTR_SHADOW:
2196 		vmcb->ctrl.intr_shadow = (val != 0) ? 1 : 0;
2197 		break;
2198 
2199 	case VM_REG_GUEST_EFER:
2200 		fieldp = vmcb_regptr(vmcb, ident, &dirty);
2201 		/* EFER_SVM must always be set when the guest is executing */
2202 		*fieldp = val | EFER_SVM;
2203 		dirty |= VMCB_CACHE_CR;
2204 		break;
2205 
2206 	case VM_REG_GUEST_CR0:
2207 		svm_set_cr0(sc, vcpu, val, false);
2208 		break;
2209 	case VM_REG_GUEST_CR2:
2210 	case VM_REG_GUEST_CR3:
2211 	case VM_REG_GUEST_CR4:
2212 	case VM_REG_GUEST_DR6:
2213 	case VM_REG_GUEST_DR7:
2214 	case VM_REG_GUEST_RAX:
2215 	case VM_REG_GUEST_RFLAGS:
2216 	case VM_REG_GUEST_RIP:
2217 	case VM_REG_GUEST_RSP:
2218 		fieldp = vmcb_regptr(vmcb, ident, &dirty);
2219 		*fieldp = val;
2220 		break;
2221 
2222 	case VM_REG_GUEST_CS:
2223 	case VM_REG_GUEST_DS:
2224 	case VM_REG_GUEST_ES:
2225 	case VM_REG_GUEST_SS:
2226 	case VM_REG_GUEST_FS:
2227 	case VM_REG_GUEST_GS:
2228 	case VM_REG_GUEST_LDTR:
2229 	case VM_REG_GUEST_TR:
2230 		dirty |= VMCB_CACHE_SEG;
2231 		seg = vmcb_segptr(vmcb, ident);
2232 		seg->selector = (uint16_t)val;
2233 		break;
2234 
2235 	case VM_REG_GUEST_GDTR:
2236 	case VM_REG_GUEST_IDTR:
2237 		/* GDTR and IDTR don't have segment selectors */
2238 		return (EINVAL);
2239 
2240 	case VM_REG_GUEST_PDPTE0:
2241 	case VM_REG_GUEST_PDPTE1:
2242 	case VM_REG_GUEST_PDPTE2:
2243 	case VM_REG_GUEST_PDPTE3:
2244 		/*
2245 		 * PDPEs (AMD's PDPTE) are not cached under SVM, so we can
2246 		 * ignore attempts to set them.  See handler in svm_getreg() for
2247 		 * more details.
2248 		 */
2249 		break;
2250 
2251 	default:
2252 		return (EINVAL);
2253 	}
2254 
2255 	if (dirty != VMCB_CACHE_NONE) {
2256 		svm_set_dirty(sc, vcpu, dirty);
2257 	}
2258 
2259 	/*
2260 	 * XXX deal with CR3 and invalidate TLB entries tagged with the
2261 	 * vcpu's ASID. This needs to be treated differently depending on
2262 	 * whether 'running' is true/false.
2263 	 */
2264 
2265 	return (0);
2266 }
2267 
2268 static int
2269 svm_setdesc(void *arg, int vcpu, int reg, const struct seg_desc *desc)
2270 {
2271 	struct vmcb *vmcb;
2272 	struct svm_softc *sc;
2273 	struct vmcb_segment *seg;
2274 
2275 	sc = arg;
2276 	vmcb = svm_get_vmcb(sc, vcpu);
2277 
2278 	switch (reg) {
2279 	case VM_REG_GUEST_CS:
2280 	case VM_REG_GUEST_DS:
2281 	case VM_REG_GUEST_ES:
2282 	case VM_REG_GUEST_SS:
2283 	case VM_REG_GUEST_FS:
2284 	case VM_REG_GUEST_GS:
2285 	case VM_REG_GUEST_LDTR:
2286 	case VM_REG_GUEST_TR:
2287 		svm_set_dirty(sc, vcpu, VMCB_CACHE_SEG);
2288 		seg = vmcb_segptr(vmcb, reg);
2289 		/*
2290 		 * Map seg_desc access to VMCB attribute format.
2291 		 *
2292 		 * SVM uses the 'P' bit in the segment attributes to indicate a
2293 		 * NULL segment so clear it if the segment is marked unusable.
2294 		 */
2295 		seg->attrib = VMCB_ACCESS2ATTR(desc->access);
2296 		if (SEG_DESC_UNUSABLE(desc->access)) {
2297 			seg->attrib &= ~0x80;
2298 		}
2299 		/*
2300 		 * Keep CPL synced with the DPL specified for %ss.
2301 		 *
2302 		 * KVM notes that a SYSRET to non-cpl-3 is possible on AMD
2303 		 * (unlike Intel), but accepts such a possible deviation for
2304 		 * what is otherwise unreasonable behavior for a guest OS, since
2305 		 * they do the same synchronization.
2306 		 */
2307 		if (reg == VM_REG_GUEST_SS) {
2308 			vmcb->state.cpl = SEG_DESC_DPL(desc->access);
2309 		}
2310 		break;
2311 
2312 	case VM_REG_GUEST_GDTR:
2313 	case VM_REG_GUEST_IDTR:
2314 		svm_set_dirty(sc, vcpu, VMCB_CACHE_DT);
2315 		seg = vmcb_segptr(vmcb, reg);
2316 		break;
2317 
2318 	default:
2319 		return (EINVAL);
2320 	}
2321 
2322 	ASSERT(seg != NULL);
2323 	seg->base = desc->base;
2324 	seg->limit = desc->limit;
2325 
2326 	return (0);
2327 }
2328 
2329 static int
2330 svm_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2331 {
2332 	struct vmcb *vmcb;
2333 	struct svm_softc *sc;
2334 	struct vmcb_segment *seg;
2335 
2336 	sc = arg;
2337 	vmcb = svm_get_vmcb(sc, vcpu);
2338 
2339 	switch (reg) {
2340 	case VM_REG_GUEST_DS:
2341 	case VM_REG_GUEST_ES:
2342 	case VM_REG_GUEST_FS:
2343 	case VM_REG_GUEST_GS:
2344 	case VM_REG_GUEST_SS:
2345 	case VM_REG_GUEST_LDTR:
2346 		seg = vmcb_segptr(vmcb, reg);
2347 		desc->access = VMCB_ATTR2ACCESS(seg->attrib);
2348 		/*
2349 		 * VT-x uses bit 16 to indicate a segment that has been loaded
2350 		 * with a NULL selector (aka unusable). The 'desc->access'
2351 		 * field is interpreted in the VT-x format by the
2352 		 * processor-independent code.
2353 		 *
2354 		 * SVM uses the 'P' bit to convey the same information so
2355 		 * convert it into the VT-x format. For more details refer to
2356 		 * section "Segment State in the VMCB" in APMv2.
2357 		 */
2358 		if ((desc->access & 0x80) == 0) {
2359 			/* Unusable segment */
2360 			desc->access |= 0x10000;
2361 		}
2362 		break;
2363 
2364 	case VM_REG_GUEST_CS:
2365 	case VM_REG_GUEST_TR:
2366 		seg = vmcb_segptr(vmcb, reg);
2367 		desc->access = VMCB_ATTR2ACCESS(seg->attrib);
2368 		break;
2369 
2370 	case VM_REG_GUEST_GDTR:
2371 	case VM_REG_GUEST_IDTR:
2372 		seg = vmcb_segptr(vmcb, reg);
2373 		/*
2374 		 * Since there are no access bits associated with the GDTR or
2375 		 * the IDTR, zero out the field to ensure it does not contain
2376 		 * garbage which might confuse the consumer.
2377 		 */
2378 		desc->access = 0;
2379 		break;
2380 
2381 	default:
2382 		return (EINVAL);
2383 	}
2384 
2385 	ASSERT(seg != NULL);
2386 	desc->base = seg->base;
2387 	desc->limit = seg->limit;
2388 	return (0);
2389 }
2390 
2391 static int
2392 svm_get_msr(void *arg, int vcpu, uint32_t msr, uint64_t *valp)
2393 {
2394 	struct svm_softc *sc = arg;
2395 	struct vmcb *vmcb = svm_get_vmcb(sc, vcpu);
2396 	const uint64_t *msrp = vmcb_msr_ptr(vmcb, msr, NULL);
2397 
2398 	if (msrp != NULL) {
2399 		*valp = *msrp;
2400 		return (0);
2401 	}
2402 
2403 	return (EINVAL);
2404 }
2405 
2406 static int
2407 svm_set_msr(void *arg, int vcpu, uint32_t msr, uint64_t val)
2408 {
2409 	struct svm_softc *sc = arg;
2410 	struct vmcb *vmcb = svm_get_vmcb(sc, vcpu);
2411 
2412 	uint32_t dirty = 0;
2413 	uint64_t *msrp = vmcb_msr_ptr(vmcb, msr, &dirty);
2414 	if (msrp == NULL) {
2415 		return (EINVAL);
2416 	}
2417 	switch (msr) {
2418 	case MSR_EFER:
2419 		/*
2420 		 * For now, just clone the logic from
2421 		 * svm_setreg():
2422 		 *
2423 		 * EFER_SVM must always be set when the guest is
2424 		 * executing
2425 		 */
2426 		*msrp = val | EFER_SVM;
2427 		break;
2428 	/* TODO: other necessary MSR masking */
2429 	default:
2430 		*msrp = val;
2431 		break;
2432 	}
2433 	if (dirty != 0) {
2434 		svm_set_dirty(sc, vcpu, dirty);
2435 	}
2436 	return (0);
2437 
2438 }
2439 
2440 static int
2441 svm_setcap(void *arg, int vcpu, int type, int val)
2442 {
2443 	struct svm_softc *sc;
2444 	int error;
2445 
2446 	sc = arg;
2447 	error = 0;
2448 	switch (type) {
2449 	case VM_CAP_HALT_EXIT:
2450 		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2451 		    VMCB_INTCPT_HLT, val);
2452 		break;
2453 	case VM_CAP_PAUSE_EXIT:
2454 		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2455 		    VMCB_INTCPT_PAUSE, val);
2456 		break;
2457 	default:
2458 		error = ENOENT;
2459 		break;
2460 	}
2461 	return (error);
2462 }
2463 
2464 static int
2465 svm_getcap(void *arg, int vcpu, int type, int *retval)
2466 {
2467 	struct svm_softc *sc;
2468 	int error;
2469 
2470 	sc = arg;
2471 	error = 0;
2472 
2473 	switch (type) {
2474 	case VM_CAP_HALT_EXIT:
2475 		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2476 		    VMCB_INTCPT_HLT);
2477 		break;
2478 	case VM_CAP_PAUSE_EXIT:
2479 		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2480 		    VMCB_INTCPT_PAUSE);
2481 		break;
2482 	default:
2483 		error = ENOENT;
2484 		break;
2485 	}
2486 	return (error);
2487 }
2488 
2489 static struct vlapic *
2490 svm_vlapic_init(void *arg, int vcpuid)
2491 {
2492 	struct svm_softc *svm_sc;
2493 	struct vlapic *vlapic;
2494 
2495 	svm_sc = arg;
2496 	vlapic = kmem_zalloc(sizeof (struct vlapic), KM_SLEEP);
2497 	vlapic->vm = svm_sc->vm;
2498 	vlapic->vcpuid = vcpuid;
2499 	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2500 
2501 	vlapic_init(vlapic);
2502 
2503 	return (vlapic);
2504 }
2505 
2506 static void
2507 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2508 {
2509 	vlapic_cleanup(vlapic);
2510 	kmem_free(vlapic, sizeof (struct vlapic));
2511 }
2512 
2513 static void
2514 svm_savectx(void *arg, int vcpu)
2515 {
2516 	struct svm_softc *sc = arg;
2517 
2518 	if (sc->vcpu[vcpu].loaded) {
2519 		svm_msr_guest_exit(sc, vcpu);
2520 	}
2521 }
2522 
2523 static void
2524 svm_restorectx(void *arg, int vcpu)
2525 {
2526 	struct svm_softc *sc = arg;
2527 
2528 	if (sc->vcpu[vcpu].loaded) {
2529 		svm_msr_guest_enter(sc, vcpu);
2530 	}
2531 }
2532 
2533 struct vmm_ops vmm_ops_amd = {
2534 	.init		= svm_init,
2535 	.cleanup	= svm_cleanup,
2536 	.resume		= svm_restore,
2537 
2538 	.vminit		= svm_vminit,
2539 	.vmrun		= svm_vmrun,
2540 	.vmcleanup	= svm_vmcleanup,
2541 	.vmgetreg	= svm_getreg,
2542 	.vmsetreg	= svm_setreg,
2543 	.vmgetdesc	= svm_getdesc,
2544 	.vmsetdesc	= svm_setdesc,
2545 	.vmgetcap	= svm_getcap,
2546 	.vmsetcap	= svm_setcap,
2547 	.vlapic_init	= svm_vlapic_init,
2548 	.vlapic_cleanup	= svm_vlapic_cleanup,
2549 
2550 	.vmsavectx	= svm_savectx,
2551 	.vmrestorectx	= svm_restorectx,
2552 
2553 	.vmgetmsr	= svm_get_msr,
2554 	.vmsetmsr	= svm_set_msr,
2555 };
2556