2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2011 NetApp, Inc.
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, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
41 #include <sys/sysctl.h>
46 #include <machine/psl.h>
47 #include <machine/cpufunc.h>
48 #include <machine/md_var.h>
49 #include <machine/segments.h>
50 #include <machine/smp.h>
51 #include <machine/specialreg.h>
52 #include <machine/vmparam.h>
54 #include <machine/vmm.h>
55 #include <machine/vmm_dev.h>
56 #include <machine/vmm_instruction_emul.h>
57 #include "vmm_lapic.h"
59 #include "vmm_ioport.h"
64 #include "vlapic_priv.h"
67 #include "vmx_cpufunc.h"
71 #include "vmx_controls.h"
73 #define PINBASED_CTLS_ONE_SETTING \
74 (PINBASED_EXTINT_EXITING | \
75 PINBASED_NMI_EXITING | \
77 #define PINBASED_CTLS_ZERO_SETTING 0
79 #define PROCBASED_CTLS_WINDOW_SETTING \
80 (PROCBASED_INT_WINDOW_EXITING | \
81 PROCBASED_NMI_WINDOW_EXITING)
83 #define PROCBASED_CTLS_ONE_SETTING \
84 (PROCBASED_SECONDARY_CONTROLS | \
85 PROCBASED_MWAIT_EXITING | \
86 PROCBASED_MONITOR_EXITING | \
87 PROCBASED_IO_EXITING | \
88 PROCBASED_MSR_BITMAPS | \
89 PROCBASED_CTLS_WINDOW_SETTING | \
90 PROCBASED_CR8_LOAD_EXITING | \
91 PROCBASED_CR8_STORE_EXITING)
92 #define PROCBASED_CTLS_ZERO_SETTING \
93 (PROCBASED_CR3_LOAD_EXITING | \
94 PROCBASED_CR3_STORE_EXITING | \
97 #define PROCBASED_CTLS2_ONE_SETTING PROCBASED2_ENABLE_EPT
98 #define PROCBASED_CTLS2_ZERO_SETTING 0
100 #define VM_EXIT_CTLS_ONE_SETTING \
101 (VM_EXIT_HOST_LMA | \
102 VM_EXIT_SAVE_EFER | \
103 VM_EXIT_LOAD_EFER | \
104 VM_EXIT_ACKNOWLEDGE_INTERRUPT)
106 #define VM_EXIT_CTLS_ZERO_SETTING VM_EXIT_SAVE_DEBUG_CONTROLS
108 #define VM_ENTRY_CTLS_ONE_SETTING (VM_ENTRY_LOAD_EFER)
110 #define VM_ENTRY_CTLS_ZERO_SETTING \
111 (VM_ENTRY_LOAD_DEBUG_CONTROLS | \
112 VM_ENTRY_INTO_SMM | \
113 VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
118 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
119 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
121 SYSCTL_DECL(_hw_vmm);
122 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
124 int vmxon_enabled[MAXCPU];
125 static char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
127 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
128 static uint32_t exit_ctls, entry_ctls;
130 static uint64_t cr0_ones_mask, cr0_zeros_mask;
131 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
132 &cr0_ones_mask, 0, NULL);
133 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
134 &cr0_zeros_mask, 0, NULL);
136 static uint64_t cr4_ones_mask, cr4_zeros_mask;
137 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
138 &cr4_ones_mask, 0, NULL);
139 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
140 &cr4_zeros_mask, 0, NULL);
142 static int vmx_initialized;
143 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
144 &vmx_initialized, 0, "Intel VMX initialized");
147 * Optional capabilities
149 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap, CTLFLAG_RW, NULL, NULL);
151 static int cap_halt_exit;
152 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
153 "HLT triggers a VM-exit");
155 static int cap_pause_exit;
156 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
157 0, "PAUSE triggers a VM-exit");
159 static int cap_unrestricted_guest;
160 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
161 &cap_unrestricted_guest, 0, "Unrestricted guests");
163 static int cap_monitor_trap;
164 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
165 &cap_monitor_trap, 0, "Monitor trap flag");
167 static int cap_invpcid;
168 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
169 0, "Guests are allowed to use INVPCID");
171 static int virtual_interrupt_delivery;
172 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
173 &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
175 static int posted_interrupts;
176 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
177 &posted_interrupts, 0, "APICv posted interrupt support");
179 static int pirvec = -1;
180 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
181 &pirvec, 0, "APICv posted interrupt vector");
183 static struct unrhdr *vpid_unr;
184 static u_int vpid_alloc_failed;
185 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
186 &vpid_alloc_failed, 0, NULL);
189 * Use the last page below 4GB as the APIC access address. This address is
190 * occupied by the boot firmware so it is guaranteed that it will not conflict
191 * with a page in system memory.
193 #define APIC_ACCESS_ADDRESS 0xFFFFF000
195 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
196 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
197 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
198 static void vmx_inject_pir(struct vlapic *vlapic);
202 exit_reason_to_str(int reason)
204 static char reasonbuf[32];
207 case EXIT_REASON_EXCEPTION:
209 case EXIT_REASON_EXT_INTR:
211 case EXIT_REASON_TRIPLE_FAULT:
212 return "triplefault";
213 case EXIT_REASON_INIT:
215 case EXIT_REASON_SIPI:
217 case EXIT_REASON_IO_SMI:
219 case EXIT_REASON_SMI:
221 case EXIT_REASON_INTR_WINDOW:
223 case EXIT_REASON_NMI_WINDOW:
225 case EXIT_REASON_TASK_SWITCH:
227 case EXIT_REASON_CPUID:
229 case EXIT_REASON_GETSEC:
231 case EXIT_REASON_HLT:
233 case EXIT_REASON_INVD:
235 case EXIT_REASON_INVLPG:
237 case EXIT_REASON_RDPMC:
239 case EXIT_REASON_RDTSC:
241 case EXIT_REASON_RSM:
243 case EXIT_REASON_VMCALL:
245 case EXIT_REASON_VMCLEAR:
247 case EXIT_REASON_VMLAUNCH:
249 case EXIT_REASON_VMPTRLD:
251 case EXIT_REASON_VMPTRST:
253 case EXIT_REASON_VMREAD:
255 case EXIT_REASON_VMRESUME:
257 case EXIT_REASON_VMWRITE:
259 case EXIT_REASON_VMXOFF:
261 case EXIT_REASON_VMXON:
263 case EXIT_REASON_CR_ACCESS:
265 case EXIT_REASON_DR_ACCESS:
267 case EXIT_REASON_INOUT:
269 case EXIT_REASON_RDMSR:
271 case EXIT_REASON_WRMSR:
273 case EXIT_REASON_INVAL_VMCS:
275 case EXIT_REASON_INVAL_MSR:
277 case EXIT_REASON_MWAIT:
279 case EXIT_REASON_MTF:
281 case EXIT_REASON_MONITOR:
283 case EXIT_REASON_PAUSE:
285 case EXIT_REASON_MCE_DURING_ENTRY:
286 return "mce-during-entry";
287 case EXIT_REASON_TPR:
289 case EXIT_REASON_APIC_ACCESS:
290 return "apic-access";
291 case EXIT_REASON_GDTR_IDTR:
293 case EXIT_REASON_LDTR_TR:
295 case EXIT_REASON_EPT_FAULT:
297 case EXIT_REASON_EPT_MISCONFIG:
298 return "eptmisconfig";
299 case EXIT_REASON_INVEPT:
301 case EXIT_REASON_RDTSCP:
303 case EXIT_REASON_VMX_PREEMPT:
305 case EXIT_REASON_INVVPID:
307 case EXIT_REASON_WBINVD:
309 case EXIT_REASON_XSETBV:
311 case EXIT_REASON_APIC_WRITE:
314 snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
321 vmx_allow_x2apic_msrs(struct vmx *vmx)
328 * Allow readonly access to the following x2APIC MSRs from the guest.
330 error += guest_msr_ro(vmx, MSR_APIC_ID);
331 error += guest_msr_ro(vmx, MSR_APIC_VERSION);
332 error += guest_msr_ro(vmx, MSR_APIC_LDR);
333 error += guest_msr_ro(vmx, MSR_APIC_SVR);
335 for (i = 0; i < 8; i++)
336 error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
338 for (i = 0; i < 8; i++)
339 error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
341 for (i = 0; i < 8; i++)
342 error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
344 error += guest_msr_ro(vmx, MSR_APIC_ESR);
345 error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
346 error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
347 error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
348 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
349 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
350 error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
351 error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
352 error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
353 error += guest_msr_ro(vmx, MSR_APIC_ICR);
356 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
358 * These registers get special treatment described in the section
359 * "Virtualizing MSR-Based APIC Accesses".
361 error += guest_msr_rw(vmx, MSR_APIC_TPR);
362 error += guest_msr_rw(vmx, MSR_APIC_EOI);
363 error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
369 vmx_fix_cr0(u_long cr0)
372 return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
376 vmx_fix_cr4(u_long cr4)
379 return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
385 if (vpid < 0 || vpid > 0xffff)
386 panic("vpid_free: invalid vpid %d", vpid);
389 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
390 * the unit number allocator.
393 if (vpid > VM_MAXCPU)
394 free_unr(vpid_unr, vpid);
398 vpid_alloc(uint16_t *vpid, int num)
402 if (num <= 0 || num > VM_MAXCPU)
403 panic("invalid number of vpids requested: %d", num);
406 * If the "enable vpid" execution control is not enabled then the
407 * VPID is required to be 0 for all vcpus.
409 if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
410 for (i = 0; i < num; i++)
416 * Allocate a unique VPID for each vcpu from the unit number allocator.
418 for (i = 0; i < num; i++) {
419 x = alloc_unr(vpid_unr);
427 atomic_add_int(&vpid_alloc_failed, 1);
430 * If the unit number allocator does not have enough unique
431 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
433 * These VPIDs are not be unique across VMs but this does not
434 * affect correctness because the combined mappings are also
435 * tagged with the EP4TA which is unique for each VM.
437 * It is still sub-optimal because the invvpid will invalidate
438 * combined mappings for a particular VPID across all EP4TAs.
443 for (i = 0; i < num; i++)
452 * VPID 0 is required when the "enable VPID" execution control is
455 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
456 * unit number allocator does not have sufficient unique VPIDs to
457 * satisfy the allocation.
459 * The remaining VPIDs are managed by the unit number allocator.
461 vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
465 vmx_disable(void *arg __unused)
467 struct invvpid_desc invvpid_desc = { 0 };
468 struct invept_desc invept_desc = { 0 };
470 if (vmxon_enabled[curcpu]) {
472 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
474 * VMXON or VMXOFF are not required to invalidate any TLB
475 * caching structures. This prevents potential retention of
476 * cached information in the TLB between distinct VMX episodes.
478 invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
479 invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
482 load_cr4(rcr4() & ~CR4_VMXE);
490 lapic_ipi_free(pirvec);
492 if (vpid_unr != NULL) {
493 delete_unrhdr(vpid_unr);
497 smp_rendezvous(NULL, vmx_disable, NULL, NULL);
503 vmx_enable(void *arg __unused)
506 uint64_t feature_control;
508 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
509 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
510 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
511 wrmsr(MSR_IA32_FEATURE_CONTROL,
512 feature_control | IA32_FEATURE_CONTROL_VMX_EN |
513 IA32_FEATURE_CONTROL_LOCK);
516 load_cr4(rcr4() | CR4_VMXE);
518 *(uint32_t *)vmxon_region[curcpu] = vmx_revision();
519 error = vmxon(vmxon_region[curcpu]);
521 vmxon_enabled[curcpu] = 1;
528 if (vmxon_enabled[curcpu])
529 vmxon(vmxon_region[curcpu]);
535 int error, use_tpr_shadow;
536 uint64_t basic, fixed0, fixed1, feature_control;
537 uint32_t tmp, procbased2_vid_bits;
539 /* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
540 if (!(cpu_feature2 & CPUID2_VMX)) {
541 printf("vmx_init: processor does not support VMX operation\n");
546 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
547 * are set (bits 0 and 2 respectively).
549 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
550 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
551 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
552 printf("vmx_init: VMX operation disabled by BIOS\n");
557 * Verify capabilities MSR_VMX_BASIC:
558 * - bit 54 indicates support for INS/OUTS decoding
560 basic = rdmsr(MSR_VMX_BASIC);
561 if ((basic & (1UL << 54)) == 0) {
562 printf("vmx_init: processor does not support desired basic "
567 /* Check support for primary processor-based VM-execution controls */
568 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
569 MSR_VMX_TRUE_PROCBASED_CTLS,
570 PROCBASED_CTLS_ONE_SETTING,
571 PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
573 printf("vmx_init: processor does not support desired primary "
574 "processor-based controls\n");
578 /* Clear the processor-based ctl bits that are set on demand */
579 procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
581 /* Check support for secondary processor-based VM-execution controls */
582 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
583 MSR_VMX_PROCBASED_CTLS2,
584 PROCBASED_CTLS2_ONE_SETTING,
585 PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
587 printf("vmx_init: processor does not support desired secondary "
588 "processor-based controls\n");
592 /* Check support for VPID */
593 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
594 PROCBASED2_ENABLE_VPID, 0, &tmp);
596 procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
598 /* Check support for pin-based VM-execution controls */
599 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
600 MSR_VMX_TRUE_PINBASED_CTLS,
601 PINBASED_CTLS_ONE_SETTING,
602 PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
604 printf("vmx_init: processor does not support desired "
605 "pin-based controls\n");
609 /* Check support for VM-exit controls */
610 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
611 VM_EXIT_CTLS_ONE_SETTING,
612 VM_EXIT_CTLS_ZERO_SETTING,
615 printf("vmx_init: processor does not support desired "
620 /* Check support for VM-entry controls */
621 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
622 VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
625 printf("vmx_init: processor does not support desired "
631 * Check support for optional features by testing them
634 cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
635 MSR_VMX_TRUE_PROCBASED_CTLS,
636 PROCBASED_HLT_EXITING, 0,
639 cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
640 MSR_VMX_PROCBASED_CTLS,
644 cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
645 MSR_VMX_TRUE_PROCBASED_CTLS,
646 PROCBASED_PAUSE_EXITING, 0,
649 cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
650 MSR_VMX_PROCBASED_CTLS2,
651 PROCBASED2_UNRESTRICTED_GUEST, 0,
654 cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
655 MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
659 * Check support for virtual interrupt delivery.
661 procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
662 PROCBASED2_VIRTUALIZE_X2APIC_MODE |
663 PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
664 PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
666 use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
667 MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
670 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
671 procbased2_vid_bits, 0, &tmp);
672 if (error == 0 && use_tpr_shadow) {
673 virtual_interrupt_delivery = 1;
674 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
675 &virtual_interrupt_delivery);
678 if (virtual_interrupt_delivery) {
679 procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
680 procbased_ctls2 |= procbased2_vid_bits;
681 procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
684 * No need to emulate accesses to %CR8 if virtual
685 * interrupt delivery is enabled.
687 procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
688 procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
691 * Check for Posted Interrupts only if Virtual Interrupt
692 * Delivery is enabled.
694 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
695 MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
698 pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
699 &IDTVEC(justreturn));
702 printf("vmx_init: unable to allocate "
703 "posted interrupt vector\n");
706 posted_interrupts = 1;
707 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
713 if (posted_interrupts)
714 pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
717 error = ept_init(ipinum);
719 printf("vmx_init: ept initialization failed (%d)\n", error);
724 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
726 fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
727 fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
728 cr0_ones_mask = fixed0 & fixed1;
729 cr0_zeros_mask = ~fixed0 & ~fixed1;
732 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
733 * if unrestricted guest execution is allowed.
735 if (cap_unrestricted_guest)
736 cr0_ones_mask &= ~(CR0_PG | CR0_PE);
739 * Do not allow the guest to set CR0_NW or CR0_CD.
741 cr0_zeros_mask |= (CR0_NW | CR0_CD);
743 fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
744 fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
745 cr4_ones_mask = fixed0 & fixed1;
746 cr4_zeros_mask = ~fixed0 & ~fixed1;
752 /* enable VMX operation */
753 smp_rendezvous(NULL, vmx_enable, NULL, NULL);
761 vmx_trigger_hostintr(int vector)
764 struct gate_descriptor *gd;
768 KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
769 "invalid vector %d", vector));
770 KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
772 KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
773 "has invalid type %d", vector, gd->gd_type));
774 KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
775 "has invalid dpl %d", vector, gd->gd_dpl));
776 KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
777 "for vector %d has invalid selector %d", vector, gd->gd_selector));
778 KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
779 "IST %d", vector, gd->gd_ist));
781 func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
786 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
788 int error, mask_ident, shadow_ident;
791 if (which != 0 && which != 4)
792 panic("vmx_setup_cr_shadow: unknown cr%d", which);
795 mask_ident = VMCS_CR0_MASK;
796 mask_value = cr0_ones_mask | cr0_zeros_mask;
797 shadow_ident = VMCS_CR0_SHADOW;
799 mask_ident = VMCS_CR4_MASK;
800 mask_value = cr4_ones_mask | cr4_zeros_mask;
801 shadow_ident = VMCS_CR4_SHADOW;
804 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
808 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
814 #define vmx_setup_cr0_shadow(vmcs,init) vmx_setup_cr_shadow(0, (vmcs), (init))
815 #define vmx_setup_cr4_shadow(vmcs,init) vmx_setup_cr_shadow(4, (vmcs), (init))
818 vmx_vminit(struct vm *vm, pmap_t pmap)
820 uint16_t vpid[VM_MAXCPU];
826 vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
827 if ((uintptr_t)vmx & PAGE_MASK) {
828 panic("malloc of struct vmx not aligned on %d byte boundary",
833 vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
836 * Clean up EPTP-tagged guest physical and combined mappings
838 * VMX transitions are not required to invalidate any guest physical
839 * mappings. So, it may be possible for stale guest physical mappings
840 * to be present in the processor TLBs.
842 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
844 ept_invalidate_mappings(vmx->eptp);
846 msr_bitmap_initialize(vmx->msr_bitmap);
849 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
850 * The guest FSBASE and GSBASE are saved and restored during
851 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
852 * always restored from the vmcs host state area on vm-exit.
854 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
855 * how they are saved/restored so can be directly accessed by the
858 * MSR_EFER is saved and restored in the guest VMCS area on a
859 * VM exit and entry respectively. It is also restored from the
860 * host VMCS area on a VM exit.
862 * The TSC MSR is exposed read-only. Writes are disallowed as
863 * that will impact the host TSC. If the guest does a write
864 * the "use TSC offsetting" execution control is enabled and the
865 * difference between the host TSC and the guest TSC is written
866 * into the TSC offset in the VMCS.
868 if (guest_msr_rw(vmx, MSR_GSBASE) ||
869 guest_msr_rw(vmx, MSR_FSBASE) ||
870 guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
871 guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
872 guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
873 guest_msr_rw(vmx, MSR_EFER) ||
874 guest_msr_ro(vmx, MSR_TSC))
875 panic("vmx_vminit: error setting guest msr access");
877 vpid_alloc(vpid, VM_MAXCPU);
879 if (virtual_interrupt_delivery) {
880 error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
881 APIC_ACCESS_ADDRESS);
882 /* XXX this should really return an error to the caller */
883 KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
886 for (i = 0; i < VM_MAXCPU; i++) {
887 vmcs = &vmx->vmcs[i];
888 vmcs->identifier = vmx_revision();
889 error = vmclear(vmcs);
891 panic("vmx_vminit: vmclear error %d on vcpu %d\n",
895 vmx_msr_guest_init(vmx, i);
897 error = vmcs_init(vmcs);
898 KASSERT(error == 0, ("vmcs_init error %d", error));
902 error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
903 error += vmwrite(VMCS_EPTP, vmx->eptp);
904 error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
905 error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
906 error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
907 error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
908 error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
909 error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
910 error += vmwrite(VMCS_VPID, vpid[i]);
912 /* exception bitmap */
913 if (vcpu_trace_exceptions(vm, i))
914 exc_bitmap = 0xffffffff;
916 exc_bitmap = 1 << IDT_MC;
917 error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
919 if (virtual_interrupt_delivery) {
920 error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
921 error += vmwrite(VMCS_VIRTUAL_APIC,
922 vtophys(&vmx->apic_page[i]));
923 error += vmwrite(VMCS_EOI_EXIT0, 0);
924 error += vmwrite(VMCS_EOI_EXIT1, 0);
925 error += vmwrite(VMCS_EOI_EXIT2, 0);
926 error += vmwrite(VMCS_EOI_EXIT3, 0);
928 if (posted_interrupts) {
929 error += vmwrite(VMCS_PIR_VECTOR, pirvec);
930 error += vmwrite(VMCS_PIR_DESC,
931 vtophys(&vmx->pir_desc[i]));
934 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
937 vmx->cap[i].proc_ctls = procbased_ctls;
938 vmx->cap[i].proc_ctls2 = procbased_ctls2;
940 vmx->state[i].nextrip = ~0;
941 vmx->state[i].lastcpu = NOCPU;
942 vmx->state[i].vpid = vpid[i];
945 * Set up the CR0/4 shadows, and init the read shadow
946 * to the power-on register value from the Intel Sys Arch.
950 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
952 panic("vmx_setup_cr0_shadow %d", error);
954 error = vmx_setup_cr4_shadow(vmcs, 0);
956 panic("vmx_setup_cr4_shadow %d", error);
958 vmx->ctx[i].pmap = pmap;
965 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
969 func = vmxctx->guest_rax;
971 handled = x86_emulate_cpuid(vm, vcpu,
972 (uint32_t*)(&vmxctx->guest_rax),
973 (uint32_t*)(&vmxctx->guest_rbx),
974 (uint32_t*)(&vmxctx->guest_rcx),
975 (uint32_t*)(&vmxctx->guest_rdx));
980 vmx_run_trace(struct vmx *vmx, int vcpu)
983 VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
988 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
992 VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
993 handled ? "handled" : "unhandled",
994 exit_reason_to_str(exit_reason), rip);
999 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1002 VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1006 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1007 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1010 * Invalidate guest mappings identified by its vpid from the TLB.
1012 static __inline void
1013 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1015 struct vmxstate *vmxstate;
1016 struct invvpid_desc invvpid_desc;
1018 vmxstate = &vmx->state[vcpu];
1019 if (vmxstate->vpid == 0)
1024 * Set the 'lastcpu' to an invalid host cpu.
1026 * This will invalidate TLB entries tagged with the vcpu's
1027 * vpid the next time it runs via vmx_set_pcpu_defaults().
1029 vmxstate->lastcpu = NOCPU;
1033 KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1034 "critical section", __func__, vcpu));
1037 * Invalidate all mappings tagged with 'vpid'
1039 * We do this because this vcpu was executing on a different host
1040 * cpu when it last ran. We do not track whether it invalidated
1041 * mappings associated with its 'vpid' during that run. So we must
1042 * assume that the mappings associated with 'vpid' on 'curcpu' are
1043 * stale and invalidate them.
1045 * Note that we incur this penalty only when the scheduler chooses to
1046 * move the thread associated with this vcpu between host cpus.
1048 * Note also that this will invalidate mappings tagged with 'vpid'
1051 if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1052 invvpid_desc._res1 = 0;
1053 invvpid_desc._res2 = 0;
1054 invvpid_desc.vpid = vmxstate->vpid;
1055 invvpid_desc.linear_addr = 0;
1056 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1057 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1060 * The invvpid can be skipped if an invept is going to
1061 * be performed before entering the guest. The invept
1062 * will invalidate combined mappings tagged with
1063 * 'vmx->eptp' for all vpids.
1065 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1070 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1072 struct vmxstate *vmxstate;
1074 vmxstate = &vmx->state[vcpu];
1075 if (vmxstate->lastcpu == curcpu)
1078 vmxstate->lastcpu = curcpu;
1080 vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1082 vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1083 vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1084 vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1085 vmx_invvpid(vmx, vcpu, pmap, 1);
1089 * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1091 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1093 static void __inline
1094 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1097 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1098 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1099 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1100 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1104 static void __inline
1105 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1108 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1109 ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1110 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1111 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1112 VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1115 static void __inline
1116 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1119 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1120 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1121 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1122 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1126 static void __inline
1127 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1130 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1131 ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1132 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1133 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1134 VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1138 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1142 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1143 vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1144 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1145 VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1148 error = vmwrite(VMCS_TSC_OFFSET, offset);
1153 #define NMI_BLOCKING (VMCS_INTERRUPTIBILITY_NMI_BLOCKING | \
1154 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1155 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING | \
1156 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1159 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1163 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1164 KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1165 "interruptibility-state %#x", gi));
1167 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1168 KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1169 "VM-entry interruption information %#x", info));
1172 * Inject the virtual NMI. The vector must be the NMI IDT entry
1173 * or the VMCS entry check will fail.
1175 info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1176 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1178 VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1180 /* Clear the request */
1181 vm_nmi_clear(vmx->vm, vcpu);
1185 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1188 int vector, need_nmi_exiting, extint_pending;
1189 uint64_t rflags, entryinfo;
1192 if (vmx->state[vcpu].nextrip != guestrip) {
1193 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1194 if (gi & HWINTR_BLOCKING) {
1195 VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1196 "cleared due to rip change: %#lx/%#lx",
1197 vmx->state[vcpu].nextrip, guestrip);
1198 gi &= ~HWINTR_BLOCKING;
1199 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1203 if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1204 KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1205 "intinfo is not valid: %#lx", __func__, entryinfo));
1207 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1208 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1209 "pending exception: %#lx/%#x", __func__, entryinfo, info));
1212 vector = info & 0xff;
1213 if (vector == IDT_BP || vector == IDT_OF) {
1215 * VT-x requires #BP and #OF to be injected as software
1218 info &= ~VMCS_INTR_T_MASK;
1219 info |= VMCS_INTR_T_SWEXCEPTION;
1222 if (info & VMCS_INTR_DEL_ERRCODE)
1223 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1225 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1228 if (vm_nmi_pending(vmx->vm, vcpu)) {
1230 * If there are no conditions blocking NMI injection then
1231 * inject it directly here otherwise enable "NMI window
1232 * exiting" to inject it as soon as we can.
1234 * We also check for STI_BLOCKING because some implementations
1235 * don't allow NMI injection in this case. If we are running
1236 * on a processor that doesn't have this restriction it will
1237 * immediately exit and the NMI will be injected in the
1238 * "NMI window exiting" handler.
1240 need_nmi_exiting = 1;
1241 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1242 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1243 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1244 if ((info & VMCS_INTR_VALID) == 0) {
1245 vmx_inject_nmi(vmx, vcpu);
1246 need_nmi_exiting = 0;
1248 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1249 "due to VM-entry intr info %#x", info);
1252 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1253 "Guest Interruptibility-state %#x", gi);
1256 if (need_nmi_exiting)
1257 vmx_set_nmi_window_exiting(vmx, vcpu);
1260 extint_pending = vm_extint_pending(vmx->vm, vcpu);
1262 if (!extint_pending && virtual_interrupt_delivery) {
1263 vmx_inject_pir(vlapic);
1268 * If interrupt-window exiting is already in effect then don't bother
1269 * checking for pending interrupts. This is just an optimization and
1270 * not needed for correctness.
1272 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1273 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1274 "pending int_window_exiting");
1278 if (!extint_pending) {
1279 /* Ask the local apic for a vector to inject */
1280 if (!vlapic_pending_intr(vlapic, &vector))
1284 * From the Intel SDM, Volume 3, Section "Maskable
1285 * Hardware Interrupts":
1286 * - maskable interrupt vectors [16,255] can be delivered
1287 * through the local APIC.
1289 KASSERT(vector >= 16 && vector <= 255,
1290 ("invalid vector %d from local APIC", vector));
1292 /* Ask the legacy pic for a vector to inject */
1293 vatpic_pending_intr(vmx->vm, &vector);
1296 * From the Intel SDM, Volume 3, Section "Maskable
1297 * Hardware Interrupts":
1298 * - maskable interrupt vectors [0,255] can be delivered
1299 * through the INTR pin.
1301 KASSERT(vector >= 0 && vector <= 255,
1302 ("invalid vector %d from INTR", vector));
1305 /* Check RFLAGS.IF and the interruptibility state of the guest */
1306 rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1307 if ((rflags & PSL_I) == 0) {
1308 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1309 "rflags %#lx", vector, rflags);
1313 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1314 if (gi & HWINTR_BLOCKING) {
1315 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1316 "Guest Interruptibility-state %#x", vector, gi);
1320 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1321 if (info & VMCS_INTR_VALID) {
1323 * This is expected and could happen for multiple reasons:
1324 * - A vectoring VM-entry was aborted due to astpending
1325 * - A VM-exit happened during event injection.
1326 * - An exception was injected above.
1327 * - An NMI was injected above or after "NMI window exiting"
1329 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1330 "VM-entry intr info %#x", vector, info);
1334 /* Inject the interrupt */
1335 info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1337 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1339 if (!extint_pending) {
1340 /* Update the Local APIC ISR */
1341 vlapic_intr_accepted(vlapic, vector);
1343 vm_extint_clear(vmx->vm, vcpu);
1344 vatpic_intr_accepted(vmx->vm, vector);
1347 * After we accepted the current ExtINT the PIC may
1348 * have posted another one. If that is the case, set
1349 * the Interrupt Window Exiting execution control so
1350 * we can inject that one too.
1352 * Also, interrupt window exiting allows us to inject any
1353 * pending APIC vector that was preempted by the ExtINT
1354 * as soon as possible. This applies both for the software
1355 * emulated vlapic and the hardware assisted virtual APIC.
1357 vmx_set_int_window_exiting(vmx, vcpu);
1360 VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1366 * Set the Interrupt Window Exiting execution control so we can inject
1367 * the interrupt as soon as blocking condition goes away.
1369 vmx_set_int_window_exiting(vmx, vcpu);
1373 * If the Virtual NMIs execution control is '1' then the logical processor
1374 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1375 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1376 * virtual-NMI blocking.
1378 * This unblocking occurs even if the IRET causes a fault. In this case the
1379 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1382 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1386 VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1387 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1388 gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1389 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1393 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1397 VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1398 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1399 gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1400 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1404 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1408 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1409 KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1410 ("NMI blocking is not in effect %#x", gi));
1414 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1416 struct vmxctx *vmxctx;
1418 const struct xsave_limits *limits;
1420 vmxctx = &vmx->ctx[vcpu];
1421 limits = vmm_get_xsave_limits();
1424 * Note that the processor raises a GP# fault on its own if
1425 * xsetbv is executed for CPL != 0, so we do not have to
1426 * emulate that fault here.
1429 /* Only xcr0 is supported. */
1430 if (vmxctx->guest_rcx != 0) {
1431 vm_inject_gp(vmx->vm, vcpu);
1435 /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1436 if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1437 vm_inject_ud(vmx->vm, vcpu);
1441 xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1442 if ((xcrval & ~limits->xcr0_allowed) != 0) {
1443 vm_inject_gp(vmx->vm, vcpu);
1447 if (!(xcrval & XFEATURE_ENABLED_X87)) {
1448 vm_inject_gp(vmx->vm, vcpu);
1452 /* AVX (YMM_Hi128) requires SSE. */
1453 if (xcrval & XFEATURE_ENABLED_AVX &&
1454 (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1455 vm_inject_gp(vmx->vm, vcpu);
1460 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1461 * ZMM_Hi256, and Hi16_ZMM.
1463 if (xcrval & XFEATURE_AVX512 &&
1464 (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1465 (XFEATURE_AVX512 | XFEATURE_AVX)) {
1466 vm_inject_gp(vmx->vm, vcpu);
1471 * Intel MPX requires both bound register state flags to be
1474 if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1475 ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1476 vm_inject_gp(vmx->vm, vcpu);
1481 * This runs "inside" vmrun() with the guest's FPU state, so
1482 * modifying xcr0 directly modifies the guest's xcr0, not the
1485 load_xcr(0, xcrval);
1490 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1492 const struct vmxctx *vmxctx;
1494 vmxctx = &vmx->ctx[vcpu];
1498 return (vmxctx->guest_rax);
1500 return (vmxctx->guest_rcx);
1502 return (vmxctx->guest_rdx);
1504 return (vmxctx->guest_rbx);
1506 return (vmcs_read(VMCS_GUEST_RSP));
1508 return (vmxctx->guest_rbp);
1510 return (vmxctx->guest_rsi);
1512 return (vmxctx->guest_rdi);
1514 return (vmxctx->guest_r8);
1516 return (vmxctx->guest_r9);
1518 return (vmxctx->guest_r10);
1520 return (vmxctx->guest_r11);
1522 return (vmxctx->guest_r12);
1524 return (vmxctx->guest_r13);
1526 return (vmxctx->guest_r14);
1528 return (vmxctx->guest_r15);
1530 panic("invalid vmx register %d", ident);
1535 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1537 struct vmxctx *vmxctx;
1539 vmxctx = &vmx->ctx[vcpu];
1543 vmxctx->guest_rax = regval;
1546 vmxctx->guest_rcx = regval;
1549 vmxctx->guest_rdx = regval;
1552 vmxctx->guest_rbx = regval;
1555 vmcs_write(VMCS_GUEST_RSP, regval);
1558 vmxctx->guest_rbp = regval;
1561 vmxctx->guest_rsi = regval;
1564 vmxctx->guest_rdi = regval;
1567 vmxctx->guest_r8 = regval;
1570 vmxctx->guest_r9 = regval;
1573 vmxctx->guest_r10 = regval;
1576 vmxctx->guest_r11 = regval;
1579 vmxctx->guest_r12 = regval;
1582 vmxctx->guest_r13 = regval;
1585 vmxctx->guest_r14 = regval;
1588 vmxctx->guest_r15 = regval;
1591 panic("invalid vmx register %d", ident);
1596 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1598 uint64_t crval, regval;
1600 /* We only handle mov to %cr0 at this time */
1601 if ((exitqual & 0xf0) != 0x00)
1604 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1606 vmcs_write(VMCS_CR0_SHADOW, regval);
1608 crval = regval | cr0_ones_mask;
1609 crval &= ~cr0_zeros_mask;
1610 vmcs_write(VMCS_GUEST_CR0, crval);
1612 if (regval & CR0_PG) {
1613 uint64_t efer, entry_ctls;
1616 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1617 * the "IA-32e mode guest" bit in VM-entry control must be
1620 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1621 if (efer & EFER_LME) {
1623 vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1624 entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1625 entry_ctls |= VM_ENTRY_GUEST_LMA;
1626 vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1634 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1636 uint64_t crval, regval;
1638 /* We only handle mov to %cr4 at this time */
1639 if ((exitqual & 0xf0) != 0x00)
1642 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1644 vmcs_write(VMCS_CR4_SHADOW, regval);
1646 crval = regval | cr4_ones_mask;
1647 crval &= ~cr4_zeros_mask;
1648 vmcs_write(VMCS_GUEST_CR4, crval);
1654 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1656 struct vlapic *vlapic;
1660 /* We only handle mov %cr8 to/from a register at this time. */
1661 if ((exitqual & 0xe0) != 0x00) {
1665 vlapic = vm_lapic(vmx->vm, vcpu);
1666 regnum = (exitqual >> 8) & 0xf;
1667 if (exitqual & 0x10) {
1668 cr8 = vlapic_get_cr8(vlapic);
1669 vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1671 cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1672 vlapic_set_cr8(vlapic, cr8);
1679 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1686 ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1687 return ((ssar >> 5) & 0x3);
1690 static enum vm_cpu_mode
1695 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1696 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1698 return (CPU_MODE_64BIT); /* CS.L = 1 */
1700 return (CPU_MODE_COMPATIBILITY);
1701 } else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1702 return (CPU_MODE_PROTECTED);
1704 return (CPU_MODE_REAL);
1708 static enum vm_paging_mode
1709 vmx_paging_mode(void)
1712 if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1713 return (PAGING_MODE_FLAT);
1714 if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1715 return (PAGING_MODE_32);
1716 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1717 return (PAGING_MODE_64);
1719 return (PAGING_MODE_PAE);
1723 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1727 enum vm_reg_name reg;
1729 reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1730 error = vmx_getreg(vmx, vcpuid, reg, &val);
1731 KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1736 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1742 error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1743 KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1751 inout_str_addrsize(uint32_t inst_info)
1755 size = (inst_info >> 7) & 0x7;
1758 return (2); /* 16 bit */
1760 return (4); /* 32 bit */
1762 return (8); /* 64 bit */
1764 panic("%s: invalid size encoding %d", __func__, size);
1769 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1770 struct vm_inout_str *vis)
1775 vis->seg_name = VM_REG_GUEST_ES;
1777 s = (inst_info >> 15) & 0x7;
1778 vis->seg_name = vm_segment_name(s);
1781 error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1782 KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1786 vmx_paging_info(struct vm_guest_paging *paging)
1788 paging->cr3 = vmcs_guest_cr3();
1789 paging->cpl = vmx_cpl();
1790 paging->cpu_mode = vmx_cpu_mode();
1791 paging->paging_mode = vmx_paging_mode();
1795 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1797 struct vm_guest_paging *paging;
1800 paging = &vmexit->u.inst_emul.paging;
1802 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1803 vmexit->inst_length = 0;
1804 vmexit->u.inst_emul.gpa = gpa;
1805 vmexit->u.inst_emul.gla = gla;
1806 vmx_paging_info(paging);
1807 switch (paging->cpu_mode) {
1809 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1810 vmexit->u.inst_emul.cs_d = 0;
1812 case CPU_MODE_PROTECTED:
1813 case CPU_MODE_COMPATIBILITY:
1814 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1815 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1816 vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1819 vmexit->u.inst_emul.cs_base = 0;
1820 vmexit->u.inst_emul.cs_d = 0;
1823 vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1827 ept_fault_type(uint64_t ept_qual)
1831 if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1832 fault_type = VM_PROT_WRITE;
1833 else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1834 fault_type = VM_PROT_EXECUTE;
1836 fault_type= VM_PROT_READ;
1838 return (fault_type);
1842 ept_emulation_fault(uint64_t ept_qual)
1846 /* EPT fault on an instruction fetch doesn't make sense here */
1847 if (ept_qual & EPT_VIOLATION_INST_FETCH)
1850 /* EPT fault must be a read fault or a write fault */
1851 read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1852 write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1853 if ((read | write) == 0)
1857 * The EPT violation must have been caused by accessing a
1858 * guest-physical address that is a translation of a guest-linear
1861 if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1862 (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1870 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1872 uint32_t proc_ctls2;
1874 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1875 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1879 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1881 uint32_t proc_ctls2;
1883 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1884 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1888 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1891 int error, handled, offset;
1892 uint32_t *apic_regs, vector;
1896 offset = APIC_WRITE_OFFSET(qual);
1898 if (!apic_access_virtualization(vmx, vcpuid)) {
1900 * In general there should not be any APIC write VM-exits
1901 * unless APIC-access virtualization is enabled.
1903 * However self-IPI virtualization can legitimately trigger
1904 * an APIC-write VM-exit so treat it specially.
1906 if (x2apic_virtualization(vmx, vcpuid) &&
1907 offset == APIC_OFFSET_SELF_IPI) {
1908 apic_regs = (uint32_t *)(vlapic->apic_page);
1909 vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1910 vlapic_self_ipi_handler(vlapic, vector);
1917 case APIC_OFFSET_ID:
1918 vlapic_id_write_handler(vlapic);
1920 case APIC_OFFSET_LDR:
1921 vlapic_ldr_write_handler(vlapic);
1923 case APIC_OFFSET_DFR:
1924 vlapic_dfr_write_handler(vlapic);
1926 case APIC_OFFSET_SVR:
1927 vlapic_svr_write_handler(vlapic);
1929 case APIC_OFFSET_ESR:
1930 vlapic_esr_write_handler(vlapic);
1932 case APIC_OFFSET_ICR_LOW:
1934 error = vlapic_icrlo_write_handler(vlapic, &retu);
1935 if (error != 0 || retu)
1936 handled = UNHANDLED;
1938 case APIC_OFFSET_CMCI_LVT:
1939 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1940 vlapic_lvt_write_handler(vlapic, offset);
1942 case APIC_OFFSET_TIMER_ICR:
1943 vlapic_icrtmr_write_handler(vlapic);
1945 case APIC_OFFSET_TIMER_DCR:
1946 vlapic_dcr_write_handler(vlapic);
1949 handled = UNHANDLED;
1956 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1959 if (apic_access_virtualization(vmx, vcpuid) &&
1960 (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1967 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1970 int access_type, offset, allowed;
1972 if (!apic_access_virtualization(vmx, vcpuid))
1975 qual = vmexit->u.vmx.exit_qualification;
1976 access_type = APIC_ACCESS_TYPE(qual);
1977 offset = APIC_ACCESS_OFFSET(qual);
1980 if (access_type == 0) {
1982 * Read data access to the following registers is expected.
1985 case APIC_OFFSET_APR:
1986 case APIC_OFFSET_PPR:
1987 case APIC_OFFSET_RRR:
1988 case APIC_OFFSET_CMCI_LVT:
1989 case APIC_OFFSET_TIMER_CCR:
1995 } else if (access_type == 1) {
1997 * Write data access to the following registers is expected.
2000 case APIC_OFFSET_VER:
2001 case APIC_OFFSET_APR:
2002 case APIC_OFFSET_PPR:
2003 case APIC_OFFSET_RRR:
2004 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2005 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2006 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2007 case APIC_OFFSET_CMCI_LVT:
2008 case APIC_OFFSET_TIMER_CCR:
2017 vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2022 * Regardless of whether the APIC-access is allowed this handler
2023 * always returns UNHANDLED:
2024 * - if the access is allowed then it is handled by emulating the
2025 * instruction that caused the VM-exit (outside the critical section)
2026 * - if the access is not allowed then it will be converted to an
2027 * exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2032 static enum task_switch_reason
2033 vmx_task_switch_reason(uint64_t qual)
2037 reason = (qual >> 30) & 0x3;
2046 return (TSR_IDT_GATE);
2048 panic("%s: invalid reason %d", __func__, reason);
2053 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2058 error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2060 error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2066 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2068 struct vmxctx *vmxctx;
2074 error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2076 error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2080 vmxctx = &vmx->ctx[vcpuid];
2081 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2082 KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2085 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2086 KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2093 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2095 int error, errcode, errcode_valid, handled, in;
2096 struct vmxctx *vmxctx;
2097 struct vlapic *vlapic;
2098 struct vm_inout_str *vis;
2099 struct vm_task_switch *ts;
2100 uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2101 uint32_t intr_type, intr_vec, reason;
2102 uint64_t exitintinfo, qual, gpa;
2105 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2106 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2108 handled = UNHANDLED;
2109 vmxctx = &vmx->ctx[vcpu];
2111 qual = vmexit->u.vmx.exit_qualification;
2112 reason = vmexit->u.vmx.exit_reason;
2113 vmexit->exitcode = VM_EXITCODE_BOGUS;
2115 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2118 * VM-entry failures during or after loading guest state.
2120 * These VM-exits are uncommon but must be handled specially
2121 * as most VM-exit fields are not populated as usual.
2123 if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2124 VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2125 __asm __volatile("int $18");
2130 * VM exits that can be triggered during event delivery need to
2131 * be handled specially by re-injecting the event if the IDT
2132 * vectoring information field's valid bit is set.
2134 * See "Information for VM Exits During Event Delivery" in Intel SDM
2137 idtvec_info = vmcs_idt_vectoring_info();
2138 if (idtvec_info & VMCS_IDT_VEC_VALID) {
2139 idtvec_info &= ~(1 << 12); /* clear undefined bit */
2140 exitintinfo = idtvec_info;
2141 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2142 idtvec_err = vmcs_idt_vectoring_err();
2143 exitintinfo |= (uint64_t)idtvec_err << 32;
2145 error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2146 KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2150 * If 'virtual NMIs' are being used and the VM-exit
2151 * happened while injecting an NMI during the previous
2152 * VM-entry, then clear "blocking by NMI" in the
2153 * Guest Interruptibility-State so the NMI can be
2154 * reinjected on the subsequent VM-entry.
2156 * However, if the NMI was being delivered through a task
2157 * gate, then the new task must start execution with NMIs
2158 * blocked so don't clear NMI blocking in this case.
2160 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2161 if (intr_type == VMCS_INTR_T_NMI) {
2162 if (reason != EXIT_REASON_TASK_SWITCH)
2163 vmx_clear_nmi_blocking(vmx, vcpu);
2165 vmx_assert_nmi_blocking(vmx, vcpu);
2169 * Update VM-entry instruction length if the event being
2170 * delivered was a software interrupt or software exception.
2172 if (intr_type == VMCS_INTR_T_SWINTR ||
2173 intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2174 intr_type == VMCS_INTR_T_SWEXCEPTION) {
2175 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2180 case EXIT_REASON_TASK_SWITCH:
2181 ts = &vmexit->u.task_switch;
2182 ts->tsssel = qual & 0xffff;
2183 ts->reason = vmx_task_switch_reason(qual);
2185 ts->errcode_valid = 0;
2186 vmx_paging_info(&ts->paging);
2188 * If the task switch was due to a CALL, JMP, IRET, software
2189 * interrupt (INT n) or software exception (INT3, INTO),
2190 * then the saved %rip references the instruction that caused
2191 * the task switch. The instruction length field in the VMCS
2192 * is valid in this case.
2194 * In all other cases (e.g., NMI, hardware exception) the
2195 * saved %rip is one that would have been saved in the old TSS
2196 * had the task switch completed normally so the instruction
2197 * length field is not needed in this case and is explicitly
2200 if (ts->reason == TSR_IDT_GATE) {
2201 KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2202 ("invalid idtvec_info %#x for IDT task switch",
2204 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2205 if (intr_type != VMCS_INTR_T_SWINTR &&
2206 intr_type != VMCS_INTR_T_SWEXCEPTION &&
2207 intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2208 /* Task switch triggered by external event */
2210 vmexit->inst_length = 0;
2211 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2212 ts->errcode_valid = 1;
2213 ts->errcode = vmcs_idt_vectoring_err();
2217 vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2218 VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2219 "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2220 ts->ext ? "external" : "internal",
2221 ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2223 case EXIT_REASON_CR_ACCESS:
2224 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2225 switch (qual & 0xf) {
2227 handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2230 handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2233 handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2237 case EXIT_REASON_RDMSR:
2238 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2240 ecx = vmxctx->guest_rcx;
2241 VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2242 error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2244 vmexit->exitcode = VM_EXITCODE_RDMSR;
2245 vmexit->u.msr.code = ecx;
2249 /* Return to userspace with a valid exitcode */
2250 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2251 ("emulate_rdmsr retu with bogus exitcode"));
2254 case EXIT_REASON_WRMSR:
2255 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2257 eax = vmxctx->guest_rax;
2258 ecx = vmxctx->guest_rcx;
2259 edx = vmxctx->guest_rdx;
2260 VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2261 ecx, (uint64_t)edx << 32 | eax);
2262 error = emulate_wrmsr(vmx, vcpu, ecx,
2263 (uint64_t)edx << 32 | eax, &retu);
2265 vmexit->exitcode = VM_EXITCODE_WRMSR;
2266 vmexit->u.msr.code = ecx;
2267 vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2271 /* Return to userspace with a valid exitcode */
2272 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2273 ("emulate_wrmsr retu with bogus exitcode"));
2276 case EXIT_REASON_HLT:
2277 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2278 vmexit->exitcode = VM_EXITCODE_HLT;
2279 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2281 case EXIT_REASON_MTF:
2282 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2283 vmexit->exitcode = VM_EXITCODE_MTRAP;
2284 vmexit->inst_length = 0;
2286 case EXIT_REASON_PAUSE:
2287 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2288 vmexit->exitcode = VM_EXITCODE_PAUSE;
2290 case EXIT_REASON_INTR_WINDOW:
2291 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2292 vmx_clear_int_window_exiting(vmx, vcpu);
2294 case EXIT_REASON_EXT_INTR:
2296 * External interrupts serve only to cause VM exits and allow
2297 * the host interrupt handler to run.
2299 * If this external interrupt triggers a virtual interrupt
2300 * to a VM, then that state will be recorded by the
2301 * host interrupt handler in the VM's softc. We will inject
2302 * this virtual interrupt during the subsequent VM enter.
2304 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2307 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2308 * This appears to be a bug in VMware Fusion?
2310 if (!(intr_info & VMCS_INTR_VALID))
2312 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2313 (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2314 ("VM exit interruption info invalid: %#x", intr_info));
2315 vmx_trigger_hostintr(intr_info & 0xff);
2318 * This is special. We want to treat this as an 'handled'
2319 * VM-exit but not increment the instruction pointer.
2321 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2323 case EXIT_REASON_NMI_WINDOW:
2324 /* Exit to allow the pending virtual NMI to be injected */
2325 if (vm_nmi_pending(vmx->vm, vcpu))
2326 vmx_inject_nmi(vmx, vcpu);
2327 vmx_clear_nmi_window_exiting(vmx, vcpu);
2328 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2330 case EXIT_REASON_INOUT:
2331 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2332 vmexit->exitcode = VM_EXITCODE_INOUT;
2333 vmexit->u.inout.bytes = (qual & 0x7) + 1;
2334 vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2335 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2336 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2337 vmexit->u.inout.port = (uint16_t)(qual >> 16);
2338 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2339 if (vmexit->u.inout.string) {
2340 inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2341 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2342 vis = &vmexit->u.inout_str;
2343 vmx_paging_info(&vis->paging);
2344 vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2345 vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2346 vis->index = inout_str_index(vmx, vcpu, in);
2347 vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2348 vis->addrsize = inout_str_addrsize(inst_info);
2349 inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2352 case EXIT_REASON_CPUID:
2353 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2354 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2356 case EXIT_REASON_EXCEPTION:
2357 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2358 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2359 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2360 ("VM exit interruption info invalid: %#x", intr_info));
2362 intr_vec = intr_info & 0xff;
2363 intr_type = intr_info & VMCS_INTR_T_MASK;
2366 * If Virtual NMIs control is 1 and the VM-exit is due to a
2367 * fault encountered during the execution of IRET then we must
2368 * restore the state of "virtual-NMI blocking" before resuming
2371 * See "Resuming Guest Software after Handling an Exception".
2372 * See "Information for VM Exits Due to Vectored Events".
2374 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2375 (intr_vec != IDT_DF) &&
2376 (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2377 vmx_restore_nmi_blocking(vmx, vcpu);
2380 * The NMI has already been handled in vmx_exit_handle_nmi().
2382 if (intr_type == VMCS_INTR_T_NMI)
2386 * Call the machine check handler by hand. Also don't reflect
2387 * the machine check back into the guest.
2389 if (intr_vec == IDT_MC) {
2390 VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2391 __asm __volatile("int $18");
2395 if (intr_vec == IDT_PF) {
2396 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2397 KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2402 * Software exceptions exhibit trap-like behavior. This in
2403 * turn requires populating the VM-entry instruction length
2404 * so that the %rip in the trap frame is past the INT3/INTO
2407 if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2408 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2410 /* Reflect all other exceptions back into the guest */
2411 errcode_valid = errcode = 0;
2412 if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2414 errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2416 VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2417 "the guest", intr_vec, errcode);
2418 error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2419 errcode_valid, errcode, 0);
2420 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2424 case EXIT_REASON_EPT_FAULT:
2426 * If 'gpa' lies within the address space allocated to
2427 * memory then this must be a nested page fault otherwise
2428 * this must be an instruction that accesses MMIO space.
2431 if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2432 apic_access_fault(vmx, vcpu, gpa)) {
2433 vmexit->exitcode = VM_EXITCODE_PAGING;
2434 vmexit->inst_length = 0;
2435 vmexit->u.paging.gpa = gpa;
2436 vmexit->u.paging.fault_type = ept_fault_type(qual);
2437 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2438 } else if (ept_emulation_fault(qual)) {
2439 vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2440 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2443 * If Virtual NMIs control is 1 and the VM-exit is due to an
2444 * EPT fault during the execution of IRET then we must restore
2445 * the state of "virtual-NMI blocking" before resuming.
2447 * See description of "NMI unblocking due to IRET" in
2448 * "Exit Qualification for EPT Violations".
2450 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2451 (qual & EXIT_QUAL_NMIUDTI) != 0)
2452 vmx_restore_nmi_blocking(vmx, vcpu);
2454 case EXIT_REASON_VIRTUALIZED_EOI:
2455 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2456 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2457 vmexit->inst_length = 0; /* trap-like */
2459 case EXIT_REASON_APIC_ACCESS:
2460 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2462 case EXIT_REASON_APIC_WRITE:
2464 * APIC-write VM exit is trap-like so the %rip is already
2465 * pointing to the next instruction.
2467 vmexit->inst_length = 0;
2468 vlapic = vm_lapic(vmx->vm, vcpu);
2469 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2471 case EXIT_REASON_XSETBV:
2472 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2474 case EXIT_REASON_MONITOR:
2475 vmexit->exitcode = VM_EXITCODE_MONITOR;
2477 case EXIT_REASON_MWAIT:
2478 vmexit->exitcode = VM_EXITCODE_MWAIT;
2481 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2487 * It is possible that control is returned to userland
2488 * even though we were able to handle the VM exit in the
2491 * In such a case we want to make sure that the userland
2492 * restarts guest execution at the instruction *after*
2493 * the one we just processed. Therefore we update the
2494 * guest rip in the VMCS and in 'vmexit'.
2496 vmexit->rip += vmexit->inst_length;
2497 vmexit->inst_length = 0;
2498 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2500 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2502 * If this VM exit was not claimed by anybody then
2503 * treat it as a generic VMX exit.
2505 vmexit->exitcode = VM_EXITCODE_VMX;
2506 vmexit->u.vmx.status = VM_SUCCESS;
2507 vmexit->u.vmx.inst_type = 0;
2508 vmexit->u.vmx.inst_error = 0;
2511 * The exitcode and collateral have been populated.
2512 * The VM exit will be processed further in userland.
2519 static __inline void
2520 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2523 KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2524 ("vmx_exit_inst_error: invalid inst_fail_status %d",
2525 vmxctx->inst_fail_status));
2527 vmexit->inst_length = 0;
2528 vmexit->exitcode = VM_EXITCODE_VMX;
2529 vmexit->u.vmx.status = vmxctx->inst_fail_status;
2530 vmexit->u.vmx.inst_error = vmcs_instruction_error();
2531 vmexit->u.vmx.exit_reason = ~0;
2532 vmexit->u.vmx.exit_qualification = ~0;
2535 case VMX_VMRESUME_ERROR:
2536 case VMX_VMLAUNCH_ERROR:
2537 case VMX_INVEPT_ERROR:
2538 vmexit->u.vmx.inst_type = rc;
2541 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2546 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2547 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2548 * sufficient to simply vector to the NMI handler via a software interrupt.
2549 * However, this must be done before maskable interrupts are enabled
2550 * otherwise the "iret" issued by an interrupt handler will incorrectly
2551 * clear NMI blocking.
2553 static __inline void
2554 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2558 KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2560 if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2563 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2564 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2565 ("VM exit interruption info invalid: %#x", intr_info));
2567 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2568 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2569 "to NMI has invalid vector: %#x", intr_info));
2570 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2571 __asm __volatile("int $2");
2576 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2577 struct vm_eventinfo *evinfo)
2579 int rc, handled, launched;
2582 struct vmxctx *vmxctx;
2584 struct vm_exit *vmexit;
2585 struct vlapic *vlapic;
2586 uint32_t exit_reason;
2590 vmcs = &vmx->vmcs[vcpu];
2591 vmxctx = &vmx->ctx[vcpu];
2592 vlapic = vm_lapic(vm, vcpu);
2593 vmexit = vm_exitinfo(vm, vcpu);
2596 KASSERT(vmxctx->pmap == pmap,
2597 ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2599 vmx_msr_guest_enter(vmx, vcpu);
2605 * We do this every time because we may setup the virtual machine
2606 * from a different process than the one that actually runs it.
2608 * If the life of a virtual machine was spent entirely in the context
2609 * of a single process we could do this once in vmx_vminit().
2611 vmcs_write(VMCS_HOST_CR3, rcr3());
2613 vmcs_write(VMCS_GUEST_RIP, rip);
2614 vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2616 KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2617 "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2619 handled = UNHANDLED;
2621 * Interrupts are disabled from this point on until the
2622 * guest starts executing. This is done for the following
2625 * If an AST is asserted on this thread after the check below,
2626 * then the IPI_AST notification will not be lost, because it
2627 * will cause a VM exit due to external interrupt as soon as
2628 * the guest state is loaded.
2630 * A posted interrupt after 'vmx_inject_interrupts()' will
2631 * not be "lost" because it will be held pending in the host
2632 * APIC because interrupts are disabled. The pending interrupt
2633 * will be recognized as soon as the guest state is loaded.
2635 * The same reasoning applies to the IPI generated by
2636 * pmap_invalidate_ept().
2639 vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2642 * Check for vcpu suspension after injecting events because
2643 * vmx_inject_interrupts() can suspend the vcpu due to a
2646 if (vcpu_suspended(evinfo)) {
2648 vm_exit_suspended(vmx->vm, vcpu, rip);
2652 if (vcpu_rendezvous_pending(evinfo)) {
2654 vm_exit_rendezvous(vmx->vm, vcpu, rip);
2658 if (vcpu_reqidle(evinfo)) {
2660 vm_exit_reqidle(vmx->vm, vcpu, rip);
2664 if (vcpu_should_yield(vm, vcpu)) {
2666 vm_exit_astpending(vmx->vm, vcpu, rip);
2667 vmx_astpending_trace(vmx, vcpu, rip);
2672 vmx_run_trace(vmx, vcpu);
2673 rc = vmx_enter_guest(vmxctx, vmx, launched);
2675 /* Collect some information for VM exit processing */
2676 vmexit->rip = rip = vmcs_guest_rip();
2677 vmexit->inst_length = vmexit_instruction_length();
2678 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2679 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2681 /* Update 'nextrip' */
2682 vmx->state[vcpu].nextrip = rip;
2684 if (rc == VMX_GUEST_VMEXIT) {
2685 vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2687 handled = vmx_exit_process(vmx, vcpu, vmexit);
2690 vmx_exit_inst_error(vmxctx, rc, vmexit);
2693 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2698 * If a VM exit has been handled then the exitcode must be BOGUS
2699 * If a VM exit is not handled then the exitcode must not be BOGUS
2701 if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2702 (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2703 panic("Mismatch between handled (%d) and exitcode (%d)",
2704 handled, vmexit->exitcode);
2708 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2710 VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2714 vmx_msr_guest_exit(vmx, vcpu);
2720 vmx_vmcleanup(void *arg)
2723 struct vmx *vmx = arg;
2725 if (apic_access_virtualization(vmx, 0))
2726 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2728 for (i = 0; i < VM_MAXCPU; i++)
2729 vpid_free(vmx->state[i].vpid);
2737 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2741 case VM_REG_GUEST_RAX:
2742 return (&vmxctx->guest_rax);
2743 case VM_REG_GUEST_RBX:
2744 return (&vmxctx->guest_rbx);
2745 case VM_REG_GUEST_RCX:
2746 return (&vmxctx->guest_rcx);
2747 case VM_REG_GUEST_RDX:
2748 return (&vmxctx->guest_rdx);
2749 case VM_REG_GUEST_RSI:
2750 return (&vmxctx->guest_rsi);
2751 case VM_REG_GUEST_RDI:
2752 return (&vmxctx->guest_rdi);
2753 case VM_REG_GUEST_RBP:
2754 return (&vmxctx->guest_rbp);
2755 case VM_REG_GUEST_R8:
2756 return (&vmxctx->guest_r8);
2757 case VM_REG_GUEST_R9:
2758 return (&vmxctx->guest_r9);
2759 case VM_REG_GUEST_R10:
2760 return (&vmxctx->guest_r10);
2761 case VM_REG_GUEST_R11:
2762 return (&vmxctx->guest_r11);
2763 case VM_REG_GUEST_R12:
2764 return (&vmxctx->guest_r12);
2765 case VM_REG_GUEST_R13:
2766 return (&vmxctx->guest_r13);
2767 case VM_REG_GUEST_R14:
2768 return (&vmxctx->guest_r14);
2769 case VM_REG_GUEST_R15:
2770 return (&vmxctx->guest_r15);
2771 case VM_REG_GUEST_CR2:
2772 return (&vmxctx->guest_cr2);
2780 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2784 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2792 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2796 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2804 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2809 error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2810 VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2811 *retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2816 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2823 * Forcing the vcpu into an interrupt shadow is not supported.
2830 vmcs = &vmx->vmcs[vcpu];
2831 ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2832 error = vmcs_getreg(vmcs, running, ident, &gi);
2834 gi &= ~HWINTR_BLOCKING;
2835 error = vmcs_setreg(vmcs, running, ident, gi);
2838 VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2839 error ? "failed" : "succeeded");
2844 vmx_shadow_reg(int reg)
2851 case VM_REG_GUEST_CR0:
2852 shreg = VMCS_CR0_SHADOW;
2854 case VM_REG_GUEST_CR4:
2855 shreg = VMCS_CR4_SHADOW;
2865 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2867 int running, hostcpu;
2868 struct vmx *vmx = arg;
2870 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2871 if (running && hostcpu != curcpu)
2872 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2874 if (reg == VM_REG_GUEST_INTR_SHADOW)
2875 return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2877 if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2880 return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2884 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2886 int error, hostcpu, running, shadow;
2889 struct vmx *vmx = arg;
2891 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2892 if (running && hostcpu != curcpu)
2893 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2895 if (reg == VM_REG_GUEST_INTR_SHADOW)
2896 return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2898 if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2901 error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2905 * If the "load EFER" VM-entry control is 1 then the
2906 * value of EFER.LMA must be identical to "IA-32e mode guest"
2907 * bit in the VM-entry control.
2909 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2910 (reg == VM_REG_GUEST_EFER)) {
2911 vmcs_getreg(&vmx->vmcs[vcpu], running,
2912 VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2914 ctls |= VM_ENTRY_GUEST_LMA;
2916 ctls &= ~VM_ENTRY_GUEST_LMA;
2917 vmcs_setreg(&vmx->vmcs[vcpu], running,
2918 VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2921 shadow = vmx_shadow_reg(reg);
2924 * Store the unmodified value in the shadow
2926 error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2927 VMCS_IDENT(shadow), val);
2930 if (reg == VM_REG_GUEST_CR3) {
2932 * Invalidate the guest vcpu's TLB mappings to emulate
2933 * the behavior of updating %cr3.
2935 * XXX the processor retains global mappings when %cr3
2936 * is updated but vmx_invvpid() does not.
2938 pmap = vmx->ctx[vcpu].pmap;
2939 vmx_invvpid(vmx, vcpu, pmap, running);
2947 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2949 int hostcpu, running;
2950 struct vmx *vmx = arg;
2952 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2953 if (running && hostcpu != curcpu)
2954 panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2956 return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2960 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2962 int hostcpu, running;
2963 struct vmx *vmx = arg;
2965 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2966 if (running && hostcpu != curcpu)
2967 panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2969 return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2973 vmx_getcap(void *arg, int vcpu, int type, int *retval)
2975 struct vmx *vmx = arg;
2981 vcap = vmx->cap[vcpu].set;
2984 case VM_CAP_HALT_EXIT:
2988 case VM_CAP_PAUSE_EXIT:
2992 case VM_CAP_MTRAP_EXIT:
2993 if (cap_monitor_trap)
2996 case VM_CAP_UNRESTRICTED_GUEST:
2997 if (cap_unrestricted_guest)
3000 case VM_CAP_ENABLE_INVPCID:
3009 *retval = (vcap & (1 << type)) ? 1 : 0;
3015 vmx_setcap(void *arg, int vcpu, int type, int val)
3017 struct vmx *vmx = arg;
3018 struct vmcs *vmcs = &vmx->vmcs[vcpu];
3030 case VM_CAP_HALT_EXIT:
3031 if (cap_halt_exit) {
3033 pptr = &vmx->cap[vcpu].proc_ctls;
3035 flag = PROCBASED_HLT_EXITING;
3036 reg = VMCS_PRI_PROC_BASED_CTLS;
3039 case VM_CAP_MTRAP_EXIT:
3040 if (cap_monitor_trap) {
3042 pptr = &vmx->cap[vcpu].proc_ctls;
3044 flag = PROCBASED_MTF;
3045 reg = VMCS_PRI_PROC_BASED_CTLS;
3048 case VM_CAP_PAUSE_EXIT:
3049 if (cap_pause_exit) {
3051 pptr = &vmx->cap[vcpu].proc_ctls;
3053 flag = PROCBASED_PAUSE_EXITING;
3054 reg = VMCS_PRI_PROC_BASED_CTLS;
3057 case VM_CAP_UNRESTRICTED_GUEST:
3058 if (cap_unrestricted_guest) {
3060 pptr = &vmx->cap[vcpu].proc_ctls2;
3062 flag = PROCBASED2_UNRESTRICTED_GUEST;
3063 reg = VMCS_SEC_PROC_BASED_CTLS;
3066 case VM_CAP_ENABLE_INVPCID:
3069 pptr = &vmx->cap[vcpu].proc_ctls2;
3071 flag = PROCBASED2_ENABLE_INVPCID;
3072 reg = VMCS_SEC_PROC_BASED_CTLS;
3086 error = vmwrite(reg, baseval);
3093 * Update optional stored flags, and record
3101 vmx->cap[vcpu].set |= (1 << type);
3103 vmx->cap[vcpu].set &= ~(1 << type);
3112 struct vlapic vlapic;
3113 struct pir_desc *pir_desc;
3117 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg) \
3119 VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d", \
3120 level ? "level" : "edge", vector); \
3121 VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]); \
3122 VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]); \
3123 VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]); \
3124 VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]); \
3125 VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3129 * vlapic->ops handlers that utilize the APICv hardware assist described in
3130 * Chapter 29 of the Intel SDM.
3133 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3135 struct vlapic_vtx *vlapic_vtx;
3136 struct pir_desc *pir_desc;
3140 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3141 pir_desc = vlapic_vtx->pir_desc;
3144 * Keep track of interrupt requests in the PIR descriptor. This is
3145 * because the virtual APIC page pointed to by the VMCS cannot be
3146 * modified if the vcpu is running.
3149 mask = 1UL << (vector % 64);
3150 atomic_set_long(&pir_desc->pir[idx], mask);
3151 notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3153 VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3154 level, "vmx_set_intr_ready");
3159 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3161 struct vlapic_vtx *vlapic_vtx;
3162 struct pir_desc *pir_desc;
3163 struct LAPIC *lapic;
3164 uint64_t pending, pirval;
3169 * This function is only expected to be called from the 'HLT' exit
3170 * handler which does not care about the vector that is pending.
3172 KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3174 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3175 pir_desc = vlapic_vtx->pir_desc;
3177 pending = atomic_load_acq_long(&pir_desc->pending);
3180 * While a virtual interrupt may have already been
3181 * processed the actual delivery maybe pending the
3182 * interruptibility of the guest. Recognize a pending
3183 * interrupt by reevaluating virtual interrupts
3184 * following Section 29.2.1 in the Intel SDM Volume 3.
3189 vmx_getreg(vlapic_vtx->vmx, vlapic->vcpuid,
3190 VMCS_IDENT(VMCS_GUEST_INTR_STATUS), &val);
3191 rvi = val & APIC_TPR_INT;
3192 lapic = vlapic->apic_page;
3193 ppr = lapic->ppr & APIC_TPR_INT;
3202 * If there is an interrupt pending then it will be recognized only
3203 * if its priority is greater than the processor priority.
3205 * Special case: if the processor priority is zero then any pending
3206 * interrupt will be recognized.
3208 lapic = vlapic->apic_page;
3209 ppr = lapic->ppr & APIC_TPR_INT;
3213 VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3216 for (i = 3; i >= 0; i--) {
3217 pirval = pir_desc->pir[i];
3219 vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3227 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3230 panic("vmx_intr_accepted: not expected to be called");
3234 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3236 struct vlapic_vtx *vlapic_vtx;
3241 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3242 KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3243 ("vmx_set_tmr: vcpu cannot be running"));
3245 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3246 vmx = vlapic_vtx->vmx;
3247 vmcs = &vmx->vmcs[vlapic->vcpuid];
3248 mask = 1UL << (vector % 64);
3251 val = vmcs_read(VMCS_EOI_EXIT(vector));
3256 vmcs_write(VMCS_EOI_EXIT(vector), val);
3261 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3265 uint32_t proc_ctls2;
3268 vcpuid = vlapic->vcpuid;
3269 vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3270 vmcs = &vmx->vmcs[vcpuid];
3272 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3273 KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3274 ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3276 proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3277 proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3278 vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3281 vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3284 if (vlapic->vcpuid == 0) {
3286 * The nested page table mappings are shared by all vcpus
3287 * so unmap the APIC access page just once.
3289 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3290 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3294 * The MSR bitmap is shared by all vcpus so modify it only
3295 * once in the context of vcpu 0.
3297 error = vmx_allow_x2apic_msrs(vmx);
3298 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3304 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3307 ipi_cpu(hostcpu, pirvec);
3311 * Transfer the pending interrupts in the PIR descriptor to the IRR
3312 * in the virtual APIC page.
3315 vmx_inject_pir(struct vlapic *vlapic)
3317 struct vlapic_vtx *vlapic_vtx;
3318 struct pir_desc *pir_desc;
3319 struct LAPIC *lapic;
3320 uint64_t val, pirval;
3321 int rvi, pirbase = -1;
3322 uint16_t intr_status_old, intr_status_new;
3324 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3325 pir_desc = vlapic_vtx->pir_desc;
3326 if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3327 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3328 "no posted interrupt pending");
3334 lapic = vlapic->apic_page;
3336 val = atomic_readandclear_long(&pir_desc->pir[0]);
3339 lapic->irr1 |= val >> 32;
3344 val = atomic_readandclear_long(&pir_desc->pir[1]);
3347 lapic->irr3 |= val >> 32;
3352 val = atomic_readandclear_long(&pir_desc->pir[2]);
3355 lapic->irr5 |= val >> 32;
3360 val = atomic_readandclear_long(&pir_desc->pir[3]);
3363 lapic->irr7 |= val >> 32;
3368 VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3371 * Update RVI so the processor can evaluate pending virtual
3372 * interrupts on VM-entry.
3374 * It is possible for pirval to be 0 here, even though the
3375 * pending bit has been set. The scenario is:
3376 * CPU-Y is sending a posted interrupt to CPU-X, which
3377 * is running a guest and processing posted interrupts in h/w.
3378 * CPU-X will eventually exit and the state seen in s/w is
3379 * the pending bit set, but no PIR bits set.
3382 * (vm running) (host running)
3383 * rx posted interrupt
3386 * READ/CLEAR PIR bits
3389 * pending bit set, PIR 0
3392 rvi = pirbase + flsl(pirval) - 1;
3393 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3394 intr_status_new = (intr_status_old & 0xFF00) | rvi;
3395 if (intr_status_new > intr_status_old) {
3396 vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3397 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3398 "guest_intr_status changed from 0x%04x to 0x%04x",
3399 intr_status_old, intr_status_new);
3404 static struct vlapic *
3405 vmx_vlapic_init(void *arg, int vcpuid)
3408 struct vlapic *vlapic;
3409 struct vlapic_vtx *vlapic_vtx;
3413 vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3414 vlapic->vm = vmx->vm;
3415 vlapic->vcpuid = vcpuid;
3416 vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3418 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3419 vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3420 vlapic_vtx->vmx = vmx;
3422 if (virtual_interrupt_delivery) {
3423 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3424 vlapic->ops.pending_intr = vmx_pending_intr;
3425 vlapic->ops.intr_accepted = vmx_intr_accepted;
3426 vlapic->ops.set_tmr = vmx_set_tmr;
3427 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3430 if (posted_interrupts)
3431 vlapic->ops.post_intr = vmx_post_intr;
3433 vlapic_init(vlapic);
3439 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3442 vlapic_cleanup(vlapic);
3443 free(vlapic, M_VLAPIC);
3446 struct vmm_ops vmm_ops_intel = {