2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice unmodified, this list of conditions, and the following
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
39 #include <sys/sysctl.h>
44 #include <machine/cpufunc.h>
45 #include <machine/psl.h>
46 #include <machine/md_var.h>
47 #include <machine/reg.h>
48 #include <machine/specialreg.h>
49 #include <machine/smp.h>
50 #include <machine/vmm.h>
51 #include <machine/vmm_dev.h>
52 #include <machine/vmm_instruction_emul.h>
54 #include "vmm_lapic.h"
57 #include "vmm_ioport.h"
60 #include "vlapic_priv.h"
65 #include "svm_softc.h"
70 SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
73 * SVM CPUID function 0x8000_000A, edx bit decoding.
75 #define AMD_CPUID_SVM_NP BIT(0) /* Nested paging or RVI */
76 #define AMD_CPUID_SVM_LBR BIT(1) /* Last branch virtualization */
77 #define AMD_CPUID_SVM_SVML BIT(2) /* SVM lock */
78 #define AMD_CPUID_SVM_NRIP_SAVE BIT(3) /* Next RIP is saved */
79 #define AMD_CPUID_SVM_TSC_RATE BIT(4) /* TSC rate control. */
80 #define AMD_CPUID_SVM_VMCB_CLEAN BIT(5) /* VMCB state caching */
81 #define AMD_CPUID_SVM_FLUSH_BY_ASID BIT(6) /* Flush by ASID */
82 #define AMD_CPUID_SVM_DECODE_ASSIST BIT(7) /* Decode assist */
83 #define AMD_CPUID_SVM_PAUSE_INC BIT(10) /* Pause intercept filter. */
84 #define AMD_CPUID_SVM_PAUSE_FTH BIT(12) /* Pause filter threshold */
85 #define AMD_CPUID_SVM_AVIC BIT(13) /* AVIC present */
87 #define VMCB_CACHE_DEFAULT (VMCB_CACHE_ASID | \
98 static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
99 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
102 static MALLOC_DEFINE(M_SVM, "svm", "svm");
103 static MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
105 /* Per-CPU context area. */
106 extern struct pcpu __pcpu[];
108 static uint32_t svm_feature = ~0U; /* AMD SVM features. */
109 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RDTUN, &svm_feature, 0,
110 "SVM features advertised by CPUID.8000000AH:EDX");
112 static int disable_npf_assist;
113 SYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
114 &disable_npf_assist, 0, NULL);
116 /* Maximum ASIDs supported by the processor */
117 static uint32_t nasid;
118 SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RDTUN, &nasid, 0,
119 "Number of ASIDs supported by this processor");
121 /* Current ASID generation for each host cpu */
122 static struct asid asid[MAXCPU];
125 * SVM host state saved area of size 4KB for each core.
127 static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
129 static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
130 static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
131 static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
133 static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
139 return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
146 return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
150 svm_disable(void *arg __unused)
154 efer = rdmsr(MSR_EFER);
156 wrmsr(MSR_EFER, efer);
160 * Disable SVM on all CPUs.
166 smp_rendezvous(NULL, svm_disable, NULL, NULL);
171 * Verify that all the features required by bhyve are available.
174 check_svm_features(void)
178 /* CPUID Fn8000_000A is for SVM */
179 do_cpuid(0x8000000A, regs);
180 svm_feature &= regs[3];
183 * The number of ASIDs can be configured to be less than what is
184 * supported by the hardware but not more.
186 if (nasid == 0 || nasid > regs[1])
188 KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
190 /* bhyve requires the Nested Paging feature */
191 if (!(svm_feature & AMD_CPUID_SVM_NP)) {
192 printf("SVM: Nested Paging feature not available.\n");
196 /* bhyve requires the NRIP Save feature */
197 if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
198 printf("SVM: NRIP Save feature not available.\n");
206 svm_enable(void *arg __unused)
210 efer = rdmsr(MSR_EFER);
212 wrmsr(MSR_EFER, efer);
214 wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
218 * Return 1 if SVM is enabled on this processor and 0 otherwise.
225 /* Section 15.4 Enabling SVM from APM2. */
226 if ((amd_feature2 & AMDID2_SVM) == 0) {
227 printf("SVM: not available.\n");
231 msr = rdmsr(MSR_VM_CR);
232 if ((msr & VM_CR_SVMDIS) != 0) {
233 printf("SVM: disabled by BIOS.\n");
245 if (!svm_available())
248 error = check_svm_features();
252 vmcb_clean &= VMCB_CACHE_DEFAULT;
254 for (cpu = 0; cpu < MAXCPU; cpu++) {
256 * Initialize the host ASIDs to their "highest" valid values.
258 * The next ASID allocation will rollover both 'gen' and 'num'
259 * and start off the sequence at {1,1}.
261 asid[cpu].gen = ~0UL;
262 asid[cpu].num = nasid - 1;
266 svm_npt_init(ipinum);
268 /* Enable SVM on all CPUs */
269 smp_rendezvous(NULL, svm_enable, NULL, NULL);
281 /* Pentium compatible MSRs */
282 #define MSR_PENTIUM_START 0
283 #define MSR_PENTIUM_END 0x1FFF
284 /* AMD 6th generation and Intel compatible MSRs */
285 #define MSR_AMD6TH_START 0xC0000000UL
286 #define MSR_AMD6TH_END 0xC0001FFFUL
287 /* AMD 7th and 8th generation compatible MSRs */
288 #define MSR_AMD7TH_START 0xC0010000UL
289 #define MSR_AMD7TH_END 0xC0011FFFUL
292 * Get the index and bit position for a MSR in permission bitmap.
293 * Two bits are used for each MSR: lower bit for read and higher bit for write.
296 svm_msr_index(uint64_t msr, int *index, int *bit)
301 *bit = (msr % 4) * 2;
304 if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
309 base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
310 if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
311 off = (msr - MSR_AMD6TH_START);
312 *index = (off + base) / 4;
316 base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
317 if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
318 off = (msr - MSR_AMD7TH_START);
319 *index = (off + base) / 4;
327 * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
330 svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
332 int index, bit, error;
334 error = svm_msr_index(msr, &index, &bit);
335 KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
336 KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
337 ("%s: invalid index %d for msr %#lx", __func__, index, msr));
338 KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
339 "msr %#lx", __func__, bit, msr));
342 perm_bitmap[index] &= ~(1UL << bit);
345 perm_bitmap[index] &= ~(2UL << bit);
349 svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
352 svm_msr_perm(perm_bitmap, msr, true, true);
356 svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
359 svm_msr_perm(perm_bitmap, msr, true, false);
363 svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
365 struct vmcb_ctrl *ctrl;
367 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
369 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
370 return (ctrl->intercept[idx] & bitmask ? 1 : 0);
374 svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
377 struct vmcb_ctrl *ctrl;
380 KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
382 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
383 oldval = ctrl->intercept[idx];
386 ctrl->intercept[idx] |= bitmask;
388 ctrl->intercept[idx] &= ~bitmask;
390 if (ctrl->intercept[idx] != oldval) {
391 svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
392 VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
393 "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
398 svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
401 svm_set_intercept(sc, vcpu, off, bitmask, 0);
405 svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
408 svm_set_intercept(sc, vcpu, off, bitmask, 1);
412 vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
413 uint64_t msrpm_base_pa, uint64_t np_pml4)
415 struct vmcb_ctrl *ctrl;
416 struct vmcb_state *state;
420 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
421 state = svm_get_vmcb_state(sc, vcpu);
423 ctrl->iopm_base_pa = iopm_base_pa;
424 ctrl->msrpm_base_pa = msrpm_base_pa;
426 /* Enable nested paging */
428 ctrl->n_cr3 = np_pml4;
431 * Intercept accesses to the control registers that are not shadowed
432 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
434 for (n = 0; n < 16; n++) {
435 mask = (BIT(n) << 16) | BIT(n);
436 if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
437 svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
439 svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
444 * Intercept everything when tracing guest exceptions otherwise
445 * just intercept machine check exception.
447 if (vcpu_trace_exceptions(sc->vm, vcpu)) {
448 for (n = 0; n < 32; n++) {
450 * Skip unimplemented vectors in the exception bitmap.
452 if (n == 2 || n == 9) {
455 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
458 svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
461 /* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
462 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
463 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
464 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
465 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
466 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
467 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
468 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
469 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
470 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
471 VMCB_INTCPT_FERR_FREEZE);
473 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
474 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
477 * From section "Canonicalization and Consistency Checks" in APMv2
478 * the VMRUN intercept bit must be set to pass the consistency check.
480 svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
483 * The ASID will be set to a non-zero value just before VMRUN.
488 * Section 15.21.1, Interrupt Masking in EFLAGS
489 * Section 15.21.2, Virtualizing APIC.TPR
491 * This must be set for %rflag and %cr8 isolation of guest and host.
493 ctrl->v_intr_masking = 1;
495 /* Enable Last Branch Record aka LBR for debugging */
496 ctrl->lbr_virt_en = 1;
497 state->dbgctl = BIT(0);
499 /* EFER_SVM must always be set when the guest is executing */
500 state->efer = EFER_SVM;
502 /* Set up the PAT to power-on state */
503 state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK) |
504 PAT_VALUE(1, PAT_WRITE_THROUGH) |
505 PAT_VALUE(2, PAT_UNCACHED) |
506 PAT_VALUE(3, PAT_UNCACHEABLE) |
507 PAT_VALUE(4, PAT_WRITE_BACK) |
508 PAT_VALUE(5, PAT_WRITE_THROUGH) |
509 PAT_VALUE(6, PAT_UNCACHED) |
510 PAT_VALUE(7, PAT_UNCACHEABLE);
512 /* Set up DR6/7 to power-on state */
513 state->dr6 = DBREG_DR6_RESERVED1;
514 state->dr7 = DBREG_DR7_RESERVED1;
518 * Initialize a virtual machine.
521 svm_vminit(struct vm *vm, pmap_t pmap)
523 struct svm_softc *svm_sc;
524 struct svm_vcpu *vcpu;
525 vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
528 svm_sc = malloc(sizeof (*svm_sc), M_SVM, M_WAITOK | M_ZERO);
529 if (((uintptr_t)svm_sc & PAGE_MASK) != 0)
530 panic("malloc of svm_softc not aligned on page boundary");
532 svm_sc->msr_bitmap = contigmalloc(SVM_MSR_BITMAP_SIZE, M_SVM,
533 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
534 if (svm_sc->msr_bitmap == NULL)
535 panic("contigmalloc of SVM MSR bitmap failed");
536 svm_sc->iopm_bitmap = contigmalloc(SVM_IO_BITMAP_SIZE, M_SVM,
537 M_WAITOK, 0, ~(vm_paddr_t)0, PAGE_SIZE, 0);
538 if (svm_sc->iopm_bitmap == NULL)
539 panic("contigmalloc of SVM IO bitmap failed");
542 svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
545 * Intercept read and write accesses to all MSRs.
547 memset(svm_sc->msr_bitmap, 0xFF, SVM_MSR_BITMAP_SIZE);
550 * Access to the following MSRs is redirected to the VMCB when the
551 * guest is executing. Therefore it is safe to allow the guest to
552 * read/write these MSRs directly without hypervisor involvement.
554 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
555 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
556 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
558 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
559 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
560 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
561 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
562 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
563 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
564 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
565 svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
567 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
570 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
572 svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
574 /* Intercept access to all I/O ports. */
575 memset(svm_sc->iopm_bitmap, 0xFF, SVM_IO_BITMAP_SIZE);
577 iopm_pa = vtophys(svm_sc->iopm_bitmap);
578 msrpm_pa = vtophys(svm_sc->msr_bitmap);
579 pml4_pa = svm_sc->nptp;
580 for (i = 0; i < VM_MAXCPU; i++) {
581 vcpu = svm_get_vcpu(svm_sc, i);
583 vcpu->lastcpu = NOCPU;
584 vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
585 vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
586 svm_msr_guest_init(svm_sc, i);
592 * Collateral for a generic SVM VM-exit.
595 vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
598 vme->exitcode = VM_EXITCODE_SVM;
599 vme->u.svm.exitcode = code;
600 vme->u.svm.exitinfo1 = info1;
601 vme->u.svm.exitinfo2 = info2;
605 svm_cpl(struct vmcb_state *state)
610 * "Retrieve the CPL from the CPL field in the VMCB, not
611 * from any segment DPL"
616 static enum vm_cpu_mode
617 svm_vcpu_mode(struct vmcb *vmcb)
619 struct vmcb_segment seg;
620 struct vmcb_state *state;
623 state = &vmcb->state;
625 if (state->efer & EFER_LMA) {
626 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
627 KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
631 * Section 4.8.1 for APM2, check if Code Segment has
632 * Long attribute set in descriptor.
634 if (seg.attrib & VMCB_CS_ATTRIB_L)
635 return (CPU_MODE_64BIT);
637 return (CPU_MODE_COMPATIBILITY);
638 } else if (state->cr0 & CR0_PE) {
639 return (CPU_MODE_PROTECTED);
641 return (CPU_MODE_REAL);
645 static enum vm_paging_mode
646 svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
649 if ((cr0 & CR0_PG) == 0)
650 return (PAGING_MODE_FLAT);
651 if ((cr4 & CR4_PAE) == 0)
652 return (PAGING_MODE_32);
654 return (PAGING_MODE_64);
656 return (PAGING_MODE_PAE);
660 * ins/outs utility routines
663 svm_inout_str_index(struct svm_regctx *regs, int in)
667 val = in ? regs->sctx_rdi : regs->sctx_rsi;
673 svm_inout_str_count(struct svm_regctx *regs, int rep)
677 val = rep ? regs->sctx_rcx : 1;
683 svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
684 int in, struct vm_inout_str *vis)
689 vis->seg_name = VM_REG_GUEST_ES;
691 /* The segment field has standard encoding */
692 s = (info1 >> 10) & 0x7;
693 vis->seg_name = vm_segment_name(s);
696 error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
697 KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
701 svm_inout_str_addrsize(uint64_t info1)
705 size = (info1 >> 7) & 0x7;
708 return (2); /* 16 bit */
710 return (4); /* 32 bit */
712 return (8); /* 64 bit */
714 panic("%s: invalid size encoding %d", __func__, size);
719 svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
721 struct vmcb_state *state;
723 state = &vmcb->state;
724 paging->cr3 = state->cr3;
725 paging->cpl = svm_cpl(state);
726 paging->cpu_mode = svm_vcpu_mode(vmcb);
727 paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
734 * Handle guest I/O intercept.
737 svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
739 struct vmcb_ctrl *ctrl;
740 struct vmcb_state *state;
741 struct svm_regctx *regs;
742 struct vm_inout_str *vis;
746 state = svm_get_vmcb_state(svm_sc, vcpu);
747 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
748 regs = svm_get_guest_regctx(svm_sc, vcpu);
750 info1 = ctrl->exitinfo1;
751 inout_string = info1 & BIT(2) ? 1 : 0;
754 * The effective segment number in EXITINFO1[12:10] is populated
755 * only if the processor has the DecodeAssist capability.
757 * XXX this is not specified explicitly in APMv2 but can be verified
760 if (inout_string && !decode_assist())
763 vmexit->exitcode = VM_EXITCODE_INOUT;
764 vmexit->u.inout.in = (info1 & BIT(0)) ? 1 : 0;
765 vmexit->u.inout.string = inout_string;
766 vmexit->u.inout.rep = (info1 & BIT(3)) ? 1 : 0;
767 vmexit->u.inout.bytes = (info1 >> 4) & 0x7;
768 vmexit->u.inout.port = (uint16_t)(info1 >> 16);
769 vmexit->u.inout.eax = (uint32_t)(state->rax);
772 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
773 vis = &vmexit->u.inout_str;
774 svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
775 vis->rflags = state->rflags;
776 vis->cr0 = state->cr0;
777 vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
778 vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
779 vis->addrsize = svm_inout_str_addrsize(info1);
780 svm_inout_str_seginfo(svm_sc, vcpu, info1,
781 vmexit->u.inout.in, vis);
788 npf_fault_type(uint64_t exitinfo1)
791 if (exitinfo1 & VMCB_NPF_INFO1_W)
792 return (VM_PROT_WRITE);
793 else if (exitinfo1 & VMCB_NPF_INFO1_ID)
794 return (VM_PROT_EXECUTE);
796 return (VM_PROT_READ);
800 svm_npf_emul_fault(uint64_t exitinfo1)
803 if (exitinfo1 & VMCB_NPF_INFO1_ID) {
807 if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
811 if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
819 svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
821 struct vm_guest_paging *paging;
822 struct vmcb_segment seg;
823 struct vmcb_ctrl *ctrl;
828 paging = &vmexit->u.inst_emul.paging;
830 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
831 vmexit->u.inst_emul.gpa = gpa;
832 vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
833 svm_paging_info(vmcb, paging);
835 error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
836 KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
838 switch(paging->cpu_mode) {
840 vmexit->u.inst_emul.cs_base = seg.base;
841 vmexit->u.inst_emul.cs_d = 0;
843 case CPU_MODE_PROTECTED:
844 case CPU_MODE_COMPATIBILITY:
845 vmexit->u.inst_emul.cs_base = seg.base;
848 * Section 4.8.1 of APM2, Default Operand Size or D bit.
850 vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
854 vmexit->u.inst_emul.cs_base = 0;
855 vmexit->u.inst_emul.cs_d = 0;
860 * Copy the instruction bytes into 'vie' if available.
862 if (decode_assist() && !disable_npf_assist) {
863 inst_len = ctrl->inst_len;
864 inst_bytes = ctrl->inst_bytes;
869 vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
874 intrtype_to_str(int intr_type)
877 case VMCB_EVENTINJ_TYPE_INTR:
879 case VMCB_EVENTINJ_TYPE_NMI:
881 case VMCB_EVENTINJ_TYPE_INTn:
883 case VMCB_EVENTINJ_TYPE_EXCEPTION:
884 return ("exception");
886 panic("%s: unknown intr_type %d", __func__, intr_type);
892 * Inject an event to vcpu as described in section 15.20, "Event injection".
895 svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
896 uint32_t error, bool ec_valid)
898 struct vmcb_ctrl *ctrl;
900 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
902 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
903 ("%s: event already pending %#lx", __func__, ctrl->eventinj));
905 KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
909 case VMCB_EVENTINJ_TYPE_INTR:
910 case VMCB_EVENTINJ_TYPE_NMI:
911 case VMCB_EVENTINJ_TYPE_INTn:
913 case VMCB_EVENTINJ_TYPE_EXCEPTION:
914 if (vector >= 0 && vector <= 31 && vector != 2)
918 panic("%s: invalid intr_type/vector: %d/%d", __func__,
921 ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
923 ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
924 ctrl->eventinj |= (uint64_t)error << 32;
925 VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
926 intrtype_to_str(intr_type), vector, error);
928 VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
929 intrtype_to_str(intr_type), vector);
934 svm_update_virqinfo(struct svm_softc *sc, int vcpu)
937 struct vlapic *vlapic;
938 struct vmcb_ctrl *ctrl;
941 vlapic = vm_lapic(vm, vcpu);
942 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
944 /* Update %cr8 in the emulated vlapic */
945 vlapic_set_cr8(vlapic, ctrl->v_tpr);
947 /* Virtual interrupt injection is not used. */
948 KASSERT(ctrl->v_intr_vector == 0, ("%s: invalid "
949 "v_intr_vector %d", __func__, ctrl->v_intr_vector));
953 svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
955 struct vmcb_ctrl *ctrl;
958 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
959 intinfo = ctrl->exitintinfo;
960 if (!VMCB_EXITINTINFO_VALID(intinfo))
964 * From APMv2, Section "Intercepts during IDT interrupt delivery"
966 * If a #VMEXIT happened during event delivery then record the event
967 * that was being delivered.
969 VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
970 intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
971 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
972 vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
977 vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
980 return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
986 enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
988 struct vmcb_ctrl *ctrl;
990 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
992 if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
993 KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
994 KASSERT(vintr_intercept_enabled(sc, vcpu),
995 ("%s: vintr intercept should be enabled", __func__));
999 VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
1001 ctrl->v_ign_tpr = 1;
1002 ctrl->v_intr_vector = 0;
1003 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1004 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1007 static __inline void
1008 disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
1010 struct vmcb_ctrl *ctrl;
1012 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1014 if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
1015 KASSERT(!vintr_intercept_enabled(sc, vcpu),
1016 ("%s: vintr intercept should be disabled", __func__));
1020 VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
1022 ctrl->v_intr_vector = 0;
1023 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1024 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
1028 svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1030 struct vmcb_ctrl *ctrl;
1033 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1034 oldval = ctrl->intr_shadow;
1035 newval = val ? 1 : 0;
1036 if (newval != oldval) {
1037 ctrl->intr_shadow = newval;
1038 VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1044 svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1046 struct vmcb_ctrl *ctrl;
1048 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1049 *val = ctrl->intr_shadow;
1054 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1055 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1056 * to track when the vcpu is done handling the NMI.
1059 nmi_blocked(struct svm_softc *sc, int vcpu)
1063 blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1069 enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1072 KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1073 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1074 svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1078 clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1082 KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1083 VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1085 * When the IRET intercept is cleared the vcpu will attempt to execute
1086 * the "iret" when it runs next. However, it is possible to inject
1087 * another NMI into the vcpu before the "iret" has actually executed.
1089 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1090 * it will trap back into the hypervisor. If an NMI is pending for
1091 * the vcpu it will be injected into the guest.
1093 * XXX this needs to be fixed
1095 svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1098 * Set 'intr_shadow' to prevent an NMI from being injected on the
1101 error = svm_modify_intr_shadow(sc, vcpu, 1);
1102 KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1105 #define EFER_MBZ_BITS 0xFFFFFFFFFFFF0200UL
1108 svm_write_efer(struct svm_softc *sc, int vcpu, uint64_t newval, bool *retu)
1110 struct vm_exit *vme;
1111 struct vmcb_state *state;
1112 uint64_t changed, lma, oldval;
1115 state = svm_get_vmcb_state(sc, vcpu);
1117 oldval = state->efer;
1118 VCPU_CTR2(sc->vm, vcpu, "wrmsr(efer) %#lx/%#lx", oldval, newval);
1120 newval &= ~0xFE; /* clear the Read-As-Zero (RAZ) bits */
1121 changed = oldval ^ newval;
1123 if (newval & EFER_MBZ_BITS)
1126 /* APMv2 Table 14-5 "Long-Mode Consistency Checks" */
1127 if (changed & EFER_LME) {
1128 if (state->cr0 & CR0_PG)
1132 /* EFER.LMA = EFER.LME & CR0.PG */
1133 if ((newval & EFER_LME) != 0 && (state->cr0 & CR0_PG) != 0)
1138 if ((newval & EFER_LMA) != lma)
1141 if (newval & EFER_NXE) {
1142 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_NO_EXECUTE))
1147 * XXX bhyve does not enforce segment limits in 64-bit mode. Until
1148 * this is fixed flag guest attempt to set EFER_LMSLE as an error.
1150 if (newval & EFER_LMSLE) {
1151 vme = vm_exitinfo(sc->vm, vcpu);
1152 vm_exit_svm(vme, VMCB_EXIT_MSR, 1, 0);
1157 if (newval & EFER_FFXSR) {
1158 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_FFXSR))
1162 if (newval & EFER_TCE) {
1163 if (!vm_cpuid_capability(sc->vm, vcpu, VCC_TCE))
1167 error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, newval);
1168 KASSERT(error == 0, ("%s: error %d updating efer", __func__, error));
1171 vm_inject_gp(sc->vm, vcpu);
1176 emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1182 error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1183 else if (num == MSR_EFER)
1184 error = svm_write_efer(sc, vcpu, val, retu);
1186 error = svm_wrmsr(sc, vcpu, num, val, retu);
1192 emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1194 struct vmcb_state *state;
1195 struct svm_regctx *ctx;
1200 error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1202 error = svm_rdmsr(sc, vcpu, num, &result, retu);
1205 state = svm_get_vmcb_state(sc, vcpu);
1206 ctx = svm_get_guest_regctx(sc, vcpu);
1207 state->rax = result & 0xffffffff;
1208 ctx->sctx_rdx = result >> 32;
1216 exit_reason_to_str(uint64_t reason)
1218 static char reasonbuf[32];
1221 case VMCB_EXIT_INVALID:
1222 return ("invalvmcb");
1223 case VMCB_EXIT_SHUTDOWN:
1224 return ("shutdown");
1226 return ("nptfault");
1227 case VMCB_EXIT_PAUSE:
1231 case VMCB_EXIT_CPUID:
1237 case VMCB_EXIT_INTR:
1241 case VMCB_EXIT_VINTR:
1245 case VMCB_EXIT_IRET:
1247 case VMCB_EXIT_MONITOR:
1249 case VMCB_EXIT_MWAIT:
1252 snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1259 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1260 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1261 * and exceptions caused by INT3, INTO and BOUND instructions.
1263 * Return 1 if the nRIP is valid and 0 otherwise.
1266 nrip_valid(uint64_t exitcode)
1269 case 0x00 ... 0x0F: /* read of CR0 through CR15 */
1270 case 0x10 ... 0x1F: /* write of CR0 through CR15 */
1271 case 0x20 ... 0x2F: /* read of DR0 through DR15 */
1272 case 0x30 ... 0x3F: /* write of DR0 through DR15 */
1273 case 0x43: /* INT3 */
1274 case 0x44: /* INTO */
1275 case 0x45: /* BOUND */
1276 case 0x65 ... 0x7C: /* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1277 case 0x80 ... 0x8D: /* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1285 svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1288 struct vmcb_state *state;
1289 struct vmcb_ctrl *ctrl;
1290 struct svm_regctx *ctx;
1291 uint64_t code, info1, info2, val;
1292 uint32_t eax, ecx, edx;
1293 int error, errcode_valid, handled, idtvec, reflect;
1296 ctx = svm_get_guest_regctx(svm_sc, vcpu);
1297 vmcb = svm_get_vmcb(svm_sc, vcpu);
1298 state = &vmcb->state;
1302 code = ctrl->exitcode;
1303 info1 = ctrl->exitinfo1;
1304 info2 = ctrl->exitinfo2;
1306 vmexit->exitcode = VM_EXITCODE_BOGUS;
1307 vmexit->rip = state->rip;
1308 vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1310 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1313 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1314 * in an inconsistent state and can trigger assertions that would
1315 * never happen otherwise.
1317 if (code == VMCB_EXIT_INVALID) {
1318 vm_exit_svm(vmexit, code, info1, info2);
1322 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1323 "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1325 KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1326 ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1327 vmexit->inst_length, code, info1, info2));
1329 svm_update_virqinfo(svm_sc, vcpu);
1330 svm_save_intinfo(svm_sc, vcpu);
1333 case VMCB_EXIT_IRET:
1335 * Restart execution at "iret" but with the intercept cleared.
1337 vmexit->inst_length = 0;
1338 clear_nmi_blocking(svm_sc, vcpu);
1341 case VMCB_EXIT_VINTR: /* interrupt window exiting */
1342 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1345 case VMCB_EXIT_INTR: /* external interrupt */
1346 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1349 case VMCB_EXIT_NMI: /* external NMI */
1353 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1355 idtvec = code - 0x40;
1359 * Call the machine check handler by hand. Also don't
1360 * reflect the machine check back into the guest.
1363 VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1364 __asm __volatile("int $18");
1367 error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1369 KASSERT(error == 0, ("%s: error %d updating cr2",
1389 * The 'nrip' field is populated for INT3, INTO and
1390 * BOUND exceptions and this also implies that
1391 * 'inst_length' is non-zero.
1393 * Reset 'inst_length' to zero so the guest %rip at
1394 * event injection is identical to what it was when
1395 * the exception originally happened.
1397 VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1398 "to zero before injecting exception %d",
1399 vmexit->inst_length, idtvec);
1400 vmexit->inst_length = 0;
1407 KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1408 "when reflecting exception %d into guest",
1409 vmexit->inst_length, idtvec));
1412 /* Reflect the exception back into the guest */
1413 VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1414 "%d/%#x into the guest", idtvec, (int)info1);
1415 error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1416 errcode_valid, info1, 0);
1417 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1422 case VMCB_EXIT_MSR: /* MSR access. */
1424 ecx = ctx->sctx_rcx;
1425 edx = ctx->sctx_rdx;
1429 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1430 val = (uint64_t)edx << 32 | eax;
1431 VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1433 if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1434 vmexit->exitcode = VM_EXITCODE_WRMSR;
1435 vmexit->u.msr.code = ecx;
1436 vmexit->u.msr.wval = val;
1440 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1441 ("emulate_wrmsr retu with bogus exitcode"));
1444 VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1445 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1446 if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1447 vmexit->exitcode = VM_EXITCODE_RDMSR;
1448 vmexit->u.msr.code = ecx;
1452 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1453 ("emulate_rdmsr retu with bogus exitcode"));
1458 handled = svm_handle_io(svm_sc, vcpu, vmexit);
1459 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1461 case VMCB_EXIT_CPUID:
1462 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1463 handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1464 (uint32_t *)&state->rax,
1465 (uint32_t *)&ctx->sctx_rbx,
1466 (uint32_t *)&ctx->sctx_rcx,
1467 (uint32_t *)&ctx->sctx_rdx);
1470 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1471 vmexit->exitcode = VM_EXITCODE_HLT;
1472 vmexit->u.hlt.rflags = state->rflags;
1474 case VMCB_EXIT_PAUSE:
1475 vmexit->exitcode = VM_EXITCODE_PAUSE;
1476 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1479 /* EXITINFO2 contains the faulting guest physical address */
1480 if (info1 & VMCB_NPF_INFO1_RSV) {
1481 VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1482 "reserved bits set: info1(%#lx) info2(%#lx)",
1484 } else if (vm_mem_allocated(svm_sc->vm, vcpu, info2)) {
1485 vmexit->exitcode = VM_EXITCODE_PAGING;
1486 vmexit->u.paging.gpa = info2;
1487 vmexit->u.paging.fault_type = npf_fault_type(info1);
1488 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1489 VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1490 "on gpa %#lx/%#lx at rip %#lx",
1491 info2, info1, state->rip);
1492 } else if (svm_npf_emul_fault(info1)) {
1493 svm_handle_inst_emul(vmcb, info2, vmexit);
1494 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1495 VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1496 "for gpa %#lx/%#lx at rip %#lx",
1497 info2, info1, state->rip);
1500 case VMCB_EXIT_MONITOR:
1501 vmexit->exitcode = VM_EXITCODE_MONITOR;
1503 case VMCB_EXIT_MWAIT:
1504 vmexit->exitcode = VM_EXITCODE_MWAIT;
1507 vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1511 VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1512 handled ? "handled" : "unhandled", exit_reason_to_str(code),
1513 vmexit->rip, vmexit->inst_length);
1516 vmexit->rip += vmexit->inst_length;
1517 vmexit->inst_length = 0;
1518 state->rip = vmexit->rip;
1520 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1522 * If this VM exit was not claimed by anybody then
1523 * treat it as a generic SVM exit.
1525 vm_exit_svm(vmexit, code, info1, info2);
1528 * The exitcode and collateral have been populated.
1529 * The VM exit will be processed further in userland.
1537 svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1541 if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1544 KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1545 "valid: %#lx", __func__, intinfo));
1547 svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1548 VMCB_EXITINTINFO_VECTOR(intinfo),
1549 VMCB_EXITINTINFO_EC(intinfo),
1550 VMCB_EXITINTINFO_EC_VALID(intinfo));
1551 vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1552 VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1556 * Inject event to virtual cpu.
1559 svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1561 struct vmcb_ctrl *ctrl;
1562 struct vmcb_state *state;
1563 struct svm_vcpu *vcpustate;
1565 int vector, need_intr_window;
1568 state = svm_get_vmcb_state(sc, vcpu);
1569 ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1570 vcpustate = svm_get_vcpu(sc, vcpu);
1572 need_intr_window = 0;
1574 if (vcpustate->nextrip != state->rip) {
1575 ctrl->intr_shadow = 0;
1576 VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1577 "cleared due to rip change: %#lx/%#lx",
1578 vcpustate->nextrip, state->rip);
1582 * Inject pending events or exceptions for this vcpu.
1584 * An event might be pending because the previous #VMEXIT happened
1585 * during event delivery (i.e. ctrl->exitintinfo).
1587 * An event might also be pending because an exception was injected
1588 * by the hypervisor (e.g. #PF during instruction emulation).
1590 svm_inj_intinfo(sc, vcpu);
1592 /* NMI event has priority over interrupts. */
1593 if (vm_nmi_pending(sc->vm, vcpu)) {
1594 if (nmi_blocked(sc, vcpu)) {
1596 * Can't inject another NMI if the guest has not
1597 * yet executed an "iret" after the last NMI.
1599 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1601 } else if (ctrl->intr_shadow) {
1603 * Can't inject an NMI if the vcpu is in an intr_shadow.
1605 VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1606 "interrupt shadow");
1607 need_intr_window = 1;
1609 } else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1611 * If there is already an exception/interrupt pending
1612 * then defer the NMI until after that.
1614 VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1615 "eventinj %#lx", ctrl->eventinj);
1618 * Use self-IPI to trigger a VM-exit as soon as
1619 * possible after the event injection is completed.
1621 * This works only if the external interrupt exiting
1622 * is at a lower priority than the event injection.
1624 * Although not explicitly specified in APMv2 the
1625 * relative priorities were verified empirically.
1627 ipi_cpu(curcpu, IPI_AST); /* XXX vmm_ipinum? */
1629 vm_nmi_clear(sc->vm, vcpu);
1631 /* Inject NMI, vector number is not used */
1632 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1635 /* virtual NMI blocking is now in effect */
1636 enable_nmi_blocking(sc, vcpu);
1638 VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1642 extint_pending = vm_extint_pending(sc->vm, vcpu);
1643 if (!extint_pending) {
1644 if (!vlapic_pending_intr(vlapic, &vector))
1646 KASSERT(vector >= 16 && vector <= 255,
1647 ("invalid vector %d from local APIC", vector));
1649 /* Ask the legacy pic for a vector to inject */
1650 vatpic_pending_intr(sc->vm, &vector);
1651 KASSERT(vector >= 0 && vector <= 255,
1652 ("invalid vector %d from INTR", vector));
1656 * If the guest has disabled interrupts or is in an interrupt shadow
1657 * then we cannot inject the pending interrupt.
1659 if ((state->rflags & PSL_I) == 0) {
1660 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1661 "rflags %#lx", vector, state->rflags);
1662 need_intr_window = 1;
1666 if (ctrl->intr_shadow) {
1667 VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1668 "interrupt shadow", vector);
1669 need_intr_window = 1;
1673 if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1674 VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1675 "eventinj %#lx", vector, ctrl->eventinj);
1676 need_intr_window = 1;
1680 svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1682 if (!extint_pending) {
1683 vlapic_intr_accepted(vlapic, vector);
1685 vm_extint_clear(sc->vm, vcpu);
1686 vatpic_intr_accepted(sc->vm, vector);
1690 * Force a VM-exit as soon as the vcpu is ready to accept another
1691 * interrupt. This is done because the PIC might have another vector
1692 * that it wants to inject. Also, if the APIC has a pending interrupt
1693 * that was preempted by the ExtInt then it allows us to inject the
1694 * APIC vector as soon as possible.
1696 need_intr_window = 1;
1699 * The guest can modify the TPR by writing to %CR8. In guest mode
1700 * the processor reflects this write to V_TPR without hypervisor
1703 * The guest can also modify the TPR by writing to it via the memory
1704 * mapped APIC page. In this case, the write will be emulated by the
1705 * hypervisor. For this reason V_TPR must be updated before every
1708 v_tpr = vlapic_get_cr8(vlapic);
1709 KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1710 if (ctrl->v_tpr != v_tpr) {
1711 VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1712 ctrl->v_tpr, v_tpr);
1713 ctrl->v_tpr = v_tpr;
1714 svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1717 if (need_intr_window) {
1719 * We use V_IRQ in conjunction with the VINTR intercept to
1720 * trap into the hypervisor as soon as a virtual interrupt
1723 * Since injected events are not subject to intercept checks
1724 * we need to ensure that the V_IRQ is not actually going to
1725 * be delivered on VM entry. The KASSERT below enforces this.
1727 KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1728 (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1729 ("Bogus intr_window_exiting: eventinj (%#lx), "
1730 "intr_shadow (%u), rflags (%#lx)",
1731 ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1732 enable_intr_window_exiting(sc, vcpu);
1734 disable_intr_window_exiting(sc, vcpu);
1738 static __inline void
1739 restore_host_tss(void)
1741 struct system_segment_descriptor *tss_sd;
1744 * The TSS descriptor was in use prior to launching the guest so it
1745 * has been marked busy.
1747 * 'ltr' requires the descriptor to be marked available so change the
1748 * type to "64-bit available TSS".
1750 tss_sd = PCPU_GET(tss);
1751 tss_sd->sd_type = SDT_SYSTSS;
1752 ltr(GSEL(GPROC0_SEL, SEL_KPL));
1756 check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1758 struct svm_vcpu *vcpustate;
1759 struct vmcb_ctrl *ctrl;
1763 KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1764 "active on cpu %u", __func__, thiscpu));
1766 vcpustate = svm_get_vcpu(sc, vcpuid);
1767 ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1770 * The TLB entries associated with the vcpu's ASID are not valid
1771 * if either of the following conditions is true:
1773 * 1. The vcpu's ASID generation is different than the host cpu's
1774 * ASID generation. This happens when the vcpu migrates to a new
1775 * host cpu. It can also happen when the number of vcpus executing
1776 * on a host cpu is greater than the number of ASIDs available.
1778 * 2. The pmap generation number is different than the value cached in
1779 * the 'vcpustate'. This happens when the host invalidates pages
1780 * belonging to the guest.
1782 * asidgen eptgen Action
1789 * (a) There is no mismatch in eptgen or ASID generation and therefore
1790 * no further action is needed.
1792 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1793 * retained and the TLB entries associated with this ASID
1794 * are flushed by VMRUN.
1796 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1799 * (c) A new ASID is allocated.
1801 * (d) A new ASID is allocated.
1805 eptgen = pmap->pm_eptgen;
1806 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1808 if (vcpustate->asid.gen != asid[thiscpu].gen) {
1809 alloc_asid = true; /* (c) and (d) */
1810 } else if (vcpustate->eptgen != eptgen) {
1811 if (flush_by_asid())
1812 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST; /* (b1) */
1814 alloc_asid = true; /* (b2) */
1817 * This is the common case (a).
1819 KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1820 KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1821 ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1825 if (++asid[thiscpu].num >= nasid) {
1826 asid[thiscpu].num = 1;
1827 if (++asid[thiscpu].gen == 0)
1828 asid[thiscpu].gen = 1;
1830 * If this cpu does not support "flush-by-asid"
1831 * then flush the entire TLB on a generation
1832 * bump. Subsequent ASID allocation in this
1833 * generation can be done without a TLB flush.
1835 if (!flush_by_asid())
1836 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1838 vcpustate->asid.gen = asid[thiscpu].gen;
1839 vcpustate->asid.num = asid[thiscpu].num;
1841 ctrl->asid = vcpustate->asid.num;
1842 svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1844 * If this cpu supports "flush-by-asid" then the TLB
1845 * was not flushed after the generation bump. The TLB
1846 * is flushed selectively after every new ASID allocation.
1848 if (flush_by_asid())
1849 ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1851 vcpustate->eptgen = eptgen;
1853 KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1854 KASSERT(ctrl->asid == vcpustate->asid.num,
1855 ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1858 static __inline void
1862 __asm __volatile("clgi");
1865 static __inline void
1869 __asm __volatile("stgi");
1872 static __inline void
1873 svm_dr_enter_guest(struct svm_regctx *gctx)
1876 /* Save host control debug registers. */
1877 gctx->host_dr7 = rdr7();
1878 gctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
1881 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
1882 * exceptions in the host based on the guest DRx values. The
1883 * guest DR6, DR7, and DEBUGCTL are saved/restored in the
1887 wrmsr(MSR_DEBUGCTLMSR, 0);
1889 /* Save host debug registers. */
1890 gctx->host_dr0 = rdr0();
1891 gctx->host_dr1 = rdr1();
1892 gctx->host_dr2 = rdr2();
1893 gctx->host_dr3 = rdr3();
1894 gctx->host_dr6 = rdr6();
1896 /* Restore guest debug registers. */
1897 load_dr0(gctx->sctx_dr0);
1898 load_dr1(gctx->sctx_dr1);
1899 load_dr2(gctx->sctx_dr2);
1900 load_dr3(gctx->sctx_dr3);
1903 static __inline void
1904 svm_dr_leave_guest(struct svm_regctx *gctx)
1907 /* Save guest debug registers. */
1908 gctx->sctx_dr0 = rdr0();
1909 gctx->sctx_dr1 = rdr1();
1910 gctx->sctx_dr2 = rdr2();
1911 gctx->sctx_dr3 = rdr3();
1914 * Restore host debug registers. Restore DR7 and DEBUGCTL
1917 load_dr0(gctx->host_dr0);
1918 load_dr1(gctx->host_dr1);
1919 load_dr2(gctx->host_dr2);
1920 load_dr3(gctx->host_dr3);
1921 load_dr6(gctx->host_dr6);
1922 wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
1923 load_dr7(gctx->host_dr7);
1927 * Start vcpu with specified RIP.
1930 svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1931 struct vm_eventinfo *evinfo)
1933 struct svm_regctx *gctx;
1934 struct svm_softc *svm_sc;
1935 struct svm_vcpu *vcpustate;
1936 struct vmcb_state *state;
1937 struct vmcb_ctrl *ctrl;
1938 struct vm_exit *vmexit;
1939 struct vlapic *vlapic;
1947 vcpustate = svm_get_vcpu(svm_sc, vcpu);
1948 state = svm_get_vmcb_state(svm_sc, vcpu);
1949 ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1950 vmexit = vm_exitinfo(vm, vcpu);
1951 vlapic = vm_lapic(vm, vcpu);
1953 gctx = svm_get_guest_regctx(svm_sc, vcpu);
1954 vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1956 if (vcpustate->lastcpu != curcpu) {
1958 * Force new ASID allocation by invalidating the generation.
1960 vcpustate->asid.gen = 0;
1963 * Invalidate the VMCB state cache by marking all fields dirty.
1965 svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1969 * Setting 'vcpustate->lastcpu' here is bit premature because
1970 * we may return from this function without actually executing
1971 * the VMRUN instruction. This could happen if a rendezvous
1972 * or an AST is pending on the first time through the loop.
1974 * This works for now but any new side-effects of vcpu
1975 * migration should take this case into account.
1977 vcpustate->lastcpu = curcpu;
1978 vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1981 svm_msr_guest_enter(svm_sc, vcpu);
1983 /* Update Guest RIP */
1988 * Disable global interrupts to guarantee atomicity during
1989 * loading of guest state. This includes not only the state
1990 * loaded by the "vmrun" instruction but also software state
1991 * maintained by the hypervisor: suspended and rendezvous
1992 * state, NPT generation number, vlapic interrupts etc.
1996 if (vcpu_suspended(evinfo)) {
1998 vm_exit_suspended(vm, vcpu, state->rip);
2002 if (vcpu_rendezvous_pending(evinfo)) {
2004 vm_exit_rendezvous(vm, vcpu, state->rip);
2008 if (vcpu_reqidle(evinfo)) {
2010 vm_exit_reqidle(vm, vcpu, state->rip);
2014 /* We are asked to give the cpu by scheduler. */
2015 if (vcpu_should_yield(vm, vcpu)) {
2017 vm_exit_astpending(vm, vcpu, state->rip);
2021 if (vcpu_debugged(vm, vcpu)) {
2023 vm_exit_debug(vm, vcpu, state->rip);
2027 svm_inj_interrupts(svm_sc, vcpu, vlapic);
2029 /* Activate the nested pmap on 'curcpu' */
2030 CPU_SET_ATOMIC_ACQ(curcpu, &pmap->pm_active);
2033 * Check the pmap generation and the ASID generation to
2034 * ensure that the vcpu does not use stale TLB mappings.
2036 check_asid(svm_sc, vcpu, pmap, curcpu);
2038 ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
2039 vcpustate->dirty = 0;
2040 VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
2042 /* Launch Virtual Machine. */
2043 VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
2044 svm_dr_enter_guest(gctx);
2045 svm_launch(vmcb_pa, gctx, &__pcpu[curcpu]);
2046 svm_dr_leave_guest(gctx);
2048 CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
2051 * The host GDTR and IDTR is saved by VMRUN and restored
2052 * automatically on #VMEXIT. However, the host TSS needs
2053 * to be restored explicitly.
2057 /* #VMEXIT disables interrupts so re-enable them here. */
2060 /* Update 'nextrip' */
2061 vcpustate->nextrip = state->rip;
2063 /* Handle #VMEXIT and if required return to user space. */
2064 handled = svm_vmexit(svm_sc, vcpu, vmexit);
2067 svm_msr_guest_exit(svm_sc, vcpu);
2073 svm_vmcleanup(void *arg)
2075 struct svm_softc *sc = arg;
2077 contigfree(sc->iopm_bitmap, SVM_IO_BITMAP_SIZE, M_SVM);
2078 contigfree(sc->msr_bitmap, SVM_MSR_BITMAP_SIZE, M_SVM);
2083 swctx_regptr(struct svm_regctx *regctx, int reg)
2087 case VM_REG_GUEST_RBX:
2088 return (®ctx->sctx_rbx);
2089 case VM_REG_GUEST_RCX:
2090 return (®ctx->sctx_rcx);
2091 case VM_REG_GUEST_RDX:
2092 return (®ctx->sctx_rdx);
2093 case VM_REG_GUEST_RDI:
2094 return (®ctx->sctx_rdi);
2095 case VM_REG_GUEST_RSI:
2096 return (®ctx->sctx_rsi);
2097 case VM_REG_GUEST_RBP:
2098 return (®ctx->sctx_rbp);
2099 case VM_REG_GUEST_R8:
2100 return (®ctx->sctx_r8);
2101 case VM_REG_GUEST_R9:
2102 return (®ctx->sctx_r9);
2103 case VM_REG_GUEST_R10:
2104 return (®ctx->sctx_r10);
2105 case VM_REG_GUEST_R11:
2106 return (®ctx->sctx_r11);
2107 case VM_REG_GUEST_R12:
2108 return (®ctx->sctx_r12);
2109 case VM_REG_GUEST_R13:
2110 return (®ctx->sctx_r13);
2111 case VM_REG_GUEST_R14:
2112 return (®ctx->sctx_r14);
2113 case VM_REG_GUEST_R15:
2114 return (®ctx->sctx_r15);
2115 case VM_REG_GUEST_DR0:
2116 return (®ctx->sctx_dr0);
2117 case VM_REG_GUEST_DR1:
2118 return (®ctx->sctx_dr1);
2119 case VM_REG_GUEST_DR2:
2120 return (®ctx->sctx_dr2);
2121 case VM_REG_GUEST_DR3:
2122 return (®ctx->sctx_dr3);
2129 svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2131 struct svm_softc *svm_sc;
2136 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2137 return (svm_get_intr_shadow(svm_sc, vcpu, val));
2140 if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2144 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2151 VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2156 svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2158 struct svm_softc *svm_sc;
2163 if (ident == VM_REG_GUEST_INTR_SHADOW) {
2164 return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2167 if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2171 reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2179 * XXX deal with CR3 and invalidate TLB entries tagged with the
2180 * vcpu's ASID. This needs to be treated differently depending on
2181 * whether 'running' is true/false.
2184 VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2189 svm_setcap(void *arg, int vcpu, int type, int val)
2191 struct svm_softc *sc;
2197 case VM_CAP_HALT_EXIT:
2198 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2199 VMCB_INTCPT_HLT, val);
2201 case VM_CAP_PAUSE_EXIT:
2202 svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2203 VMCB_INTCPT_PAUSE, val);
2205 case VM_CAP_UNRESTRICTED_GUEST:
2206 /* Unrestricted guest execution cannot be disabled in SVM */
2218 svm_getcap(void *arg, int vcpu, int type, int *retval)
2220 struct svm_softc *sc;
2227 case VM_CAP_HALT_EXIT:
2228 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2231 case VM_CAP_PAUSE_EXIT:
2232 *retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2235 case VM_CAP_UNRESTRICTED_GUEST:
2236 *retval = 1; /* unrestricted guest is always enabled */
2245 static struct vlapic *
2246 svm_vlapic_init(void *arg, int vcpuid)
2248 struct svm_softc *svm_sc;
2249 struct vlapic *vlapic;
2252 vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2253 vlapic->vm = svm_sc->vm;
2254 vlapic->vcpuid = vcpuid;
2255 vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2257 vlapic_init(vlapic);
2263 svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2266 vlapic_cleanup(vlapic);
2267 free(vlapic, M_SVM_VLAPIC);
2270 struct vmm_ops vmm_ops_amd = {