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/reg.h>
48 #include <machine/segments.h>
49 #include <machine/smp.h>
50 #include <machine/specialreg.h>
51 #include <machine/vmparam.h>
53 #include <machine/vmm.h>
54 #include <machine/vmm_dev.h>
55 #include <machine/vmm_instruction_emul.h>
56 #include "vmm_lapic.h"
58 #include "vmm_ioport.h"
63 #include "vlapic_priv.h"
66 #include "vmx_cpufunc.h"
70 #include "vmx_controls.h"
72 #define PINBASED_CTLS_ONE_SETTING \
73 (PINBASED_EXTINT_EXITING | \
74 PINBASED_NMI_EXITING | \
76 #define PINBASED_CTLS_ZERO_SETTING 0
78 #define PROCBASED_CTLS_WINDOW_SETTING \
79 (PROCBASED_INT_WINDOW_EXITING | \
80 PROCBASED_NMI_WINDOW_EXITING)
82 #define PROCBASED_CTLS_ONE_SETTING \
83 (PROCBASED_SECONDARY_CONTROLS | \
84 PROCBASED_MWAIT_EXITING | \
85 PROCBASED_MONITOR_EXITING | \
86 PROCBASED_IO_EXITING | \
87 PROCBASED_MSR_BITMAPS | \
88 PROCBASED_CTLS_WINDOW_SETTING | \
89 PROCBASED_CR8_LOAD_EXITING | \
90 PROCBASED_CR8_STORE_EXITING)
91 #define PROCBASED_CTLS_ZERO_SETTING \
92 (PROCBASED_CR3_LOAD_EXITING | \
93 PROCBASED_CR3_STORE_EXITING | \
96 #define PROCBASED_CTLS2_ONE_SETTING PROCBASED2_ENABLE_EPT
97 #define PROCBASED_CTLS2_ZERO_SETTING 0
99 #define VM_EXIT_CTLS_ONE_SETTING \
100 (VM_EXIT_SAVE_DEBUG_CONTROLS | \
102 VM_EXIT_SAVE_EFER | \
103 VM_EXIT_LOAD_EFER | \
104 VM_EXIT_ACKNOWLEDGE_INTERRUPT)
106 #define VM_EXIT_CTLS_ZERO_SETTING 0
108 #define VM_ENTRY_CTLS_ONE_SETTING \
109 (VM_ENTRY_LOAD_DEBUG_CONTROLS | \
112 #define VM_ENTRY_CTLS_ZERO_SETTING \
113 (VM_ENTRY_INTO_SMM | \
114 VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
119 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
120 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
122 SYSCTL_DECL(_hw_vmm);
123 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
125 int vmxon_enabled[MAXCPU];
126 static char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
128 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
129 static uint32_t exit_ctls, entry_ctls;
131 static uint64_t cr0_ones_mask, cr0_zeros_mask;
132 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
133 &cr0_ones_mask, 0, NULL);
134 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
135 &cr0_zeros_mask, 0, NULL);
137 static uint64_t cr4_ones_mask, cr4_zeros_mask;
138 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
139 &cr4_ones_mask, 0, NULL);
140 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
141 &cr4_zeros_mask, 0, NULL);
143 static int vmx_initialized;
144 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
145 &vmx_initialized, 0, "Intel VMX initialized");
148 * Optional capabilities
150 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap, CTLFLAG_RW, NULL, NULL);
152 static int cap_halt_exit;
153 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
154 "HLT triggers a VM-exit");
156 static int cap_pause_exit;
157 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
158 0, "PAUSE triggers a VM-exit");
160 static int cap_unrestricted_guest;
161 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
162 &cap_unrestricted_guest, 0, "Unrestricted guests");
164 static int cap_monitor_trap;
165 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
166 &cap_monitor_trap, 0, "Monitor trap flag");
168 static int cap_invpcid;
169 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
170 0, "Guests are allowed to use INVPCID");
172 static int virtual_interrupt_delivery;
173 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
174 &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
176 static int posted_interrupts;
177 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
178 &posted_interrupts, 0, "APICv posted interrupt support");
180 static int pirvec = -1;
181 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
182 &pirvec, 0, "APICv posted interrupt vector");
184 static struct unrhdr *vpid_unr;
185 static u_int vpid_alloc_failed;
186 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
187 &vpid_alloc_failed, 0, NULL);
189 static int guest_l1d_flush;
190 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush, CTLFLAG_RD,
191 &guest_l1d_flush, 0, NULL);
192 static int guest_l1d_flush_sw;
193 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush_sw, CTLFLAG_RD,
194 &guest_l1d_flush_sw, 0, NULL);
196 static struct msr_entry msr_load_list[1] __aligned(16);
199 * Use the last page below 4GB as the APIC access address. This address is
200 * occupied by the boot firmware so it is guaranteed that it will not conflict
201 * with a page in system memory.
203 #define APIC_ACCESS_ADDRESS 0xFFFFF000
205 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
206 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
207 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
208 static void vmx_inject_pir(struct vlapic *vlapic);
212 exit_reason_to_str(int reason)
214 static char reasonbuf[32];
217 case EXIT_REASON_EXCEPTION:
219 case EXIT_REASON_EXT_INTR:
221 case EXIT_REASON_TRIPLE_FAULT:
222 return "triplefault";
223 case EXIT_REASON_INIT:
225 case EXIT_REASON_SIPI:
227 case EXIT_REASON_IO_SMI:
229 case EXIT_REASON_SMI:
231 case EXIT_REASON_INTR_WINDOW:
233 case EXIT_REASON_NMI_WINDOW:
235 case EXIT_REASON_TASK_SWITCH:
237 case EXIT_REASON_CPUID:
239 case EXIT_REASON_GETSEC:
241 case EXIT_REASON_HLT:
243 case EXIT_REASON_INVD:
245 case EXIT_REASON_INVLPG:
247 case EXIT_REASON_RDPMC:
249 case EXIT_REASON_RDTSC:
251 case EXIT_REASON_RSM:
253 case EXIT_REASON_VMCALL:
255 case EXIT_REASON_VMCLEAR:
257 case EXIT_REASON_VMLAUNCH:
259 case EXIT_REASON_VMPTRLD:
261 case EXIT_REASON_VMPTRST:
263 case EXIT_REASON_VMREAD:
265 case EXIT_REASON_VMRESUME:
267 case EXIT_REASON_VMWRITE:
269 case EXIT_REASON_VMXOFF:
271 case EXIT_REASON_VMXON:
273 case EXIT_REASON_CR_ACCESS:
275 case EXIT_REASON_DR_ACCESS:
277 case EXIT_REASON_INOUT:
279 case EXIT_REASON_RDMSR:
281 case EXIT_REASON_WRMSR:
283 case EXIT_REASON_INVAL_VMCS:
285 case EXIT_REASON_INVAL_MSR:
287 case EXIT_REASON_MWAIT:
289 case EXIT_REASON_MTF:
291 case EXIT_REASON_MONITOR:
293 case EXIT_REASON_PAUSE:
295 case EXIT_REASON_MCE_DURING_ENTRY:
296 return "mce-during-entry";
297 case EXIT_REASON_TPR:
299 case EXIT_REASON_APIC_ACCESS:
300 return "apic-access";
301 case EXIT_REASON_GDTR_IDTR:
303 case EXIT_REASON_LDTR_TR:
305 case EXIT_REASON_EPT_FAULT:
307 case EXIT_REASON_EPT_MISCONFIG:
308 return "eptmisconfig";
309 case EXIT_REASON_INVEPT:
311 case EXIT_REASON_RDTSCP:
313 case EXIT_REASON_VMX_PREEMPT:
315 case EXIT_REASON_INVVPID:
317 case EXIT_REASON_WBINVD:
319 case EXIT_REASON_XSETBV:
321 case EXIT_REASON_APIC_WRITE:
324 snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
331 vmx_allow_x2apic_msrs(struct vmx *vmx)
338 * Allow readonly access to the following x2APIC MSRs from the guest.
340 error += guest_msr_ro(vmx, MSR_APIC_ID);
341 error += guest_msr_ro(vmx, MSR_APIC_VERSION);
342 error += guest_msr_ro(vmx, MSR_APIC_LDR);
343 error += guest_msr_ro(vmx, MSR_APIC_SVR);
345 for (i = 0; i < 8; i++)
346 error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
348 for (i = 0; i < 8; i++)
349 error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
351 for (i = 0; i < 8; i++)
352 error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
354 error += guest_msr_ro(vmx, MSR_APIC_ESR);
355 error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
356 error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
357 error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
358 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
359 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
360 error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
361 error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
362 error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
363 error += guest_msr_ro(vmx, MSR_APIC_ICR);
366 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
368 * These registers get special treatment described in the section
369 * "Virtualizing MSR-Based APIC Accesses".
371 error += guest_msr_rw(vmx, MSR_APIC_TPR);
372 error += guest_msr_rw(vmx, MSR_APIC_EOI);
373 error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
379 vmx_fix_cr0(u_long cr0)
382 return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
386 vmx_fix_cr4(u_long cr4)
389 return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
395 if (vpid < 0 || vpid > 0xffff)
396 panic("vpid_free: invalid vpid %d", vpid);
399 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
400 * the unit number allocator.
403 if (vpid > VM_MAXCPU)
404 free_unr(vpid_unr, vpid);
408 vpid_alloc(uint16_t *vpid, int num)
412 if (num <= 0 || num > VM_MAXCPU)
413 panic("invalid number of vpids requested: %d", num);
416 * If the "enable vpid" execution control is not enabled then the
417 * VPID is required to be 0 for all vcpus.
419 if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
420 for (i = 0; i < num; i++)
426 * Allocate a unique VPID for each vcpu from the unit number allocator.
428 for (i = 0; i < num; i++) {
429 x = alloc_unr(vpid_unr);
437 atomic_add_int(&vpid_alloc_failed, 1);
440 * If the unit number allocator does not have enough unique
441 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
443 * These VPIDs are not be unique across VMs but this does not
444 * affect correctness because the combined mappings are also
445 * tagged with the EP4TA which is unique for each VM.
447 * It is still sub-optimal because the invvpid will invalidate
448 * combined mappings for a particular VPID across all EP4TAs.
453 for (i = 0; i < num; i++)
462 * VPID 0 is required when the "enable VPID" execution control is
465 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
466 * unit number allocator does not have sufficient unique VPIDs to
467 * satisfy the allocation.
469 * The remaining VPIDs are managed by the unit number allocator.
471 vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
475 vmx_disable(void *arg __unused)
477 struct invvpid_desc invvpid_desc = { 0 };
478 struct invept_desc invept_desc = { 0 };
480 if (vmxon_enabled[curcpu]) {
482 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
484 * VMXON or VMXOFF are not required to invalidate any TLB
485 * caching structures. This prevents potential retention of
486 * cached information in the TLB between distinct VMX episodes.
488 invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
489 invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
492 load_cr4(rcr4() & ~CR4_VMXE);
500 lapic_ipi_free(pirvec);
502 if (vpid_unr != NULL) {
503 delete_unrhdr(vpid_unr);
507 if (nmi_flush_l1d_sw == 1)
508 nmi_flush_l1d_sw = 0;
510 smp_rendezvous(NULL, vmx_disable, NULL, NULL);
516 vmx_enable(void *arg __unused)
519 uint64_t feature_control;
521 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
522 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
523 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
524 wrmsr(MSR_IA32_FEATURE_CONTROL,
525 feature_control | IA32_FEATURE_CONTROL_VMX_EN |
526 IA32_FEATURE_CONTROL_LOCK);
529 load_cr4(rcr4() | CR4_VMXE);
531 *(uint32_t *)vmxon_region[curcpu] = vmx_revision();
532 error = vmxon(vmxon_region[curcpu]);
534 vmxon_enabled[curcpu] = 1;
541 if (vmxon_enabled[curcpu])
542 vmxon(vmxon_region[curcpu]);
548 int error, use_tpr_shadow;
549 uint64_t basic, fixed0, fixed1, feature_control;
550 uint32_t tmp, procbased2_vid_bits;
552 /* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
553 if (!(cpu_feature2 & CPUID2_VMX)) {
554 printf("vmx_init: processor does not support VMX operation\n");
559 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
560 * are set (bits 0 and 2 respectively).
562 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
563 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
564 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
565 printf("vmx_init: VMX operation disabled by BIOS\n");
570 * Verify capabilities MSR_VMX_BASIC:
571 * - bit 54 indicates support for INS/OUTS decoding
573 basic = rdmsr(MSR_VMX_BASIC);
574 if ((basic & (1UL << 54)) == 0) {
575 printf("vmx_init: processor does not support desired basic "
580 /* Check support for primary processor-based VM-execution controls */
581 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
582 MSR_VMX_TRUE_PROCBASED_CTLS,
583 PROCBASED_CTLS_ONE_SETTING,
584 PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
586 printf("vmx_init: processor does not support desired primary "
587 "processor-based controls\n");
591 /* Clear the processor-based ctl bits that are set on demand */
592 procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
594 /* Check support for secondary processor-based VM-execution controls */
595 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
596 MSR_VMX_PROCBASED_CTLS2,
597 PROCBASED_CTLS2_ONE_SETTING,
598 PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
600 printf("vmx_init: processor does not support desired secondary "
601 "processor-based controls\n");
605 /* Check support for VPID */
606 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
607 PROCBASED2_ENABLE_VPID, 0, &tmp);
609 procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
611 /* Check support for pin-based VM-execution controls */
612 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
613 MSR_VMX_TRUE_PINBASED_CTLS,
614 PINBASED_CTLS_ONE_SETTING,
615 PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
617 printf("vmx_init: processor does not support desired "
618 "pin-based controls\n");
622 /* Check support for VM-exit controls */
623 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
624 VM_EXIT_CTLS_ONE_SETTING,
625 VM_EXIT_CTLS_ZERO_SETTING,
628 printf("vmx_init: processor does not support desired "
633 /* Check support for VM-entry controls */
634 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
635 VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
638 printf("vmx_init: processor does not support desired "
644 * Check support for optional features by testing them
647 cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
648 MSR_VMX_TRUE_PROCBASED_CTLS,
649 PROCBASED_HLT_EXITING, 0,
652 cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
653 MSR_VMX_PROCBASED_CTLS,
657 cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
658 MSR_VMX_TRUE_PROCBASED_CTLS,
659 PROCBASED_PAUSE_EXITING, 0,
662 cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
663 MSR_VMX_PROCBASED_CTLS2,
664 PROCBASED2_UNRESTRICTED_GUEST, 0,
667 cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
668 MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
672 * Check support for virtual interrupt delivery.
674 procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
675 PROCBASED2_VIRTUALIZE_X2APIC_MODE |
676 PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
677 PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
679 use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
680 MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
683 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
684 procbased2_vid_bits, 0, &tmp);
685 if (error == 0 && use_tpr_shadow) {
686 virtual_interrupt_delivery = 1;
687 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
688 &virtual_interrupt_delivery);
691 if (virtual_interrupt_delivery) {
692 procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
693 procbased_ctls2 |= procbased2_vid_bits;
694 procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
697 * No need to emulate accesses to %CR8 if virtual
698 * interrupt delivery is enabled.
700 procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
701 procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
704 * Check for Posted Interrupts only if Virtual Interrupt
705 * Delivery is enabled.
707 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
708 MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
711 pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
712 &IDTVEC(justreturn));
715 printf("vmx_init: unable to allocate "
716 "posted interrupt vector\n");
719 posted_interrupts = 1;
720 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
726 if (posted_interrupts)
727 pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
730 error = ept_init(ipinum);
732 printf("vmx_init: ept initialization failed (%d)\n", error);
736 guest_l1d_flush = (cpu_ia32_arch_caps &
737 IA32_ARCH_CAP_SKIP_L1DFL_VMENTRY) == 0;
738 TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
741 * L1D cache flush is enabled. Use IA32_FLUSH_CMD MSR when
742 * available. Otherwise fall back to the software flush
743 * method which loads enough data from the kernel text to
744 * flush existing L1D content, both on VMX entry and on NMI
747 if (guest_l1d_flush) {
748 if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
749 guest_l1d_flush_sw = 1;
750 TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
751 &guest_l1d_flush_sw);
753 if (guest_l1d_flush_sw) {
754 if (nmi_flush_l1d_sw <= 1)
755 nmi_flush_l1d_sw = 1;
757 msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
758 msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
763 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
765 fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
766 fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
767 cr0_ones_mask = fixed0 & fixed1;
768 cr0_zeros_mask = ~fixed0 & ~fixed1;
771 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
772 * if unrestricted guest execution is allowed.
774 if (cap_unrestricted_guest)
775 cr0_ones_mask &= ~(CR0_PG | CR0_PE);
778 * Do not allow the guest to set CR0_NW or CR0_CD.
780 cr0_zeros_mask |= (CR0_NW | CR0_CD);
782 fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
783 fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
784 cr4_ones_mask = fixed0 & fixed1;
785 cr4_zeros_mask = ~fixed0 & ~fixed1;
791 /* enable VMX operation */
792 smp_rendezvous(NULL, vmx_enable, NULL, NULL);
800 vmx_trigger_hostintr(int vector)
803 struct gate_descriptor *gd;
807 KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
808 "invalid vector %d", vector));
809 KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
811 KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
812 "has invalid type %d", vector, gd->gd_type));
813 KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
814 "has invalid dpl %d", vector, gd->gd_dpl));
815 KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
816 "for vector %d has invalid selector %d", vector, gd->gd_selector));
817 KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
818 "IST %d", vector, gd->gd_ist));
820 func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
825 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
827 int error, mask_ident, shadow_ident;
830 if (which != 0 && which != 4)
831 panic("vmx_setup_cr_shadow: unknown cr%d", which);
834 mask_ident = VMCS_CR0_MASK;
835 mask_value = cr0_ones_mask | cr0_zeros_mask;
836 shadow_ident = VMCS_CR0_SHADOW;
838 mask_ident = VMCS_CR4_MASK;
839 mask_value = cr4_ones_mask | cr4_zeros_mask;
840 shadow_ident = VMCS_CR4_SHADOW;
843 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
847 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
853 #define vmx_setup_cr0_shadow(vmcs,init) vmx_setup_cr_shadow(0, (vmcs), (init))
854 #define vmx_setup_cr4_shadow(vmcs,init) vmx_setup_cr_shadow(4, (vmcs), (init))
857 vmx_vminit(struct vm *vm, pmap_t pmap)
859 uint16_t vpid[VM_MAXCPU];
865 vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
866 if ((uintptr_t)vmx & PAGE_MASK) {
867 panic("malloc of struct vmx not aligned on %d byte boundary",
872 vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
875 * Clean up EPTP-tagged guest physical and combined mappings
877 * VMX transitions are not required to invalidate any guest physical
878 * mappings. So, it may be possible for stale guest physical mappings
879 * to be present in the processor TLBs.
881 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
883 ept_invalidate_mappings(vmx->eptp);
885 msr_bitmap_initialize(vmx->msr_bitmap);
888 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
889 * The guest FSBASE and GSBASE are saved and restored during
890 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
891 * always restored from the vmcs host state area on vm-exit.
893 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
894 * how they are saved/restored so can be directly accessed by the
897 * MSR_EFER is saved and restored in the guest VMCS area on a
898 * VM exit and entry respectively. It is also restored from the
899 * host VMCS area on a VM exit.
901 * The TSC MSR is exposed read-only. Writes are disallowed as
902 * that will impact the host TSC. If the guest does a write
903 * the "use TSC offsetting" execution control is enabled and the
904 * difference between the host TSC and the guest TSC is written
905 * into the TSC offset in the VMCS.
907 if (guest_msr_rw(vmx, MSR_GSBASE) ||
908 guest_msr_rw(vmx, MSR_FSBASE) ||
909 guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
910 guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
911 guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
912 guest_msr_rw(vmx, MSR_EFER) ||
913 guest_msr_ro(vmx, MSR_TSC))
914 panic("vmx_vminit: error setting guest msr access");
916 vpid_alloc(vpid, VM_MAXCPU);
918 if (virtual_interrupt_delivery) {
919 error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
920 APIC_ACCESS_ADDRESS);
921 /* XXX this should really return an error to the caller */
922 KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
925 for (i = 0; i < VM_MAXCPU; i++) {
926 vmcs = &vmx->vmcs[i];
927 vmcs->identifier = vmx_revision();
928 error = vmclear(vmcs);
930 panic("vmx_vminit: vmclear error %d on vcpu %d\n",
934 vmx_msr_guest_init(vmx, i);
936 error = vmcs_init(vmcs);
937 KASSERT(error == 0, ("vmcs_init error %d", error));
941 error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
942 error += vmwrite(VMCS_EPTP, vmx->eptp);
943 error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
944 error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
945 error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
946 error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
947 error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
948 error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
949 error += vmwrite(VMCS_VPID, vpid[i]);
951 if (guest_l1d_flush && !guest_l1d_flush_sw) {
952 vmcs_write(VMCS_ENTRY_MSR_LOAD, pmap_kextract(
953 (vm_offset_t)&msr_load_list[0]));
954 vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
955 nitems(msr_load_list));
956 vmcs_write(VMCS_EXIT_MSR_STORE, 0);
957 vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
960 /* exception bitmap */
961 if (vcpu_trace_exceptions(vm, i))
962 exc_bitmap = 0xffffffff;
964 exc_bitmap = 1 << IDT_MC;
965 error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
967 vmx->ctx[i].guest_dr6 = DBREG_DR6_RESERVED1;
968 error += vmwrite(VMCS_GUEST_DR7, DBREG_DR7_RESERVED1);
970 if (virtual_interrupt_delivery) {
971 error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
972 error += vmwrite(VMCS_VIRTUAL_APIC,
973 vtophys(&vmx->apic_page[i]));
974 error += vmwrite(VMCS_EOI_EXIT0, 0);
975 error += vmwrite(VMCS_EOI_EXIT1, 0);
976 error += vmwrite(VMCS_EOI_EXIT2, 0);
977 error += vmwrite(VMCS_EOI_EXIT3, 0);
979 if (posted_interrupts) {
980 error += vmwrite(VMCS_PIR_VECTOR, pirvec);
981 error += vmwrite(VMCS_PIR_DESC,
982 vtophys(&vmx->pir_desc[i]));
985 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
988 vmx->cap[i].proc_ctls = procbased_ctls;
989 vmx->cap[i].proc_ctls2 = procbased_ctls2;
991 vmx->state[i].nextrip = ~0;
992 vmx->state[i].lastcpu = NOCPU;
993 vmx->state[i].vpid = vpid[i];
996 * Set up the CR0/4 shadows, and init the read shadow
997 * to the power-on register value from the Intel Sys Arch.
1001 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
1003 panic("vmx_setup_cr0_shadow %d", error);
1005 error = vmx_setup_cr4_shadow(vmcs, 0);
1007 panic("vmx_setup_cr4_shadow %d", error);
1009 vmx->ctx[i].pmap = pmap;
1016 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
1020 func = vmxctx->guest_rax;
1022 handled = x86_emulate_cpuid(vm, vcpu,
1023 (uint32_t*)(&vmxctx->guest_rax),
1024 (uint32_t*)(&vmxctx->guest_rbx),
1025 (uint32_t*)(&vmxctx->guest_rcx),
1026 (uint32_t*)(&vmxctx->guest_rdx));
1030 static __inline void
1031 vmx_run_trace(struct vmx *vmx, int vcpu)
1034 VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
1038 static __inline void
1039 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
1043 VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
1044 handled ? "handled" : "unhandled",
1045 exit_reason_to_str(exit_reason), rip);
1049 static __inline void
1050 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1053 VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1057 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1058 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1061 * Invalidate guest mappings identified by its vpid from the TLB.
1063 static __inline void
1064 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1066 struct vmxstate *vmxstate;
1067 struct invvpid_desc invvpid_desc;
1069 vmxstate = &vmx->state[vcpu];
1070 if (vmxstate->vpid == 0)
1075 * Set the 'lastcpu' to an invalid host cpu.
1077 * This will invalidate TLB entries tagged with the vcpu's
1078 * vpid the next time it runs via vmx_set_pcpu_defaults().
1080 vmxstate->lastcpu = NOCPU;
1084 KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1085 "critical section", __func__, vcpu));
1088 * Invalidate all mappings tagged with 'vpid'
1090 * We do this because this vcpu was executing on a different host
1091 * cpu when it last ran. We do not track whether it invalidated
1092 * mappings associated with its 'vpid' during that run. So we must
1093 * assume that the mappings associated with 'vpid' on 'curcpu' are
1094 * stale and invalidate them.
1096 * Note that we incur this penalty only when the scheduler chooses to
1097 * move the thread associated with this vcpu between host cpus.
1099 * Note also that this will invalidate mappings tagged with 'vpid'
1102 if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1103 invvpid_desc._res1 = 0;
1104 invvpid_desc._res2 = 0;
1105 invvpid_desc.vpid = vmxstate->vpid;
1106 invvpid_desc.linear_addr = 0;
1107 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1108 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1111 * The invvpid can be skipped if an invept is going to
1112 * be performed before entering the guest. The invept
1113 * will invalidate combined mappings tagged with
1114 * 'vmx->eptp' for all vpids.
1116 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1121 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1123 struct vmxstate *vmxstate;
1125 vmxstate = &vmx->state[vcpu];
1126 if (vmxstate->lastcpu == curcpu)
1129 vmxstate->lastcpu = curcpu;
1131 vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1133 vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1134 vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1135 vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1136 vmx_invvpid(vmx, vcpu, pmap, 1);
1140 * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1142 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1144 static void __inline
1145 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1148 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1149 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1150 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1151 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1155 static void __inline
1156 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1159 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1160 ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1161 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1162 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1163 VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1166 static void __inline
1167 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1170 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1171 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1172 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1173 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1177 static void __inline
1178 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1181 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1182 ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1183 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1184 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1185 VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1189 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1193 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1194 vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1195 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1196 VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1199 error = vmwrite(VMCS_TSC_OFFSET, offset);
1204 #define NMI_BLOCKING (VMCS_INTERRUPTIBILITY_NMI_BLOCKING | \
1205 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1206 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING | \
1207 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1210 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1214 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1215 KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1216 "interruptibility-state %#x", gi));
1218 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1219 KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1220 "VM-entry interruption information %#x", info));
1223 * Inject the virtual NMI. The vector must be the NMI IDT entry
1224 * or the VMCS entry check will fail.
1226 info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1227 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1229 VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1231 /* Clear the request */
1232 vm_nmi_clear(vmx->vm, vcpu);
1236 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1239 int vector, need_nmi_exiting, extint_pending;
1240 uint64_t rflags, entryinfo;
1243 if (vmx->state[vcpu].nextrip != guestrip) {
1244 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1245 if (gi & HWINTR_BLOCKING) {
1246 VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1247 "cleared due to rip change: %#lx/%#lx",
1248 vmx->state[vcpu].nextrip, guestrip);
1249 gi &= ~HWINTR_BLOCKING;
1250 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1254 if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1255 KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1256 "intinfo is not valid: %#lx", __func__, entryinfo));
1258 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1259 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1260 "pending exception: %#lx/%#x", __func__, entryinfo, info));
1263 vector = info & 0xff;
1264 if (vector == IDT_BP || vector == IDT_OF) {
1266 * VT-x requires #BP and #OF to be injected as software
1269 info &= ~VMCS_INTR_T_MASK;
1270 info |= VMCS_INTR_T_SWEXCEPTION;
1273 if (info & VMCS_INTR_DEL_ERRCODE)
1274 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1276 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1279 if (vm_nmi_pending(vmx->vm, vcpu)) {
1281 * If there are no conditions blocking NMI injection then
1282 * inject it directly here otherwise enable "NMI window
1283 * exiting" to inject it as soon as we can.
1285 * We also check for STI_BLOCKING because some implementations
1286 * don't allow NMI injection in this case. If we are running
1287 * on a processor that doesn't have this restriction it will
1288 * immediately exit and the NMI will be injected in the
1289 * "NMI window exiting" handler.
1291 need_nmi_exiting = 1;
1292 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1293 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1294 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1295 if ((info & VMCS_INTR_VALID) == 0) {
1296 vmx_inject_nmi(vmx, vcpu);
1297 need_nmi_exiting = 0;
1299 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1300 "due to VM-entry intr info %#x", info);
1303 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1304 "Guest Interruptibility-state %#x", gi);
1307 if (need_nmi_exiting)
1308 vmx_set_nmi_window_exiting(vmx, vcpu);
1311 extint_pending = vm_extint_pending(vmx->vm, vcpu);
1313 if (!extint_pending && virtual_interrupt_delivery) {
1314 vmx_inject_pir(vlapic);
1319 * If interrupt-window exiting is already in effect then don't bother
1320 * checking for pending interrupts. This is just an optimization and
1321 * not needed for correctness.
1323 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1324 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1325 "pending int_window_exiting");
1329 if (!extint_pending) {
1330 /* Ask the local apic for a vector to inject */
1331 if (!vlapic_pending_intr(vlapic, &vector))
1335 * From the Intel SDM, Volume 3, Section "Maskable
1336 * Hardware Interrupts":
1337 * - maskable interrupt vectors [16,255] can be delivered
1338 * through the local APIC.
1340 KASSERT(vector >= 16 && vector <= 255,
1341 ("invalid vector %d from local APIC", vector));
1343 /* Ask the legacy pic for a vector to inject */
1344 vatpic_pending_intr(vmx->vm, &vector);
1347 * From the Intel SDM, Volume 3, Section "Maskable
1348 * Hardware Interrupts":
1349 * - maskable interrupt vectors [0,255] can be delivered
1350 * through the INTR pin.
1352 KASSERT(vector >= 0 && vector <= 255,
1353 ("invalid vector %d from INTR", vector));
1356 /* Check RFLAGS.IF and the interruptibility state of the guest */
1357 rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1358 if ((rflags & PSL_I) == 0) {
1359 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1360 "rflags %#lx", vector, rflags);
1364 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1365 if (gi & HWINTR_BLOCKING) {
1366 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1367 "Guest Interruptibility-state %#x", vector, gi);
1371 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1372 if (info & VMCS_INTR_VALID) {
1374 * This is expected and could happen for multiple reasons:
1375 * - A vectoring VM-entry was aborted due to astpending
1376 * - A VM-exit happened during event injection.
1377 * - An exception was injected above.
1378 * - An NMI was injected above or after "NMI window exiting"
1380 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1381 "VM-entry intr info %#x", vector, info);
1385 /* Inject the interrupt */
1386 info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1388 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1390 if (!extint_pending) {
1391 /* Update the Local APIC ISR */
1392 vlapic_intr_accepted(vlapic, vector);
1394 vm_extint_clear(vmx->vm, vcpu);
1395 vatpic_intr_accepted(vmx->vm, vector);
1398 * After we accepted the current ExtINT the PIC may
1399 * have posted another one. If that is the case, set
1400 * the Interrupt Window Exiting execution control so
1401 * we can inject that one too.
1403 * Also, interrupt window exiting allows us to inject any
1404 * pending APIC vector that was preempted by the ExtINT
1405 * as soon as possible. This applies both for the software
1406 * emulated vlapic and the hardware assisted virtual APIC.
1408 vmx_set_int_window_exiting(vmx, vcpu);
1411 VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1417 * Set the Interrupt Window Exiting execution control so we can inject
1418 * the interrupt as soon as blocking condition goes away.
1420 vmx_set_int_window_exiting(vmx, vcpu);
1424 * If the Virtual NMIs execution control is '1' then the logical processor
1425 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1426 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1427 * virtual-NMI blocking.
1429 * This unblocking occurs even if the IRET causes a fault. In this case the
1430 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1433 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1437 VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1438 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1439 gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1440 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1444 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1448 VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1449 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1450 gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1451 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1455 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1459 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1460 KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1461 ("NMI blocking is not in effect %#x", gi));
1465 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1467 struct vmxctx *vmxctx;
1469 const struct xsave_limits *limits;
1471 vmxctx = &vmx->ctx[vcpu];
1472 limits = vmm_get_xsave_limits();
1475 * Note that the processor raises a GP# fault on its own if
1476 * xsetbv is executed for CPL != 0, so we do not have to
1477 * emulate that fault here.
1480 /* Only xcr0 is supported. */
1481 if (vmxctx->guest_rcx != 0) {
1482 vm_inject_gp(vmx->vm, vcpu);
1486 /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1487 if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1488 vm_inject_ud(vmx->vm, vcpu);
1492 xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1493 if ((xcrval & ~limits->xcr0_allowed) != 0) {
1494 vm_inject_gp(vmx->vm, vcpu);
1498 if (!(xcrval & XFEATURE_ENABLED_X87)) {
1499 vm_inject_gp(vmx->vm, vcpu);
1503 /* AVX (YMM_Hi128) requires SSE. */
1504 if (xcrval & XFEATURE_ENABLED_AVX &&
1505 (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1506 vm_inject_gp(vmx->vm, vcpu);
1511 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1512 * ZMM_Hi256, and Hi16_ZMM.
1514 if (xcrval & XFEATURE_AVX512 &&
1515 (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1516 (XFEATURE_AVX512 | XFEATURE_AVX)) {
1517 vm_inject_gp(vmx->vm, vcpu);
1522 * Intel MPX requires both bound register state flags to be
1525 if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1526 ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1527 vm_inject_gp(vmx->vm, vcpu);
1532 * This runs "inside" vmrun() with the guest's FPU state, so
1533 * modifying xcr0 directly modifies the guest's xcr0, not the
1536 load_xcr(0, xcrval);
1541 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1543 const struct vmxctx *vmxctx;
1545 vmxctx = &vmx->ctx[vcpu];
1549 return (vmxctx->guest_rax);
1551 return (vmxctx->guest_rcx);
1553 return (vmxctx->guest_rdx);
1555 return (vmxctx->guest_rbx);
1557 return (vmcs_read(VMCS_GUEST_RSP));
1559 return (vmxctx->guest_rbp);
1561 return (vmxctx->guest_rsi);
1563 return (vmxctx->guest_rdi);
1565 return (vmxctx->guest_r8);
1567 return (vmxctx->guest_r9);
1569 return (vmxctx->guest_r10);
1571 return (vmxctx->guest_r11);
1573 return (vmxctx->guest_r12);
1575 return (vmxctx->guest_r13);
1577 return (vmxctx->guest_r14);
1579 return (vmxctx->guest_r15);
1581 panic("invalid vmx register %d", ident);
1586 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1588 struct vmxctx *vmxctx;
1590 vmxctx = &vmx->ctx[vcpu];
1594 vmxctx->guest_rax = regval;
1597 vmxctx->guest_rcx = regval;
1600 vmxctx->guest_rdx = regval;
1603 vmxctx->guest_rbx = regval;
1606 vmcs_write(VMCS_GUEST_RSP, regval);
1609 vmxctx->guest_rbp = regval;
1612 vmxctx->guest_rsi = regval;
1615 vmxctx->guest_rdi = regval;
1618 vmxctx->guest_r8 = regval;
1621 vmxctx->guest_r9 = regval;
1624 vmxctx->guest_r10 = regval;
1627 vmxctx->guest_r11 = regval;
1630 vmxctx->guest_r12 = regval;
1633 vmxctx->guest_r13 = regval;
1636 vmxctx->guest_r14 = regval;
1639 vmxctx->guest_r15 = regval;
1642 panic("invalid vmx register %d", ident);
1647 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1649 uint64_t crval, regval;
1651 /* We only handle mov to %cr0 at this time */
1652 if ((exitqual & 0xf0) != 0x00)
1655 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1657 vmcs_write(VMCS_CR0_SHADOW, regval);
1659 crval = regval | cr0_ones_mask;
1660 crval &= ~cr0_zeros_mask;
1661 vmcs_write(VMCS_GUEST_CR0, crval);
1663 if (regval & CR0_PG) {
1664 uint64_t efer, entry_ctls;
1667 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1668 * the "IA-32e mode guest" bit in VM-entry control must be
1671 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1672 if (efer & EFER_LME) {
1674 vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1675 entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1676 entry_ctls |= VM_ENTRY_GUEST_LMA;
1677 vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1685 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1687 uint64_t crval, regval;
1689 /* We only handle mov to %cr4 at this time */
1690 if ((exitqual & 0xf0) != 0x00)
1693 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1695 vmcs_write(VMCS_CR4_SHADOW, regval);
1697 crval = regval | cr4_ones_mask;
1698 crval &= ~cr4_zeros_mask;
1699 vmcs_write(VMCS_GUEST_CR4, crval);
1705 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1707 struct vlapic *vlapic;
1711 /* We only handle mov %cr8 to/from a register at this time. */
1712 if ((exitqual & 0xe0) != 0x00) {
1716 vlapic = vm_lapic(vmx->vm, vcpu);
1717 regnum = (exitqual >> 8) & 0xf;
1718 if (exitqual & 0x10) {
1719 cr8 = vlapic_get_cr8(vlapic);
1720 vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1722 cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1723 vlapic_set_cr8(vlapic, cr8);
1730 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1737 ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1738 return ((ssar >> 5) & 0x3);
1741 static enum vm_cpu_mode
1746 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1747 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1749 return (CPU_MODE_64BIT); /* CS.L = 1 */
1751 return (CPU_MODE_COMPATIBILITY);
1752 } else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1753 return (CPU_MODE_PROTECTED);
1755 return (CPU_MODE_REAL);
1759 static enum vm_paging_mode
1760 vmx_paging_mode(void)
1763 if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1764 return (PAGING_MODE_FLAT);
1765 if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1766 return (PAGING_MODE_32);
1767 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1768 return (PAGING_MODE_64);
1770 return (PAGING_MODE_PAE);
1774 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1778 enum vm_reg_name reg;
1780 reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1781 error = vmx_getreg(vmx, vcpuid, reg, &val);
1782 KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1787 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1793 error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1794 KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1802 inout_str_addrsize(uint32_t inst_info)
1806 size = (inst_info >> 7) & 0x7;
1809 return (2); /* 16 bit */
1811 return (4); /* 32 bit */
1813 return (8); /* 64 bit */
1815 panic("%s: invalid size encoding %d", __func__, size);
1820 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1821 struct vm_inout_str *vis)
1826 vis->seg_name = VM_REG_GUEST_ES;
1828 s = (inst_info >> 15) & 0x7;
1829 vis->seg_name = vm_segment_name(s);
1832 error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1833 KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1837 vmx_paging_info(struct vm_guest_paging *paging)
1839 paging->cr3 = vmcs_guest_cr3();
1840 paging->cpl = vmx_cpl();
1841 paging->cpu_mode = vmx_cpu_mode();
1842 paging->paging_mode = vmx_paging_mode();
1846 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1848 struct vm_guest_paging *paging;
1851 paging = &vmexit->u.inst_emul.paging;
1853 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1854 vmexit->inst_length = 0;
1855 vmexit->u.inst_emul.gpa = gpa;
1856 vmexit->u.inst_emul.gla = gla;
1857 vmx_paging_info(paging);
1858 switch (paging->cpu_mode) {
1860 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1861 vmexit->u.inst_emul.cs_d = 0;
1863 case CPU_MODE_PROTECTED:
1864 case CPU_MODE_COMPATIBILITY:
1865 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1866 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1867 vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1870 vmexit->u.inst_emul.cs_base = 0;
1871 vmexit->u.inst_emul.cs_d = 0;
1874 vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1878 ept_fault_type(uint64_t ept_qual)
1882 if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1883 fault_type = VM_PROT_WRITE;
1884 else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1885 fault_type = VM_PROT_EXECUTE;
1887 fault_type= VM_PROT_READ;
1889 return (fault_type);
1893 ept_emulation_fault(uint64_t ept_qual)
1897 /* EPT fault on an instruction fetch doesn't make sense here */
1898 if (ept_qual & EPT_VIOLATION_INST_FETCH)
1901 /* EPT fault must be a read fault or a write fault */
1902 read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1903 write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1904 if ((read | write) == 0)
1908 * The EPT violation must have been caused by accessing a
1909 * guest-physical address that is a translation of a guest-linear
1912 if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1913 (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1921 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1923 uint32_t proc_ctls2;
1925 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1926 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1930 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1932 uint32_t proc_ctls2;
1934 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1935 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1939 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1942 int error, handled, offset;
1943 uint32_t *apic_regs, vector;
1947 offset = APIC_WRITE_OFFSET(qual);
1949 if (!apic_access_virtualization(vmx, vcpuid)) {
1951 * In general there should not be any APIC write VM-exits
1952 * unless APIC-access virtualization is enabled.
1954 * However self-IPI virtualization can legitimately trigger
1955 * an APIC-write VM-exit so treat it specially.
1957 if (x2apic_virtualization(vmx, vcpuid) &&
1958 offset == APIC_OFFSET_SELF_IPI) {
1959 apic_regs = (uint32_t *)(vlapic->apic_page);
1960 vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1961 vlapic_self_ipi_handler(vlapic, vector);
1968 case APIC_OFFSET_ID:
1969 vlapic_id_write_handler(vlapic);
1971 case APIC_OFFSET_LDR:
1972 vlapic_ldr_write_handler(vlapic);
1974 case APIC_OFFSET_DFR:
1975 vlapic_dfr_write_handler(vlapic);
1977 case APIC_OFFSET_SVR:
1978 vlapic_svr_write_handler(vlapic);
1980 case APIC_OFFSET_ESR:
1981 vlapic_esr_write_handler(vlapic);
1983 case APIC_OFFSET_ICR_LOW:
1985 error = vlapic_icrlo_write_handler(vlapic, &retu);
1986 if (error != 0 || retu)
1987 handled = UNHANDLED;
1989 case APIC_OFFSET_CMCI_LVT:
1990 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1991 vlapic_lvt_write_handler(vlapic, offset);
1993 case APIC_OFFSET_TIMER_ICR:
1994 vlapic_icrtmr_write_handler(vlapic);
1996 case APIC_OFFSET_TIMER_DCR:
1997 vlapic_dcr_write_handler(vlapic);
2000 handled = UNHANDLED;
2007 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
2010 if (apic_access_virtualization(vmx, vcpuid) &&
2011 (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
2018 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2021 int access_type, offset, allowed;
2023 if (!apic_access_virtualization(vmx, vcpuid))
2026 qual = vmexit->u.vmx.exit_qualification;
2027 access_type = APIC_ACCESS_TYPE(qual);
2028 offset = APIC_ACCESS_OFFSET(qual);
2031 if (access_type == 0) {
2033 * Read data access to the following registers is expected.
2036 case APIC_OFFSET_APR:
2037 case APIC_OFFSET_PPR:
2038 case APIC_OFFSET_RRR:
2039 case APIC_OFFSET_CMCI_LVT:
2040 case APIC_OFFSET_TIMER_CCR:
2046 } else if (access_type == 1) {
2048 * Write data access to the following registers is expected.
2051 case APIC_OFFSET_VER:
2052 case APIC_OFFSET_APR:
2053 case APIC_OFFSET_PPR:
2054 case APIC_OFFSET_RRR:
2055 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2056 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2057 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2058 case APIC_OFFSET_CMCI_LVT:
2059 case APIC_OFFSET_TIMER_CCR:
2068 vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2073 * Regardless of whether the APIC-access is allowed this handler
2074 * always returns UNHANDLED:
2075 * - if the access is allowed then it is handled by emulating the
2076 * instruction that caused the VM-exit (outside the critical section)
2077 * - if the access is not allowed then it will be converted to an
2078 * exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2083 static enum task_switch_reason
2084 vmx_task_switch_reason(uint64_t qual)
2088 reason = (qual >> 30) & 0x3;
2097 return (TSR_IDT_GATE);
2099 panic("%s: invalid reason %d", __func__, reason);
2104 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2109 error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2111 error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2117 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2119 struct vmxctx *vmxctx;
2125 error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2127 error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2131 vmxctx = &vmx->ctx[vcpuid];
2132 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2133 KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2136 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2137 KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2144 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2146 int error, errcode, errcode_valid, handled, in;
2147 struct vmxctx *vmxctx;
2148 struct vlapic *vlapic;
2149 struct vm_inout_str *vis;
2150 struct vm_task_switch *ts;
2151 uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2152 uint32_t intr_type, intr_vec, reason;
2153 uint64_t exitintinfo, qual, gpa;
2156 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2157 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2159 handled = UNHANDLED;
2160 vmxctx = &vmx->ctx[vcpu];
2162 qual = vmexit->u.vmx.exit_qualification;
2163 reason = vmexit->u.vmx.exit_reason;
2164 vmexit->exitcode = VM_EXITCODE_BOGUS;
2166 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2169 * VM-entry failures during or after loading guest state.
2171 * These VM-exits are uncommon but must be handled specially
2172 * as most VM-exit fields are not populated as usual.
2174 if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2175 VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2176 __asm __volatile("int $18");
2181 * VM exits that can be triggered during event delivery need to
2182 * be handled specially by re-injecting the event if the IDT
2183 * vectoring information field's valid bit is set.
2185 * See "Information for VM Exits During Event Delivery" in Intel SDM
2188 idtvec_info = vmcs_idt_vectoring_info();
2189 if (idtvec_info & VMCS_IDT_VEC_VALID) {
2190 idtvec_info &= ~(1 << 12); /* clear undefined bit */
2191 exitintinfo = idtvec_info;
2192 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2193 idtvec_err = vmcs_idt_vectoring_err();
2194 exitintinfo |= (uint64_t)idtvec_err << 32;
2196 error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2197 KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2201 * If 'virtual NMIs' are being used and the VM-exit
2202 * happened while injecting an NMI during the previous
2203 * VM-entry, then clear "blocking by NMI" in the
2204 * Guest Interruptibility-State so the NMI can be
2205 * reinjected on the subsequent VM-entry.
2207 * However, if the NMI was being delivered through a task
2208 * gate, then the new task must start execution with NMIs
2209 * blocked so don't clear NMI blocking in this case.
2211 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2212 if (intr_type == VMCS_INTR_T_NMI) {
2213 if (reason != EXIT_REASON_TASK_SWITCH)
2214 vmx_clear_nmi_blocking(vmx, vcpu);
2216 vmx_assert_nmi_blocking(vmx, vcpu);
2220 * Update VM-entry instruction length if the event being
2221 * delivered was a software interrupt or software exception.
2223 if (intr_type == VMCS_INTR_T_SWINTR ||
2224 intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2225 intr_type == VMCS_INTR_T_SWEXCEPTION) {
2226 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2231 case EXIT_REASON_TASK_SWITCH:
2232 ts = &vmexit->u.task_switch;
2233 ts->tsssel = qual & 0xffff;
2234 ts->reason = vmx_task_switch_reason(qual);
2236 ts->errcode_valid = 0;
2237 vmx_paging_info(&ts->paging);
2239 * If the task switch was due to a CALL, JMP, IRET, software
2240 * interrupt (INT n) or software exception (INT3, INTO),
2241 * then the saved %rip references the instruction that caused
2242 * the task switch. The instruction length field in the VMCS
2243 * is valid in this case.
2245 * In all other cases (e.g., NMI, hardware exception) the
2246 * saved %rip is one that would have been saved in the old TSS
2247 * had the task switch completed normally so the instruction
2248 * length field is not needed in this case and is explicitly
2251 if (ts->reason == TSR_IDT_GATE) {
2252 KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2253 ("invalid idtvec_info %#x for IDT task switch",
2255 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2256 if (intr_type != VMCS_INTR_T_SWINTR &&
2257 intr_type != VMCS_INTR_T_SWEXCEPTION &&
2258 intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2259 /* Task switch triggered by external event */
2261 vmexit->inst_length = 0;
2262 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2263 ts->errcode_valid = 1;
2264 ts->errcode = vmcs_idt_vectoring_err();
2268 vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2269 VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2270 "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2271 ts->ext ? "external" : "internal",
2272 ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2274 case EXIT_REASON_CR_ACCESS:
2275 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2276 switch (qual & 0xf) {
2278 handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2281 handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2284 handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2288 case EXIT_REASON_RDMSR:
2289 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2291 ecx = vmxctx->guest_rcx;
2292 VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2293 error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2295 vmexit->exitcode = VM_EXITCODE_RDMSR;
2296 vmexit->u.msr.code = ecx;
2300 /* Return to userspace with a valid exitcode */
2301 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2302 ("emulate_rdmsr retu with bogus exitcode"));
2305 case EXIT_REASON_WRMSR:
2306 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2308 eax = vmxctx->guest_rax;
2309 ecx = vmxctx->guest_rcx;
2310 edx = vmxctx->guest_rdx;
2311 VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2312 ecx, (uint64_t)edx << 32 | eax);
2313 error = emulate_wrmsr(vmx, vcpu, ecx,
2314 (uint64_t)edx << 32 | eax, &retu);
2316 vmexit->exitcode = VM_EXITCODE_WRMSR;
2317 vmexit->u.msr.code = ecx;
2318 vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2322 /* Return to userspace with a valid exitcode */
2323 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2324 ("emulate_wrmsr retu with bogus exitcode"));
2327 case EXIT_REASON_HLT:
2328 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2329 vmexit->exitcode = VM_EXITCODE_HLT;
2330 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2332 case EXIT_REASON_MTF:
2333 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2334 vmexit->exitcode = VM_EXITCODE_MTRAP;
2335 vmexit->inst_length = 0;
2337 case EXIT_REASON_PAUSE:
2338 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2339 vmexit->exitcode = VM_EXITCODE_PAUSE;
2341 case EXIT_REASON_INTR_WINDOW:
2342 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2343 vmx_clear_int_window_exiting(vmx, vcpu);
2345 case EXIT_REASON_EXT_INTR:
2347 * External interrupts serve only to cause VM exits and allow
2348 * the host interrupt handler to run.
2350 * If this external interrupt triggers a virtual interrupt
2351 * to a VM, then that state will be recorded by the
2352 * host interrupt handler in the VM's softc. We will inject
2353 * this virtual interrupt during the subsequent VM enter.
2355 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2358 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2359 * This appears to be a bug in VMware Fusion?
2361 if (!(intr_info & VMCS_INTR_VALID))
2363 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2364 (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2365 ("VM exit interruption info invalid: %#x", intr_info));
2366 vmx_trigger_hostintr(intr_info & 0xff);
2369 * This is special. We want to treat this as an 'handled'
2370 * VM-exit but not increment the instruction pointer.
2372 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2374 case EXIT_REASON_NMI_WINDOW:
2375 /* Exit to allow the pending virtual NMI to be injected */
2376 if (vm_nmi_pending(vmx->vm, vcpu))
2377 vmx_inject_nmi(vmx, vcpu);
2378 vmx_clear_nmi_window_exiting(vmx, vcpu);
2379 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2381 case EXIT_REASON_INOUT:
2382 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2383 vmexit->exitcode = VM_EXITCODE_INOUT;
2384 vmexit->u.inout.bytes = (qual & 0x7) + 1;
2385 vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2386 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2387 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2388 vmexit->u.inout.port = (uint16_t)(qual >> 16);
2389 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2390 if (vmexit->u.inout.string) {
2391 inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2392 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2393 vis = &vmexit->u.inout_str;
2394 vmx_paging_info(&vis->paging);
2395 vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2396 vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2397 vis->index = inout_str_index(vmx, vcpu, in);
2398 vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2399 vis->addrsize = inout_str_addrsize(inst_info);
2400 inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2403 case EXIT_REASON_CPUID:
2404 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2405 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2407 case EXIT_REASON_EXCEPTION:
2408 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2409 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2410 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2411 ("VM exit interruption info invalid: %#x", intr_info));
2413 intr_vec = intr_info & 0xff;
2414 intr_type = intr_info & VMCS_INTR_T_MASK;
2417 * If Virtual NMIs control is 1 and the VM-exit is due to a
2418 * fault encountered during the execution of IRET then we must
2419 * restore the state of "virtual-NMI blocking" before resuming
2422 * See "Resuming Guest Software after Handling an Exception".
2423 * See "Information for VM Exits Due to Vectored Events".
2425 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2426 (intr_vec != IDT_DF) &&
2427 (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2428 vmx_restore_nmi_blocking(vmx, vcpu);
2431 * The NMI has already been handled in vmx_exit_handle_nmi().
2433 if (intr_type == VMCS_INTR_T_NMI)
2437 * Call the machine check handler by hand. Also don't reflect
2438 * the machine check back into the guest.
2440 if (intr_vec == IDT_MC) {
2441 VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2442 __asm __volatile("int $18");
2446 if (intr_vec == IDT_PF) {
2447 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2448 KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2453 * Software exceptions exhibit trap-like behavior. This in
2454 * turn requires populating the VM-entry instruction length
2455 * so that the %rip in the trap frame is past the INT3/INTO
2458 if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2459 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2461 /* Reflect all other exceptions back into the guest */
2462 errcode_valid = errcode = 0;
2463 if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2465 errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2467 VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2468 "the guest", intr_vec, errcode);
2469 error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2470 errcode_valid, errcode, 0);
2471 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2475 case EXIT_REASON_EPT_FAULT:
2477 * If 'gpa' lies within the address space allocated to
2478 * memory then this must be a nested page fault otherwise
2479 * this must be an instruction that accesses MMIO space.
2482 if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2483 apic_access_fault(vmx, vcpu, gpa)) {
2484 vmexit->exitcode = VM_EXITCODE_PAGING;
2485 vmexit->inst_length = 0;
2486 vmexit->u.paging.gpa = gpa;
2487 vmexit->u.paging.fault_type = ept_fault_type(qual);
2488 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2489 } else if (ept_emulation_fault(qual)) {
2490 vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2491 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2494 * If Virtual NMIs control is 1 and the VM-exit is due to an
2495 * EPT fault during the execution of IRET then we must restore
2496 * the state of "virtual-NMI blocking" before resuming.
2498 * See description of "NMI unblocking due to IRET" in
2499 * "Exit Qualification for EPT Violations".
2501 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2502 (qual & EXIT_QUAL_NMIUDTI) != 0)
2503 vmx_restore_nmi_blocking(vmx, vcpu);
2505 case EXIT_REASON_VIRTUALIZED_EOI:
2506 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2507 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2508 vmexit->inst_length = 0; /* trap-like */
2510 case EXIT_REASON_APIC_ACCESS:
2511 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2513 case EXIT_REASON_APIC_WRITE:
2515 * APIC-write VM exit is trap-like so the %rip is already
2516 * pointing to the next instruction.
2518 vmexit->inst_length = 0;
2519 vlapic = vm_lapic(vmx->vm, vcpu);
2520 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2522 case EXIT_REASON_XSETBV:
2523 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2525 case EXIT_REASON_MONITOR:
2526 vmexit->exitcode = VM_EXITCODE_MONITOR;
2528 case EXIT_REASON_MWAIT:
2529 vmexit->exitcode = VM_EXITCODE_MWAIT;
2532 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2538 * It is possible that control is returned to userland
2539 * even though we were able to handle the VM exit in the
2542 * In such a case we want to make sure that the userland
2543 * restarts guest execution at the instruction *after*
2544 * the one we just processed. Therefore we update the
2545 * guest rip in the VMCS and in 'vmexit'.
2547 vmexit->rip += vmexit->inst_length;
2548 vmexit->inst_length = 0;
2549 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2551 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2553 * If this VM exit was not claimed by anybody then
2554 * treat it as a generic VMX exit.
2556 vmexit->exitcode = VM_EXITCODE_VMX;
2557 vmexit->u.vmx.status = VM_SUCCESS;
2558 vmexit->u.vmx.inst_type = 0;
2559 vmexit->u.vmx.inst_error = 0;
2562 * The exitcode and collateral have been populated.
2563 * The VM exit will be processed further in userland.
2570 static __inline void
2571 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2574 KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2575 ("vmx_exit_inst_error: invalid inst_fail_status %d",
2576 vmxctx->inst_fail_status));
2578 vmexit->inst_length = 0;
2579 vmexit->exitcode = VM_EXITCODE_VMX;
2580 vmexit->u.vmx.status = vmxctx->inst_fail_status;
2581 vmexit->u.vmx.inst_error = vmcs_instruction_error();
2582 vmexit->u.vmx.exit_reason = ~0;
2583 vmexit->u.vmx.exit_qualification = ~0;
2586 case VMX_VMRESUME_ERROR:
2587 case VMX_VMLAUNCH_ERROR:
2588 case VMX_INVEPT_ERROR:
2589 vmexit->u.vmx.inst_type = rc;
2592 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2597 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2598 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2599 * sufficient to simply vector to the NMI handler via a software interrupt.
2600 * However, this must be done before maskable interrupts are enabled
2601 * otherwise the "iret" issued by an interrupt handler will incorrectly
2602 * clear NMI blocking.
2604 static __inline void
2605 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2609 KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2611 if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2614 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2615 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2616 ("VM exit interruption info invalid: %#x", intr_info));
2618 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2619 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2620 "to NMI has invalid vector: %#x", intr_info));
2621 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2622 __asm __volatile("int $2");
2626 static __inline void
2627 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2631 /* Save host control debug registers. */
2632 vmxctx->host_dr7 = rdr7();
2633 vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2636 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2637 * exceptions in the host based on the guest DRx values. The
2638 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2641 wrmsr(MSR_DEBUGCTLMSR, 0);
2644 * Disable single stepping the kernel to avoid corrupting the
2645 * guest DR6. A debugger might still be able to corrupt the
2646 * guest DR6 by setting a breakpoint after this point and then
2649 rflags = read_rflags();
2650 vmxctx->host_tf = rflags & PSL_T;
2651 write_rflags(rflags & ~PSL_T);
2653 /* Save host debug registers. */
2654 vmxctx->host_dr0 = rdr0();
2655 vmxctx->host_dr1 = rdr1();
2656 vmxctx->host_dr2 = rdr2();
2657 vmxctx->host_dr3 = rdr3();
2658 vmxctx->host_dr6 = rdr6();
2660 /* Restore guest debug registers. */
2661 load_dr0(vmxctx->guest_dr0);
2662 load_dr1(vmxctx->guest_dr1);
2663 load_dr2(vmxctx->guest_dr2);
2664 load_dr3(vmxctx->guest_dr3);
2665 load_dr6(vmxctx->guest_dr6);
2668 static __inline void
2669 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2672 /* Save guest debug registers. */
2673 vmxctx->guest_dr0 = rdr0();
2674 vmxctx->guest_dr1 = rdr1();
2675 vmxctx->guest_dr2 = rdr2();
2676 vmxctx->guest_dr3 = rdr3();
2677 vmxctx->guest_dr6 = rdr6();
2680 * Restore host debug registers. Restore DR7, DEBUGCTL, and
2683 load_dr0(vmxctx->host_dr0);
2684 load_dr1(vmxctx->host_dr1);
2685 load_dr2(vmxctx->host_dr2);
2686 load_dr3(vmxctx->host_dr3);
2687 load_dr6(vmxctx->host_dr6);
2688 wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2689 load_dr7(vmxctx->host_dr7);
2690 write_rflags(read_rflags() | vmxctx->host_tf);
2694 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2695 struct vm_eventinfo *evinfo)
2697 int rc, handled, launched;
2700 struct vmxctx *vmxctx;
2702 struct vm_exit *vmexit;
2703 struct vlapic *vlapic;
2704 uint32_t exit_reason;
2705 struct region_descriptor gdtr, idtr;
2710 vmcs = &vmx->vmcs[vcpu];
2711 vmxctx = &vmx->ctx[vcpu];
2712 vlapic = vm_lapic(vm, vcpu);
2713 vmexit = vm_exitinfo(vm, vcpu);
2716 KASSERT(vmxctx->pmap == pmap,
2717 ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2719 vmx_msr_guest_enter(vmx, vcpu);
2725 * We do this every time because we may setup the virtual machine
2726 * from a different process than the one that actually runs it.
2728 * If the life of a virtual machine was spent entirely in the context
2729 * of a single process we could do this once in vmx_vminit().
2731 vmcs_write(VMCS_HOST_CR3, rcr3());
2733 vmcs_write(VMCS_GUEST_RIP, rip);
2734 vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2736 KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2737 "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2739 handled = UNHANDLED;
2741 * Interrupts are disabled from this point on until the
2742 * guest starts executing. This is done for the following
2745 * If an AST is asserted on this thread after the check below,
2746 * then the IPI_AST notification will not be lost, because it
2747 * will cause a VM exit due to external interrupt as soon as
2748 * the guest state is loaded.
2750 * A posted interrupt after 'vmx_inject_interrupts()' will
2751 * not be "lost" because it will be held pending in the host
2752 * APIC because interrupts are disabled. The pending interrupt
2753 * will be recognized as soon as the guest state is loaded.
2755 * The same reasoning applies to the IPI generated by
2756 * pmap_invalidate_ept().
2759 vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2762 * Check for vcpu suspension after injecting events because
2763 * vmx_inject_interrupts() can suspend the vcpu due to a
2766 if (vcpu_suspended(evinfo)) {
2768 vm_exit_suspended(vmx->vm, vcpu, rip);
2772 if (vcpu_rendezvous_pending(evinfo)) {
2774 vm_exit_rendezvous(vmx->vm, vcpu, rip);
2778 if (vcpu_reqidle(evinfo)) {
2780 vm_exit_reqidle(vmx->vm, vcpu, rip);
2784 if (vcpu_should_yield(vm, vcpu)) {
2786 vm_exit_astpending(vmx->vm, vcpu, rip);
2787 vmx_astpending_trace(vmx, vcpu, rip);
2793 * VM exits restore the base address but not the
2794 * limits of GDTR and IDTR. The VMCS only stores the
2795 * base address, so VM exits set the limits to 0xffff.
2796 * Save and restore the full GDTR and IDTR to restore
2799 * The VMCS does not save the LDTR at all, and VM
2800 * exits clear LDTR as if a NULL selector were loaded.
2801 * The userspace hypervisor probably doesn't use a
2802 * LDT, but save and restore it to be safe.
2808 vmx_run_trace(vmx, vcpu);
2809 vmx_dr_enter_guest(vmxctx);
2810 rc = vmx_enter_guest(vmxctx, vmx, launched);
2811 vmx_dr_leave_guest(vmxctx);
2817 /* Collect some information for VM exit processing */
2818 vmexit->rip = rip = vmcs_guest_rip();
2819 vmexit->inst_length = vmexit_instruction_length();
2820 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2821 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2823 /* Update 'nextrip' */
2824 vmx->state[vcpu].nextrip = rip;
2826 if (rc == VMX_GUEST_VMEXIT) {
2827 vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2829 handled = vmx_exit_process(vmx, vcpu, vmexit);
2832 vmx_exit_inst_error(vmxctx, rc, vmexit);
2835 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2840 * If a VM exit has been handled then the exitcode must be BOGUS
2841 * If a VM exit is not handled then the exitcode must not be BOGUS
2843 if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2844 (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2845 panic("Mismatch between handled (%d) and exitcode (%d)",
2846 handled, vmexit->exitcode);
2850 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2852 VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2856 vmx_msr_guest_exit(vmx, vcpu);
2862 vmx_vmcleanup(void *arg)
2865 struct vmx *vmx = arg;
2867 if (apic_access_virtualization(vmx, 0))
2868 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2870 for (i = 0; i < VM_MAXCPU; i++)
2871 vpid_free(vmx->state[i].vpid);
2879 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2883 case VM_REG_GUEST_RAX:
2884 return (&vmxctx->guest_rax);
2885 case VM_REG_GUEST_RBX:
2886 return (&vmxctx->guest_rbx);
2887 case VM_REG_GUEST_RCX:
2888 return (&vmxctx->guest_rcx);
2889 case VM_REG_GUEST_RDX:
2890 return (&vmxctx->guest_rdx);
2891 case VM_REG_GUEST_RSI:
2892 return (&vmxctx->guest_rsi);
2893 case VM_REG_GUEST_RDI:
2894 return (&vmxctx->guest_rdi);
2895 case VM_REG_GUEST_RBP:
2896 return (&vmxctx->guest_rbp);
2897 case VM_REG_GUEST_R8:
2898 return (&vmxctx->guest_r8);
2899 case VM_REG_GUEST_R9:
2900 return (&vmxctx->guest_r9);
2901 case VM_REG_GUEST_R10:
2902 return (&vmxctx->guest_r10);
2903 case VM_REG_GUEST_R11:
2904 return (&vmxctx->guest_r11);
2905 case VM_REG_GUEST_R12:
2906 return (&vmxctx->guest_r12);
2907 case VM_REG_GUEST_R13:
2908 return (&vmxctx->guest_r13);
2909 case VM_REG_GUEST_R14:
2910 return (&vmxctx->guest_r14);
2911 case VM_REG_GUEST_R15:
2912 return (&vmxctx->guest_r15);
2913 case VM_REG_GUEST_CR2:
2914 return (&vmxctx->guest_cr2);
2915 case VM_REG_GUEST_DR0:
2916 return (&vmxctx->guest_dr0);
2917 case VM_REG_GUEST_DR1:
2918 return (&vmxctx->guest_dr1);
2919 case VM_REG_GUEST_DR2:
2920 return (&vmxctx->guest_dr2);
2921 case VM_REG_GUEST_DR3:
2922 return (&vmxctx->guest_dr3);
2923 case VM_REG_GUEST_DR6:
2924 return (&vmxctx->guest_dr6);
2932 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2936 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2944 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2948 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2956 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2961 error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2962 VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2963 *retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2968 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2975 * Forcing the vcpu into an interrupt shadow is not supported.
2982 vmcs = &vmx->vmcs[vcpu];
2983 ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2984 error = vmcs_getreg(vmcs, running, ident, &gi);
2986 gi &= ~HWINTR_BLOCKING;
2987 error = vmcs_setreg(vmcs, running, ident, gi);
2990 VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2991 error ? "failed" : "succeeded");
2996 vmx_shadow_reg(int reg)
3003 case VM_REG_GUEST_CR0:
3004 shreg = VMCS_CR0_SHADOW;
3006 case VM_REG_GUEST_CR4:
3007 shreg = VMCS_CR4_SHADOW;
3017 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
3019 int running, hostcpu;
3020 struct vmx *vmx = arg;
3022 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3023 if (running && hostcpu != curcpu)
3024 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
3026 if (reg == VM_REG_GUEST_INTR_SHADOW)
3027 return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
3029 if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
3032 return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
3036 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3038 int error, hostcpu, running, shadow;
3041 struct vmx *vmx = arg;
3043 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3044 if (running && hostcpu != curcpu)
3045 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
3047 if (reg == VM_REG_GUEST_INTR_SHADOW)
3048 return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
3050 if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
3053 error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
3057 * If the "load EFER" VM-entry control is 1 then the
3058 * value of EFER.LMA must be identical to "IA-32e mode guest"
3059 * bit in the VM-entry control.
3061 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
3062 (reg == VM_REG_GUEST_EFER)) {
3063 vmcs_getreg(&vmx->vmcs[vcpu], running,
3064 VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
3066 ctls |= VM_ENTRY_GUEST_LMA;
3068 ctls &= ~VM_ENTRY_GUEST_LMA;
3069 vmcs_setreg(&vmx->vmcs[vcpu], running,
3070 VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3073 shadow = vmx_shadow_reg(reg);
3076 * Store the unmodified value in the shadow
3078 error = vmcs_setreg(&vmx->vmcs[vcpu], running,
3079 VMCS_IDENT(shadow), val);
3082 if (reg == VM_REG_GUEST_CR3) {
3084 * Invalidate the guest vcpu's TLB mappings to emulate
3085 * the behavior of updating %cr3.
3087 * XXX the processor retains global mappings when %cr3
3088 * is updated but vmx_invvpid() does not.
3090 pmap = vmx->ctx[vcpu].pmap;
3091 vmx_invvpid(vmx, vcpu, pmap, running);
3099 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3101 int hostcpu, running;
3102 struct vmx *vmx = arg;
3104 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3105 if (running && hostcpu != curcpu)
3106 panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3108 return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
3112 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3114 int hostcpu, running;
3115 struct vmx *vmx = arg;
3117 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3118 if (running && hostcpu != curcpu)
3119 panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3121 return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
3125 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3127 struct vmx *vmx = arg;
3133 vcap = vmx->cap[vcpu].set;
3136 case VM_CAP_HALT_EXIT:
3140 case VM_CAP_PAUSE_EXIT:
3144 case VM_CAP_MTRAP_EXIT:
3145 if (cap_monitor_trap)
3148 case VM_CAP_UNRESTRICTED_GUEST:
3149 if (cap_unrestricted_guest)
3152 case VM_CAP_ENABLE_INVPCID:
3161 *retval = (vcap & (1 << type)) ? 1 : 0;
3167 vmx_setcap(void *arg, int vcpu, int type, int val)
3169 struct vmx *vmx = arg;
3170 struct vmcs *vmcs = &vmx->vmcs[vcpu];
3182 case VM_CAP_HALT_EXIT:
3183 if (cap_halt_exit) {
3185 pptr = &vmx->cap[vcpu].proc_ctls;
3187 flag = PROCBASED_HLT_EXITING;
3188 reg = VMCS_PRI_PROC_BASED_CTLS;
3191 case VM_CAP_MTRAP_EXIT:
3192 if (cap_monitor_trap) {
3194 pptr = &vmx->cap[vcpu].proc_ctls;
3196 flag = PROCBASED_MTF;
3197 reg = VMCS_PRI_PROC_BASED_CTLS;
3200 case VM_CAP_PAUSE_EXIT:
3201 if (cap_pause_exit) {
3203 pptr = &vmx->cap[vcpu].proc_ctls;
3205 flag = PROCBASED_PAUSE_EXITING;
3206 reg = VMCS_PRI_PROC_BASED_CTLS;
3209 case VM_CAP_UNRESTRICTED_GUEST:
3210 if (cap_unrestricted_guest) {
3212 pptr = &vmx->cap[vcpu].proc_ctls2;
3214 flag = PROCBASED2_UNRESTRICTED_GUEST;
3215 reg = VMCS_SEC_PROC_BASED_CTLS;
3218 case VM_CAP_ENABLE_INVPCID:
3221 pptr = &vmx->cap[vcpu].proc_ctls2;
3223 flag = PROCBASED2_ENABLE_INVPCID;
3224 reg = VMCS_SEC_PROC_BASED_CTLS;
3238 error = vmwrite(reg, baseval);
3245 * Update optional stored flags, and record
3253 vmx->cap[vcpu].set |= (1 << type);
3255 vmx->cap[vcpu].set &= ~(1 << type);
3264 struct vlapic vlapic;
3265 struct pir_desc *pir_desc;
3269 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg) \
3271 VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d", \
3272 level ? "level" : "edge", vector); \
3273 VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]); \
3274 VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]); \
3275 VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]); \
3276 VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]); \
3277 VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3281 * vlapic->ops handlers that utilize the APICv hardware assist described in
3282 * Chapter 29 of the Intel SDM.
3285 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3287 struct vlapic_vtx *vlapic_vtx;
3288 struct pir_desc *pir_desc;
3292 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3293 pir_desc = vlapic_vtx->pir_desc;
3296 * Keep track of interrupt requests in the PIR descriptor. This is
3297 * because the virtual APIC page pointed to by the VMCS cannot be
3298 * modified if the vcpu is running.
3301 mask = 1UL << (vector % 64);
3302 atomic_set_long(&pir_desc->pir[idx], mask);
3303 notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3305 VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3306 level, "vmx_set_intr_ready");
3311 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3313 struct vlapic_vtx *vlapic_vtx;
3314 struct pir_desc *pir_desc;
3315 struct LAPIC *lapic;
3316 uint64_t pending, pirval;
3321 * This function is only expected to be called from the 'HLT' exit
3322 * handler which does not care about the vector that is pending.
3324 KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3326 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3327 pir_desc = vlapic_vtx->pir_desc;
3329 pending = atomic_load_acq_long(&pir_desc->pending);
3331 return (0); /* common case */
3334 * If there is an interrupt pending then it will be recognized only
3335 * if its priority is greater than the processor priority.
3337 * Special case: if the processor priority is zero then any pending
3338 * interrupt will be recognized.
3340 lapic = vlapic->apic_page;
3341 ppr = lapic->ppr & 0xf0;
3345 VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3348 for (i = 3; i >= 0; i--) {
3349 pirval = pir_desc->pir[i];
3351 vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3359 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3362 panic("vmx_intr_accepted: not expected to be called");
3366 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3368 struct vlapic_vtx *vlapic_vtx;
3373 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3374 KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3375 ("vmx_set_tmr: vcpu cannot be running"));
3377 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3378 vmx = vlapic_vtx->vmx;
3379 vmcs = &vmx->vmcs[vlapic->vcpuid];
3380 mask = 1UL << (vector % 64);
3383 val = vmcs_read(VMCS_EOI_EXIT(vector));
3388 vmcs_write(VMCS_EOI_EXIT(vector), val);
3393 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3397 uint32_t proc_ctls2;
3400 vcpuid = vlapic->vcpuid;
3401 vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3402 vmcs = &vmx->vmcs[vcpuid];
3404 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3405 KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3406 ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3408 proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3409 proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3410 vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3413 vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3416 if (vlapic->vcpuid == 0) {
3418 * The nested page table mappings are shared by all vcpus
3419 * so unmap the APIC access page just once.
3421 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3422 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3426 * The MSR bitmap is shared by all vcpus so modify it only
3427 * once in the context of vcpu 0.
3429 error = vmx_allow_x2apic_msrs(vmx);
3430 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3436 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3439 ipi_cpu(hostcpu, pirvec);
3443 * Transfer the pending interrupts in the PIR descriptor to the IRR
3444 * in the virtual APIC page.
3447 vmx_inject_pir(struct vlapic *vlapic)
3449 struct vlapic_vtx *vlapic_vtx;
3450 struct pir_desc *pir_desc;
3451 struct LAPIC *lapic;
3452 uint64_t val, pirval;
3453 int rvi, pirbase = -1;
3454 uint16_t intr_status_old, intr_status_new;
3456 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3457 pir_desc = vlapic_vtx->pir_desc;
3458 if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3459 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3460 "no posted interrupt pending");
3466 lapic = vlapic->apic_page;
3468 val = atomic_readandclear_long(&pir_desc->pir[0]);
3471 lapic->irr1 |= val >> 32;
3476 val = atomic_readandclear_long(&pir_desc->pir[1]);
3479 lapic->irr3 |= val >> 32;
3484 val = atomic_readandclear_long(&pir_desc->pir[2]);
3487 lapic->irr5 |= val >> 32;
3492 val = atomic_readandclear_long(&pir_desc->pir[3]);
3495 lapic->irr7 |= val >> 32;
3500 VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3503 * Update RVI so the processor can evaluate pending virtual
3504 * interrupts on VM-entry.
3506 * It is possible for pirval to be 0 here, even though the
3507 * pending bit has been set. The scenario is:
3508 * CPU-Y is sending a posted interrupt to CPU-X, which
3509 * is running a guest and processing posted interrupts in h/w.
3510 * CPU-X will eventually exit and the state seen in s/w is
3511 * the pending bit set, but no PIR bits set.
3514 * (vm running) (host running)
3515 * rx posted interrupt
3518 * READ/CLEAR PIR bits
3521 * pending bit set, PIR 0
3524 rvi = pirbase + flsl(pirval) - 1;
3525 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3526 intr_status_new = (intr_status_old & 0xFF00) | rvi;
3527 if (intr_status_new > intr_status_old) {
3528 vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3529 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3530 "guest_intr_status changed from 0x%04x to 0x%04x",
3531 intr_status_old, intr_status_new);
3536 static struct vlapic *
3537 vmx_vlapic_init(void *arg, int vcpuid)
3540 struct vlapic *vlapic;
3541 struct vlapic_vtx *vlapic_vtx;
3545 vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3546 vlapic->vm = vmx->vm;
3547 vlapic->vcpuid = vcpuid;
3548 vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3550 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3551 vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3552 vlapic_vtx->vmx = vmx;
3554 if (virtual_interrupt_delivery) {
3555 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3556 vlapic->ops.pending_intr = vmx_pending_intr;
3557 vlapic->ops.intr_accepted = vmx_intr_accepted;
3558 vlapic->ops.set_tmr = vmx_set_tmr;
3559 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3562 if (posted_interrupts)
3563 vlapic->ops.post_intr = vmx_post_intr;
3565 vlapic_init(vlapic);
3571 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3574 vlapic_cleanup(vlapic);
3575 free(vlapic, M_VLAPIC);
3578 struct vmm_ops vmm_ops_intel = {