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/pmap.h>
45 #include <machine/md_var.h>
46 #include <machine/specialreg.h>
47 #include <machine/smp.h>
48 #include <machine/vmm.h>
49 #include <machine/vmm_dev.h>
50 #include <machine/vmm_instruction_emul.h>
52 #include "vmm_lapic.h"
55 #include "vmm_ioport.h"
58 #include "vlapic_priv.h"
63 #include "svm_softc.h"
68 SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
71 * SVM CPUID function 0x8000_000A, edx bit decoding.
73 #define AMD_CPUID_SVM_NP BIT(0) /* Nested paging or RVI */
74 #define AMD_CPUID_SVM_LBR BIT(1) /* Last branch virtualization */
75 #define AMD_CPUID_SVM_SVML BIT(2) /* SVM lock */
76 #define AMD_CPUID_SVM_NRIP_SAVE BIT(3) /* Next RIP is saved */
77 #define AMD_CPUID_SVM_TSC_RATE BIT(4) /* TSC rate control. */
78 #define AMD_CPUID_SVM_VMCB_CLEAN BIT(5) /* VMCB state caching */
79 #define AMD_CPUID_SVM_FLUSH_BY_ASID BIT(6) /* Flush by ASID */
80 #define AMD_CPUID_SVM_DECODE_ASSIST BIT(7) /* Decode assist */
81 #define AMD_CPUID_SVM_PAUSE_INC BIT(10) /* Pause intercept filter. */
82 #define AMD_CPUID_SVM_PAUSE_FTH BIT(12) /* Pause filter threshold */
83 #define AMD_CPUID_SVM_AVIC BIT(13) /* AVIC present */
85 #define VMCB_CACHE_DEFAULT (VMCB_CACHE_ASID | \
95 static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
96 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
99 static MALLOC_DEFINE(M_SVM, "svm", "svm");
100 static MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
102 /* Per-CPU context area. */
103 extern struct pcpu __pcpu[];
105 static uint32_t svm_feature; /* AMD SVM features. */
106 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RD, &svm_feature, 0,
107 "SVM features advertised by CPUID.8000000AH:EDX");
109 static int disable_npf_assist;
110 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
111 &disable_npf_assist, 0, NULL);
113 /* Maximum ASIDs supported by the processor */
114 static uint32_t nasid;
115 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RD, &nasid, 0,
116 "Number of ASIDs supported by this processor");
118 /* Current ASID generation for each host cpu */
119 static struct asid asid[MAXCPU];
122 * SVM host state saved area of size 4KB for each core.
124 static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
126 static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
127 static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
128 static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
130 static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
136 return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
143 return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
147 svm_disable(void *arg __unused)
151 efer = rdmsr(MSR_EFER);
153 wrmsr(MSR_EFER, efer);
157 * Disable SVM on all CPUs.
163 smp_rendezvous(NULL, svm_disable, NULL, NULL);
168 * Verify that all the features required by bhyve are available.
171 check_svm_features(void)
175 /* CPUID Fn8000_000A is for SVM */
176 do_cpuid(0x8000000A, regs);
177 svm_feature = regs[3];
180 KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
182 /* bhyve requires the Nested Paging feature */
183 if (!(svm_feature & AMD_CPUID_SVM_NP)) {
184 printf("SVM: Nested Paging feature not available.\n");
188 /* bhyve requires the NRIP Save feature */
189 if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
190 printf("SVM: NRIP Save feature not available.\n");
198 svm_enable(void *arg __unused)
202 efer = rdmsr(MSR_EFER);
204 wrmsr(MSR_EFER, efer);
206 wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
210 * Return 1 if SVM is enabled on this processor and 0 otherwise.
217 /* Section 15.4 Enabling SVM from APM2. */
218 if ((amd_feature2 & AMDID2_SVM) == 0) {
219 printf("SVM: not available.\n");
223 msr = rdmsr(MSR_VM_CR);
224 if ((msr & VM_CR_SVMDIS) != 0) {
225 printf("SVM: disabled by BIOS.\n");
237 if (!svm_available())
240 error = check_svm_features();
244 vmcb_clean &= VMCB_CACHE_DEFAULT;
246 for (cpu = 0; cpu < MAXCPU; cpu++) {
248 * Initialize the host ASIDs to their "highest" valid values.
250 * The next ASID allocation will rollover both 'gen' and 'num'
251 * and start off the sequence at {1,1}.
253 asid[cpu].gen = ~0UL;
254 asid[cpu].num = nasid - 1;
258 svm_npt_init(ipinum);
260 /* Enable SVM on all CPUs */
261 smp_rendezvous(NULL, svm_enable, NULL, NULL);
273 /* Pentium compatible MSRs */
274 #define MSR_PENTIUM_START 0
275 #define MSR_PENTIUM_END 0x1FFF
276 /* AMD 6th generation and Intel compatible MSRs */
277 #define MSR_AMD6TH_START 0xC0000000UL
278 #define MSR_AMD6TH_END 0xC0001FFFUL
279 /* AMD 7th and 8th generation compatible MSRs */
280 #define MSR_AMD7TH_START 0xC0010000UL
281 #define MSR_AMD7TH_END 0xC0011FFFUL
284 * Get the index and bit position for a MSR in permission bitmap.
285 * Two bits are used for each MSR: lower bit for read and higher bit for write.
288 svm_msr_index(uint64_t msr, int *index, int *bit)
293 *bit = (msr % 4) * 2;
296 if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
301 base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
302 if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
303 off = (msr - MSR_AMD6TH_START);
304 *index = (off + base) / 4;
308 base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
309 if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
310 off = (msr - MSR_AMD7TH_START);
311 *index = (off + base) / 4;
319 * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
322 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
324 int index, bit, error;
326 error = svm_msr_index(msr, &index, &bit);
327 KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
328 KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
329 ("%s: invalid index %d for msr %#lx", __func__, index, msr));
330 KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
331 "msr %#lx", __func__, bit, msr));
334 perm_bitmap[index] &= ~(1UL << bit);
337 perm_bitmap[index] &= ~(2UL << bit);
341 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
344 svm_msr_perm(perm_bitmap, msr, true, true);
348 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
351 svm_msr_perm(perm_bitmap, msr, true, false);
355 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
357 struct vmcb_ctrl *ctrl;
359 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
361 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
362 return (ctrl->intercept[idx] & bitmask ? 1 : 0);
366 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
369 struct vmcb_ctrl *ctrl;
372 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
374 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
375 oldval = ctrl->intercept[idx];
378 ctrl->intercept[idx] |= bitmask;
380 ctrl->intercept[idx] &= ~bitmask;
382 if (ctrl->intercept[idx] != oldval) {
383 svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
384 VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
385 "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
390 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
393 svm_set_intercept(sc, vcpu, off, bitmask, 0);
397 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
400 svm_set_intercept(sc, vcpu, off, bitmask, 1);
404 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
405 uint64_t msrpm_base_pa, uint64_t np_pml4)
407 struct vmcb_ctrl *ctrl;
408 struct vmcb_state *state;
412 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
413 state = svm_get_vmcb_state(sc, vcpu);
415 ctrl->iopm_base_pa = iopm_base_pa;
416 ctrl->msrpm_base_pa = msrpm_base_pa;
418 /* Enable nested paging */
420 ctrl->n_cr3 = np_pml4;
423 * Intercept accesses to the control registers that are not shadowed
424 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
426 for (n = 0; n < 16; n++) {
427 mask = (BIT(n) << 16) | BIT(n);
428 if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
429 svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
431 svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
436 * Intercept everything when tracing guest exceptions otherwise
437 * just intercept machine check exception.
439 if (vcpu_trace_exceptions(sc->vm, vcpu)) {
440 for (n = 0; n < 32; n++) {
442 * Skip unimplemented vectors in the exception bitmap.
444 if (n == 2 || n == 9) {
447 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
450 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
453 /* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
454 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
455 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
456 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
457 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
458 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
459 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
460 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
461 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
462 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
463 VMCB_INTCPT_FERR_FREEZE);
465 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
466 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
469 * From section "Canonicalization and Consistency Checks" in APMv2
470 * the VMRUN intercept bit must be set to pass the consistency check.
472 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
475 * The ASID will be set to a non-zero value just before VMRUN.
480 * Section 15.21.1, Interrupt Masking in EFLAGS
481 * Section 15.21.2, Virtualizing APIC.TPR
483 * This must be set for %rflag and %cr8 isolation of guest and host.
485 ctrl->v_intr_masking = 1;
487 /* Enable Last Branch Record aka LBR for debugging */
488 ctrl->lbr_virt_en = 1;
489 state->dbgctl = BIT(0);
491 /* EFER_SVM must always be set when the guest is executing */
492 state->efer = EFER_SVM;
494 /* Set up the PAT to power-on state */
495 state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK) |
496 PAT_VALUE(1, PAT_WRITE_THROUGH) |
497 PAT_VALUE(2, PAT_UNCACHED) |
498 PAT_VALUE(3, PAT_UNCACHEABLE) |
499 PAT_VALUE(4, PAT_WRITE_BACK) |
500 PAT_VALUE(5, PAT_WRITE_THROUGH) |
501 PAT_VALUE(6, PAT_UNCACHED) |
502 PAT_VALUE(7, PAT_UNCACHEABLE);
506 * Initialize a virtual machine.
509 svm_vminit(struct vm *vm, pmap_t pmap)
511 struct svm_softc *svm_sc;
512 struct svm_vcpu *vcpu;
513 vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
516 svm_sc = malloc(sizeof (struct svm_softc), M_SVM, M_WAITOK | M_ZERO);
518 svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
521 * Intercept read and write accesses to all MSRs.
523 memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
526 * Access to the following MSRs is redirected to the VMCB when the
527 * guest is executing. Therefore it is safe to allow the guest to
528 * read/write these MSRs directly without hypervisor involvement.
530 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
531 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
532 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
534 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
535 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
536 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
537 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
538 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
539 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
540 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
541 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
543 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
546 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
548 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
550 /* Intercept access to all I/O ports. */
551 memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
553 iopm_pa = vtophys(svm_sc->iopm_bitmap);
554 msrpm_pa = vtophys(svm_sc->msr_bitmap);
555 pml4_pa = svm_sc->nptp;
556 for (i = 0; i < VM_MAXCPU; i++) {
557 vcpu = svm_get_vcpu(svm_sc, i);
559 vcpu->lastcpu = NOCPU;
560 vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
561 vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
562 svm_msr_guest_init(svm_sc, i);
568 * Collateral for a generic SVM VM-exit.
571 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
574 vme->exitcode = VM_EXITCODE_SVM;
575 vme->u.svm.exitcode = code;
576 vme->u.svm.exitinfo1 = info1;
577 vme->u.svm.exitinfo2 = info2;
581 svm_cpl(struct vmcb_state *state)
586 * "Retrieve the CPL from the CPL field in the VMCB, not
587 * from any segment DPL"
592 static enum vm_cpu_mode
593 svm_vcpu_mode(struct vmcb *vmcb)
595 struct vmcb_segment seg;
596 struct vmcb_state *state;
599 state = &vmcb->state;
601 if (state->efer & EFER_LMA) {
602 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
603 KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
607 * Section 4.8.1 for APM2, check if Code Segment has
608 * Long attribute set in descriptor.
610 if (seg.attrib & VMCB_CS_ATTRIB_L)
611 return (CPU_MODE_64BIT);
613 return (CPU_MODE_COMPATIBILITY);
614 } else if (state->cr0 & CR0_PE) {
615 return (CPU_MODE_PROTECTED);
617 return (CPU_MODE_REAL);
621 static enum vm_paging_mode
622 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
625 if ((cr0 & CR0_PG) == 0)
626 return (PAGING_MODE_FLAT);
627 if ((cr4 & CR4_PAE) == 0)
628 return (PAGING_MODE_32);
630 return (PAGING_MODE_64);
632 return (PAGING_MODE_PAE);
636 * ins/outs utility routines
639 svm_inout_str_index(struct svm_regctx *regs, int in)
643 val = in ? regs->sctx_rdi : regs->sctx_rsi;
649 svm_inout_str_count(struct svm_regctx *regs, int rep)
653 val = rep ? regs->sctx_rcx : 1;
659 svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
660 int in, struct vm_inout_str *vis)
665 vis->seg_name = VM_REG_GUEST_ES;
667 /* The segment field has standard encoding */
668 s = (info1 >> 10) & 0x7;
669 vis->seg_name = vm_segment_name(s);
672 error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
673 KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
677 svm_inout_str_addrsize(uint64_t info1)
681 size = (info1 >> 7) & 0x7;
684 return (2); /* 16 bit */
686 return (4); /* 32 bit */
688 return (8); /* 64 bit */
690 panic("%s: invalid size encoding %d", __func__, size);
695 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
697 struct vmcb_state *state;
699 state = &vmcb->state;
700 paging->cr3 = state->cr3;
701 paging->cpl = svm_cpl(state);
702 paging->cpu_mode = svm_vcpu_mode(vmcb);
703 paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
710 * Handle guest I/O intercept.
713 svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
715 struct vmcb_ctrl *ctrl;
716 struct vmcb_state *state;
717 struct svm_regctx *regs;
718 struct vm_inout_str *vis;
722 state = svm_get_vmcb_state(svm_sc, vcpu);
723 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
724 regs = svm_get_guest_regctx(svm_sc, vcpu);
726 info1 = ctrl->exitinfo1;
727 inout_string = info1 & BIT(2) ? 1 : 0;
730 * The effective segment number in EXITINFO1[12:10] is populated
731 * only if the processor has the DecodeAssist capability.
733 * XXX this is not specified explicitly in APMv2 but can be verified
736 if (inout_string && !decode_assist())
739 vmexit->exitcode = VM_EXITCODE_INOUT;
740 vmexit->u.inout.in = (info1 & BIT(0)) ? 1 : 0;
741 vmexit->u.inout.string = inout_string;
742 vmexit->u.inout.rep = (info1 & BIT(3)) ? 1 : 0;
743 vmexit->u.inout.bytes = (info1 >> 4) & 0x7;
744 vmexit->u.inout.port = (uint16_t)(info1 >> 16);
745 vmexit->u.inout.eax = (uint32_t)(state->rax);
748 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
749 vis = &vmexit->u.inout_str;
750 svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
751 vis->rflags = state->rflags;
752 vis->cr0 = state->cr0;
753 vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
754 vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
755 vis->addrsize = svm_inout_str_addrsize(info1);
756 svm_inout_str_seginfo(svm_sc, vcpu, info1,
757 vmexit->u.inout.in, vis);
764 npf_fault_type(uint64_t exitinfo1)
767 if (exitinfo1 & VMCB_NPF_INFO1_W)
768 return (VM_PROT_WRITE);
769 else if (exitinfo1 & VMCB_NPF_INFO1_ID)
770 return (VM_PROT_EXECUTE);
772 return (VM_PROT_READ);
776 svm_npf_emul_fault(uint64_t exitinfo1)
779 if (exitinfo1 & VMCB_NPF_INFO1_ID) {
783 if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
787 if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
795 svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
797 struct vm_guest_paging *paging;
798 struct vmcb_segment seg;
799 struct vmcb_ctrl *ctrl;
804 paging = &vmexit->u.inst_emul.paging;
806 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
807 vmexit->u.inst_emul.gpa = gpa;
808 vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
809 svm_paging_info(vmcb, paging);
811 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
812 KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
814 switch(paging->cpu_mode) {
816 vmexit->u.inst_emul.cs_base = seg.base;
817 vmexit->u.inst_emul.cs_d = 0;
819 case CPU_MODE_PROTECTED:
820 case CPU_MODE_COMPATIBILITY:
821 vmexit->u.inst_emul.cs_base = seg.base;
824 * Section 4.8.1 of APM2, Default Operand Size or D bit.
826 vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
830 vmexit->u.inst_emul.cs_base = 0;
831 vmexit->u.inst_emul.cs_d = 0;
836 * Copy the instruction bytes into 'vie' if available.
838 if (decode_assist() && !disable_npf_assist) {
839 inst_len = ctrl->inst_len;
840 inst_bytes = ctrl->inst_bytes;
845 vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
850 intrtype_to_str(int intr_type)
853 case VMCB_EVENTINJ_TYPE_INTR:
855 case VMCB_EVENTINJ_TYPE_NMI:
857 case VMCB_EVENTINJ_TYPE_INTn:
859 case VMCB_EVENTINJ_TYPE_EXCEPTION:
860 return ("exception");
862 panic("%s: unknown intr_type %d", __func__, intr_type);
868 * Inject an event to vcpu as described in section 15.20, "Event injection".
871 svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
872 uint32_t error, bool ec_valid)
874 struct vmcb_ctrl *ctrl;
876 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
878 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
879 ("%s: event already pending %#lx", __func__, ctrl->eventinj));
881 KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
885 case VMCB_EVENTINJ_TYPE_INTR:
886 case VMCB_EVENTINJ_TYPE_NMI:
887 case VMCB_EVENTINJ_TYPE_INTn:
889 case VMCB_EVENTINJ_TYPE_EXCEPTION:
890 if (vector >= 0 && vector <= 31 && vector != 2)
894 panic("%s: invalid intr_type/vector: %d/%d", __func__,
897 ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
899 ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
900 ctrl->eventinj |= (uint64_t)error << 32;
901 VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
902 intrtype_to_str(intr_type), vector, error);
904 VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
905 intrtype_to_str(intr_type), vector);
910 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
913 struct vlapic *vlapic;
914 struct vmcb_ctrl *ctrl;
918 vlapic = vm_lapic(vm, vcpu);
919 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
921 /* Update %cr8 in the emulated vlapic */
922 vlapic_set_cr8(vlapic, ctrl->v_tpr);
925 * If V_IRQ indicates that the interrupt injection attempted on then
926 * last VMRUN was successful then update the vlapic accordingly.
928 if (ctrl->v_intr_vector != 0) {
929 pending = ctrl->v_irq;
930 KASSERT(ctrl->v_intr_vector >= 16, ("%s: invalid "
931 "v_intr_vector %d", __func__, ctrl->v_intr_vector));
932 KASSERT(!ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
933 VCPU_CTR2(vm, vcpu, "v_intr_vector %d %s", ctrl->v_intr_vector,
934 pending ? "pending" : "accepted");
936 vlapic_intr_accepted(vlapic, ctrl->v_intr_vector);
941 svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
943 struct vmcb_ctrl *ctrl;
946 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
947 intinfo = ctrl->exitintinfo;
948 if (!VMCB_EXITINTINFO_VALID(intinfo))
952 * From APMv2, Section "Intercepts during IDT interrupt delivery"
954 * If a #VMEXIT happened during event delivery then record the event
955 * that was being delivered.
957 VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
958 intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
959 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
960 vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
964 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
967 return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
972 enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
974 struct vmcb_ctrl *ctrl;
976 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
978 if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
979 KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
980 KASSERT(vintr_intercept_enabled(sc, vcpu),
981 ("%s: vintr intercept should be enabled", __func__));
985 VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
988 ctrl->v_intr_vector = 0;
989 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
990 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
994 disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
996 struct vmcb_ctrl *ctrl;
998 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1000 if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
1001 KASSERT(!vintr_intercept_enabled(sc, vcpu),
1002 ("%s: vintr intercept should be disabled", __func__));
1007 if (ctrl->v_intr_vector == 0)
1008 VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
1010 VCPU_CTR0(sc->vm, vcpu, "Clearing V_IRQ interrupt injection");
1013 ctrl->v_intr_vector = 0;
1014 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1015 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1019 svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1021 struct vmcb_ctrl *ctrl;
1024 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1025 oldval = ctrl->intr_shadow;
1026 newval = val ? 1 : 0;
1027 if (newval != oldval) {
1028 ctrl->intr_shadow = newval;
1029 VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1035 svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1037 struct vmcb_ctrl *ctrl;
1039 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1040 *val = ctrl->intr_shadow;
1045 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1046 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1047 * to track when the vcpu is done handling the NMI.
1050 nmi_blocked(struct svm_softc *sc, int vcpu)
1054 blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1060 enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1063 KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1064 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1065 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1069 clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1073 KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1074 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1076 * When the IRET intercept is cleared the vcpu will attempt to execute
1077 * the "iret" when it runs next. However, it is possible to inject
1078 * another NMI into the vcpu before the "iret" has actually executed.
1080 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1081 * it will trap back into the hypervisor. If an NMI is pending for
1082 * the vcpu it will be injected into the guest.
1084 * XXX this needs to be fixed
1086 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1089 * Set 'intr_shadow' to prevent an NMI from being injected on the
1092 error = svm_modify_intr_shadow(sc, vcpu, 1);
1093 KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1096 #define EFER_MBZ_BITS 0xFFFFFFFFFFFF0200UL
1099 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval, bool *retu)
1101 struct vm_exit *vme;
1102 struct vmcb_state *state;
1103 uint64_t changed, lma, oldval;
1106 state = svm_get_vmcb_state(sc, vcpu);
1108 oldval = state->efer;
1109 VCPU_CTR2(sc->vm, vcpu, "wrmsr(efer) %#lx/%#lx", oldval, newval);
1111 newval &= ~0xFE; /* clear the Read-As-Zero (RAZ) bits */
1112 changed = oldval ^ newval;
1114 if (newval & EFER_MBZ_BITS)
1117 /* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1118 if (changed & EFER_LME) {
1119 if (state->cr0 & CR0_PG)
1123 /* EFER.LMA = EFER.LME & CR0.PG */
1124 if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0)
1129 if ((newval & EFER_LMA) != lma)
1132 if (newval & EFER_NXE) {
1133 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE))
1138 * XXX bhyve does not enforce segment limits in 64-bit mode. Until
1139 * this is fixed flag guest attempt to set EFER_LMSLE as an error.
1141 if (newval & EFER_LMSLE) {
1142 vme = vm_exitinfo(sc->vm, vcpu);
1143 vm_exit_svm(vme, VMCB_EXIT_MSR, 1, 0);
1148 if (newval & EFER_FFXSR) {
1149 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR))
1153 if (newval & EFER_TCE) {
1154 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_TCE))
1158 error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1159 KASSERT(error == 0, ("%s: error %d updating efer", __func__, error));
1162 vm_inject_gp(sc->vm, vcpu);
1167 emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1173 error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1174 else if (num == MSR_EFER)
1175 error = svm_write_efer(sc, vcpu, val, retu);
1177 error = svm_wrmsr(sc, vcpu, num, val, retu);
1183 emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1185 struct vmcb_state *state;
1186 struct svm_regctx *ctx;
1191 error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1193 error = svm_rdmsr(sc, vcpu, num, &result, retu);
1196 state = svm_get_vmcb_state(sc, vcpu);
1197 ctx = svm_get_guest_regctx(sc, vcpu);
1198 state->rax = result & 0xffffffff;
1199 ctx->sctx_rdx = result >> 32;
1207 exit_reason_to_str(uint64_t reason)
1209 static char reasonbuf[32];
1212 case VMCB_EXIT_INVALID:
1213 return ("invalvmcb");
1214 case VMCB_EXIT_SHUTDOWN:
1215 return ("shutdown");
1217 return ("nptfault");
1218 case VMCB_EXIT_PAUSE:
1222 case VMCB_EXIT_CPUID:
1228 case VMCB_EXIT_INTR:
1232 case VMCB_EXIT_VINTR:
1236 case VMCB_EXIT_IRET:
1238 case VMCB_EXIT_MONITOR:
1240 case VMCB_EXIT_MWAIT:
1243 snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1250 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1251 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1252 * and exceptions caused by INT3, INTO and BOUND instructions.
1254 * Return 1 if the nRIP is valid and 0 otherwise.
1257 nrip_valid(uint64_t exitcode)
1260 case 0x00 ... 0x0F: /* read of CR0 through CR15 */
1261 case 0x10 ... 0x1F: /* write of CR0 through CR15 */
1262 case 0x20 ... 0x2F: /* read of DR0 through DR15 */
1263 case 0x30 ... 0x3F: /* write of DR0 through DR15 */
1264 case 0x43: /* INT3 */
1265 case 0x44: /* INTO */
1266 case 0x45: /* BOUND */
1267 case 0x65 ... 0x7C: /* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1268 case 0x80 ... 0x8D: /* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1276 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1279 struct vmcb_state *state;
1280 struct vmcb_ctrl *ctrl;
1281 struct svm_regctx *ctx;
1282 uint64_t code, info1, info2, val;
1283 uint32_t eax, ecx, edx;
1284 int error, errcode_valid, handled, idtvec, reflect;
1287 ctx = svm_get_guest_regctx(svm_sc, vcpu);
1288 vmcb = svm_get_vmcb(svm_sc, vcpu);
1289 state = &vmcb->state;
1293 code = ctrl->exitcode;
1294 info1 = ctrl->exitinfo1;
1295 info2 = ctrl->exitinfo2;
1297 vmexit->exitcode = VM_EXITCODE_BOGUS;
1298 vmexit->rip = state->rip;
1299 vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1301 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1304 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1305 * in an inconsistent state and can trigger assertions that would
1306 * never happen otherwise.
1308 if (code == VMCB_EXIT_INVALID) {
1309 vm_exit_svm(vmexit, code, info1, info2);
1313 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1314 "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1316 KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1317 ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1318 vmexit->inst_length, code, info1, info2));
1320 svm_update_virqinfo(svm_sc, vcpu);
1321 svm_save_intinfo(svm_sc, vcpu);
1324 case VMCB_EXIT_IRET:
1326 * Restart execution at "iret" but with the intercept cleared.
1328 vmexit->inst_length = 0;
1329 clear_nmi_blocking(svm_sc, vcpu);
1332 case VMCB_EXIT_VINTR: /* interrupt window exiting */
1333 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1336 case VMCB_EXIT_INTR: /* external interrupt */
1337 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1340 case VMCB_EXIT_NMI: /* external NMI */
1344 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1346 idtvec = code - 0x40;
1350 * Call the machine check handler by hand. Also don't
1351 * reflect the machine check back into the guest.
1354 VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1355 __asm __volatile("int $18");
1358 error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1360 KASSERT(error == 0, ("%s: error %d updating cr2",
1380 * The 'nrip' field is populated for INT3, INTO and
1381 * BOUND exceptions and this also implies that
1382 * 'inst_length' is non-zero.
1384 * Reset 'inst_length' to zero so the guest %rip at
1385 * event injection is identical to what it was when
1386 * the exception originally happened.
1388 VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1389 "to zero before injecting exception %d",
1390 vmexit->inst_length, idtvec);
1391 vmexit->inst_length = 0;
1398 KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1399 "when reflecting exception %d into guest",
1400 vmexit->inst_length, idtvec));
1403 /* Reflect the exception back into the guest */
1404 VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1405 "%d/%#x into the guest", idtvec, (int)info1);
1406 error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1407 errcode_valid, info1, 0);
1408 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1413 case VMCB_EXIT_MSR: /* MSR access. */
1415 ecx = ctx->sctx_rcx;
1416 edx = ctx->sctx_rdx;
1420 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1421 val = (uint64_t)edx << 32 | eax;
1422 VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1424 if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1425 vmexit->exitcode = VM_EXITCODE_WRMSR;
1426 vmexit->u.msr.code = ecx;
1427 vmexit->u.msr.wval = val;
1431 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1432 ("emulate_wrmsr retu with bogus exitcode"));
1435 VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1436 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1437 if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1438 vmexit->exitcode = VM_EXITCODE_RDMSR;
1439 vmexit->u.msr.code = ecx;
1443 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1444 ("emulate_rdmsr retu with bogus exitcode"));
1449 handled = svm_handle_io(svm_sc, vcpu, vmexit);
1450 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1452 case VMCB_EXIT_CPUID:
1453 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1454 handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1455 (uint32_t *)&state->rax,
1456 (uint32_t *)&ctx->sctx_rbx,
1457 (uint32_t *)&ctx->sctx_rcx,
1458 (uint32_t *)&ctx->sctx_rdx);
1461 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1462 vmexit->exitcode = VM_EXITCODE_HLT;
1463 vmexit->u.hlt.rflags = state->rflags;
1465 case VMCB_EXIT_PAUSE:
1466 vmexit->exitcode = VM_EXITCODE_PAUSE;
1467 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1470 /* EXITINFO2 contains the faulting guest physical address */
1471 if (info1 & VMCB_NPF_INFO1_RSV) {
1472 VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1473 "reserved bits set: info1(%#lx) info2(%#lx)",
1475 } else if (vm_mem_allocated(svm_sc->vm, info2)) {
1476 vmexit->exitcode = VM_EXITCODE_PAGING;
1477 vmexit->u.paging.gpa = info2;
1478 vmexit->u.paging.fault_type = npf_fault_type(info1);
1479 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1480 VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1481 "on gpa %#lx/%#lx at rip %#lx",
1482 info2, info1, state->rip);
1483 } else if (svm_npf_emul_fault(info1)) {
1484 svm_handle_inst_emul(vmcb, info2, vmexit);
1485 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1486 VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1487 "for gpa %#lx/%#lx at rip %#lx",
1488 info2, info1, state->rip);
1491 case VMCB_EXIT_MONITOR:
1492 vmexit->exitcode = VM_EXITCODE_MONITOR;
1494 case VMCB_EXIT_MWAIT:
1495 vmexit->exitcode = VM_EXITCODE_MWAIT;
1498 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1502 VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1503 handled ? "handled" : "unhandled", exit_reason_to_str(code),
1504 vmexit->rip, vmexit->inst_length);
1507 vmexit->rip += vmexit->inst_length;
1508 vmexit->inst_length = 0;
1509 state->rip = vmexit->rip;
1511 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1513 * If this VM exit was not claimed by anybody then
1514 * treat it as a generic SVM exit.
1516 vm_exit_svm(vmexit, code, info1, info2);
1519 * The exitcode and collateral have been populated.
1520 * The VM exit will be processed further in userland.
1528 svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1532 if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1535 KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1536 "valid: %#lx", __func__, intinfo));
1538 svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1539 VMCB_EXITINTINFO_VECTOR(intinfo),
1540 VMCB_EXITINTINFO_EC(intinfo),
1541 VMCB_EXITINTINFO_EC_VALID(intinfo));
1542 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1543 VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1547 * Inject event to virtual cpu.
1550 svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1552 struct vmcb_ctrl *ctrl;
1553 struct vmcb_state *state;
1554 struct svm_vcpu *vcpustate;
1556 int vector, need_intr_window, pending_apic_vector;
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;
1563 pending_apic_vector = 0;
1565 if (vcpustate->nextrip != state->rip) {
1566 ctrl->intr_shadow = 0;
1567 VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1568 "cleared due to rip change: %#lx/%#lx",
1569 vcpustate->nextrip, state->rip);
1573 * Inject pending events or exceptions for this vcpu.
1575 * An event might be pending because the previous #VMEXIT happened
1576 * during event delivery (i.e. ctrl->exitintinfo).
1578 * An event might also be pending because an exception was injected
1579 * by the hypervisor (e.g. #PF during instruction emulation).
1581 svm_inj_intinfo(sc, vcpu);
1583 /* NMI event has priority over interrupts. */
1584 if (vm_nmi_pending(sc->vm, vcpu)) {
1585 if (nmi_blocked(sc, vcpu)) {
1587 * Can't inject another NMI if the guest has not
1588 * yet executed an "iret" after the last NMI.
1590 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1592 } else if (ctrl->intr_shadow) {
1594 * Can't inject an NMI if the vcpu is in an intr_shadow.
1596 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1597 "interrupt shadow");
1598 need_intr_window = 1;
1600 } else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1602 * If there is already an exception/interrupt pending
1603 * then defer the NMI until after that.
1605 VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1606 "eventinj %#lx", ctrl->eventinj);
1609 * Use self-IPI to trigger a VM-exit as soon as
1610 * possible after the event injection is completed.
1612 * This works only if the external interrupt exiting
1613 * is at a lower priority than the event injection.
1615 * Although not explicitly specified in APMv2 the
1616 * relative priorities were verified empirically.
1618 ipi_cpu(curcpu, IPI_AST); /* XXX vmm_ipinum? */
1620 vm_nmi_clear(sc->vm, vcpu);
1622 /* Inject NMI, vector number is not used */
1623 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1626 /* virtual NMI blocking is now in effect */
1627 enable_nmi_blocking(sc, vcpu);
1629 VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1633 if (!vm_extint_pending(sc->vm, vcpu)) {
1635 * APIC interrupts are delivered using the V_IRQ offload.
1637 * The primary benefit is that the hypervisor doesn't need to
1638 * deal with the various conditions that inhibit interrupts.
1639 * It also means that TPR changes via CR8 will be handled
1640 * without any hypervisor involvement.
1642 * Note that the APIC vector must remain pending in the vIRR
1643 * until it is confirmed that it was delivered to the guest.
1644 * This can be confirmed based on the value of V_IRQ at the
1645 * next #VMEXIT (1 = pending, 0 = delivered).
1647 * Also note that it is possible that another higher priority
1648 * vector can become pending before this vector is delivered
1649 * to the guest. This is alright because vcpu_notify_event()
1650 * will send an IPI and force the vcpu to trap back into the
1651 * hypervisor. The higher priority vector will be injected on
1654 if (vlapic_pending_intr(vlapic, &vector)) {
1655 KASSERT(vector >= 16 && vector <= 255,
1656 ("invalid vector %d from local APIC", vector));
1657 pending_apic_vector = vector;
1662 /* Ask the legacy pic for a vector to inject */
1663 vatpic_pending_intr(sc->vm, &vector);
1664 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d from INTR",
1668 * If the guest has disabled interrupts or is in an interrupt shadow
1669 * then we cannot inject the pending interrupt.
1671 if ((state->rflags & PSL_I) == 0) {
1672 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1673 "rflags %#lx", vector, state->rflags);
1674 need_intr_window = 1;
1678 if (ctrl->intr_shadow) {
1679 VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1680 "interrupt shadow", vector);
1681 need_intr_window = 1;
1685 if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1686 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1687 "eventinj %#lx", vector, ctrl->eventinj);
1688 need_intr_window = 1;
1693 * Legacy PIC interrupts are delivered via the event injection
1696 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1698 vm_extint_clear(sc->vm, vcpu);
1699 vatpic_intr_accepted(sc->vm, vector);
1702 * Force a VM-exit as soon as the vcpu is ready to accept another
1703 * interrupt. This is done because the PIC might have another vector
1704 * that it wants to inject. Also, if the APIC has a pending interrupt
1705 * that was preempted by the ExtInt then it allows us to inject the
1706 * APIC vector as soon as possible.
1708 need_intr_window = 1;
1711 * The guest can modify the TPR by writing to %CR8. In guest mode
1712 * the processor reflects this write to V_TPR without hypervisor
1715 * The guest can also modify the TPR by writing to it via the memory
1716 * mapped APIC page. In this case, the write will be emulated by the
1717 * hypervisor. For this reason V_TPR must be updated before every
1720 v_tpr = vlapic_get_cr8(vlapic);
1721 KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1722 if (ctrl->v_tpr != v_tpr) {
1723 VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1724 ctrl->v_tpr, v_tpr);
1725 ctrl->v_tpr = v_tpr;
1726 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1729 if (pending_apic_vector) {
1731 * If an APIC vector is being injected then interrupt window
1732 * exiting is not possible on this VMRUN.
1734 KASSERT(!need_intr_window, ("intr_window exiting impossible"));
1735 VCPU_CTR1(sc->vm, vcpu, "Injecting vector %d using V_IRQ",
1736 pending_apic_vector);
1739 ctrl->v_ign_tpr = 0;
1740 ctrl->v_intr_vector = pending_apic_vector;
1741 ctrl->v_intr_prio = pending_apic_vector >> 4;
1742 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1743 } else if (need_intr_window) {
1745 * We use V_IRQ in conjunction with the VINTR intercept to
1746 * trap into the hypervisor as soon as a virtual interrupt
1749 * Since injected events are not subject to intercept checks
1750 * we need to ensure that the V_IRQ is not actually going to
1751 * be delivered on VM entry. The KASSERT below enforces this.
1753 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1754 (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1755 ("Bogus intr_window_exiting: eventinj (%#lx), "
1756 "intr_shadow (%u), rflags (%#lx)",
1757 ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1758 enable_intr_window_exiting(sc, vcpu);
1760 disable_intr_window_exiting(sc, vcpu);
1764 static __inline void
1765 restore_host_tss(void)
1767 struct system_segment_descriptor *tss_sd;
1770 * The TSS descriptor was in use prior to launching the guest so it
1771 * has been marked busy.
1773 * 'ltr' requires the descriptor to be marked available so change the
1774 * type to "64-bit available TSS".
1776 tss_sd = PCPU_GET(tss);
1777 tss_sd->sd_type = SDT_SYSTSS;
1778 ltr(GSEL(GPROC0_SEL, SEL_KPL));
1782 check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1784 struct svm_vcpu *vcpustate;
1785 struct vmcb_ctrl *ctrl;
1789 KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1790 "active on cpu %u", __func__, thiscpu));
1792 vcpustate = svm_get_vcpu(sc, vcpuid);
1793 ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1796 * The TLB entries associated with the vcpu's ASID are not valid
1797 * if either of the following conditions is true:
1799 * 1. The vcpu's ASID generation is different than the host cpu's
1800 * ASID generation. This happens when the vcpu migrates to a new
1801 * host cpu. It can also happen when the number of vcpus executing
1802 * on a host cpu is greater than the number of ASIDs available.
1804 * 2. The pmap generation number is different than the value cached in
1805 * the 'vcpustate'. This happens when the host invalidates pages
1806 * belonging to the guest.
1808 * asidgen eptgen Action
1815 * (a) There is no mismatch in eptgen or ASID generation and therefore
1816 * no further action is needed.
1818 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1819 * retained and the TLB entries associated with this ASID
1820 * are flushed by VMRUN.
1822 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1825 * (c) A new ASID is allocated.
1827 * (d) A new ASID is allocated.
1831 eptgen = pmap->pm_eptgen;
1832 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1834 if (vcpustate->asid.gen != asid[thiscpu].gen) {
1835 alloc_asid = true; /* (c) and (d) */
1836 } else if (vcpustate->eptgen != eptgen) {
1837 if (flush_by_asid())
1838 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST; /* (b1) */
1840 alloc_asid = true; /* (b2) */
1843 * This is the common case (a).
1845 KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1846 KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1847 ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1851 if (++asid[thiscpu].num >= nasid) {
1852 asid[thiscpu].num = 1;
1853 if (++asid[thiscpu].gen == 0)
1854 asid[thiscpu].gen = 1;
1856 * If this cpu does not support "flush-by-asid"
1857 * then flush the entire TLB on a generation
1858 * bump. Subsequent ASID allocation in this
1859 * generation can be done without a TLB flush.
1861 if (!flush_by_asid())
1862 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1864 vcpustate->asid.gen = asid[thiscpu].gen;
1865 vcpustate->asid.num = asid[thiscpu].num;
1867 ctrl->asid = vcpustate->asid.num;
1868 svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1870 * If this cpu supports "flush-by-asid" then the TLB
1871 * was not flushed after the generation bump. The TLB
1872 * is flushed selectively after every new ASID allocation.
1874 if (flush_by_asid())
1875 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1877 vcpustate->eptgen = eptgen;
1879 KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1880 KASSERT(ctrl->asid == vcpustate->asid.num,
1881 ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1884 static __inline void
1888 __asm __volatile("clgi");
1891 static __inline void
1895 __asm __volatile("stgi");
1899 * Start vcpu with specified RIP.
1902 svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1903 void *rend_cookie, void *suspended_cookie)
1905 struct svm_regctx *gctx;
1906 struct svm_softc *svm_sc;
1907 struct svm_vcpu *vcpustate;
1908 struct vmcb_state *state;
1909 struct vmcb_ctrl *ctrl;
1910 struct vm_exit *vmexit;
1911 struct vlapic *vlapic;
1920 vcpustate = svm_get_vcpu(svm_sc, vcpu);
1921 state = svm_get_vmcb_state(svm_sc, vcpu);
1922 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1923 vmexit = vm_exitinfo(vm, vcpu);
1924 vlapic = vm_lapic(vm, vcpu);
1927 * Stash 'curcpu' on the stack as 'thiscpu'.
1929 * The per-cpu data area is not accessible until MSR_GSBASE is restored
1930 * after the #VMEXIT. Since VMRUN is executed inside a critical section
1931 * 'curcpu' and 'thiscpu' are guaranteed to identical.
1935 gctx = svm_get_guest_regctx(svm_sc, vcpu);
1936 vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1938 if (vcpustate->lastcpu != thiscpu) {
1940 * Force new ASID allocation by invalidating the generation.
1942 vcpustate->asid.gen = 0;
1945 * Invalidate the VMCB state cache by marking all fields dirty.
1947 svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1951 * Setting 'vcpustate->lastcpu' here is bit premature because
1952 * we may return from this function without actually executing
1953 * the VMRUN instruction. This could happen if a rendezvous
1954 * or an AST is pending on the first time through the loop.
1956 * This works for now but any new side-effects of vcpu
1957 * migration should take this case into account.
1959 vcpustate->lastcpu = thiscpu;
1960 vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1963 svm_msr_guest_enter(svm_sc, vcpu);
1965 /* Update Guest RIP */
1970 * Disable global interrupts to guarantee atomicity during
1971 * loading of guest state. This includes not only the state
1972 * loaded by the "vmrun" instruction but also software state
1973 * maintained by the hypervisor: suspended and rendezvous
1974 * state, NPT generation number, vlapic interrupts etc.
1978 if (vcpu_suspended(suspended_cookie)) {
1980 vm_exit_suspended(vm, vcpu, state->rip);
1984 if (vcpu_rendezvous_pending(rend_cookie)) {
1986 vm_exit_rendezvous(vm, vcpu, state->rip);
1990 /* We are asked to give the cpu by scheduler. */
1991 if (vcpu_should_yield(vm, vcpu)) {
1993 vm_exit_astpending(vm, vcpu, state->rip);
1997 svm_inj_interrupts(svm_sc, vcpu, vlapic);
1999 /* Activate the nested pmap on 'thiscpu' */
2000 CPU_SET_ATOMIC_ACQ(thiscpu, &pmap->pm_active);
2003 * Check the pmap generation and the ASID generation to
2004 * ensure that the vcpu does not use stale TLB mappings.
2006 check_asid(svm_sc, vcpu, pmap, thiscpu);
2008 ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
2009 vcpustate->dirty = 0;
2010 VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
2012 /* Launch Virtual Machine. */
2013 VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
2014 svm_launch(vmcb_pa, gctx);
2016 CPU_CLR_ATOMIC(thiscpu, &pmap->pm_active);
2019 * Restore MSR_GSBASE to point to the pcpu data area.
2021 * Note that accesses done via PCPU_GET/PCPU_SET will work
2022 * only after MSR_GSBASE is restored.
2024 * Also note that we don't bother restoring MSR_KGSBASE
2025 * since it is not used in the kernel and will be restored
2026 * when the VMRUN ioctl returns to userspace.
2028 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[thiscpu]);
2029 KASSERT(curcpu == thiscpu, ("thiscpu/curcpu (%u/%u) mismatch",
2033 * The host GDTR and IDTR is saved by VMRUN and restored
2034 * automatically on #VMEXIT. However, the host TSS needs
2035 * to be restored explicitly.
2039 /* #VMEXIT disables interrupts so re-enable them here. */
2042 /* Update 'nextrip' */
2043 vcpustate->nextrip = state->rip;
2045 /* Handle #VMEXIT and if required return to user space. */
2046 handled = svm_vmexit(svm_sc, vcpu, vmexit);
2049 svm_msr_guest_exit(svm_sc, vcpu);
2055 svm_vmcleanup(void *arg)
2057 struct svm_softc *sc = arg;
2063 swctx_regptr(struct svm_regctx *regctx, int reg)
2067 case VM_REG_GUEST_RBX:
2068 return (®ctx->sctx_rbx);
2069 case VM_REG_GUEST_RCX:
2070 return (®ctx->sctx_rcx);
2071 case VM_REG_GUEST_RDX:
2072 return (®ctx->sctx_rdx);
2073 case VM_REG_GUEST_RDI:
2074 return (®ctx->sctx_rdi);
2075 case VM_REG_GUEST_RSI:
2076 return (®ctx->sctx_rsi);
2077 case VM_REG_GUEST_RBP:
2078 return (®ctx->sctx_rbp);
2079 case VM_REG_GUEST_R8:
2080 return (®ctx->sctx_r8);
2081 case VM_REG_GUEST_R9:
2082 return (®ctx->sctx_r9);
2083 case VM_REG_GUEST_R10:
2084 return (®ctx->sctx_r10);
2085 case VM_REG_GUEST_R11:
2086 return (®ctx->sctx_r11);
2087 case VM_REG_GUEST_R12:
2088 return (®ctx->sctx_r12);
2089 case VM_REG_GUEST_R13:
2090 return (®ctx->sctx_r13);
2091 case VM_REG_GUEST_R14:
2092 return (®ctx->sctx_r14);
2093 case VM_REG_GUEST_R15:
2094 return (®ctx->sctx_r15);
2101 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2103 struct svm_softc *svm_sc;
2108 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2109 return (svm_get_intr_shadow(svm_sc, vcpu, val));
2112 if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2116 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2123 VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2128 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2130 struct svm_softc *svm_sc;
2135 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2136 return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2139 if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2143 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2151 * XXX deal with CR3 and invalidate TLB entries tagged with the
2152 * vcpu's ASID. This needs to be treated differently depending on
2153 * whether 'running' is true/false.
2156 VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2161 svm_setcap(void *arg, int vcpu, int type, int val)
2163 struct svm_softc *sc;
2169 case VM_CAP_HALT_EXIT:
2170 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2171 VMCB_INTCPT_HLT, val);
2173 case VM_CAP_PAUSE_EXIT:
2174 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2175 VMCB_INTCPT_PAUSE, val);
2177 case VM_CAP_UNRESTRICTED_GUEST:
2178 /* Unrestricted guest execution cannot be disabled in SVM */
2190 svm_getcap(void *arg, int vcpu, int type, int *retval)
2192 struct svm_softc *sc;
2199 case VM_CAP_HALT_EXIT:
2200 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2203 case VM_CAP_PAUSE_EXIT:
2204 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2207 case VM_CAP_UNRESTRICTED_GUEST:
2208 *retval = 1; /* unrestricted guest is always enabled */
2217 static struct vlapic *
2218 svm_vlapic_init(void *arg, int vcpuid)
2220 struct svm_softc *svm_sc;
2221 struct vlapic *vlapic;
2224 vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2225 vlapic->vm = svm_sc->vm;
2226 vlapic->vcpuid = vcpuid;
2227 vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2229 vlapic_init(vlapic);
2235 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2238 vlapic_cleanup(vlapic);
2239 free(vlapic, M_SVM_VLAPIC);
2242 struct vmm_ops vmm_ops_amd = {