2 * Copyright (c) 2011 NetApp, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
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/psl.h>
45 #include <machine/cpufunc.h>
46 #include <machine/md_var.h>
47 #include <machine/segments.h>
48 #include <machine/smp.h>
49 #include <machine/specialreg.h>
50 #include <machine/vmparam.h>
52 #include <machine/vmm.h>
53 #include <machine/vmm_dev.h>
55 #include "vmm_ioport.h"
62 #include "vlapic_priv.h"
66 #include "vmx_cpufunc.h"
69 #include "vmx_controls.h"
71 #define PINBASED_CTLS_ONE_SETTING \
72 (PINBASED_EXTINT_EXITING | \
73 PINBASED_NMI_EXITING | \
75 #define PINBASED_CTLS_ZERO_SETTING 0
77 #define PROCBASED_CTLS_WINDOW_SETTING \
78 (PROCBASED_INT_WINDOW_EXITING | \
79 PROCBASED_NMI_WINDOW_EXITING)
81 #define PROCBASED_CTLS_ONE_SETTING \
82 (PROCBASED_SECONDARY_CONTROLS | \
83 PROCBASED_IO_EXITING | \
84 PROCBASED_MSR_BITMAPS | \
85 PROCBASED_CTLS_WINDOW_SETTING)
86 #define PROCBASED_CTLS_ZERO_SETTING \
87 (PROCBASED_CR3_LOAD_EXITING | \
88 PROCBASED_CR3_STORE_EXITING | \
91 #define PROCBASED_CTLS2_ONE_SETTING PROCBASED2_ENABLE_EPT
92 #define PROCBASED_CTLS2_ZERO_SETTING 0
94 #define VM_EXIT_CTLS_ONE_SETTING_NO_PAT \
99 #define VM_EXIT_CTLS_ONE_SETTING \
100 (VM_EXIT_CTLS_ONE_SETTING_NO_PAT | \
101 VM_EXIT_ACKNOWLEDGE_INTERRUPT | \
104 #define VM_EXIT_CTLS_ZERO_SETTING VM_EXIT_SAVE_DEBUG_CONTROLS
106 #define VM_ENTRY_CTLS_ONE_SETTING_NO_PAT VM_ENTRY_LOAD_EFER
108 #define VM_ENTRY_CTLS_ONE_SETTING \
109 (VM_ENTRY_CTLS_ONE_SETTING_NO_PAT | \
111 #define VM_ENTRY_CTLS_ZERO_SETTING \
112 (VM_ENTRY_LOAD_DEBUG_CONTROLS | \
113 VM_ENTRY_INTO_SMM | \
114 VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
116 #define guest_msr_rw(vmx, msr) \
117 msr_bitmap_change_access((vmx)->msr_bitmap, (msr), MSR_BITMAP_ACCESS_RW)
119 #define guest_msr_ro(vmx, msr) \
120 msr_bitmap_change_access((vmx)->msr_bitmap, (msr), MSR_BITMAP_ACCESS_READ)
125 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
126 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
128 SYSCTL_DECL(_hw_vmm);
129 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
131 int vmxon_enabled[MAXCPU];
132 static char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
134 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
135 static uint32_t exit_ctls, entry_ctls;
137 static uint64_t cr0_ones_mask, cr0_zeros_mask;
138 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
139 &cr0_ones_mask, 0, NULL);
140 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
141 &cr0_zeros_mask, 0, NULL);
143 static uint64_t cr4_ones_mask, cr4_zeros_mask;
144 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
145 &cr4_ones_mask, 0, NULL);
146 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
147 &cr4_zeros_mask, 0, NULL);
149 static int vmx_no_patmsr;
151 static int vmx_initialized;
152 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
153 &vmx_initialized, 0, "Intel VMX initialized");
156 * Optional capabilities
158 static int cap_halt_exit;
159 static int cap_pause_exit;
160 static int cap_unrestricted_guest;
161 static int cap_monitor_trap;
162 static int cap_invpcid;
164 static int virtual_interrupt_delivery;
165 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
166 &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
168 static int posted_interrupts;
169 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupts, CTLFLAG_RD,
170 &posted_interrupts, 0, "APICv posted interrupt support");
173 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
174 &pirvec, 0, "APICv posted interrupt vector");
176 static struct unrhdr *vpid_unr;
177 static u_int vpid_alloc_failed;
178 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
179 &vpid_alloc_failed, 0, NULL);
182 * Use the last page below 4GB as the APIC access address. This address is
183 * occupied by the boot firmware so it is guaranteed that it will not conflict
184 * with a page in system memory.
186 #define APIC_ACCESS_ADDRESS 0xFFFFF000
188 static void vmx_inject_pir(struct vlapic *vlapic);
192 exit_reason_to_str(int reason)
194 static char reasonbuf[32];
197 case EXIT_REASON_EXCEPTION:
199 case EXIT_REASON_EXT_INTR:
201 case EXIT_REASON_TRIPLE_FAULT:
202 return "triplefault";
203 case EXIT_REASON_INIT:
205 case EXIT_REASON_SIPI:
207 case EXIT_REASON_IO_SMI:
209 case EXIT_REASON_SMI:
211 case EXIT_REASON_INTR_WINDOW:
213 case EXIT_REASON_NMI_WINDOW:
215 case EXIT_REASON_TASK_SWITCH:
217 case EXIT_REASON_CPUID:
219 case EXIT_REASON_GETSEC:
221 case EXIT_REASON_HLT:
223 case EXIT_REASON_INVD:
225 case EXIT_REASON_INVLPG:
227 case EXIT_REASON_RDPMC:
229 case EXIT_REASON_RDTSC:
231 case EXIT_REASON_RSM:
233 case EXIT_REASON_VMCALL:
235 case EXIT_REASON_VMCLEAR:
237 case EXIT_REASON_VMLAUNCH:
239 case EXIT_REASON_VMPTRLD:
241 case EXIT_REASON_VMPTRST:
243 case EXIT_REASON_VMREAD:
245 case EXIT_REASON_VMRESUME:
247 case EXIT_REASON_VMWRITE:
249 case EXIT_REASON_VMXOFF:
251 case EXIT_REASON_VMXON:
253 case EXIT_REASON_CR_ACCESS:
255 case EXIT_REASON_DR_ACCESS:
257 case EXIT_REASON_INOUT:
259 case EXIT_REASON_RDMSR:
261 case EXIT_REASON_WRMSR:
263 case EXIT_REASON_INVAL_VMCS:
265 case EXIT_REASON_INVAL_MSR:
267 case EXIT_REASON_MWAIT:
269 case EXIT_REASON_MTF:
271 case EXIT_REASON_MONITOR:
273 case EXIT_REASON_PAUSE:
275 case EXIT_REASON_MCE:
277 case EXIT_REASON_TPR:
279 case EXIT_REASON_APIC_ACCESS:
280 return "apic-access";
281 case EXIT_REASON_GDTR_IDTR:
283 case EXIT_REASON_LDTR_TR:
285 case EXIT_REASON_EPT_FAULT:
287 case EXIT_REASON_EPT_MISCONFIG:
288 return "eptmisconfig";
289 case EXIT_REASON_INVEPT:
291 case EXIT_REASON_RDTSCP:
293 case EXIT_REASON_VMX_PREEMPT:
295 case EXIT_REASON_INVVPID:
297 case EXIT_REASON_WBINVD:
299 case EXIT_REASON_XSETBV:
301 case EXIT_REASON_APIC_WRITE:
304 snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
311 vmx_allow_x2apic_msrs(struct vmx *vmx)
318 * Allow readonly access to the following x2APIC MSRs from the guest.
320 error += guest_msr_ro(vmx, MSR_APIC_ID);
321 error += guest_msr_ro(vmx, MSR_APIC_VERSION);
322 error += guest_msr_ro(vmx, MSR_APIC_LDR);
323 error += guest_msr_ro(vmx, MSR_APIC_SVR);
325 for (i = 0; i < 8; i++)
326 error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
328 for (i = 0; i < 8; i++)
329 error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
331 for (i = 0; i < 8; i++)
332 error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
334 error += guest_msr_ro(vmx, MSR_APIC_ESR);
335 error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
336 error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
337 error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
338 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
339 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
340 error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
341 error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
342 error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
343 error += guest_msr_ro(vmx, MSR_APIC_ICR);
346 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
348 * These registers get special treatment described in the section
349 * "Virtualizing MSR-Based APIC Accesses".
351 error += guest_msr_rw(vmx, MSR_APIC_TPR);
352 error += guest_msr_rw(vmx, MSR_APIC_EOI);
353 error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
359 vmx_fix_cr0(u_long cr0)
362 return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
366 vmx_fix_cr4(u_long cr4)
369 return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
375 if (vpid < 0 || vpid > 0xffff)
376 panic("vpid_free: invalid vpid %d", vpid);
379 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
380 * the unit number allocator.
383 if (vpid > VM_MAXCPU)
384 free_unr(vpid_unr, vpid);
388 vpid_alloc(uint16_t *vpid, int num)
392 if (num <= 0 || num > VM_MAXCPU)
393 panic("invalid number of vpids requested: %d", num);
396 * If the "enable vpid" execution control is not enabled then the
397 * VPID is required to be 0 for all vcpus.
399 if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
400 for (i = 0; i < num; i++)
406 * Allocate a unique VPID for each vcpu from the unit number allocator.
408 for (i = 0; i < num; i++) {
409 x = alloc_unr(vpid_unr);
417 atomic_add_int(&vpid_alloc_failed, 1);
420 * If the unit number allocator does not have enough unique
421 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
423 * These VPIDs are not be unique across VMs but this does not
424 * affect correctness because the combined mappings are also
425 * tagged with the EP4TA which is unique for each VM.
427 * It is still sub-optimal because the invvpid will invalidate
428 * combined mappings for a particular VPID across all EP4TAs.
433 for (i = 0; i < num; i++)
442 * VPID 0 is required when the "enable VPID" execution control is
445 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
446 * unit number allocator does not have sufficient unique VPIDs to
447 * satisfy the allocation.
449 * The remaining VPIDs are managed by the unit number allocator.
451 vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
455 msr_save_area_init(struct msr_entry *g_area, int *g_count)
459 static struct msr_entry guest_msrs[] = {
460 { MSR_KGSBASE, 0, 0 },
463 cnt = sizeof(guest_msrs) / sizeof(guest_msrs[0]);
464 if (cnt > GUEST_MSR_MAX_ENTRIES)
465 panic("guest msr save area overrun");
466 bcopy(guest_msrs, g_area, sizeof(guest_msrs));
471 vmx_disable(void *arg __unused)
473 struct invvpid_desc invvpid_desc = { 0 };
474 struct invept_desc invept_desc = { 0 };
476 if (vmxon_enabled[curcpu]) {
478 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
480 * VMXON or VMXOFF are not required to invalidate any TLB
481 * caching structures. This prevents potential retention of
482 * cached information in the TLB between distinct VMX episodes.
484 invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
485 invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
488 load_cr4(rcr4() & ~CR4_VMXE);
496 vmm_ipi_free(pirvec);
498 if (vpid_unr != NULL) {
499 delete_unrhdr(vpid_unr);
503 smp_rendezvous(NULL, vmx_disable, NULL, NULL);
509 vmx_enable(void *arg __unused)
513 load_cr4(rcr4() | CR4_VMXE);
515 *(uint32_t *)vmxon_region[curcpu] = vmx_revision();
516 error = vmxon(vmxon_region[curcpu]);
518 vmxon_enabled[curcpu] = 1;
525 if (vmxon_enabled[curcpu])
526 vmxon(vmxon_region[curcpu]);
532 int error, use_tpr_shadow;
533 uint64_t fixed0, fixed1, feature_control;
534 uint32_t tmp, procbased2_vid_bits;
536 /* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
537 if (!(cpu_feature2 & CPUID2_VMX)) {
538 printf("vmx_init: processor does not support VMX operation\n");
543 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
544 * are set (bits 0 and 2 respectively).
546 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
547 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
548 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
549 printf("vmx_init: VMX operation disabled by BIOS\n");
553 /* Check support for primary processor-based VM-execution controls */
554 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
555 MSR_VMX_TRUE_PROCBASED_CTLS,
556 PROCBASED_CTLS_ONE_SETTING,
557 PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
559 printf("vmx_init: processor does not support desired primary "
560 "processor-based controls\n");
564 /* Clear the processor-based ctl bits that are set on demand */
565 procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
567 /* Check support for secondary processor-based VM-execution controls */
568 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
569 MSR_VMX_PROCBASED_CTLS2,
570 PROCBASED_CTLS2_ONE_SETTING,
571 PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
573 printf("vmx_init: processor does not support desired secondary "
574 "processor-based controls\n");
578 /* Check support for VPID */
579 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
580 PROCBASED2_ENABLE_VPID, 0, &tmp);
582 procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
584 /* Check support for pin-based VM-execution controls */
585 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
586 MSR_VMX_TRUE_PINBASED_CTLS,
587 PINBASED_CTLS_ONE_SETTING,
588 PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
590 printf("vmx_init: processor does not support desired "
591 "pin-based controls\n");
595 /* Check support for VM-exit controls */
596 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
597 VM_EXIT_CTLS_ONE_SETTING,
598 VM_EXIT_CTLS_ZERO_SETTING,
601 /* Try again without the PAT MSR bits */
602 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS,
603 MSR_VMX_TRUE_EXIT_CTLS,
604 VM_EXIT_CTLS_ONE_SETTING_NO_PAT,
605 VM_EXIT_CTLS_ZERO_SETTING,
608 printf("vmx_init: processor does not support desired "
613 printf("vmm: PAT MSR access not supported\n");
614 guest_msr_valid(MSR_PAT);
619 /* Check support for VM-entry controls */
620 if (!vmx_no_patmsr) {
621 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS,
622 MSR_VMX_TRUE_ENTRY_CTLS,
623 VM_ENTRY_CTLS_ONE_SETTING,
624 VM_ENTRY_CTLS_ZERO_SETTING,
627 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS,
628 MSR_VMX_TRUE_ENTRY_CTLS,
629 VM_ENTRY_CTLS_ONE_SETTING_NO_PAT,
630 VM_ENTRY_CTLS_ZERO_SETTING,
635 printf("vmx_init: processor does not support desired "
641 * Check support for optional features by testing them
644 cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
645 MSR_VMX_TRUE_PROCBASED_CTLS,
646 PROCBASED_HLT_EXITING, 0,
649 cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
650 MSR_VMX_PROCBASED_CTLS,
654 cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
655 MSR_VMX_TRUE_PROCBASED_CTLS,
656 PROCBASED_PAUSE_EXITING, 0,
659 cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
660 MSR_VMX_PROCBASED_CTLS2,
661 PROCBASED2_UNRESTRICTED_GUEST, 0,
664 cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
665 MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
669 * Check support for virtual interrupt delivery.
671 procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
672 PROCBASED2_VIRTUALIZE_X2APIC_MODE |
673 PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
674 PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
676 use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
677 MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
680 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
681 procbased2_vid_bits, 0, &tmp);
682 if (error == 0 && use_tpr_shadow) {
683 virtual_interrupt_delivery = 1;
684 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
685 &virtual_interrupt_delivery);
688 if (virtual_interrupt_delivery) {
689 procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
690 procbased_ctls2 |= procbased2_vid_bits;
691 procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
694 * Check for Posted Interrupts only if Virtual Interrupt
695 * Delivery is enabled.
697 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
698 MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
701 pirvec = vmm_ipi_alloc();
704 printf("vmx_init: unable to allocate "
705 "posted interrupt vector\n");
708 posted_interrupts = 1;
709 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
715 if (posted_interrupts)
716 pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
719 error = ept_init(ipinum);
721 printf("vmx_init: ept initialization failed (%d)\n", error);
726 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
728 fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
729 fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
730 cr0_ones_mask = fixed0 & fixed1;
731 cr0_zeros_mask = ~fixed0 & ~fixed1;
734 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
735 * if unrestricted guest execution is allowed.
737 if (cap_unrestricted_guest)
738 cr0_ones_mask &= ~(CR0_PG | CR0_PE);
741 * Do not allow the guest to set CR0_NW or CR0_CD.
743 cr0_zeros_mask |= (CR0_NW | CR0_CD);
745 fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
746 fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
747 cr4_ones_mask = fixed0 & fixed1;
748 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];
821 int i, error, guest_msr_count;
825 vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
826 if ((uintptr_t)vmx & PAGE_MASK) {
827 panic("malloc of struct vmx not aligned on %d byte boundary",
832 vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
835 * Clean up EPTP-tagged guest physical and combined mappings
837 * VMX transitions are not required to invalidate any guest physical
838 * mappings. So, it may be possible for stale guest physical mappings
839 * to be present in the processor TLBs.
841 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
843 ept_invalidate_mappings(vmx->eptp);
845 msr_bitmap_initialize(vmx->msr_bitmap);
848 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
849 * The guest FSBASE and GSBASE are saved and restored during
850 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
851 * always restored from the vmcs host state area on vm-exit.
853 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
854 * how they are saved/restored so can be directly accessed by the
857 * Guest KGSBASE is saved and restored in the guest MSR save area.
858 * Host KGSBASE is restored before returning to userland from the pcb.
859 * There will be a window of time when we are executing in the host
860 * kernel context with a value of KGSBASE from the guest. This is ok
861 * because the value of KGSBASE is inconsequential in kernel context.
863 * MSR_EFER is saved and restored in the guest VMCS area on a
864 * VM exit and entry respectively. It is also restored from the
865 * host VMCS area on a VM exit.
867 if (guest_msr_rw(vmx, MSR_GSBASE) ||
868 guest_msr_rw(vmx, MSR_FSBASE) ||
869 guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
870 guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
871 guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
872 guest_msr_rw(vmx, MSR_KGSBASE) ||
873 guest_msr_rw(vmx, MSR_EFER))
874 panic("vmx_vminit: error setting guest msr access");
877 * MSR_PAT is saved and restored in the guest VMCS are on a VM exit
878 * and entry respectively. It is also restored from the host VMCS
879 * area on a VM exit. However, if running on a system with no
880 * MSR_PAT save/restore support, leave access disabled so accesses
883 if (!vmx_no_patmsr && guest_msr_rw(vmx, MSR_PAT))
884 panic("vmx_vminit: error setting guest pat msr access");
886 vpid_alloc(vpid, VM_MAXCPU);
888 if (virtual_interrupt_delivery) {
889 error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
890 APIC_ACCESS_ADDRESS);
891 /* XXX this should really return an error to the caller */
892 KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
895 for (i = 0; i < VM_MAXCPU; i++) {
896 vmcs = &vmx->vmcs[i];
897 vmcs->identifier = vmx_revision();
898 error = vmclear(vmcs);
900 panic("vmx_vminit: vmclear error %d on vcpu %d\n",
904 error = vmcs_init(vmcs);
905 KASSERT(error == 0, ("vmcs_init error %d", error));
909 error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
910 error += vmwrite(VMCS_EPTP, vmx->eptp);
911 error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
912 error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
913 error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
914 error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
915 error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
916 error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
917 error += vmwrite(VMCS_VPID, vpid[i]);
918 if (virtual_interrupt_delivery) {
919 error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
920 error += vmwrite(VMCS_VIRTUAL_APIC,
921 vtophys(&vmx->apic_page[i]));
922 error += vmwrite(VMCS_EOI_EXIT0, 0);
923 error += vmwrite(VMCS_EOI_EXIT1, 0);
924 error += vmwrite(VMCS_EOI_EXIT2, 0);
925 error += vmwrite(VMCS_EOI_EXIT3, 0);
927 if (posted_interrupts) {
928 error += vmwrite(VMCS_PIR_VECTOR, pirvec);
929 error += vmwrite(VMCS_PIR_DESC,
930 vtophys(&vmx->pir_desc[i]));
933 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
936 vmx->cap[i].proc_ctls = procbased_ctls;
937 vmx->cap[i].proc_ctls2 = procbased_ctls2;
939 vmx->state[i].lastcpu = -1;
940 vmx->state[i].vpid = vpid[i];
942 msr_save_area_init(vmx->guest_msrs[i], &guest_msr_count);
944 error = vmcs_set_msr_save(vmcs, vtophys(vmx->guest_msrs[i]),
947 panic("vmcs_set_msr_save error %d", error);
950 * Set up the CR0/4 shadows, and init the read shadow
951 * to the power-on register value from the Intel Sys Arch.
955 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
957 panic("vmx_setup_cr0_shadow %d", error);
959 error = vmx_setup_cr4_shadow(vmcs, 0);
961 panic("vmx_setup_cr4_shadow %d", error);
963 vmx->ctx[i].pmap = pmap;
970 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
974 func = vmxctx->guest_rax;
976 handled = x86_emulate_cpuid(vm, vcpu,
977 (uint32_t*)(&vmxctx->guest_rax),
978 (uint32_t*)(&vmxctx->guest_rbx),
979 (uint32_t*)(&vmxctx->guest_rcx),
980 (uint32_t*)(&vmxctx->guest_rdx));
985 vmx_run_trace(struct vmx *vmx, int vcpu)
988 VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
993 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
997 VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
998 handled ? "handled" : "unhandled",
999 exit_reason_to_str(exit_reason), rip);
1003 static __inline void
1004 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1007 VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1011 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1014 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1016 struct vmxstate *vmxstate;
1017 struct invvpid_desc invvpid_desc;
1019 vmxstate = &vmx->state[vcpu];
1020 if (vmxstate->lastcpu == curcpu)
1023 vmxstate->lastcpu = curcpu;
1025 vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1027 vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1028 vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1029 vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1032 * If we are using VPIDs then invalidate all mappings tagged with 'vpid'
1034 * We do this because this vcpu was executing on a different host
1035 * cpu when it last ran. We do not track whether it invalidated
1036 * mappings associated with its 'vpid' during that run. So we must
1037 * assume that the mappings associated with 'vpid' on 'curcpu' are
1038 * stale and invalidate them.
1040 * Note that we incur this penalty only when the scheduler chooses to
1041 * move the thread associated with this vcpu between host cpus.
1043 * Note also that this will invalidate mappings tagged with 'vpid'
1046 if (vmxstate->vpid != 0) {
1047 if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1048 invvpid_desc._res1 = 0;
1049 invvpid_desc._res2 = 0;
1050 invvpid_desc.vpid = vmxstate->vpid;
1051 invvpid_desc.linear_addr = 0;
1052 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1055 * The invvpid can be skipped if an invept is going to
1056 * be performed before entering the guest. The invept
1057 * will invalidate combined mappings tagged with
1058 * 'vmx->eptp' for all vpids.
1060 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1066 * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1068 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1070 static void __inline
1071 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1074 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1075 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1076 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1077 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1081 static void __inline
1082 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1085 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1086 ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1087 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1088 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1089 VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1092 static void __inline
1093 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1096 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1097 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1098 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1099 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1103 static void __inline
1104 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1107 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1108 ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1109 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1110 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1111 VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1114 #define NMI_BLOCKING (VMCS_INTERRUPTIBILITY_NMI_BLOCKING | \
1115 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1116 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING | \
1117 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1120 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1124 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1125 KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1126 "interruptibility-state %#x", gi));
1128 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1129 KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1130 "VM-entry interruption information %#x", info));
1133 * Inject the virtual NMI. The vector must be the NMI IDT entry
1134 * or the VMCS entry check will fail.
1136 info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1137 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1139 VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1141 /* Clear the request */
1142 vm_nmi_clear(vmx->vm, vcpu);
1146 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic)
1148 struct vm_exception exc;
1149 int vector, need_nmi_exiting, extint_pending;
1153 if (vm_exception_pending(vmx->vm, vcpu, &exc)) {
1154 KASSERT(exc.vector >= 0 && exc.vector < 32,
1155 ("%s: invalid exception vector %d", __func__, exc.vector));
1157 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1158 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1159 "pending exception %d: %#x", __func__, exc.vector, info));
1161 info = exc.vector | VMCS_INTR_T_HWEXCEPTION | VMCS_INTR_VALID;
1162 if (exc.error_code_valid) {
1163 info |= VMCS_INTR_DEL_ERRCODE;
1164 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, exc.error_code);
1166 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1169 if (vm_nmi_pending(vmx->vm, vcpu)) {
1171 * If there are no conditions blocking NMI injection then
1172 * inject it directly here otherwise enable "NMI window
1173 * exiting" to inject it as soon as we can.
1175 * We also check for STI_BLOCKING because some implementations
1176 * don't allow NMI injection in this case. If we are running
1177 * on a processor that doesn't have this restriction it will
1178 * immediately exit and the NMI will be injected in the
1179 * "NMI window exiting" handler.
1181 need_nmi_exiting = 1;
1182 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1183 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1184 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1185 if ((info & VMCS_INTR_VALID) == 0) {
1186 vmx_inject_nmi(vmx, vcpu);
1187 need_nmi_exiting = 0;
1189 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1190 "due to VM-entry intr info %#x", info);
1193 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1194 "Guest Interruptibility-state %#x", gi);
1197 if (need_nmi_exiting)
1198 vmx_set_nmi_window_exiting(vmx, vcpu);
1201 extint_pending = vm_extint_pending(vmx->vm, vcpu);
1203 if (!extint_pending && virtual_interrupt_delivery) {
1204 vmx_inject_pir(vlapic);
1209 * If interrupt-window exiting is already in effect then don't bother
1210 * checking for pending interrupts. This is just an optimization and
1211 * not needed for correctness.
1213 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1214 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1215 "pending int_window_exiting");
1219 if (!extint_pending) {
1220 /* Ask the local apic for a vector to inject */
1221 if (!vlapic_pending_intr(vlapic, &vector))
1225 * From the Intel SDM, Volume 3, Section "Maskable
1226 * Hardware Interrupts":
1227 * - maskable interrupt vectors [16,255] can be delivered
1228 * through the local APIC.
1230 KASSERT(vector >= 16 && vector <= 255,
1231 ("invalid vector %d from local APIC", vector));
1233 /* Ask the legacy pic for a vector to inject */
1234 vatpic_pending_intr(vmx->vm, &vector);
1237 * From the Intel SDM, Volume 3, Section "Maskable
1238 * Hardware Interrupts":
1239 * - maskable interrupt vectors [0,255] can be delivered
1240 * through the INTR pin.
1242 KASSERT(vector >= 0 && vector <= 255,
1243 ("invalid vector %d from INTR", vector));
1246 /* Check RFLAGS.IF and the interruptibility state of the guest */
1247 rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1248 if ((rflags & PSL_I) == 0) {
1249 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1250 "rflags %#lx", vector, rflags);
1254 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1255 if (gi & HWINTR_BLOCKING) {
1256 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1257 "Guest Interruptibility-state %#x", vector, gi);
1261 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1262 if (info & VMCS_INTR_VALID) {
1264 * This is expected and could happen for multiple reasons:
1265 * - A vectoring VM-entry was aborted due to astpending
1266 * - A VM-exit happened during event injection.
1267 * - An exception was injected above.
1268 * - An NMI was injected above or after "NMI window exiting"
1270 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1271 "VM-entry intr info %#x", vector, info);
1275 /* Inject the interrupt */
1276 info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1278 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1280 if (!extint_pending) {
1281 /* Update the Local APIC ISR */
1282 vlapic_intr_accepted(vlapic, vector);
1284 vm_extint_clear(vmx->vm, vcpu);
1285 vatpic_intr_accepted(vmx->vm, vector);
1288 * After we accepted the current ExtINT the PIC may
1289 * have posted another one. If that is the case, set
1290 * the Interrupt Window Exiting execution control so
1291 * we can inject that one too.
1293 if (vm_extint_pending(vmx->vm, vcpu))
1294 vmx_set_int_window_exiting(vmx, vcpu);
1297 VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1303 * Set the Interrupt Window Exiting execution control so we can inject
1304 * the interrupt as soon as blocking condition goes away.
1306 vmx_set_int_window_exiting(vmx, vcpu);
1310 * If the Virtual NMIs execution control is '1' then the logical processor
1311 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1312 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1313 * virtual-NMI blocking.
1315 * This unblocking occurs even if the IRET causes a fault. In this case the
1316 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1319 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1323 VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1324 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1325 gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1326 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1330 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1334 VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1335 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1336 gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1337 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1341 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1343 struct vmxctx *vmxctx;
1345 const struct xsave_limits *limits;
1347 vmxctx = &vmx->ctx[vcpu];
1348 limits = vmm_get_xsave_limits();
1351 * Note that the processor raises a GP# fault on its own if
1352 * xsetbv is executed for CPL != 0, so we do not have to
1353 * emulate that fault here.
1356 /* Only xcr0 is supported. */
1357 if (vmxctx->guest_rcx != 0) {
1358 vm_inject_gp(vmx->vm, vcpu);
1362 /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1363 if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1364 vm_inject_ud(vmx->vm, vcpu);
1368 xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1369 if ((xcrval & ~limits->xcr0_allowed) != 0) {
1370 vm_inject_gp(vmx->vm, vcpu);
1374 if (!(xcrval & XFEATURE_ENABLED_X87)) {
1375 vm_inject_gp(vmx->vm, vcpu);
1379 /* AVX (YMM_Hi128) requires SSE. */
1380 if (xcrval & XFEATURE_ENABLED_AVX &&
1381 (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1382 vm_inject_gp(vmx->vm, vcpu);
1387 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1388 * ZMM_Hi256, and Hi16_ZMM.
1390 if (xcrval & XFEATURE_AVX512 &&
1391 (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1392 (XFEATURE_AVX512 | XFEATURE_AVX)) {
1393 vm_inject_gp(vmx->vm, vcpu);
1398 * Intel MPX requires both bound register state flags to be
1401 if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1402 ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1403 vm_inject_gp(vmx->vm, vcpu);
1408 * This runs "inside" vmrun() with the guest's FPU state, so
1409 * modifying xcr0 directly modifies the guest's xcr0, not the
1412 load_xcr(0, xcrval);
1417 vmx_emulate_cr_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1419 int cr, vmcs_guest_cr, vmcs_shadow_cr;
1420 uint64_t crval, regval, ones_mask, zeros_mask;
1421 const struct vmxctx *vmxctx;
1423 /* We only handle mov to %cr0 or %cr4 at this time */
1424 if ((exitqual & 0xf0) != 0x00)
1427 cr = exitqual & 0xf;
1428 if (cr != 0 && cr != 4)
1431 regval = 0; /* silence gcc */
1432 vmxctx = &vmx->ctx[vcpu];
1435 * We must use vmcs_write() directly here because vmcs_setreg() will
1436 * call vmclear(vmcs) as a side-effect which we certainly don't want.
1438 switch ((exitqual >> 8) & 0xf) {
1440 regval = vmxctx->guest_rax;
1443 regval = vmxctx->guest_rcx;
1446 regval = vmxctx->guest_rdx;
1449 regval = vmxctx->guest_rbx;
1452 regval = vmcs_read(VMCS_GUEST_RSP);
1455 regval = vmxctx->guest_rbp;
1458 regval = vmxctx->guest_rsi;
1461 regval = vmxctx->guest_rdi;
1464 regval = vmxctx->guest_r8;
1467 regval = vmxctx->guest_r9;
1470 regval = vmxctx->guest_r10;
1473 regval = vmxctx->guest_r11;
1476 regval = vmxctx->guest_r12;
1479 regval = vmxctx->guest_r13;
1482 regval = vmxctx->guest_r14;
1485 regval = vmxctx->guest_r15;
1490 ones_mask = cr0_ones_mask;
1491 zeros_mask = cr0_zeros_mask;
1492 vmcs_guest_cr = VMCS_GUEST_CR0;
1493 vmcs_shadow_cr = VMCS_CR0_SHADOW;
1495 ones_mask = cr4_ones_mask;
1496 zeros_mask = cr4_zeros_mask;
1497 vmcs_guest_cr = VMCS_GUEST_CR4;
1498 vmcs_shadow_cr = VMCS_CR4_SHADOW;
1500 vmcs_write(vmcs_shadow_cr, regval);
1502 crval = regval | ones_mask;
1503 crval &= ~zeros_mask;
1504 vmcs_write(vmcs_guest_cr, crval);
1506 if (cr == 0 && regval & CR0_PG) {
1507 uint64_t efer, entry_ctls;
1510 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1511 * the "IA-32e mode guest" bit in VM-entry control must be
1514 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1515 if (efer & EFER_LME) {
1517 vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1518 entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1519 entry_ctls |= VM_ENTRY_GUEST_LMA;
1520 vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1527 static enum vie_cpu_mode
1531 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA)
1532 return (CPU_MODE_64BIT);
1534 return (CPU_MODE_COMPATIBILITY);
1537 static enum vie_paging_mode
1538 vmx_paging_mode(void)
1541 if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1542 return (PAGING_MODE_FLAT);
1543 if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1544 return (PAGING_MODE_32);
1545 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1546 return (PAGING_MODE_64);
1548 return (PAGING_MODE_PAE);
1552 ept_fault_type(uint64_t ept_qual)
1556 if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1557 fault_type = VM_PROT_WRITE;
1558 else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1559 fault_type = VM_PROT_EXECUTE;
1561 fault_type= VM_PROT_READ;
1563 return (fault_type);
1567 ept_emulation_fault(uint64_t ept_qual)
1571 /* EPT fault on an instruction fetch doesn't make sense here */
1572 if (ept_qual & EPT_VIOLATION_INST_FETCH)
1575 /* EPT fault must be a read fault or a write fault */
1576 read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1577 write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1578 if ((read | write) == 0)
1582 * The EPT violation must have been caused by accessing a
1583 * guest-physical address that is a translation of a guest-linear
1586 if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1587 (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1595 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1597 uint32_t proc_ctls2;
1599 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1600 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1604 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1606 uint32_t proc_ctls2;
1608 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1609 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1613 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1616 int error, handled, offset;
1617 uint32_t *apic_regs, vector;
1621 offset = APIC_WRITE_OFFSET(qual);
1623 if (!apic_access_virtualization(vmx, vcpuid)) {
1625 * In general there should not be any APIC write VM-exits
1626 * unless APIC-access virtualization is enabled.
1628 * However self-IPI virtualization can legitimately trigger
1629 * an APIC-write VM-exit so treat it specially.
1631 if (x2apic_virtualization(vmx, vcpuid) &&
1632 offset == APIC_OFFSET_SELF_IPI) {
1633 apic_regs = (uint32_t *)(vlapic->apic_page);
1634 vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1635 vlapic_self_ipi_handler(vlapic, vector);
1642 case APIC_OFFSET_ID:
1643 vlapic_id_write_handler(vlapic);
1645 case APIC_OFFSET_LDR:
1646 vlapic_ldr_write_handler(vlapic);
1648 case APIC_OFFSET_DFR:
1649 vlapic_dfr_write_handler(vlapic);
1651 case APIC_OFFSET_SVR:
1652 vlapic_svr_write_handler(vlapic);
1654 case APIC_OFFSET_ESR:
1655 vlapic_esr_write_handler(vlapic);
1657 case APIC_OFFSET_ICR_LOW:
1659 error = vlapic_icrlo_write_handler(vlapic, &retu);
1660 if (error != 0 || retu)
1661 handled = UNHANDLED;
1663 case APIC_OFFSET_CMCI_LVT:
1664 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1665 vlapic_lvt_write_handler(vlapic, offset);
1667 case APIC_OFFSET_TIMER_ICR:
1668 vlapic_icrtmr_write_handler(vlapic);
1670 case APIC_OFFSET_TIMER_DCR:
1671 vlapic_dcr_write_handler(vlapic);
1674 handled = UNHANDLED;
1681 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1684 if (apic_access_virtualization(vmx, vcpuid) &&
1685 (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1692 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1695 int access_type, offset, allowed;
1697 if (!apic_access_virtualization(vmx, vcpuid))
1700 qual = vmexit->u.vmx.exit_qualification;
1701 access_type = APIC_ACCESS_TYPE(qual);
1702 offset = APIC_ACCESS_OFFSET(qual);
1705 if (access_type == 0) {
1707 * Read data access to the following registers is expected.
1710 case APIC_OFFSET_APR:
1711 case APIC_OFFSET_PPR:
1712 case APIC_OFFSET_RRR:
1713 case APIC_OFFSET_CMCI_LVT:
1714 case APIC_OFFSET_TIMER_CCR:
1720 } else if (access_type == 1) {
1722 * Write data access to the following registers is expected.
1725 case APIC_OFFSET_VER:
1726 case APIC_OFFSET_APR:
1727 case APIC_OFFSET_PPR:
1728 case APIC_OFFSET_RRR:
1729 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1730 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1731 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1732 case APIC_OFFSET_CMCI_LVT:
1733 case APIC_OFFSET_TIMER_CCR:
1742 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1743 vmexit->u.inst_emul.gpa = DEFAULT_APIC_BASE + offset;
1744 vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
1745 vmexit->u.inst_emul.cr3 = vmcs_guest_cr3();
1746 vmexit->u.inst_emul.cpu_mode = vmx_cpu_mode();
1747 vmexit->u.inst_emul.paging_mode = vmx_paging_mode();
1751 * Regardless of whether the APIC-access is allowed this handler
1752 * always returns UNHANDLED:
1753 * - if the access is allowed then it is handled by emulating the
1754 * instruction that caused the VM-exit (outside the critical section)
1755 * - if the access is not allowed then it will be converted to an
1756 * exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
1762 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1765 struct vmxctx *vmxctx;
1766 struct vlapic *vlapic;
1767 uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, reason;
1771 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
1772 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
1774 handled = UNHANDLED;
1775 vmxctx = &vmx->ctx[vcpu];
1777 qual = vmexit->u.vmx.exit_qualification;
1778 reason = vmexit->u.vmx.exit_reason;
1779 vmexit->exitcode = VM_EXITCODE_BOGUS;
1781 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
1784 * VM exits that could be triggered during event injection on the
1785 * previous VM entry need to be handled specially by re-injecting
1788 * See "Information for VM Exits During Event Delivery" in Intel SDM
1792 case EXIT_REASON_EPT_FAULT:
1793 case EXIT_REASON_EPT_MISCONFIG:
1794 case EXIT_REASON_APIC_ACCESS:
1795 case EXIT_REASON_TASK_SWITCH:
1796 case EXIT_REASON_EXCEPTION:
1797 idtvec_info = vmcs_idt_vectoring_info();
1798 if (idtvec_info & VMCS_IDT_VEC_VALID) {
1799 idtvec_info &= ~(1 << 12); /* clear undefined bit */
1800 vmcs_write(VMCS_ENTRY_INTR_INFO, idtvec_info);
1801 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
1802 idtvec_err = vmcs_idt_vectoring_err();
1803 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR,
1807 * If 'virtual NMIs' are being used and the VM-exit
1808 * happened while injecting an NMI during the previous
1809 * VM-entry, then clear "blocking by NMI" in the Guest
1810 * Interruptibility-state.
1812 if ((idtvec_info & VMCS_INTR_T_MASK) ==
1814 vmx_clear_nmi_blocking(vmx, vcpu);
1816 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
1824 case EXIT_REASON_CR_ACCESS:
1825 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
1826 handled = vmx_emulate_cr_access(vmx, vcpu, qual);
1828 case EXIT_REASON_RDMSR:
1829 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
1831 ecx = vmxctx->guest_rcx;
1832 error = emulate_rdmsr(vmx->vm, vcpu, ecx, &retu);
1834 vmexit->exitcode = VM_EXITCODE_RDMSR;
1835 vmexit->u.msr.code = ecx;
1839 /* Return to userspace with a valid exitcode */
1840 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1841 ("emulate_wrmsr retu with bogus exitcode"));
1844 case EXIT_REASON_WRMSR:
1845 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
1847 eax = vmxctx->guest_rax;
1848 ecx = vmxctx->guest_rcx;
1849 edx = vmxctx->guest_rdx;
1850 error = emulate_wrmsr(vmx->vm, vcpu, ecx,
1851 (uint64_t)edx << 32 | eax, &retu);
1853 vmexit->exitcode = VM_EXITCODE_WRMSR;
1854 vmexit->u.msr.code = ecx;
1855 vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
1859 /* Return to userspace with a valid exitcode */
1860 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1861 ("emulate_wrmsr retu with bogus exitcode"));
1864 case EXIT_REASON_HLT:
1865 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
1866 vmexit->exitcode = VM_EXITCODE_HLT;
1867 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1869 case EXIT_REASON_MTF:
1870 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
1871 vmexit->exitcode = VM_EXITCODE_MTRAP;
1873 case EXIT_REASON_PAUSE:
1874 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
1875 vmexit->exitcode = VM_EXITCODE_PAUSE;
1877 case EXIT_REASON_INTR_WINDOW:
1878 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
1879 vmx_clear_int_window_exiting(vmx, vcpu);
1881 case EXIT_REASON_EXT_INTR:
1883 * External interrupts serve only to cause VM exits and allow
1884 * the host interrupt handler to run.
1886 * If this external interrupt triggers a virtual interrupt
1887 * to a VM, then that state will be recorded by the
1888 * host interrupt handler in the VM's softc. We will inject
1889 * this virtual interrupt during the subsequent VM enter.
1891 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
1894 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
1895 * This appears to be a bug in VMware Fusion?
1897 if (!(intr_info & VMCS_INTR_VALID))
1899 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
1900 (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
1901 ("VM exit interruption info invalid: %#x", intr_info));
1902 vmx_trigger_hostintr(intr_info & 0xff);
1905 * This is special. We want to treat this as an 'handled'
1906 * VM-exit but not increment the instruction pointer.
1908 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
1910 case EXIT_REASON_NMI_WINDOW:
1911 /* Exit to allow the pending virtual NMI to be injected */
1912 if (vm_nmi_pending(vmx->vm, vcpu))
1913 vmx_inject_nmi(vmx, vcpu);
1914 vmx_clear_nmi_window_exiting(vmx, vcpu);
1915 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
1917 case EXIT_REASON_INOUT:
1918 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
1919 vmexit->exitcode = VM_EXITCODE_INOUT;
1920 vmexit->u.inout.bytes = (qual & 0x7) + 1;
1921 vmexit->u.inout.in = (qual & 0x8) ? 1 : 0;
1922 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
1923 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
1924 vmexit->u.inout.port = (uint16_t)(qual >> 16);
1925 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
1926 error = emulate_ioport(vmx->vm, vcpu, vmexit);
1929 vmxctx->guest_rax = vmexit->u.inout.eax;
1932 case EXIT_REASON_CPUID:
1933 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
1934 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
1936 case EXIT_REASON_EXCEPTION:
1937 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
1938 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
1939 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
1940 ("VM exit interruption info invalid: %#x", intr_info));
1943 * If Virtual NMIs control is 1 and the VM-exit is due to a
1944 * fault encountered during the execution of IRET then we must
1945 * restore the state of "virtual-NMI blocking" before resuming
1948 * See "Resuming Guest Software after Handling an Exception".
1950 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
1951 (intr_info & 0xff) != IDT_DF &&
1952 (intr_info & EXIT_QUAL_NMIUDTI) != 0)
1953 vmx_restore_nmi_blocking(vmx, vcpu);
1956 * The NMI has already been handled in vmx_exit_handle_nmi().
1958 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI)
1961 case EXIT_REASON_EPT_FAULT:
1963 * If 'gpa' lies within the address space allocated to
1964 * memory then this must be a nested page fault otherwise
1965 * this must be an instruction that accesses MMIO space.
1968 if (vm_mem_allocated(vmx->vm, gpa) ||
1969 apic_access_fault(vmx, vcpu, gpa)) {
1970 vmexit->exitcode = VM_EXITCODE_PAGING;
1971 vmexit->u.paging.gpa = gpa;
1972 vmexit->u.paging.fault_type = ept_fault_type(qual);
1973 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1974 } else if (ept_emulation_fault(qual)) {
1975 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1976 vmexit->u.inst_emul.gpa = gpa;
1977 vmexit->u.inst_emul.gla = vmcs_gla();
1978 vmexit->u.inst_emul.cr3 = vmcs_guest_cr3();
1979 vmexit->u.inst_emul.cpu_mode = vmx_cpu_mode();
1980 vmexit->u.inst_emul.paging_mode = vmx_paging_mode();
1981 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
1984 * If Virtual NMIs control is 1 and the VM-exit is due to an
1985 * EPT fault during the execution of IRET then we must restore
1986 * the state of "virtual-NMI blocking" before resuming.
1988 * See description of "NMI unblocking due to IRET" in
1989 * "Exit Qualification for EPT Violations".
1991 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
1992 (qual & EXIT_QUAL_NMIUDTI) != 0)
1993 vmx_restore_nmi_blocking(vmx, vcpu);
1995 case EXIT_REASON_VIRTUALIZED_EOI:
1996 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
1997 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
1998 vmexit->inst_length = 0; /* trap-like */
2000 case EXIT_REASON_APIC_ACCESS:
2001 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2003 case EXIT_REASON_APIC_WRITE:
2005 * APIC-write VM exit is trap-like so the %rip is already
2006 * pointing to the next instruction.
2008 vmexit->inst_length = 0;
2009 vlapic = vm_lapic(vmx->vm, vcpu);
2010 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2012 case EXIT_REASON_XSETBV:
2013 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2016 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2022 * It is possible that control is returned to userland
2023 * even though we were able to handle the VM exit in the
2026 * In such a case we want to make sure that the userland
2027 * restarts guest execution at the instruction *after*
2028 * the one we just processed. Therefore we update the
2029 * guest rip in the VMCS and in 'vmexit'.
2031 vmexit->rip += vmexit->inst_length;
2032 vmexit->inst_length = 0;
2033 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2035 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2037 * If this VM exit was not claimed by anybody then
2038 * treat it as a generic VMX exit.
2040 vmexit->exitcode = VM_EXITCODE_VMX;
2041 vmexit->u.vmx.status = VM_SUCCESS;
2042 vmexit->u.vmx.inst_type = 0;
2043 vmexit->u.vmx.inst_error = 0;
2046 * The exitcode and collateral have been populated.
2047 * The VM exit will be processed further in userland.
2055 vmx_exit_astpending(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2058 vmexit->rip = vmcs_guest_rip();
2059 vmexit->inst_length = 0;
2060 vmexit->exitcode = VM_EXITCODE_BOGUS;
2061 vmx_astpending_trace(vmx, vcpu, vmexit->rip);
2062 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_ASTPENDING, 1);
2068 vmx_exit_rendezvous(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2071 vmexit->rip = vmcs_guest_rip();
2072 vmexit->inst_length = 0;
2073 vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
2074 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RENDEZVOUS, 1);
2080 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2083 KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2084 ("vmx_exit_inst_error: invalid inst_fail_status %d",
2085 vmxctx->inst_fail_status));
2087 vmexit->inst_length = 0;
2088 vmexit->exitcode = VM_EXITCODE_VMX;
2089 vmexit->u.vmx.status = vmxctx->inst_fail_status;
2090 vmexit->u.vmx.inst_error = vmcs_instruction_error();
2091 vmexit->u.vmx.exit_reason = ~0;
2092 vmexit->u.vmx.exit_qualification = ~0;
2095 case VMX_VMRESUME_ERROR:
2096 case VMX_VMLAUNCH_ERROR:
2097 case VMX_INVEPT_ERROR:
2098 vmexit->u.vmx.inst_type = rc;
2101 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2108 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2109 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2110 * sufficient to simply vector to the NMI handler via a software interrupt.
2111 * However, this must be done before maskable interrupts are enabled
2112 * otherwise the "iret" issued by an interrupt handler will incorrectly
2113 * clear NMI blocking.
2115 static __inline void
2116 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2120 KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2122 if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2125 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2126 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2127 ("VM exit interruption info invalid: %#x", intr_info));
2129 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2130 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2131 "to NMI has invalid vector: %#x", intr_info));
2132 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2133 __asm __volatile("int $2");
2138 vmx_run(void *arg, int vcpu, register_t startrip, pmap_t pmap,
2139 void *rendezvous_cookie, void *suspend_cookie)
2141 int rc, handled, launched;
2144 struct vmxctx *vmxctx;
2146 struct vm_exit *vmexit;
2147 struct vlapic *vlapic;
2149 uint32_t exit_reason;
2153 vmcs = &vmx->vmcs[vcpu];
2154 vmxctx = &vmx->ctx[vcpu];
2155 vlapic = vm_lapic(vm, vcpu);
2156 vmexit = vm_exitinfo(vm, vcpu);
2159 KASSERT(vmxctx->pmap == pmap,
2160 ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2166 * We do this every time because we may setup the virtual machine
2167 * from a different process than the one that actually runs it.
2169 * If the life of a virtual machine was spent entirely in the context
2170 * of a single process we could do this once in vmx_vminit().
2172 vmcs_write(VMCS_HOST_CR3, rcr3());
2174 vmcs_write(VMCS_GUEST_RIP, startrip);
2175 vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2178 * Interrupts are disabled from this point on until the
2179 * guest starts executing. This is done for the following
2182 * If an AST is asserted on this thread after the check below,
2183 * then the IPI_AST notification will not be lost, because it
2184 * will cause a VM exit due to external interrupt as soon as
2185 * the guest state is loaded.
2187 * A posted interrupt after 'vmx_inject_interrupts()' will
2188 * not be "lost" because it will be held pending in the host
2189 * APIC because interrupts are disabled. The pending interrupt
2190 * will be recognized as soon as the guest state is loaded.
2192 * The same reasoning applies to the IPI generated by
2193 * pmap_invalidate_ept().
2196 if (vcpu_suspended(suspend_cookie)) {
2198 vm_exit_suspended(vmx->vm, vcpu, vmcs_guest_rip());
2199 handled = UNHANDLED;
2203 if (vcpu_rendezvous_pending(rendezvous_cookie)) {
2205 handled = vmx_exit_rendezvous(vmx, vcpu, vmexit);
2209 if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
2211 handled = vmx_exit_astpending(vmx, vcpu, vmexit);
2215 vmx_inject_interrupts(vmx, vcpu, vlapic);
2216 vmx_run_trace(vmx, vcpu);
2217 rc = vmx_enter_guest(vmxctx, vmx, launched);
2219 /* Collect some information for VM exit processing */
2220 vmexit->rip = rip = vmcs_guest_rip();
2221 vmexit->inst_length = vmexit_instruction_length();
2222 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2223 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2225 if (rc == VMX_GUEST_VMEXIT) {
2226 vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2228 handled = vmx_exit_process(vmx, vcpu, vmexit);
2231 handled = vmx_exit_inst_error(vmxctx, rc, vmexit);
2234 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2238 * If a VM exit has been handled then the exitcode must be BOGUS
2239 * If a VM exit is not handled then the exitcode must not be BOGUS
2241 if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2242 (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2243 panic("Mismatch between handled (%d) and exitcode (%d)",
2244 handled, vmexit->exitcode);
2248 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2250 VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2258 vmx_vmcleanup(void *arg)
2261 struct vmx *vmx = arg;
2263 if (apic_access_virtualization(vmx, 0))
2264 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2266 for (i = 0; i < VM_MAXCPU; i++)
2267 vpid_free(vmx->state[i].vpid);
2270 * XXXSMP we also need to clear the VMCS active on the other vcpus.
2272 error = vmclear(&vmx->vmcs[0]);
2274 panic("vmx_vmcleanup: vmclear error %d on vcpu 0", error);
2282 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2286 case VM_REG_GUEST_RAX:
2287 return (&vmxctx->guest_rax);
2288 case VM_REG_GUEST_RBX:
2289 return (&vmxctx->guest_rbx);
2290 case VM_REG_GUEST_RCX:
2291 return (&vmxctx->guest_rcx);
2292 case VM_REG_GUEST_RDX:
2293 return (&vmxctx->guest_rdx);
2294 case VM_REG_GUEST_RSI:
2295 return (&vmxctx->guest_rsi);
2296 case VM_REG_GUEST_RDI:
2297 return (&vmxctx->guest_rdi);
2298 case VM_REG_GUEST_RBP:
2299 return (&vmxctx->guest_rbp);
2300 case VM_REG_GUEST_R8:
2301 return (&vmxctx->guest_r8);
2302 case VM_REG_GUEST_R9:
2303 return (&vmxctx->guest_r9);
2304 case VM_REG_GUEST_R10:
2305 return (&vmxctx->guest_r10);
2306 case VM_REG_GUEST_R11:
2307 return (&vmxctx->guest_r11);
2308 case VM_REG_GUEST_R12:
2309 return (&vmxctx->guest_r12);
2310 case VM_REG_GUEST_R13:
2311 return (&vmxctx->guest_r13);
2312 case VM_REG_GUEST_R14:
2313 return (&vmxctx->guest_r14);
2314 case VM_REG_GUEST_R15:
2315 return (&vmxctx->guest_r15);
2323 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2327 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2335 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2339 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2347 vmx_shadow_reg(int reg)
2354 case VM_REG_GUEST_CR0:
2355 shreg = VMCS_CR0_SHADOW;
2357 case VM_REG_GUEST_CR4:
2358 shreg = VMCS_CR4_SHADOW;
2368 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2370 int running, hostcpu;
2371 struct vmx *vmx = arg;
2373 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2374 if (running && hostcpu != curcpu)
2375 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2377 if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2380 return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2384 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2386 int error, hostcpu, running, shadow;
2388 struct vmx *vmx = arg;
2390 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2391 if (running && hostcpu != curcpu)
2392 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2394 if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2397 error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2401 * If the "load EFER" VM-entry control is 1 then the
2402 * value of EFER.LMA must be identical to "IA-32e mode guest"
2403 * bit in the VM-entry control.
2405 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2406 (reg == VM_REG_GUEST_EFER)) {
2407 vmcs_getreg(&vmx->vmcs[vcpu], running,
2408 VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2410 ctls |= VM_ENTRY_GUEST_LMA;
2412 ctls &= ~VM_ENTRY_GUEST_LMA;
2413 vmcs_setreg(&vmx->vmcs[vcpu], running,
2414 VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2417 shadow = vmx_shadow_reg(reg);
2420 * Store the unmodified value in the shadow
2422 error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2423 VMCS_IDENT(shadow), val);
2431 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2433 struct vmx *vmx = arg;
2435 return (vmcs_getdesc(&vmx->vmcs[vcpu], reg, desc));
2439 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2441 struct vmx *vmx = arg;
2443 return (vmcs_setdesc(&vmx->vmcs[vcpu], reg, desc));
2447 vmx_getcap(void *arg, int vcpu, int type, int *retval)
2449 struct vmx *vmx = arg;
2455 vcap = vmx->cap[vcpu].set;
2458 case VM_CAP_HALT_EXIT:
2462 case VM_CAP_PAUSE_EXIT:
2466 case VM_CAP_MTRAP_EXIT:
2467 if (cap_monitor_trap)
2470 case VM_CAP_UNRESTRICTED_GUEST:
2471 if (cap_unrestricted_guest)
2474 case VM_CAP_ENABLE_INVPCID:
2483 *retval = (vcap & (1 << type)) ? 1 : 0;
2489 vmx_setcap(void *arg, int vcpu, int type, int val)
2491 struct vmx *vmx = arg;
2492 struct vmcs *vmcs = &vmx->vmcs[vcpu];
2504 case VM_CAP_HALT_EXIT:
2505 if (cap_halt_exit) {
2507 pptr = &vmx->cap[vcpu].proc_ctls;
2509 flag = PROCBASED_HLT_EXITING;
2510 reg = VMCS_PRI_PROC_BASED_CTLS;
2513 case VM_CAP_MTRAP_EXIT:
2514 if (cap_monitor_trap) {
2516 pptr = &vmx->cap[vcpu].proc_ctls;
2518 flag = PROCBASED_MTF;
2519 reg = VMCS_PRI_PROC_BASED_CTLS;
2522 case VM_CAP_PAUSE_EXIT:
2523 if (cap_pause_exit) {
2525 pptr = &vmx->cap[vcpu].proc_ctls;
2527 flag = PROCBASED_PAUSE_EXITING;
2528 reg = VMCS_PRI_PROC_BASED_CTLS;
2531 case VM_CAP_UNRESTRICTED_GUEST:
2532 if (cap_unrestricted_guest) {
2534 pptr = &vmx->cap[vcpu].proc_ctls2;
2536 flag = PROCBASED2_UNRESTRICTED_GUEST;
2537 reg = VMCS_SEC_PROC_BASED_CTLS;
2540 case VM_CAP_ENABLE_INVPCID:
2543 pptr = &vmx->cap[vcpu].proc_ctls2;
2545 flag = PROCBASED2_ENABLE_INVPCID;
2546 reg = VMCS_SEC_PROC_BASED_CTLS;
2560 error = vmwrite(reg, baseval);
2567 * Update optional stored flags, and record
2575 vmx->cap[vcpu].set |= (1 << type);
2577 vmx->cap[vcpu].set &= ~(1 << type);
2586 struct vlapic vlapic;
2587 struct pir_desc *pir_desc;
2591 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg) \
2593 VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d", \
2594 level ? "level" : "edge", vector); \
2595 VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]); \
2596 VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]); \
2597 VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]); \
2598 VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]); \
2599 VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
2603 * vlapic->ops handlers that utilize the APICv hardware assist described in
2604 * Chapter 29 of the Intel SDM.
2607 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
2609 struct vlapic_vtx *vlapic_vtx;
2610 struct pir_desc *pir_desc;
2614 vlapic_vtx = (struct vlapic_vtx *)vlapic;
2615 pir_desc = vlapic_vtx->pir_desc;
2618 * Keep track of interrupt requests in the PIR descriptor. This is
2619 * because the virtual APIC page pointed to by the VMCS cannot be
2620 * modified if the vcpu is running.
2623 mask = 1UL << (vector % 64);
2624 atomic_set_long(&pir_desc->pir[idx], mask);
2625 notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
2627 VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
2628 level, "vmx_set_intr_ready");
2633 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
2635 struct vlapic_vtx *vlapic_vtx;
2636 struct pir_desc *pir_desc;
2637 struct LAPIC *lapic;
2638 uint64_t pending, pirval;
2643 * This function is only expected to be called from the 'HLT' exit
2644 * handler which does not care about the vector that is pending.
2646 KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
2648 vlapic_vtx = (struct vlapic_vtx *)vlapic;
2649 pir_desc = vlapic_vtx->pir_desc;
2651 pending = atomic_load_acq_long(&pir_desc->pending);
2653 return (0); /* common case */
2656 * If there is an interrupt pending then it will be recognized only
2657 * if its priority is greater than the processor priority.
2659 * Special case: if the processor priority is zero then any pending
2660 * interrupt will be recognized.
2662 lapic = vlapic->apic_page;
2663 ppr = lapic->ppr & 0xf0;
2667 VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
2670 for (i = 3; i >= 0; i--) {
2671 pirval = pir_desc->pir[i];
2673 vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
2681 vmx_intr_accepted(struct vlapic *vlapic, int vector)
2684 panic("vmx_intr_accepted: not expected to be called");
2688 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
2690 struct vlapic_vtx *vlapic_vtx;
2695 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
2696 KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
2697 ("vmx_set_tmr: vcpu cannot be running"));
2699 vlapic_vtx = (struct vlapic_vtx *)vlapic;
2700 vmx = vlapic_vtx->vmx;
2701 vmcs = &vmx->vmcs[vlapic->vcpuid];
2702 mask = 1UL << (vector % 64);
2705 val = vmcs_read(VMCS_EOI_EXIT(vector));
2710 vmcs_write(VMCS_EOI_EXIT(vector), val);
2715 vmx_enable_x2apic_mode(struct vlapic *vlapic)
2719 uint32_t proc_ctls2;
2722 vcpuid = vlapic->vcpuid;
2723 vmx = ((struct vlapic_vtx *)vlapic)->vmx;
2724 vmcs = &vmx->vmcs[vcpuid];
2726 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
2727 KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
2728 ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
2730 proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
2731 proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
2732 vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
2735 vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
2738 if (vlapic->vcpuid == 0) {
2740 * The nested page table mappings are shared by all vcpus
2741 * so unmap the APIC access page just once.
2743 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2744 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
2748 * The MSR bitmap is shared by all vcpus so modify it only
2749 * once in the context of vcpu 0.
2751 error = vmx_allow_x2apic_msrs(vmx);
2752 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
2758 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
2761 ipi_cpu(hostcpu, pirvec);
2765 * Transfer the pending interrupts in the PIR descriptor to the IRR
2766 * in the virtual APIC page.
2769 vmx_inject_pir(struct vlapic *vlapic)
2771 struct vlapic_vtx *vlapic_vtx;
2772 struct pir_desc *pir_desc;
2773 struct LAPIC *lapic;
2774 uint64_t val, pirval;
2775 int rvi, pirbase = -1;
2776 uint16_t intr_status_old, intr_status_new;
2778 vlapic_vtx = (struct vlapic_vtx *)vlapic;
2779 pir_desc = vlapic_vtx->pir_desc;
2780 if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
2781 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
2782 "no posted interrupt pending");
2788 lapic = vlapic->apic_page;
2790 val = atomic_readandclear_long(&pir_desc->pir[0]);
2793 lapic->irr1 |= val >> 32;
2798 val = atomic_readandclear_long(&pir_desc->pir[1]);
2801 lapic->irr3 |= val >> 32;
2806 val = atomic_readandclear_long(&pir_desc->pir[2]);
2809 lapic->irr5 |= val >> 32;
2814 val = atomic_readandclear_long(&pir_desc->pir[3]);
2817 lapic->irr7 |= val >> 32;
2822 VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
2825 * Update RVI so the processor can evaluate pending virtual
2826 * interrupts on VM-entry.
2828 * It is possible for pirval to be 0 here, even though the
2829 * pending bit has been set. The scenario is:
2830 * CPU-Y is sending a posted interrupt to CPU-X, which
2831 * is running a guest and processing posted interrupts in h/w.
2832 * CPU-X will eventually exit and the state seen in s/w is
2833 * the pending bit set, but no PIR bits set.
2836 * (vm running) (host running)
2837 * rx posted interrupt
2840 * READ/CLEAR PIR bits
2843 * pending bit set, PIR 0
2846 rvi = pirbase + flsl(pirval) - 1;
2847 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
2848 intr_status_new = (intr_status_old & 0xFF00) | rvi;
2849 if (intr_status_new > intr_status_old) {
2850 vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
2851 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
2852 "guest_intr_status changed from 0x%04x to 0x%04x",
2853 intr_status_old, intr_status_new);
2858 static struct vlapic *
2859 vmx_vlapic_init(void *arg, int vcpuid)
2862 struct vlapic *vlapic;
2863 struct vlapic_vtx *vlapic_vtx;
2867 vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
2868 vlapic->vm = vmx->vm;
2869 vlapic->vcpuid = vcpuid;
2870 vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
2872 vlapic_vtx = (struct vlapic_vtx *)vlapic;
2873 vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
2874 vlapic_vtx->vmx = vmx;
2876 if (virtual_interrupt_delivery) {
2877 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
2878 vlapic->ops.pending_intr = vmx_pending_intr;
2879 vlapic->ops.intr_accepted = vmx_intr_accepted;
2880 vlapic->ops.set_tmr = vmx_set_tmr;
2881 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
2884 if (posted_interrupts)
2885 vlapic->ops.post_intr = vmx_post_intr;
2887 vlapic_init(vlapic);
2893 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2896 vlapic_cleanup(vlapic);
2897 free(vlapic, M_VLAPIC);
2900 struct vmm_ops vmm_ops_intel = {