2 * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice unmodified, this list of conditions, and the following
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/param.h>
31 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
37 #include <sys/sysctl.h>
42 #include <machine/cpufunc.h>
43 #include <machine/psl.h>
44 #include <machine/md_var.h>
45 #include <machine/specialreg.h>
46 #include <machine/smp.h>
47 #include <machine/vmm.h>
48 #include <machine/vmm_dev.h>
49 #include <machine/vmm_instruction_emul.h>
51 #include "vmm_lapic.h"
54 #include "vmm_ioport.h"
57 #include "vlapic_priv.h"
62 #include "svm_softc.h"
67 SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
70 * SVM CPUID function 0x8000_000A, edx bit decoding.
72 #define AMD_CPUID_SVM_NP BIT(0) /* Nested paging or RVI */
73 #define AMD_CPUID_SVM_LBR BIT(1) /* Last branch virtualization */
74 #define AMD_CPUID_SVM_SVML BIT(2) /* SVM lock */
75 #define AMD_CPUID_SVM_NRIP_SAVE BIT(3) /* Next RIP is saved */
76 #define AMD_CPUID_SVM_TSC_RATE BIT(4) /* TSC rate control. */
77 #define AMD_CPUID_SVM_VMCB_CLEAN BIT(5) /* VMCB state caching */
78 #define AMD_CPUID_SVM_FLUSH_BY_ASID BIT(6) /* Flush by ASID */
79 #define AMD_CPUID_SVM_DECODE_ASSIST BIT(7) /* Decode assist */
80 #define AMD_CPUID_SVM_PAUSE_INC BIT(10) /* Pause intercept filter. */
81 #define AMD_CPUID_SVM_PAUSE_FTH BIT(12) /* Pause filter threshold */
82 #define AMD_CPUID_SVM_AVIC BIT(13) /* AVIC present */
84 #define VMCB_CACHE_DEFAULT (VMCB_CACHE_ASID | \
94 static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
95 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
98 static MALLOC_DEFINE(M_SVM, "svm", "svm");
99 static MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
101 /* Per-CPU context area. */
102 extern struct pcpu __pcpu[];
104 static uint32_t svm_feature = ~0U; /* AMD SVM features. */
105 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RDTUN, &svm_feature, 0,
106 "SVM features advertised by CPUID.8000000AH:EDX");
108 static int disable_npf_assist;
109 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
110 &disable_npf_assist, 0, NULL);
112 /* Maximum ASIDs supported by the processor */
113 static uint32_t nasid;
114 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RDTUN, &nasid, 0,
115 "Number of ASIDs supported by this processor");
117 /* Current ASID generation for each host cpu */
118 static struct asid asid[MAXCPU];
121 * SVM host state saved area of size 4KB for each core.
123 static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
125 static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
126 static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
127 static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
129 static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
135 return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
142 return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
146 svm_disable(void *arg __unused)
150 efer = rdmsr(MSR_EFER);
152 wrmsr(MSR_EFER, efer);
156 * Disable SVM on all CPUs.
162 smp_rendezvous(NULL, svm_disable, NULL, NULL);
167 * Verify that all the features required by bhyve are available.
170 check_svm_features(void)
174 /* CPUID Fn8000_000A is for SVM */
175 do_cpuid(0x8000000A, regs);
176 svm_feature &= regs[3];
179 * The number of ASIDs can be configured to be less than what is
180 * supported by the hardware but not more.
182 if (nasid == 0 || nasid > regs[1])
184 KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
186 /* bhyve requires the Nested Paging feature */
187 if (!(svm_feature & AMD_CPUID_SVM_NP)) {
188 printf("SVM: Nested Paging feature not available.\n");
192 /* bhyve requires the NRIP Save feature */
193 if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
194 printf("SVM: NRIP Save feature not available.\n");
202 svm_enable(void *arg __unused)
206 efer = rdmsr(MSR_EFER);
208 wrmsr(MSR_EFER, efer);
210 wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
214 * Return 1 if SVM is enabled on this processor and 0 otherwise.
221 /* Section 15.4 Enabling SVM from APM2. */
222 if ((amd_feature2 & AMDID2_SVM) == 0) {
223 printf("SVM: not available.\n");
227 msr = rdmsr(MSR_VM_CR);
228 if ((msr & VM_CR_SVMDIS) != 0) {
229 printf("SVM: disabled by BIOS.\n");
241 if (!svm_available())
244 error = check_svm_features();
248 vmcb_clean &= VMCB_CACHE_DEFAULT;
250 for (cpu = 0; cpu < MAXCPU; cpu++) {
252 * Initialize the host ASIDs to their "highest" valid values.
254 * The next ASID allocation will rollover both 'gen' and 'num'
255 * and start off the sequence at {1,1}.
257 asid[cpu].gen = ~0UL;
258 asid[cpu].num = nasid - 1;
262 svm_npt_init(ipinum);
264 /* Enable SVM on all CPUs */
265 smp_rendezvous(NULL, svm_enable, NULL, NULL);
277 /* Pentium compatible MSRs */
278 #define MSR_PENTIUM_START 0
279 #define MSR_PENTIUM_END 0x1FFF
280 /* AMD 6th generation and Intel compatible MSRs */
281 #define MSR_AMD6TH_START 0xC0000000UL
282 #define MSR_AMD6TH_END 0xC0001FFFUL
283 /* AMD 7th and 8th generation compatible MSRs */
284 #define MSR_AMD7TH_START 0xC0010000UL
285 #define MSR_AMD7TH_END 0xC0011FFFUL
288 * Get the index and bit position for a MSR in permission bitmap.
289 * Two bits are used for each MSR: lower bit for read and higher bit for write.
292 svm_msr_index(uint64_t msr, int *index, int *bit)
297 *bit = (msr % 4) * 2;
300 if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
305 base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
306 if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
307 off = (msr - MSR_AMD6TH_START);
308 *index = (off + base) / 4;
312 base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
313 if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
314 off = (msr - MSR_AMD7TH_START);
315 *index = (off + base) / 4;
323 * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
326 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
328 int index, bit, error;
330 error = svm_msr_index(msr, &index, &bit);
331 KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
332 KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
333 ("%s: invalid index %d for msr %#lx", __func__, index, msr));
334 KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
335 "msr %#lx", __func__, bit, msr));
338 perm_bitmap[index] &= ~(1UL << bit);
341 perm_bitmap[index] &= ~(2UL << bit);
345 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
348 svm_msr_perm(perm_bitmap, msr, true, true);
352 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
355 svm_msr_perm(perm_bitmap, msr, true, false);
359 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
361 struct vmcb_ctrl *ctrl;
363 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
365 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
366 return (ctrl->intercept[idx] & bitmask ? 1 : 0);
370 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
373 struct vmcb_ctrl *ctrl;
376 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
378 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
379 oldval = ctrl->intercept[idx];
382 ctrl->intercept[idx] |= bitmask;
384 ctrl->intercept[idx] &= ~bitmask;
386 if (ctrl->intercept[idx] != oldval) {
387 svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
388 VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
389 "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
394 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
397 svm_set_intercept(sc, vcpu, off, bitmask, 0);
401 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
404 svm_set_intercept(sc, vcpu, off, bitmask, 1);
408 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
409 uint64_t msrpm_base_pa, uint64_t np_pml4)
411 struct vmcb_ctrl *ctrl;
412 struct vmcb_state *state;
416 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
417 state = svm_get_vmcb_state(sc, vcpu);
419 ctrl->iopm_base_pa = iopm_base_pa;
420 ctrl->msrpm_base_pa = msrpm_base_pa;
422 /* Enable nested paging */
424 ctrl->n_cr3 = np_pml4;
427 * Intercept accesses to the control registers that are not shadowed
428 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
430 for (n = 0; n < 16; n++) {
431 mask = (BIT(n) << 16) | BIT(n);
432 if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
433 svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
435 svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
440 * Intercept everything when tracing guest exceptions otherwise
441 * just intercept machine check exception.
443 if (vcpu_trace_exceptions(sc->vm, vcpu)) {
444 for (n = 0; n < 32; n++) {
446 * Skip unimplemented vectors in the exception bitmap.
448 if (n == 2 || n == 9) {
451 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
454 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
457 /* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
458 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
459 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
460 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
461 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
462 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
463 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
464 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
465 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
466 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
467 VMCB_INTCPT_FERR_FREEZE);
469 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
470 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
473 * From section "Canonicalization and Consistency Checks" in APMv2
474 * the VMRUN intercept bit must be set to pass the consistency check.
476 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
479 * The ASID will be set to a non-zero value just before VMRUN.
484 * Section 15.21.1, Interrupt Masking in EFLAGS
485 * Section 15.21.2, Virtualizing APIC.TPR
487 * This must be set for %rflag and %cr8 isolation of guest and host.
489 ctrl->v_intr_masking = 1;
491 /* Enable Last Branch Record aka LBR for debugging */
492 ctrl->lbr_virt_en = 1;
493 state->dbgctl = BIT(0);
495 /* EFER_SVM must always be set when the guest is executing */
496 state->efer = EFER_SVM;
498 /* Set up the PAT to power-on state */
499 state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK) |
500 PAT_VALUE(1, PAT_WRITE_THROUGH) |
501 PAT_VALUE(2, PAT_UNCACHED) |
502 PAT_VALUE(3, PAT_UNCACHEABLE) |
503 PAT_VALUE(4, PAT_WRITE_BACK) |
504 PAT_VALUE(5, PAT_WRITE_THROUGH) |
505 PAT_VALUE(6, PAT_UNCACHED) |
506 PAT_VALUE(7, PAT_UNCACHEABLE);
510 * Initialize a virtual machine.
513 svm_vminit(struct vm *vm, pmap_t pmap)
515 struct svm_softc *svm_sc;
516 struct svm_vcpu *vcpu;
517 vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
520 svm_sc = malloc(sizeof (*svm_sc), M_SVM, M_WAITOK | M_ZERO);
521 if (((uintptr_t)svm_sc & PAGE_MASK) != 0)
522 panic("malloc of svm_softc not aligned on page boundary");
524 svm_sc->msr_bitmap = contigmalloc(SVM_MSR_BITMAP_SIZE, M_SVM,
525 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
526 if (svm_sc->msr_bitmap == NULL)
527 panic("contigmalloc of SVM MSR bitmap failed");
528 svm_sc->iopm_bitmap = contigmalloc(SVM_IO_BITMAP_SIZE, M_SVM,
529 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
530 if (svm_sc->iopm_bitmap == NULL)
531 panic("contigmalloc of SVM IO bitmap failed");
534 svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
537 * Intercept read and write accesses to all MSRs.
539 memset(svm_sc->msr_bitmap, 0xFF, SVM_MSR_BITMAP_SIZE);
542 * Access to the following MSRs is redirected to the VMCB when the
543 * guest is executing. Therefore it is safe to allow the guest to
544 * read/write these MSRs directly without hypervisor involvement.
546 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
547 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
548 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
550 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
551 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
552 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
553 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
554 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
555 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
556 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
557 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
559 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
562 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
564 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
566 /* Intercept access to all I/O ports. */
567 memset(svm_sc->iopm_bitmap, 0xFF, SVM_IO_BITMAP_SIZE);
569 iopm_pa = vtophys(svm_sc->iopm_bitmap);
570 msrpm_pa = vtophys(svm_sc->msr_bitmap);
571 pml4_pa = svm_sc->nptp;
572 for (i = 0; i < VM_MAXCPU; i++) {
573 vcpu = svm_get_vcpu(svm_sc, i);
575 vcpu->lastcpu = NOCPU;
576 vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
577 vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
578 svm_msr_guest_init(svm_sc, i);
584 * Collateral for a generic SVM VM-exit.
587 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
590 vme->exitcode = VM_EXITCODE_SVM;
591 vme->u.svm.exitcode = code;
592 vme->u.svm.exitinfo1 = info1;
593 vme->u.svm.exitinfo2 = info2;
597 svm_cpl(struct vmcb_state *state)
602 * "Retrieve the CPL from the CPL field in the VMCB, not
603 * from any segment DPL"
608 static enum vm_cpu_mode
609 svm_vcpu_mode(struct vmcb *vmcb)
611 struct vmcb_segment seg;
612 struct vmcb_state *state;
615 state = &vmcb->state;
617 if (state->efer & EFER_LMA) {
618 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
619 KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
623 * Section 4.8.1 for APM2, check if Code Segment has
624 * Long attribute set in descriptor.
626 if (seg.attrib & VMCB_CS_ATTRIB_L)
627 return (CPU_MODE_64BIT);
629 return (CPU_MODE_COMPATIBILITY);
630 } else if (state->cr0 & CR0_PE) {
631 return (CPU_MODE_PROTECTED);
633 return (CPU_MODE_REAL);
637 static enum vm_paging_mode
638 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
641 if ((cr0 & CR0_PG) == 0)
642 return (PAGING_MODE_FLAT);
643 if ((cr4 & CR4_PAE) == 0)
644 return (PAGING_MODE_32);
646 return (PAGING_MODE_64);
648 return (PAGING_MODE_PAE);
652 * ins/outs utility routines
655 svm_inout_str_index(struct svm_regctx *regs, int in)
659 val = in ? regs->sctx_rdi : regs->sctx_rsi;
665 svm_inout_str_count(struct svm_regctx *regs, int rep)
669 val = rep ? regs->sctx_rcx : 1;
675 svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
676 int in, struct vm_inout_str *vis)
681 vis->seg_name = VM_REG_GUEST_ES;
683 /* The segment field has standard encoding */
684 s = (info1 >> 10) & 0x7;
685 vis->seg_name = vm_segment_name(s);
688 error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
689 KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
693 svm_inout_str_addrsize(uint64_t info1)
697 size = (info1 >> 7) & 0x7;
700 return (2); /* 16 bit */
702 return (4); /* 32 bit */
704 return (8); /* 64 bit */
706 panic("%s: invalid size encoding %d", __func__, size);
711 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
713 struct vmcb_state *state;
715 state = &vmcb->state;
716 paging->cr3 = state->cr3;
717 paging->cpl = svm_cpl(state);
718 paging->cpu_mode = svm_vcpu_mode(vmcb);
719 paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
726 * Handle guest I/O intercept.
729 svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
731 struct vmcb_ctrl *ctrl;
732 struct vmcb_state *state;
733 struct svm_regctx *regs;
734 struct vm_inout_str *vis;
738 state = svm_get_vmcb_state(svm_sc, vcpu);
739 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
740 regs = svm_get_guest_regctx(svm_sc, vcpu);
742 info1 = ctrl->exitinfo1;
743 inout_string = info1 & BIT(2) ? 1 : 0;
746 * The effective segment number in EXITINFO1[12:10] is populated
747 * only if the processor has the DecodeAssist capability.
749 * XXX this is not specified explicitly in APMv2 but can be verified
752 if (inout_string && !decode_assist())
755 vmexit->exitcode = VM_EXITCODE_INOUT;
756 vmexit->u.inout.in = (info1 & BIT(0)) ? 1 : 0;
757 vmexit->u.inout.string = inout_string;
758 vmexit->u.inout.rep = (info1 & BIT(3)) ? 1 : 0;
759 vmexit->u.inout.bytes = (info1 >> 4) & 0x7;
760 vmexit->u.inout.port = (uint16_t)(info1 >> 16);
761 vmexit->u.inout.eax = (uint32_t)(state->rax);
764 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
765 vis = &vmexit->u.inout_str;
766 svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
767 vis->rflags = state->rflags;
768 vis->cr0 = state->cr0;
769 vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
770 vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
771 vis->addrsize = svm_inout_str_addrsize(info1);
772 svm_inout_str_seginfo(svm_sc, vcpu, info1,
773 vmexit->u.inout.in, vis);
780 npf_fault_type(uint64_t exitinfo1)
783 if (exitinfo1 & VMCB_NPF_INFO1_W)
784 return (VM_PROT_WRITE);
785 else if (exitinfo1 & VMCB_NPF_INFO1_ID)
786 return (VM_PROT_EXECUTE);
788 return (VM_PROT_READ);
792 svm_npf_emul_fault(uint64_t exitinfo1)
795 if (exitinfo1 & VMCB_NPF_INFO1_ID) {
799 if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
803 if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
811 svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
813 struct vm_guest_paging *paging;
814 struct vmcb_segment seg;
815 struct vmcb_ctrl *ctrl;
820 paging = &vmexit->u.inst_emul.paging;
822 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
823 vmexit->u.inst_emul.gpa = gpa;
824 vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
825 svm_paging_info(vmcb, paging);
827 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
828 KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
830 switch(paging->cpu_mode) {
832 vmexit->u.inst_emul.cs_base = seg.base;
833 vmexit->u.inst_emul.cs_d = 0;
835 case CPU_MODE_PROTECTED:
836 case CPU_MODE_COMPATIBILITY:
837 vmexit->u.inst_emul.cs_base = seg.base;
840 * Section 4.8.1 of APM2, Default Operand Size or D bit.
842 vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
846 vmexit->u.inst_emul.cs_base = 0;
847 vmexit->u.inst_emul.cs_d = 0;
852 * Copy the instruction bytes into 'vie' if available.
854 if (decode_assist() && !disable_npf_assist) {
855 inst_len = ctrl->inst_len;
856 inst_bytes = ctrl->inst_bytes;
861 vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
866 intrtype_to_str(int intr_type)
869 case VMCB_EVENTINJ_TYPE_INTR:
871 case VMCB_EVENTINJ_TYPE_NMI:
873 case VMCB_EVENTINJ_TYPE_INTn:
875 case VMCB_EVENTINJ_TYPE_EXCEPTION:
876 return ("exception");
878 panic("%s: unknown intr_type %d", __func__, intr_type);
884 * Inject an event to vcpu as described in section 15.20, "Event injection".
887 svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
888 uint32_t error, bool ec_valid)
890 struct vmcb_ctrl *ctrl;
892 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
894 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
895 ("%s: event already pending %#lx", __func__, ctrl->eventinj));
897 KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
901 case VMCB_EVENTINJ_TYPE_INTR:
902 case VMCB_EVENTINJ_TYPE_NMI:
903 case VMCB_EVENTINJ_TYPE_INTn:
905 case VMCB_EVENTINJ_TYPE_EXCEPTION:
906 if (vector >= 0 && vector <= 31 && vector != 2)
910 panic("%s: invalid intr_type/vector: %d/%d", __func__,
913 ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
915 ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
916 ctrl->eventinj |= (uint64_t)error << 32;
917 VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
918 intrtype_to_str(intr_type), vector, error);
920 VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
921 intrtype_to_str(intr_type), vector);
926 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
929 struct vlapic *vlapic;
930 struct vmcb_ctrl *ctrl;
933 vlapic = vm_lapic(vm, vcpu);
934 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
936 /* Update %cr8 in the emulated vlapic */
937 vlapic_set_cr8(vlapic, ctrl->v_tpr);
939 /* Virtual interrupt injection is not used. */
940 KASSERT(ctrl->v_intr_vector == 0, ("%s: invalid "
941 "v_intr_vector %d", __func__, ctrl->v_intr_vector));
945 svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
947 struct vmcb_ctrl *ctrl;
950 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
951 intinfo = ctrl->exitintinfo;
952 if (!VMCB_EXITINTINFO_VALID(intinfo))
956 * From APMv2, Section "Intercepts during IDT interrupt delivery"
958 * If a #VMEXIT happened during event delivery then record the event
959 * that was being delivered.
961 VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
962 intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
963 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
964 vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
968 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
971 return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
976 enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
978 struct vmcb_ctrl *ctrl;
980 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
982 if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
983 KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
984 KASSERT(vintr_intercept_enabled(sc, vcpu),
985 ("%s: vintr intercept should be enabled", __func__));
989 VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
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);
998 disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
1000 struct vmcb_ctrl *ctrl;
1002 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1004 if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
1005 KASSERT(!vintr_intercept_enabled(sc, vcpu),
1006 ("%s: vintr intercept should be disabled", __func__));
1010 VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
1012 ctrl->v_intr_vector = 0;
1013 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1014 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1018 svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1020 struct vmcb_ctrl *ctrl;
1023 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1024 oldval = ctrl->intr_shadow;
1025 newval = val ? 1 : 0;
1026 if (newval != oldval) {
1027 ctrl->intr_shadow = newval;
1028 VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1034 svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1036 struct vmcb_ctrl *ctrl;
1038 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1039 *val = ctrl->intr_shadow;
1044 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1045 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1046 * to track when the vcpu is done handling the NMI.
1049 nmi_blocked(struct svm_softc *sc, int vcpu)
1053 blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1059 enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1062 KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1063 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1064 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1068 clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1072 KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1073 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1075 * When the IRET intercept is cleared the vcpu will attempt to execute
1076 * the "iret" when it runs next. However, it is possible to inject
1077 * another NMI into the vcpu before the "iret" has actually executed.
1079 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1080 * it will trap back into the hypervisor. If an NMI is pending for
1081 * the vcpu it will be injected into the guest.
1083 * XXX this needs to be fixed
1085 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1088 * Set 'intr_shadow' to prevent an NMI from being injected on the
1091 error = svm_modify_intr_shadow(sc, vcpu, 1);
1092 KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1095 #define EFER_MBZ_BITS 0xFFFFFFFFFFFF0200UL
1098 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval, bool *retu)
1100 struct vm_exit *vme;
1101 struct vmcb_state *state;
1102 uint64_t changed, lma, oldval;
1105 state = svm_get_vmcb_state(sc, vcpu);
1107 oldval = state->efer;
1108 VCPU_CTR2(sc->vm, vcpu, "wrmsr(efer) %#lx/%#lx", oldval, newval);
1110 newval &= ~0xFE; /* clear the Read-As-Zero (RAZ) bits */
1111 changed = oldval ^ newval;
1113 if (newval & EFER_MBZ_BITS)
1116 /* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1117 if (changed & EFER_LME) {
1118 if (state->cr0 & CR0_PG)
1122 /* EFER.LMA = EFER.LME & CR0.PG */
1123 if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0)
1128 if ((newval & EFER_LMA) != lma)
1131 if (newval & EFER_NXE) {
1132 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE))
1137 * XXX bhyve does not enforce segment limits in 64-bit mode. Until
1138 * this is fixed flag guest attempt to set EFER_LMSLE as an error.
1140 if (newval & EFER_LMSLE) {
1141 vme = vm_exitinfo(sc->vm, vcpu);
1142 vm_exit_svm(vme, VMCB_EXIT_MSR, 1, 0);
1147 if (newval & EFER_FFXSR) {
1148 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR))
1152 if (newval & EFER_TCE) {
1153 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_TCE))
1157 error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1158 KASSERT(error == 0, ("%s: error %d updating efer", __func__, error));
1161 vm_inject_gp(sc->vm, vcpu);
1166 emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1172 error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1173 else if (num == MSR_EFER)
1174 error = svm_write_efer(sc, vcpu, val, retu);
1176 error = svm_wrmsr(sc, vcpu, num, val, retu);
1182 emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1184 struct vmcb_state *state;
1185 struct svm_regctx *ctx;
1190 error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1192 error = svm_rdmsr(sc, vcpu, num, &result, retu);
1195 state = svm_get_vmcb_state(sc, vcpu);
1196 ctx = svm_get_guest_regctx(sc, vcpu);
1197 state->rax = result & 0xffffffff;
1198 ctx->sctx_rdx = result >> 32;
1206 exit_reason_to_str(uint64_t reason)
1208 static char reasonbuf[32];
1211 case VMCB_EXIT_INVALID:
1212 return ("invalvmcb");
1213 case VMCB_EXIT_SHUTDOWN:
1214 return ("shutdown");
1216 return ("nptfault");
1217 case VMCB_EXIT_PAUSE:
1221 case VMCB_EXIT_CPUID:
1227 case VMCB_EXIT_INTR:
1231 case VMCB_EXIT_VINTR:
1235 case VMCB_EXIT_IRET:
1237 case VMCB_EXIT_MONITOR:
1239 case VMCB_EXIT_MWAIT:
1242 snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1249 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1250 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1251 * and exceptions caused by INT3, INTO and BOUND instructions.
1253 * Return 1 if the nRIP is valid and 0 otherwise.
1256 nrip_valid(uint64_t exitcode)
1259 case 0x00 ... 0x0F: /* read of CR0 through CR15 */
1260 case 0x10 ... 0x1F: /* write of CR0 through CR15 */
1261 case 0x20 ... 0x2F: /* read of DR0 through DR15 */
1262 case 0x30 ... 0x3F: /* write of DR0 through DR15 */
1263 case 0x43: /* INT3 */
1264 case 0x44: /* INTO */
1265 case 0x45: /* BOUND */
1266 case 0x65 ... 0x7C: /* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1267 case 0x80 ... 0x8D: /* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1275 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1278 struct vmcb_state *state;
1279 struct vmcb_ctrl *ctrl;
1280 struct svm_regctx *ctx;
1281 uint64_t code, info1, info2, val;
1282 uint32_t eax, ecx, edx;
1283 int error, errcode_valid, handled, idtvec, reflect;
1286 ctx = svm_get_guest_regctx(svm_sc, vcpu);
1287 vmcb = svm_get_vmcb(svm_sc, vcpu);
1288 state = &vmcb->state;
1292 code = ctrl->exitcode;
1293 info1 = ctrl->exitinfo1;
1294 info2 = ctrl->exitinfo2;
1296 vmexit->exitcode = VM_EXITCODE_BOGUS;
1297 vmexit->rip = state->rip;
1298 vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1300 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
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.
1307 if (code == VMCB_EXIT_INVALID) {
1308 vm_exit_svm(vmexit, code, info1, info2);
1312 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1313 "injection valid bit is set %#lx", __func__, ctrl->eventinj));
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));
1319 svm_update_virqinfo(svm_sc, vcpu);
1320 svm_save_intinfo(svm_sc, vcpu);
1323 case VMCB_EXIT_IRET:
1325 * Restart execution at "iret" but with the intercept cleared.
1327 vmexit->inst_length = 0;
1328 clear_nmi_blocking(svm_sc, vcpu);
1331 case VMCB_EXIT_VINTR: /* interrupt window exiting */
1332 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1335 case VMCB_EXIT_INTR: /* external interrupt */
1336 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1339 case VMCB_EXIT_NMI: /* external NMI */
1343 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1345 idtvec = code - 0x40;
1349 * Call the machine check handler by hand. Also don't
1350 * reflect the machine check back into the guest.
1353 VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1354 __asm __volatile("int $18");
1357 error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1359 KASSERT(error == 0, ("%s: error %d updating cr2",
1379 * The 'nrip' field is populated for INT3, INTO and
1380 * BOUND exceptions and this also implies that
1381 * 'inst_length' is non-zero.
1383 * Reset 'inst_length' to zero so the guest %rip at
1384 * event injection is identical to what it was when
1385 * the exception originally happened.
1387 VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1388 "to zero before injecting exception %d",
1389 vmexit->inst_length, idtvec);
1390 vmexit->inst_length = 0;
1397 KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1398 "when reflecting exception %d into guest",
1399 vmexit->inst_length, idtvec));
1402 /* Reflect the exception back into the guest */
1403 VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1404 "%d/%#x into the guest", idtvec, (int)info1);
1405 error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1406 errcode_valid, info1, 0);
1407 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1412 case VMCB_EXIT_MSR: /* MSR access. */
1414 ecx = ctx->sctx_rcx;
1415 edx = ctx->sctx_rdx;
1419 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1420 val = (uint64_t)edx << 32 | eax;
1421 VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1423 if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1424 vmexit->exitcode = VM_EXITCODE_WRMSR;
1425 vmexit->u.msr.code = ecx;
1426 vmexit->u.msr.wval = val;
1430 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1431 ("emulate_wrmsr retu with bogus exitcode"));
1434 VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1435 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1436 if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1437 vmexit->exitcode = VM_EXITCODE_RDMSR;
1438 vmexit->u.msr.code = ecx;
1442 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1443 ("emulate_rdmsr retu with bogus exitcode"));
1448 handled = svm_handle_io(svm_sc, vcpu, vmexit);
1449 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1451 case VMCB_EXIT_CPUID:
1452 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1453 handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1454 (uint32_t *)&state->rax,
1455 (uint32_t *)&ctx->sctx_rbx,
1456 (uint32_t *)&ctx->sctx_rcx,
1457 (uint32_t *)&ctx->sctx_rdx);
1460 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1461 vmexit->exitcode = VM_EXITCODE_HLT;
1462 vmexit->u.hlt.rflags = state->rflags;
1464 case VMCB_EXIT_PAUSE:
1465 vmexit->exitcode = VM_EXITCODE_PAUSE;
1466 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1469 /* EXITINFO2 contains the faulting guest physical address */
1470 if (info1 & VMCB_NPF_INFO1_RSV) {
1471 VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1472 "reserved bits set: info1(%#lx) info2(%#lx)",
1474 } else if (vm_mem_allocated(svm_sc->vm, vcpu, info2)) {
1475 vmexit->exitcode = VM_EXITCODE_PAGING;
1476 vmexit->u.paging.gpa = info2;
1477 vmexit->u.paging.fault_type = npf_fault_type(info1);
1478 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1479 VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1480 "on gpa %#lx/%#lx at rip %#lx",
1481 info2, info1, state->rip);
1482 } else if (svm_npf_emul_fault(info1)) {
1483 svm_handle_inst_emul(vmcb, info2, vmexit);
1484 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1485 VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1486 "for gpa %#lx/%#lx at rip %#lx",
1487 info2, info1, state->rip);
1490 case VMCB_EXIT_MONITOR:
1491 vmexit->exitcode = VM_EXITCODE_MONITOR;
1493 case VMCB_EXIT_MWAIT:
1494 vmexit->exitcode = VM_EXITCODE_MWAIT;
1497 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1501 VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1502 handled ? "handled" : "unhandled", exit_reason_to_str(code),
1503 vmexit->rip, vmexit->inst_length);
1506 vmexit->rip += vmexit->inst_length;
1507 vmexit->inst_length = 0;
1508 state->rip = vmexit->rip;
1510 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1512 * If this VM exit was not claimed by anybody then
1513 * treat it as a generic SVM exit.
1515 vm_exit_svm(vmexit, code, info1, info2);
1518 * The exitcode and collateral have been populated.
1519 * The VM exit will be processed further in userland.
1527 svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1531 if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1534 KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1535 "valid: %#lx", __func__, intinfo));
1537 svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1538 VMCB_EXITINTINFO_VECTOR(intinfo),
1539 VMCB_EXITINTINFO_EC(intinfo),
1540 VMCB_EXITINTINFO_EC_VALID(intinfo));
1541 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1542 VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1546 * Inject event to virtual cpu.
1549 svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1551 struct vmcb_ctrl *ctrl;
1552 struct vmcb_state *state;
1553 struct svm_vcpu *vcpustate;
1555 int vector, need_intr_window;
1558 state = svm_get_vmcb_state(sc, vcpu);
1559 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1560 vcpustate = svm_get_vcpu(sc, vcpu);
1562 need_intr_window = 0;
1564 if (vcpustate->nextrip != state->rip) {
1565 ctrl->intr_shadow = 0;
1566 VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1567 "cleared due to rip change: %#lx/%#lx",
1568 vcpustate->nextrip, state->rip);
1572 * Inject pending events or exceptions for this vcpu.
1574 * An event might be pending because the previous #VMEXIT happened
1575 * during event delivery (i.e. ctrl->exitintinfo).
1577 * An event might also be pending because an exception was injected
1578 * by the hypervisor (e.g. #PF during instruction emulation).
1580 svm_inj_intinfo(sc, vcpu);
1582 /* NMI event has priority over interrupts. */
1583 if (vm_nmi_pending(sc->vm, vcpu)) {
1584 if (nmi_blocked(sc, vcpu)) {
1586 * Can't inject another NMI if the guest has not
1587 * yet executed an "iret" after the last NMI.
1589 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1591 } else if (ctrl->intr_shadow) {
1593 * Can't inject an NMI if the vcpu is in an intr_shadow.
1595 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1596 "interrupt shadow");
1597 need_intr_window = 1;
1599 } else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1601 * If there is already an exception/interrupt pending
1602 * then defer the NMI until after that.
1604 VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1605 "eventinj %#lx", ctrl->eventinj);
1608 * Use self-IPI to trigger a VM-exit as soon as
1609 * possible after the event injection is completed.
1611 * This works only if the external interrupt exiting
1612 * is at a lower priority than the event injection.
1614 * Although not explicitly specified in APMv2 the
1615 * relative priorities were verified empirically.
1617 ipi_cpu(curcpu, IPI_AST); /* XXX vmm_ipinum? */
1619 vm_nmi_clear(sc->vm, vcpu);
1621 /* Inject NMI, vector number is not used */
1622 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1625 /* virtual NMI blocking is now in effect */
1626 enable_nmi_blocking(sc, vcpu);
1628 VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1632 extint_pending = vm_extint_pending(sc->vm, vcpu);
1633 if (!extint_pending) {
1634 if (!vlapic_pending_intr(vlapic, &vector))
1636 KASSERT(vector >= 16 && vector <= 255,
1637 ("invalid vector %d from local APIC", vector));
1639 /* Ask the legacy pic for a vector to inject */
1640 vatpic_pending_intr(sc->vm, &vector);
1641 KASSERT(vector >= 0 && vector <= 255,
1642 ("invalid vector %d from INTR", vector));
1646 * If the guest has disabled interrupts or is in an interrupt shadow
1647 * then we cannot inject the pending interrupt.
1649 if ((state->rflags & PSL_I) == 0) {
1650 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1651 "rflags %#lx", vector, state->rflags);
1652 need_intr_window = 1;
1656 if (ctrl->intr_shadow) {
1657 VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1658 "interrupt shadow", vector);
1659 need_intr_window = 1;
1663 if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1664 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1665 "eventinj %#lx", vector, ctrl->eventinj);
1666 need_intr_window = 1;
1670 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1672 if (!extint_pending) {
1673 vlapic_intr_accepted(vlapic, vector);
1675 vm_extint_clear(sc->vm, vcpu);
1676 vatpic_intr_accepted(sc->vm, vector);
1680 * Force a VM-exit as soon as the vcpu is ready to accept another
1681 * interrupt. This is done because the PIC might have another vector
1682 * that it wants to inject. Also, if the APIC has a pending interrupt
1683 * that was preempted by the ExtInt then it allows us to inject the
1684 * APIC vector as soon as possible.
1686 need_intr_window = 1;
1689 * The guest can modify the TPR by writing to %CR8. In guest mode
1690 * the processor reflects this write to V_TPR without hypervisor
1693 * The guest can also modify the TPR by writing to it via the memory
1694 * mapped APIC page. In this case, the write will be emulated by the
1695 * hypervisor. For this reason V_TPR must be updated before every
1698 v_tpr = vlapic_get_cr8(vlapic);
1699 KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1700 if (ctrl->v_tpr != v_tpr) {
1701 VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1702 ctrl->v_tpr, v_tpr);
1703 ctrl->v_tpr = v_tpr;
1704 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1707 if (need_intr_window) {
1709 * We use V_IRQ in conjunction with the VINTR intercept to
1710 * trap into the hypervisor as soon as a virtual interrupt
1713 * Since injected events are not subject to intercept checks
1714 * we need to ensure that the V_IRQ is not actually going to
1715 * be delivered on VM entry. The KASSERT below enforces this.
1717 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1718 (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1719 ("Bogus intr_window_exiting: eventinj (%#lx), "
1720 "intr_shadow (%u), rflags (%#lx)",
1721 ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1722 enable_intr_window_exiting(sc, vcpu);
1724 disable_intr_window_exiting(sc, vcpu);
1728 static __inline void
1729 restore_host_tss(void)
1731 struct system_segment_descriptor *tss_sd;
1734 * The TSS descriptor was in use prior to launching the guest so it
1735 * has been marked busy.
1737 * 'ltr' requires the descriptor to be marked available so change the
1738 * type to "64-bit available TSS".
1740 tss_sd = PCPU_GET(tss);
1741 tss_sd->sd_type = SDT_SYSTSS;
1742 ltr(GSEL(GPROC0_SEL, SEL_KPL));
1746 check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1748 struct svm_vcpu *vcpustate;
1749 struct vmcb_ctrl *ctrl;
1753 KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1754 "active on cpu %u", __func__, thiscpu));
1756 vcpustate = svm_get_vcpu(sc, vcpuid);
1757 ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1760 * The TLB entries associated with the vcpu's ASID are not valid
1761 * if either of the following conditions is true:
1763 * 1. The vcpu's ASID generation is different than the host cpu's
1764 * ASID generation. This happens when the vcpu migrates to a new
1765 * host cpu. It can also happen when the number of vcpus executing
1766 * on a host cpu is greater than the number of ASIDs available.
1768 * 2. The pmap generation number is different than the value cached in
1769 * the 'vcpustate'. This happens when the host invalidates pages
1770 * belonging to the guest.
1772 * asidgen eptgen Action
1779 * (a) There is no mismatch in eptgen or ASID generation and therefore
1780 * no further action is needed.
1782 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1783 * retained and the TLB entries associated with this ASID
1784 * are flushed by VMRUN.
1786 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1789 * (c) A new ASID is allocated.
1791 * (d) A new ASID is allocated.
1795 eptgen = pmap->pm_eptgen;
1796 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1798 if (vcpustate->asid.gen != asid[thiscpu].gen) {
1799 alloc_asid = true; /* (c) and (d) */
1800 } else if (vcpustate->eptgen != eptgen) {
1801 if (flush_by_asid())
1802 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST; /* (b1) */
1804 alloc_asid = true; /* (b2) */
1807 * This is the common case (a).
1809 KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1810 KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1811 ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1815 if (++asid[thiscpu].num >= nasid) {
1816 asid[thiscpu].num = 1;
1817 if (++asid[thiscpu].gen == 0)
1818 asid[thiscpu].gen = 1;
1820 * If this cpu does not support "flush-by-asid"
1821 * then flush the entire TLB on a generation
1822 * bump. Subsequent ASID allocation in this
1823 * generation can be done without a TLB flush.
1825 if (!flush_by_asid())
1826 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1828 vcpustate->asid.gen = asid[thiscpu].gen;
1829 vcpustate->asid.num = asid[thiscpu].num;
1831 ctrl->asid = vcpustate->asid.num;
1832 svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1834 * If this cpu supports "flush-by-asid" then the TLB
1835 * was not flushed after the generation bump. The TLB
1836 * is flushed selectively after every new ASID allocation.
1838 if (flush_by_asid())
1839 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1841 vcpustate->eptgen = eptgen;
1843 KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1844 KASSERT(ctrl->asid == vcpustate->asid.num,
1845 ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1848 static __inline void
1852 __asm __volatile("clgi");
1855 static __inline void
1859 __asm __volatile("stgi");
1863 * Start vcpu with specified RIP.
1866 svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1867 struct vm_eventinfo *evinfo)
1869 struct svm_regctx *gctx;
1870 struct svm_softc *svm_sc;
1871 struct svm_vcpu *vcpustate;
1872 struct vmcb_state *state;
1873 struct vmcb_ctrl *ctrl;
1874 struct vm_exit *vmexit;
1875 struct vlapic *vlapic;
1883 vcpustate = svm_get_vcpu(svm_sc, vcpu);
1884 state = svm_get_vmcb_state(svm_sc, vcpu);
1885 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1886 vmexit = vm_exitinfo(vm, vcpu);
1887 vlapic = vm_lapic(vm, vcpu);
1889 gctx = svm_get_guest_regctx(svm_sc, vcpu);
1890 vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1892 if (vcpustate->lastcpu != curcpu) {
1894 * Force new ASID allocation by invalidating the generation.
1896 vcpustate->asid.gen = 0;
1899 * Invalidate the VMCB state cache by marking all fields dirty.
1901 svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1905 * Setting 'vcpustate->lastcpu' here is bit premature because
1906 * we may return from this function without actually executing
1907 * the VMRUN instruction. This could happen if a rendezvous
1908 * or an AST is pending on the first time through the loop.
1910 * This works for now but any new side-effects of vcpu
1911 * migration should take this case into account.
1913 vcpustate->lastcpu = curcpu;
1914 vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1917 svm_msr_guest_enter(svm_sc, vcpu);
1919 /* Update Guest RIP */
1924 * Disable global interrupts to guarantee atomicity during
1925 * loading of guest state. This includes not only the state
1926 * loaded by the "vmrun" instruction but also software state
1927 * maintained by the hypervisor: suspended and rendezvous
1928 * state, NPT generation number, vlapic interrupts etc.
1932 if (vcpu_suspended(evinfo)) {
1934 vm_exit_suspended(vm, vcpu, state->rip);
1938 if (vcpu_rendezvous_pending(evinfo)) {
1940 vm_exit_rendezvous(vm, vcpu, state->rip);
1944 if (vcpu_reqidle(evinfo)) {
1946 vm_exit_reqidle(vm, vcpu, state->rip);
1950 /* We are asked to give the cpu by scheduler. */
1951 if (vcpu_should_yield(vm, vcpu)) {
1953 vm_exit_astpending(vm, vcpu, state->rip);
1957 svm_inj_interrupts(svm_sc, vcpu, vlapic);
1959 /* Activate the nested pmap on 'curcpu' */
1960 CPU_SET_ATOMIC_ACQ(curcpu, &pmap->pm_active);
1963 * Check the pmap generation and the ASID generation to
1964 * ensure that the vcpu does not use stale TLB mappings.
1966 check_asid(svm_sc, vcpu, pmap, curcpu);
1968 ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
1969 vcpustate->dirty = 0;
1970 VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
1972 /* Launch Virtual Machine. */
1973 VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
1974 svm_launch(vmcb_pa, gctx, &__pcpu[curcpu]);
1976 CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
1979 * The host GDTR and IDTR is saved by VMRUN and restored
1980 * automatically on #VMEXIT. However, the host TSS needs
1981 * to be restored explicitly.
1985 /* #VMEXIT disables interrupts so re-enable them here. */
1988 /* Update 'nextrip' */
1989 vcpustate->nextrip = state->rip;
1991 /* Handle #VMEXIT and if required return to user space. */
1992 handled = svm_vmexit(svm_sc, vcpu, vmexit);
1995 svm_msr_guest_exit(svm_sc, vcpu);
2001 svm_vmcleanup(void *arg)
2003 struct svm_softc *sc = arg;
2005 contigfree(sc->iopm_bitmap, SVM_IO_BITMAP_SIZE, M_SVM);
2006 contigfree(sc->msr_bitmap, SVM_MSR_BITMAP_SIZE, M_SVM);
2011 swctx_regptr(struct svm_regctx *regctx, int reg)
2015 case VM_REG_GUEST_RBX:
2016 return (®ctx->sctx_rbx);
2017 case VM_REG_GUEST_RCX:
2018 return (®ctx->sctx_rcx);
2019 case VM_REG_GUEST_RDX:
2020 return (®ctx->sctx_rdx);
2021 case VM_REG_GUEST_RDI:
2022 return (®ctx->sctx_rdi);
2023 case VM_REG_GUEST_RSI:
2024 return (®ctx->sctx_rsi);
2025 case VM_REG_GUEST_RBP:
2026 return (®ctx->sctx_rbp);
2027 case VM_REG_GUEST_R8:
2028 return (®ctx->sctx_r8);
2029 case VM_REG_GUEST_R9:
2030 return (®ctx->sctx_r9);
2031 case VM_REG_GUEST_R10:
2032 return (®ctx->sctx_r10);
2033 case VM_REG_GUEST_R11:
2034 return (®ctx->sctx_r11);
2035 case VM_REG_GUEST_R12:
2036 return (®ctx->sctx_r12);
2037 case VM_REG_GUEST_R13:
2038 return (®ctx->sctx_r13);
2039 case VM_REG_GUEST_R14:
2040 return (®ctx->sctx_r14);
2041 case VM_REG_GUEST_R15:
2042 return (®ctx->sctx_r15);
2049 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2051 struct svm_softc *svm_sc;
2056 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2057 return (svm_get_intr_shadow(svm_sc, vcpu, val));
2060 if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2064 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2071 VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2076 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2078 struct svm_softc *svm_sc;
2083 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2084 return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2087 if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2091 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2099 * XXX deal with CR3 and invalidate TLB entries tagged with the
2100 * vcpu's ASID. This needs to be treated differently depending on
2101 * whether 'running' is true/false.
2104 VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2109 svm_setcap(void *arg, int vcpu, int type, int val)
2111 struct svm_softc *sc;
2117 case VM_CAP_HALT_EXIT:
2118 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2119 VMCB_INTCPT_HLT, val);
2121 case VM_CAP_PAUSE_EXIT:
2122 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2123 VMCB_INTCPT_PAUSE, val);
2125 case VM_CAP_UNRESTRICTED_GUEST:
2126 /* Unrestricted guest execution cannot be disabled in SVM */
2138 svm_getcap(void *arg, int vcpu, int type, int *retval)
2140 struct svm_softc *sc;
2147 case VM_CAP_HALT_EXIT:
2148 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2151 case VM_CAP_PAUSE_EXIT:
2152 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2155 case VM_CAP_UNRESTRICTED_GUEST:
2156 *retval = 1; /* unrestricted guest is always enabled */
2165 static struct vlapic *
2166 svm_vlapic_init(void *arg, int vcpuid)
2168 struct svm_softc *svm_sc;
2169 struct vlapic *vlapic;
2172 vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2173 vlapic->vm = svm_sc->vm;
2174 vlapic->vcpuid = vcpuid;
2175 vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2177 vlapic_init(vlapic);
2183 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2186 vlapic_cleanup(vlapic);
2187 free(vlapic, M_SVM_VLAPIC);
2190 struct vmm_ops vmm_ops_amd = {