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 | \
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 = ~0U; /* AMD SVM features. */
106 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RDTUN, &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_RDTUN, &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 * The number of ASIDs can be configured to be less than what is
181 * supported by the hardware but not more.
183 if (nasid == 0 || nasid > regs[1])
185 KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
187 /* bhyve requires the Nested Paging feature */
188 if (!(svm_feature & AMD_CPUID_SVM_NP)) {
189 printf("SVM: Nested Paging feature not available.\n");
193 /* bhyve requires the NRIP Save feature */
194 if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
195 printf("SVM: NRIP Save feature not available.\n");
203 svm_enable(void *arg __unused)
207 efer = rdmsr(MSR_EFER);
209 wrmsr(MSR_EFER, efer);
211 wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
215 * Return 1 if SVM is enabled on this processor and 0 otherwise.
222 /* Section 15.4 Enabling SVM from APM2. */
223 if ((amd_feature2 & AMDID2_SVM) == 0) {
224 printf("SVM: not available.\n");
228 msr = rdmsr(MSR_VM_CR);
229 if ((msr & VM_CR_SVMDIS) != 0) {
230 printf("SVM: disabled by BIOS.\n");
242 if (!svm_available())
245 error = check_svm_features();
249 vmcb_clean &= VMCB_CACHE_DEFAULT;
251 for (cpu = 0; cpu < MAXCPU; cpu++) {
253 * Initialize the host ASIDs to their "highest" valid values.
255 * The next ASID allocation will rollover both 'gen' and 'num'
256 * and start off the sequence at {1,1}.
258 asid[cpu].gen = ~0UL;
259 asid[cpu].num = nasid - 1;
263 svm_npt_init(ipinum);
265 /* Enable SVM on all CPUs */
266 smp_rendezvous(NULL, svm_enable, NULL, NULL);
278 /* Pentium compatible MSRs */
279 #define MSR_PENTIUM_START 0
280 #define MSR_PENTIUM_END 0x1FFF
281 /* AMD 6th generation and Intel compatible MSRs */
282 #define MSR_AMD6TH_START 0xC0000000UL
283 #define MSR_AMD6TH_END 0xC0001FFFUL
284 /* AMD 7th and 8th generation compatible MSRs */
285 #define MSR_AMD7TH_START 0xC0010000UL
286 #define MSR_AMD7TH_END 0xC0011FFFUL
289 * Get the index and bit position for a MSR in permission bitmap.
290 * Two bits are used for each MSR: lower bit for read and higher bit for write.
293 svm_msr_index(uint64_t msr, int *index, int *bit)
298 *bit = (msr % 4) * 2;
301 if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
306 base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
307 if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
308 off = (msr - MSR_AMD6TH_START);
309 *index = (off + base) / 4;
313 base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
314 if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
315 off = (msr - MSR_AMD7TH_START);
316 *index = (off + base) / 4;
324 * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
327 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
329 int index, bit, error;
331 error = svm_msr_index(msr, &index, &bit);
332 KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
333 KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
334 ("%s: invalid index %d for msr %#lx", __func__, index, msr));
335 KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
336 "msr %#lx", __func__, bit, msr));
339 perm_bitmap[index] &= ~(1UL << bit);
342 perm_bitmap[index] &= ~(2UL << bit);
346 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
349 svm_msr_perm(perm_bitmap, msr, true, true);
353 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
356 svm_msr_perm(perm_bitmap, msr, true, false);
360 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
362 struct vmcb_ctrl *ctrl;
364 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
366 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
367 return (ctrl->intercept[idx] & bitmask ? 1 : 0);
371 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
374 struct vmcb_ctrl *ctrl;
377 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
379 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
380 oldval = ctrl->intercept[idx];
383 ctrl->intercept[idx] |= bitmask;
385 ctrl->intercept[idx] &= ~bitmask;
387 if (ctrl->intercept[idx] != oldval) {
388 svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
389 VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
390 "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
395 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
398 svm_set_intercept(sc, vcpu, off, bitmask, 0);
402 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
405 svm_set_intercept(sc, vcpu, off, bitmask, 1);
409 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
410 uint64_t msrpm_base_pa, uint64_t np_pml4)
412 struct vmcb_ctrl *ctrl;
413 struct vmcb_state *state;
417 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
418 state = svm_get_vmcb_state(sc, vcpu);
420 ctrl->iopm_base_pa = iopm_base_pa;
421 ctrl->msrpm_base_pa = msrpm_base_pa;
423 /* Enable nested paging */
425 ctrl->n_cr3 = np_pml4;
428 * Intercept accesses to the control registers that are not shadowed
429 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
431 for (n = 0; n < 16; n++) {
432 mask = (BIT(n) << 16) | BIT(n);
433 if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
434 svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
436 svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
441 * Intercept everything when tracing guest exceptions otherwise
442 * just intercept machine check exception.
444 if (vcpu_trace_exceptions(sc->vm, vcpu)) {
445 for (n = 0; n < 32; n++) {
447 * Skip unimplemented vectors in the exception bitmap.
449 if (n == 2 || n == 9) {
452 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
455 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
458 /* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
459 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
460 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
461 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
462 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
463 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
464 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
465 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
466 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
467 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
468 VMCB_INTCPT_FERR_FREEZE);
470 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
471 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
474 * From section "Canonicalization and Consistency Checks" in APMv2
475 * the VMRUN intercept bit must be set to pass the consistency check.
477 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
480 * The ASID will be set to a non-zero value just before VMRUN.
485 * Section 15.21.1, Interrupt Masking in EFLAGS
486 * Section 15.21.2, Virtualizing APIC.TPR
488 * This must be set for %rflag and %cr8 isolation of guest and host.
490 ctrl->v_intr_masking = 1;
492 /* Enable Last Branch Record aka LBR for debugging */
493 ctrl->lbr_virt_en = 1;
494 state->dbgctl = BIT(0);
496 /* EFER_SVM must always be set when the guest is executing */
497 state->efer = EFER_SVM;
499 /* Set up the PAT to power-on state */
500 state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK) |
501 PAT_VALUE(1, PAT_WRITE_THROUGH) |
502 PAT_VALUE(2, PAT_UNCACHED) |
503 PAT_VALUE(3, PAT_UNCACHEABLE) |
504 PAT_VALUE(4, PAT_WRITE_BACK) |
505 PAT_VALUE(5, PAT_WRITE_THROUGH) |
506 PAT_VALUE(6, PAT_UNCACHED) |
507 PAT_VALUE(7, PAT_UNCACHEABLE);
509 /* Set up DR6/7 to power-on state */
510 state->dr6 = 0xffff0ff0;
515 * Initialize a virtual machine.
518 svm_vminit(struct vm *vm, pmap_t pmap)
520 struct svm_softc *svm_sc;
521 struct svm_vcpu *vcpu;
522 vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
525 svm_sc = malloc(sizeof (*svm_sc), M_SVM, M_WAITOK | M_ZERO);
526 if (((uintptr_t)svm_sc & PAGE_MASK) != 0)
527 panic("malloc of svm_softc not aligned on page boundary");
529 svm_sc->msr_bitmap = contigmalloc(SVM_MSR_BITMAP_SIZE, M_SVM,
530 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
531 if (svm_sc->msr_bitmap == NULL)
532 panic("contigmalloc of SVM MSR bitmap failed");
533 svm_sc->iopm_bitmap = contigmalloc(SVM_IO_BITMAP_SIZE, M_SVM,
534 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
535 if (svm_sc->iopm_bitmap == NULL)
536 panic("contigmalloc of SVM IO bitmap failed");
539 svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
542 * Intercept read and write accesses to all MSRs.
544 memset(svm_sc->msr_bitmap, 0xFF, SVM_MSR_BITMAP_SIZE);
547 * Access to the following MSRs is redirected to the VMCB when the
548 * guest is executing. Therefore it is safe to allow the guest to
549 * read/write these MSRs directly without hypervisor involvement.
551 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
552 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
553 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
555 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
556 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
557 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
558 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
559 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
560 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
561 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
562 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
564 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
567 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
569 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
571 /* Intercept access to all I/O ports. */
572 memset(svm_sc->iopm_bitmap, 0xFF, SVM_IO_BITMAP_SIZE);
574 iopm_pa = vtophys(svm_sc->iopm_bitmap);
575 msrpm_pa = vtophys(svm_sc->msr_bitmap);
576 pml4_pa = svm_sc->nptp;
577 for (i = 0; i < VM_MAXCPU; i++) {
578 vcpu = svm_get_vcpu(svm_sc, i);
580 vcpu->lastcpu = NOCPU;
581 vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
582 vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
583 svm_msr_guest_init(svm_sc, i);
589 * Collateral for a generic SVM VM-exit.
592 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
595 vme->exitcode = VM_EXITCODE_SVM;
596 vme->u.svm.exitcode = code;
597 vme->u.svm.exitinfo1 = info1;
598 vme->u.svm.exitinfo2 = info2;
602 svm_cpl(struct vmcb_state *state)
607 * "Retrieve the CPL from the CPL field in the VMCB, not
608 * from any segment DPL"
613 static enum vm_cpu_mode
614 svm_vcpu_mode(struct vmcb *vmcb)
616 struct vmcb_segment seg;
617 struct vmcb_state *state;
620 state = &vmcb->state;
622 if (state->efer & EFER_LMA) {
623 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
624 KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
628 * Section 4.8.1 for APM2, check if Code Segment has
629 * Long attribute set in descriptor.
631 if (seg.attrib & VMCB_CS_ATTRIB_L)
632 return (CPU_MODE_64BIT);
634 return (CPU_MODE_COMPATIBILITY);
635 } else if (state->cr0 & CR0_PE) {
636 return (CPU_MODE_PROTECTED);
638 return (CPU_MODE_REAL);
642 static enum vm_paging_mode
643 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
646 if ((cr0 & CR0_PG) == 0)
647 return (PAGING_MODE_FLAT);
648 if ((cr4 & CR4_PAE) == 0)
649 return (PAGING_MODE_32);
651 return (PAGING_MODE_64);
653 return (PAGING_MODE_PAE);
657 * ins/outs utility routines
660 svm_inout_str_index(struct svm_regctx *regs, int in)
664 val = in ? regs->sctx_rdi : regs->sctx_rsi;
670 svm_inout_str_count(struct svm_regctx *regs, int rep)
674 val = rep ? regs->sctx_rcx : 1;
680 svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
681 int in, struct vm_inout_str *vis)
686 vis->seg_name = VM_REG_GUEST_ES;
688 /* The segment field has standard encoding */
689 s = (info1 >> 10) & 0x7;
690 vis->seg_name = vm_segment_name(s);
693 error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
694 KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
698 svm_inout_str_addrsize(uint64_t info1)
702 size = (info1 >> 7) & 0x7;
705 return (2); /* 16 bit */
707 return (4); /* 32 bit */
709 return (8); /* 64 bit */
711 panic("%s: invalid size encoding %d", __func__, size);
716 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
718 struct vmcb_state *state;
720 state = &vmcb->state;
721 paging->cr3 = state->cr3;
722 paging->cpl = svm_cpl(state);
723 paging->cpu_mode = svm_vcpu_mode(vmcb);
724 paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
731 * Handle guest I/O intercept.
734 svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
736 struct vmcb_ctrl *ctrl;
737 struct vmcb_state *state;
738 struct svm_regctx *regs;
739 struct vm_inout_str *vis;
743 state = svm_get_vmcb_state(svm_sc, vcpu);
744 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
745 regs = svm_get_guest_regctx(svm_sc, vcpu);
747 info1 = ctrl->exitinfo1;
748 inout_string = info1 & BIT(2) ? 1 : 0;
751 * The effective segment number in EXITINFO1[12:10] is populated
752 * only if the processor has the DecodeAssist capability.
754 * XXX this is not specified explicitly in APMv2 but can be verified
757 if (inout_string && !decode_assist())
760 vmexit->exitcode = VM_EXITCODE_INOUT;
761 vmexit->u.inout.in = (info1 & BIT(0)) ? 1 : 0;
762 vmexit->u.inout.string = inout_string;
763 vmexit->u.inout.rep = (info1 & BIT(3)) ? 1 : 0;
764 vmexit->u.inout.bytes = (info1 >> 4) & 0x7;
765 vmexit->u.inout.port = (uint16_t)(info1 >> 16);
766 vmexit->u.inout.eax = (uint32_t)(state->rax);
769 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
770 vis = &vmexit->u.inout_str;
771 svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
772 vis->rflags = state->rflags;
773 vis->cr0 = state->cr0;
774 vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
775 vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
776 vis->addrsize = svm_inout_str_addrsize(info1);
777 svm_inout_str_seginfo(svm_sc, vcpu, info1,
778 vmexit->u.inout.in, vis);
785 npf_fault_type(uint64_t exitinfo1)
788 if (exitinfo1 & VMCB_NPF_INFO1_W)
789 return (VM_PROT_WRITE);
790 else if (exitinfo1 & VMCB_NPF_INFO1_ID)
791 return (VM_PROT_EXECUTE);
793 return (VM_PROT_READ);
797 svm_npf_emul_fault(uint64_t exitinfo1)
800 if (exitinfo1 & VMCB_NPF_INFO1_ID) {
804 if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
808 if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
816 svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
818 struct vm_guest_paging *paging;
819 struct vmcb_segment seg;
820 struct vmcb_ctrl *ctrl;
825 paging = &vmexit->u.inst_emul.paging;
827 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
828 vmexit->u.inst_emul.gpa = gpa;
829 vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
830 svm_paging_info(vmcb, paging);
832 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
833 KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
835 switch(paging->cpu_mode) {
837 vmexit->u.inst_emul.cs_base = seg.base;
838 vmexit->u.inst_emul.cs_d = 0;
840 case CPU_MODE_PROTECTED:
841 case CPU_MODE_COMPATIBILITY:
842 vmexit->u.inst_emul.cs_base = seg.base;
845 * Section 4.8.1 of APM2, Default Operand Size or D bit.
847 vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
851 vmexit->u.inst_emul.cs_base = 0;
852 vmexit->u.inst_emul.cs_d = 0;
857 * Copy the instruction bytes into 'vie' if available.
859 if (decode_assist() && !disable_npf_assist) {
860 inst_len = ctrl->inst_len;
861 inst_bytes = ctrl->inst_bytes;
866 vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
871 intrtype_to_str(int intr_type)
874 case VMCB_EVENTINJ_TYPE_INTR:
876 case VMCB_EVENTINJ_TYPE_NMI:
878 case VMCB_EVENTINJ_TYPE_INTn:
880 case VMCB_EVENTINJ_TYPE_EXCEPTION:
881 return ("exception");
883 panic("%s: unknown intr_type %d", __func__, intr_type);
889 * Inject an event to vcpu as described in section 15.20, "Event injection".
892 svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
893 uint32_t error, bool ec_valid)
895 struct vmcb_ctrl *ctrl;
897 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
899 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
900 ("%s: event already pending %#lx", __func__, ctrl->eventinj));
902 KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
906 case VMCB_EVENTINJ_TYPE_INTR:
907 case VMCB_EVENTINJ_TYPE_NMI:
908 case VMCB_EVENTINJ_TYPE_INTn:
910 case VMCB_EVENTINJ_TYPE_EXCEPTION:
911 if (vector >= 0 && vector <= 31 && vector != 2)
915 panic("%s: invalid intr_type/vector: %d/%d", __func__,
918 ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
920 ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
921 ctrl->eventinj |= (uint64_t)error << 32;
922 VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
923 intrtype_to_str(intr_type), vector, error);
925 VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
926 intrtype_to_str(intr_type), vector);
931 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
934 struct vlapic *vlapic;
935 struct vmcb_ctrl *ctrl;
938 vlapic = vm_lapic(vm, vcpu);
939 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
941 /* Update %cr8 in the emulated vlapic */
942 vlapic_set_cr8(vlapic, ctrl->v_tpr);
944 /* Virtual interrupt injection is not used. */
945 KASSERT(ctrl->v_intr_vector == 0, ("%s: invalid "
946 "v_intr_vector %d", __func__, ctrl->v_intr_vector));
950 svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
952 struct vmcb_ctrl *ctrl;
955 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
956 intinfo = ctrl->exitintinfo;
957 if (!VMCB_EXITINTINFO_VALID(intinfo))
961 * From APMv2, Section "Intercepts during IDT interrupt delivery"
963 * If a #VMEXIT happened during event delivery then record the event
964 * that was being delivered.
966 VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
967 intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
968 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
969 vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
974 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
977 return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
983 enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
985 struct vmcb_ctrl *ctrl;
987 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
989 if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
990 KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
991 KASSERT(vintr_intercept_enabled(sc, vcpu),
992 ("%s: vintr intercept should be enabled", __func__));
996 VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
999 ctrl->v_intr_vector = 0;
1000 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1001 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1004 static __inline void
1005 disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
1007 struct vmcb_ctrl *ctrl;
1009 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1011 if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
1012 KASSERT(!vintr_intercept_enabled(sc, vcpu),
1013 ("%s: vintr intercept should be disabled", __func__));
1017 VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
1019 ctrl->v_intr_vector = 0;
1020 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1021 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1025 svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1027 struct vmcb_ctrl *ctrl;
1030 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1031 oldval = ctrl->intr_shadow;
1032 newval = val ? 1 : 0;
1033 if (newval != oldval) {
1034 ctrl->intr_shadow = newval;
1035 VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1041 svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1043 struct vmcb_ctrl *ctrl;
1045 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1046 *val = ctrl->intr_shadow;
1051 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1052 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1053 * to track when the vcpu is done handling the NMI.
1056 nmi_blocked(struct svm_softc *sc, int vcpu)
1060 blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1066 enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1069 KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1070 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1071 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1075 clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1079 KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1080 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1082 * When the IRET intercept is cleared the vcpu will attempt to execute
1083 * the "iret" when it runs next. However, it is possible to inject
1084 * another NMI into the vcpu before the "iret" has actually executed.
1086 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1087 * it will trap back into the hypervisor. If an NMI is pending for
1088 * the vcpu it will be injected into the guest.
1090 * XXX this needs to be fixed
1092 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1095 * Set 'intr_shadow' to prevent an NMI from being injected on the
1098 error = svm_modify_intr_shadow(sc, vcpu, 1);
1099 KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1102 #define EFER_MBZ_BITS 0xFFFFFFFFFFFF0200UL
1105 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval, bool *retu)
1107 struct vm_exit *vme;
1108 struct vmcb_state *state;
1109 uint64_t changed, lma, oldval;
1112 state = svm_get_vmcb_state(sc, vcpu);
1114 oldval = state->efer;
1115 VCPU_CTR2(sc->vm, vcpu, "wrmsr(efer) %#lx/%#lx", oldval, newval);
1117 newval &= ~0xFE; /* clear the Read-As-Zero (RAZ) bits */
1118 changed = oldval ^ newval;
1120 if (newval & EFER_MBZ_BITS)
1123 /* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1124 if (changed & EFER_LME) {
1125 if (state->cr0 & CR0_PG)
1129 /* EFER.LMA = EFER.LME & CR0.PG */
1130 if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0)
1135 if ((newval & EFER_LMA) != lma)
1138 if (newval & EFER_NXE) {
1139 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE))
1144 * XXX bhyve does not enforce segment limits in 64-bit mode. Until
1145 * this is fixed flag guest attempt to set EFER_LMSLE as an error.
1147 if (newval & EFER_LMSLE) {
1148 vme = vm_exitinfo(sc->vm, vcpu);
1149 vm_exit_svm(vme, VMCB_EXIT_MSR, 1, 0);
1154 if (newval & EFER_FFXSR) {
1155 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR))
1159 if (newval & EFER_TCE) {
1160 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_TCE))
1164 error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1165 KASSERT(error == 0, ("%s: error %d updating efer", __func__, error));
1168 vm_inject_gp(sc->vm, vcpu);
1173 emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1179 error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1180 else if (num == MSR_EFER)
1181 error = svm_write_efer(sc, vcpu, val, retu);
1183 error = svm_wrmsr(sc, vcpu, num, val, retu);
1189 emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1191 struct vmcb_state *state;
1192 struct svm_regctx *ctx;
1197 error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1199 error = svm_rdmsr(sc, vcpu, num, &result, retu);
1202 state = svm_get_vmcb_state(sc, vcpu);
1203 ctx = svm_get_guest_regctx(sc, vcpu);
1204 state->rax = result & 0xffffffff;
1205 ctx->sctx_rdx = result >> 32;
1213 exit_reason_to_str(uint64_t reason)
1215 static char reasonbuf[32];
1218 case VMCB_EXIT_INVALID:
1219 return ("invalvmcb");
1220 case VMCB_EXIT_SHUTDOWN:
1221 return ("shutdown");
1223 return ("nptfault");
1224 case VMCB_EXIT_PAUSE:
1228 case VMCB_EXIT_CPUID:
1234 case VMCB_EXIT_INTR:
1238 case VMCB_EXIT_VINTR:
1242 case VMCB_EXIT_IRET:
1244 case VMCB_EXIT_MONITOR:
1246 case VMCB_EXIT_MWAIT:
1249 snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1256 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1257 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1258 * and exceptions caused by INT3, INTO and BOUND instructions.
1260 * Return 1 if the nRIP is valid and 0 otherwise.
1263 nrip_valid(uint64_t exitcode)
1266 case 0x00 ... 0x0F: /* read of CR0 through CR15 */
1267 case 0x10 ... 0x1F: /* write of CR0 through CR15 */
1268 case 0x20 ... 0x2F: /* read of DR0 through DR15 */
1269 case 0x30 ... 0x3F: /* write of DR0 through DR15 */
1270 case 0x43: /* INT3 */
1271 case 0x44: /* INTO */
1272 case 0x45: /* BOUND */
1273 case 0x65 ... 0x7C: /* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1274 case 0x80 ... 0x8D: /* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1282 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1285 struct vmcb_state *state;
1286 struct vmcb_ctrl *ctrl;
1287 struct svm_regctx *ctx;
1288 uint64_t code, info1, info2, val;
1289 uint32_t eax, ecx, edx;
1290 int error, errcode_valid, handled, idtvec, reflect;
1293 ctx = svm_get_guest_regctx(svm_sc, vcpu);
1294 vmcb = svm_get_vmcb(svm_sc, vcpu);
1295 state = &vmcb->state;
1299 code = ctrl->exitcode;
1300 info1 = ctrl->exitinfo1;
1301 info2 = ctrl->exitinfo2;
1303 vmexit->exitcode = VM_EXITCODE_BOGUS;
1304 vmexit->rip = state->rip;
1305 vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1307 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1310 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1311 * in an inconsistent state and can trigger assertions that would
1312 * never happen otherwise.
1314 if (code == VMCB_EXIT_INVALID) {
1315 vm_exit_svm(vmexit, code, info1, info2);
1319 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1320 "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1322 KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1323 ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1324 vmexit->inst_length, code, info1, info2));
1326 svm_update_virqinfo(svm_sc, vcpu);
1327 svm_save_intinfo(svm_sc, vcpu);
1330 case VMCB_EXIT_IRET:
1332 * Restart execution at "iret" but with the intercept cleared.
1334 vmexit->inst_length = 0;
1335 clear_nmi_blocking(svm_sc, vcpu);
1338 case VMCB_EXIT_VINTR: /* interrupt window exiting */
1339 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1342 case VMCB_EXIT_INTR: /* external interrupt */
1343 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1346 case VMCB_EXIT_NMI: /* external NMI */
1350 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1352 idtvec = code - 0x40;
1356 * Call the machine check handler by hand. Also don't
1357 * reflect the machine check back into the guest.
1360 VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1361 __asm __volatile("int $18");
1364 error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1366 KASSERT(error == 0, ("%s: error %d updating cr2",
1386 * The 'nrip' field is populated for INT3, INTO and
1387 * BOUND exceptions and this also implies that
1388 * 'inst_length' is non-zero.
1390 * Reset 'inst_length' to zero so the guest %rip at
1391 * event injection is identical to what it was when
1392 * the exception originally happened.
1394 VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1395 "to zero before injecting exception %d",
1396 vmexit->inst_length, idtvec);
1397 vmexit->inst_length = 0;
1404 KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1405 "when reflecting exception %d into guest",
1406 vmexit->inst_length, idtvec));
1409 /* Reflect the exception back into the guest */
1410 VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1411 "%d/%#x into the guest", idtvec, (int)info1);
1412 error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1413 errcode_valid, info1, 0);
1414 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1419 case VMCB_EXIT_MSR: /* MSR access. */
1421 ecx = ctx->sctx_rcx;
1422 edx = ctx->sctx_rdx;
1426 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1427 val = (uint64_t)edx << 32 | eax;
1428 VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1430 if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1431 vmexit->exitcode = VM_EXITCODE_WRMSR;
1432 vmexit->u.msr.code = ecx;
1433 vmexit->u.msr.wval = val;
1437 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1438 ("emulate_wrmsr retu with bogus exitcode"));
1441 VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1442 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1443 if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1444 vmexit->exitcode = VM_EXITCODE_RDMSR;
1445 vmexit->u.msr.code = ecx;
1449 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1450 ("emulate_rdmsr retu with bogus exitcode"));
1455 handled = svm_handle_io(svm_sc, vcpu, vmexit);
1456 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1458 case VMCB_EXIT_CPUID:
1459 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1460 handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1461 (uint32_t *)&state->rax,
1462 (uint32_t *)&ctx->sctx_rbx,
1463 (uint32_t *)&ctx->sctx_rcx,
1464 (uint32_t *)&ctx->sctx_rdx);
1467 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1468 vmexit->exitcode = VM_EXITCODE_HLT;
1469 vmexit->u.hlt.rflags = state->rflags;
1471 case VMCB_EXIT_PAUSE:
1472 vmexit->exitcode = VM_EXITCODE_PAUSE;
1473 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1476 /* EXITINFO2 contains the faulting guest physical address */
1477 if (info1 & VMCB_NPF_INFO1_RSV) {
1478 VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1479 "reserved bits set: info1(%#lx) info2(%#lx)",
1481 } else if (vm_mem_allocated(svm_sc->vm, vcpu, info2)) {
1482 vmexit->exitcode = VM_EXITCODE_PAGING;
1483 vmexit->u.paging.gpa = info2;
1484 vmexit->u.paging.fault_type = npf_fault_type(info1);
1485 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1486 VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1487 "on gpa %#lx/%#lx at rip %#lx",
1488 info2, info1, state->rip);
1489 } else if (svm_npf_emul_fault(info1)) {
1490 svm_handle_inst_emul(vmcb, info2, vmexit);
1491 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1492 VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1493 "for gpa %#lx/%#lx at rip %#lx",
1494 info2, info1, state->rip);
1497 case VMCB_EXIT_MONITOR:
1498 vmexit->exitcode = VM_EXITCODE_MONITOR;
1500 case VMCB_EXIT_MWAIT:
1501 vmexit->exitcode = VM_EXITCODE_MWAIT;
1504 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1508 VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1509 handled ? "handled" : "unhandled", exit_reason_to_str(code),
1510 vmexit->rip, vmexit->inst_length);
1513 vmexit->rip += vmexit->inst_length;
1514 vmexit->inst_length = 0;
1515 state->rip = vmexit->rip;
1517 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1519 * If this VM exit was not claimed by anybody then
1520 * treat it as a generic SVM exit.
1522 vm_exit_svm(vmexit, code, info1, info2);
1525 * The exitcode and collateral have been populated.
1526 * The VM exit will be processed further in userland.
1534 svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1538 if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1541 KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1542 "valid: %#lx", __func__, intinfo));
1544 svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1545 VMCB_EXITINTINFO_VECTOR(intinfo),
1546 VMCB_EXITINTINFO_EC(intinfo),
1547 VMCB_EXITINTINFO_EC_VALID(intinfo));
1548 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1549 VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1553 * Inject event to virtual cpu.
1556 svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1558 struct vmcb_ctrl *ctrl;
1559 struct vmcb_state *state;
1560 struct svm_vcpu *vcpustate;
1562 int vector, need_intr_window;
1565 state = svm_get_vmcb_state(sc, vcpu);
1566 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1567 vcpustate = svm_get_vcpu(sc, vcpu);
1569 need_intr_window = 0;
1571 if (vcpustate->nextrip != state->rip) {
1572 ctrl->intr_shadow = 0;
1573 VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1574 "cleared due to rip change: %#lx/%#lx",
1575 vcpustate->nextrip, state->rip);
1579 * Inject pending events or exceptions for this vcpu.
1581 * An event might be pending because the previous #VMEXIT happened
1582 * during event delivery (i.e. ctrl->exitintinfo).
1584 * An event might also be pending because an exception was injected
1585 * by the hypervisor (e.g. #PF during instruction emulation).
1587 svm_inj_intinfo(sc, vcpu);
1589 /* NMI event has priority over interrupts. */
1590 if (vm_nmi_pending(sc->vm, vcpu)) {
1591 if (nmi_blocked(sc, vcpu)) {
1593 * Can't inject another NMI if the guest has not
1594 * yet executed an "iret" after the last NMI.
1596 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1598 } else if (ctrl->intr_shadow) {
1600 * Can't inject an NMI if the vcpu is in an intr_shadow.
1602 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1603 "interrupt shadow");
1604 need_intr_window = 1;
1606 } else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1608 * If there is already an exception/interrupt pending
1609 * then defer the NMI until after that.
1611 VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1612 "eventinj %#lx", ctrl->eventinj);
1615 * Use self-IPI to trigger a VM-exit as soon as
1616 * possible after the event injection is completed.
1618 * This works only if the external interrupt exiting
1619 * is at a lower priority than the event injection.
1621 * Although not explicitly specified in APMv2 the
1622 * relative priorities were verified empirically.
1624 ipi_cpu(curcpu, IPI_AST); /* XXX vmm_ipinum? */
1626 vm_nmi_clear(sc->vm, vcpu);
1628 /* Inject NMI, vector number is not used */
1629 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1632 /* virtual NMI blocking is now in effect */
1633 enable_nmi_blocking(sc, vcpu);
1635 VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1639 extint_pending = vm_extint_pending(sc->vm, vcpu);
1640 if (!extint_pending) {
1641 if (!vlapic_pending_intr(vlapic, &vector))
1643 KASSERT(vector >= 16 && vector <= 255,
1644 ("invalid vector %d from local APIC", vector));
1646 /* Ask the legacy pic for a vector to inject */
1647 vatpic_pending_intr(sc->vm, &vector);
1648 KASSERT(vector >= 0 && vector <= 255,
1649 ("invalid vector %d from INTR", vector));
1653 * If the guest has disabled interrupts or is in an interrupt shadow
1654 * then we cannot inject the pending interrupt.
1656 if ((state->rflags & PSL_I) == 0) {
1657 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1658 "rflags %#lx", vector, state->rflags);
1659 need_intr_window = 1;
1663 if (ctrl->intr_shadow) {
1664 VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1665 "interrupt shadow", vector);
1666 need_intr_window = 1;
1670 if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1671 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1672 "eventinj %#lx", vector, ctrl->eventinj);
1673 need_intr_window = 1;
1677 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1679 if (!extint_pending) {
1680 vlapic_intr_accepted(vlapic, vector);
1682 vm_extint_clear(sc->vm, vcpu);
1683 vatpic_intr_accepted(sc->vm, vector);
1687 * Force a VM-exit as soon as the vcpu is ready to accept another
1688 * interrupt. This is done because the PIC might have another vector
1689 * that it wants to inject. Also, if the APIC has a pending interrupt
1690 * that was preempted by the ExtInt then it allows us to inject the
1691 * APIC vector as soon as possible.
1693 need_intr_window = 1;
1696 * The guest can modify the TPR by writing to %CR8. In guest mode
1697 * the processor reflects this write to V_TPR without hypervisor
1700 * The guest can also modify the TPR by writing to it via the memory
1701 * mapped APIC page. In this case, the write will be emulated by the
1702 * hypervisor. For this reason V_TPR must be updated before every
1705 v_tpr = vlapic_get_cr8(vlapic);
1706 KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1707 if (ctrl->v_tpr != v_tpr) {
1708 VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1709 ctrl->v_tpr, v_tpr);
1710 ctrl->v_tpr = v_tpr;
1711 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1714 if (need_intr_window) {
1716 * We use V_IRQ in conjunction with the VINTR intercept to
1717 * trap into the hypervisor as soon as a virtual interrupt
1720 * Since injected events are not subject to intercept checks
1721 * we need to ensure that the V_IRQ is not actually going to
1722 * be delivered on VM entry. The KASSERT below enforces this.
1724 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1725 (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1726 ("Bogus intr_window_exiting: eventinj (%#lx), "
1727 "intr_shadow (%u), rflags (%#lx)",
1728 ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1729 enable_intr_window_exiting(sc, vcpu);
1731 disable_intr_window_exiting(sc, vcpu);
1735 static __inline void
1736 restore_host_tss(void)
1738 struct system_segment_descriptor *tss_sd;
1741 * The TSS descriptor was in use prior to launching the guest so it
1742 * has been marked busy.
1744 * 'ltr' requires the descriptor to be marked available so change the
1745 * type to "64-bit available TSS".
1747 tss_sd = PCPU_GET(tss);
1748 tss_sd->sd_type = SDT_SYSTSS;
1749 ltr(GSEL(GPROC0_SEL, SEL_KPL));
1753 check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1755 struct svm_vcpu *vcpustate;
1756 struct vmcb_ctrl *ctrl;
1760 KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1761 "active on cpu %u", __func__, thiscpu));
1763 vcpustate = svm_get_vcpu(sc, vcpuid);
1764 ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1767 * The TLB entries associated with the vcpu's ASID are not valid
1768 * if either of the following conditions is true:
1770 * 1. The vcpu's ASID generation is different than the host cpu's
1771 * ASID generation. This happens when the vcpu migrates to a new
1772 * host cpu. It can also happen when the number of vcpus executing
1773 * on a host cpu is greater than the number of ASIDs available.
1775 * 2. The pmap generation number is different than the value cached in
1776 * the 'vcpustate'. This happens when the host invalidates pages
1777 * belonging to the guest.
1779 * asidgen eptgen Action
1786 * (a) There is no mismatch in eptgen or ASID generation and therefore
1787 * no further action is needed.
1789 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1790 * retained and the TLB entries associated with this ASID
1791 * are flushed by VMRUN.
1793 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1796 * (c) A new ASID is allocated.
1798 * (d) A new ASID is allocated.
1802 eptgen = pmap->pm_eptgen;
1803 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1805 if (vcpustate->asid.gen != asid[thiscpu].gen) {
1806 alloc_asid = true; /* (c) and (d) */
1807 } else if (vcpustate->eptgen != eptgen) {
1808 if (flush_by_asid())
1809 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST; /* (b1) */
1811 alloc_asid = true; /* (b2) */
1814 * This is the common case (a).
1816 KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1817 KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1818 ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1822 if (++asid[thiscpu].num >= nasid) {
1823 asid[thiscpu].num = 1;
1824 if (++asid[thiscpu].gen == 0)
1825 asid[thiscpu].gen = 1;
1827 * If this cpu does not support "flush-by-asid"
1828 * then flush the entire TLB on a generation
1829 * bump. Subsequent ASID allocation in this
1830 * generation can be done without a TLB flush.
1832 if (!flush_by_asid())
1833 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1835 vcpustate->asid.gen = asid[thiscpu].gen;
1836 vcpustate->asid.num = asid[thiscpu].num;
1838 ctrl->asid = vcpustate->asid.num;
1839 svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1841 * If this cpu supports "flush-by-asid" then the TLB
1842 * was not flushed after the generation bump. The TLB
1843 * is flushed selectively after every new ASID allocation.
1845 if (flush_by_asid())
1846 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1848 vcpustate->eptgen = eptgen;
1850 KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1851 KASSERT(ctrl->asid == vcpustate->asid.num,
1852 ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1855 static __inline void
1859 __asm __volatile("clgi");
1862 static __inline void
1866 __asm __volatile("stgi");
1869 static __inline void
1870 svm_dr_enter_guest(struct svm_regctx *gctx)
1873 /* Save host control debug registers. */
1874 gctx->host_dr7 = rdr7();
1875 gctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
1878 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
1879 * exceptions in the host based on the guest DRx values. The
1880 * guest DR6, DR7, and DEBUGCTL are saved/restored in the
1884 wrmsr(MSR_DEBUGCTLMSR, 0);
1886 /* Save host debug registers. */
1887 gctx->host_dr0 = rdr0();
1888 gctx->host_dr1 = rdr1();
1889 gctx->host_dr2 = rdr2();
1890 gctx->host_dr3 = rdr3();
1891 gctx->host_dr6 = rdr6();
1893 /* Restore guest debug registers. */
1894 load_dr0(gctx->sctx_dr0);
1895 load_dr1(gctx->sctx_dr1);
1896 load_dr2(gctx->sctx_dr2);
1897 load_dr3(gctx->sctx_dr3);
1900 static __inline void
1901 svm_dr_leave_guest(struct svm_regctx *gctx)
1904 /* Save guest debug registers. */
1905 gctx->sctx_dr0 = rdr0();
1906 gctx->sctx_dr1 = rdr1();
1907 gctx->sctx_dr2 = rdr2();
1908 gctx->sctx_dr3 = rdr3();
1911 * Restore host debug registers. Restore DR7 and DEBUGCTL
1914 load_dr0(gctx->host_dr0);
1915 load_dr1(gctx->host_dr1);
1916 load_dr2(gctx->host_dr2);
1917 load_dr3(gctx->host_dr3);
1918 load_dr6(gctx->host_dr6);
1919 wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
1920 load_dr7(gctx->host_dr7);
1924 * Start vcpu with specified RIP.
1927 svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1928 struct vm_eventinfo *evinfo)
1930 struct svm_regctx *gctx;
1931 struct svm_softc *svm_sc;
1932 struct svm_vcpu *vcpustate;
1933 struct vmcb_state *state;
1934 struct vmcb_ctrl *ctrl;
1935 struct vm_exit *vmexit;
1936 struct vlapic *vlapic;
1944 vcpustate = svm_get_vcpu(svm_sc, vcpu);
1945 state = svm_get_vmcb_state(svm_sc, vcpu);
1946 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1947 vmexit = vm_exitinfo(vm, vcpu);
1948 vlapic = vm_lapic(vm, vcpu);
1950 gctx = svm_get_guest_regctx(svm_sc, vcpu);
1951 vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1953 if (vcpustate->lastcpu != curcpu) {
1955 * Force new ASID allocation by invalidating the generation.
1957 vcpustate->asid.gen = 0;
1960 * Invalidate the VMCB state cache by marking all fields dirty.
1962 svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1966 * Setting 'vcpustate->lastcpu' here is bit premature because
1967 * we may return from this function without actually executing
1968 * the VMRUN instruction. This could happen if a rendezvous
1969 * or an AST is pending on the first time through the loop.
1971 * This works for now but any new side-effects of vcpu
1972 * migration should take this case into account.
1974 vcpustate->lastcpu = curcpu;
1975 vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1978 svm_msr_guest_enter(svm_sc, vcpu);
1980 /* Update Guest RIP */
1985 * Disable global interrupts to guarantee atomicity during
1986 * loading of guest state. This includes not only the state
1987 * loaded by the "vmrun" instruction but also software state
1988 * maintained by the hypervisor: suspended and rendezvous
1989 * state, NPT generation number, vlapic interrupts etc.
1993 if (vcpu_suspended(evinfo)) {
1995 vm_exit_suspended(vm, vcpu, state->rip);
1999 if (vcpu_rendezvous_pending(evinfo)) {
2001 vm_exit_rendezvous(vm, vcpu, state->rip);
2005 if (vcpu_reqidle(evinfo)) {
2007 vm_exit_reqidle(vm, vcpu, state->rip);
2011 /* We are asked to give the cpu by scheduler. */
2012 if (vcpu_should_yield(vm, vcpu)) {
2014 vm_exit_astpending(vm, vcpu, state->rip);
2018 svm_inj_interrupts(svm_sc, vcpu, vlapic);
2020 /* Activate the nested pmap on 'curcpu' */
2021 CPU_SET_ATOMIC_ACQ(curcpu, &pmap->pm_active);
2024 * Check the pmap generation and the ASID generation to
2025 * ensure that the vcpu does not use stale TLB mappings.
2027 check_asid(svm_sc, vcpu, pmap, curcpu);
2029 ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
2030 vcpustate->dirty = 0;
2031 VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
2033 /* Launch Virtual Machine. */
2034 VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
2035 svm_dr_enter_guest(gctx);
2036 svm_launch(vmcb_pa, gctx, &__pcpu[curcpu]);
2037 svm_dr_leave_guest(gctx);
2039 CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
2042 * The host GDTR and IDTR is saved by VMRUN and restored
2043 * automatically on #VMEXIT. However, the host TSS needs
2044 * to be restored explicitly.
2048 /* #VMEXIT disables interrupts so re-enable them here. */
2051 /* Update 'nextrip' */
2052 vcpustate->nextrip = state->rip;
2054 /* Handle #VMEXIT and if required return to user space. */
2055 handled = svm_vmexit(svm_sc, vcpu, vmexit);
2058 svm_msr_guest_exit(svm_sc, vcpu);
2064 svm_vmcleanup(void *arg)
2066 struct svm_softc *sc = arg;
2068 contigfree(sc->iopm_bitmap, SVM_IO_BITMAP_SIZE, M_SVM);
2069 contigfree(sc->msr_bitmap, SVM_MSR_BITMAP_SIZE, M_SVM);
2074 swctx_regptr(struct svm_regctx *regctx, int reg)
2078 case VM_REG_GUEST_RBX:
2079 return (®ctx->sctx_rbx);
2080 case VM_REG_GUEST_RCX:
2081 return (®ctx->sctx_rcx);
2082 case VM_REG_GUEST_RDX:
2083 return (®ctx->sctx_rdx);
2084 case VM_REG_GUEST_RDI:
2085 return (®ctx->sctx_rdi);
2086 case VM_REG_GUEST_RSI:
2087 return (®ctx->sctx_rsi);
2088 case VM_REG_GUEST_RBP:
2089 return (®ctx->sctx_rbp);
2090 case VM_REG_GUEST_R8:
2091 return (®ctx->sctx_r8);
2092 case VM_REG_GUEST_R9:
2093 return (®ctx->sctx_r9);
2094 case VM_REG_GUEST_R10:
2095 return (®ctx->sctx_r10);
2096 case VM_REG_GUEST_R11:
2097 return (®ctx->sctx_r11);
2098 case VM_REG_GUEST_R12:
2099 return (®ctx->sctx_r12);
2100 case VM_REG_GUEST_R13:
2101 return (®ctx->sctx_r13);
2102 case VM_REG_GUEST_R14:
2103 return (®ctx->sctx_r14);
2104 case VM_REG_GUEST_R15:
2105 return (®ctx->sctx_r15);
2106 case VM_REG_GUEST_DR0:
2107 return (®ctx->sctx_dr0);
2108 case VM_REG_GUEST_DR1:
2109 return (®ctx->sctx_dr1);
2110 case VM_REG_GUEST_DR2:
2111 return (®ctx->sctx_dr2);
2112 case VM_REG_GUEST_DR3:
2113 return (®ctx->sctx_dr3);
2120 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2122 struct svm_softc *svm_sc;
2127 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2128 return (svm_get_intr_shadow(svm_sc, vcpu, val));
2131 if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2135 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2142 VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2147 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2149 struct svm_softc *svm_sc;
2154 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2155 return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2158 if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2162 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2170 * XXX deal with CR3 and invalidate TLB entries tagged with the
2171 * vcpu's ASID. This needs to be treated differently depending on
2172 * whether 'running' is true/false.
2175 VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2180 svm_setcap(void *arg, int vcpu, int type, int val)
2182 struct svm_softc *sc;
2188 case VM_CAP_HALT_EXIT:
2189 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2190 VMCB_INTCPT_HLT, val);
2192 case VM_CAP_PAUSE_EXIT:
2193 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2194 VMCB_INTCPT_PAUSE, val);
2196 case VM_CAP_UNRESTRICTED_GUEST:
2197 /* Unrestricted guest execution cannot be disabled in SVM */
2209 svm_getcap(void *arg, int vcpu, int type, int *retval)
2211 struct svm_softc *sc;
2218 case VM_CAP_HALT_EXIT:
2219 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2222 case VM_CAP_PAUSE_EXIT:
2223 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2226 case VM_CAP_UNRESTRICTED_GUEST:
2227 *retval = 1; /* unrestricted guest is always enabled */
2236 static struct vlapic *
2237 svm_vlapic_init(void *arg, int vcpuid)
2239 struct svm_softc *svm_sc;
2240 struct vlapic *vlapic;
2243 vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2244 vlapic->vm = svm_sc->vm;
2245 vlapic->vcpuid = vcpuid;
2246 vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2248 vlapic_init(vlapic);
2254 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2257 vlapic_cleanup(vlapic);
2258 free(vlapic, M_SVM_VLAPIC);
2261 struct vmm_ops vmm_ops_amd = {