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>
54 #include <machine/vmm_instruction_emul.h>
55 #include "vmm_lapic.h"
57 #include "vmm_ioport.h"
62 #include "vlapic_priv.h"
65 #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_MWAIT_EXITING | \
84 PROCBASED_MONITOR_EXITING | \
85 PROCBASED_IO_EXITING | \
86 PROCBASED_MSR_BITMAPS | \
87 PROCBASED_CTLS_WINDOW_SETTING | \
88 PROCBASED_CR8_LOAD_EXITING | \
89 PROCBASED_CR8_STORE_EXITING)
90 #define PROCBASED_CTLS_ZERO_SETTING \
91 (PROCBASED_CR3_LOAD_EXITING | \
92 PROCBASED_CR3_STORE_EXITING | \
95 #define PROCBASED_CTLS2_ONE_SETTING PROCBASED2_ENABLE_EPT
96 #define PROCBASED_CTLS2_ZERO_SETTING 0
98 #define VM_EXIT_CTLS_ONE_SETTING \
99 (VM_EXIT_SAVE_DEBUG_CONTROLS | \
101 VM_EXIT_SAVE_EFER | \
102 VM_EXIT_LOAD_EFER | \
103 VM_EXIT_ACKNOWLEDGE_INTERRUPT)
105 #define VM_EXIT_CTLS_ZERO_SETTING 0
107 #define VM_ENTRY_CTLS_ONE_SETTING \
108 (VM_ENTRY_LOAD_DEBUG_CONTROLS | \
111 #define VM_ENTRY_CTLS_ZERO_SETTING \
112 (VM_ENTRY_INTO_SMM | \
113 VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
118 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
119 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
121 SYSCTL_DECL(_hw_vmm);
122 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
124 int vmxon_enabled[MAXCPU];
125 static char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
127 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
128 static uint32_t exit_ctls, entry_ctls;
130 static uint64_t cr0_ones_mask, cr0_zeros_mask;
131 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
132 &cr0_ones_mask, 0, NULL);
133 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
134 &cr0_zeros_mask, 0, NULL);
136 static uint64_t cr4_ones_mask, cr4_zeros_mask;
137 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
138 &cr4_ones_mask, 0, NULL);
139 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
140 &cr4_zeros_mask, 0, NULL);
142 static int vmx_initialized;
143 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
144 &vmx_initialized, 0, "Intel VMX initialized");
147 * Optional capabilities
149 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap, CTLFLAG_RW, NULL, NULL);
151 static int cap_halt_exit;
152 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
153 "HLT triggers a VM-exit");
155 static int cap_pause_exit;
156 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
157 0, "PAUSE triggers a VM-exit");
159 static int cap_unrestricted_guest;
160 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
161 &cap_unrestricted_guest, 0, "Unrestricted guests");
163 static int cap_monitor_trap;
164 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
165 &cap_monitor_trap, 0, "Monitor trap flag");
167 static int cap_invpcid;
168 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
169 0, "Guests are allowed to use INVPCID");
171 static int virtual_interrupt_delivery;
172 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
173 &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
175 static int posted_interrupts;
176 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
177 &posted_interrupts, 0, "APICv posted interrupt support");
179 static int pirvec = -1;
180 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
181 &pirvec, 0, "APICv posted interrupt vector");
183 static struct unrhdr *vpid_unr;
184 static u_int vpid_alloc_failed;
185 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
186 &vpid_alloc_failed, 0, NULL);
188 static int guest_l1d_flush;
189 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush, CTLFLAG_RD,
190 &guest_l1d_flush, 0, NULL);
191 static int guest_l1d_flush_sw;
192 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush_sw, CTLFLAG_RD,
193 &guest_l1d_flush_sw, 0, NULL);
195 static struct msr_entry msr_load_list[1] __aligned(16);
198 * Use the last page below 4GB as the APIC access address. This address is
199 * occupied by the boot firmware so it is guaranteed that it will not conflict
200 * with a page in system memory.
202 #define APIC_ACCESS_ADDRESS 0xFFFFF000
204 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
205 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
206 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
207 static void vmx_inject_pir(struct vlapic *vlapic);
211 exit_reason_to_str(int reason)
213 static char reasonbuf[32];
216 case EXIT_REASON_EXCEPTION:
218 case EXIT_REASON_EXT_INTR:
220 case EXIT_REASON_TRIPLE_FAULT:
221 return "triplefault";
222 case EXIT_REASON_INIT:
224 case EXIT_REASON_SIPI:
226 case EXIT_REASON_IO_SMI:
228 case EXIT_REASON_SMI:
230 case EXIT_REASON_INTR_WINDOW:
232 case EXIT_REASON_NMI_WINDOW:
234 case EXIT_REASON_TASK_SWITCH:
236 case EXIT_REASON_CPUID:
238 case EXIT_REASON_GETSEC:
240 case EXIT_REASON_HLT:
242 case EXIT_REASON_INVD:
244 case EXIT_REASON_INVLPG:
246 case EXIT_REASON_RDPMC:
248 case EXIT_REASON_RDTSC:
250 case EXIT_REASON_RSM:
252 case EXIT_REASON_VMCALL:
254 case EXIT_REASON_VMCLEAR:
256 case EXIT_REASON_VMLAUNCH:
258 case EXIT_REASON_VMPTRLD:
260 case EXIT_REASON_VMPTRST:
262 case EXIT_REASON_VMREAD:
264 case EXIT_REASON_VMRESUME:
266 case EXIT_REASON_VMWRITE:
268 case EXIT_REASON_VMXOFF:
270 case EXIT_REASON_VMXON:
272 case EXIT_REASON_CR_ACCESS:
274 case EXIT_REASON_DR_ACCESS:
276 case EXIT_REASON_INOUT:
278 case EXIT_REASON_RDMSR:
280 case EXIT_REASON_WRMSR:
282 case EXIT_REASON_INVAL_VMCS:
284 case EXIT_REASON_INVAL_MSR:
286 case EXIT_REASON_MWAIT:
288 case EXIT_REASON_MTF:
290 case EXIT_REASON_MONITOR:
292 case EXIT_REASON_PAUSE:
294 case EXIT_REASON_MCE_DURING_ENTRY:
295 return "mce-during-entry";
296 case EXIT_REASON_TPR:
298 case EXIT_REASON_APIC_ACCESS:
299 return "apic-access";
300 case EXIT_REASON_GDTR_IDTR:
302 case EXIT_REASON_LDTR_TR:
304 case EXIT_REASON_EPT_FAULT:
306 case EXIT_REASON_EPT_MISCONFIG:
307 return "eptmisconfig";
308 case EXIT_REASON_INVEPT:
310 case EXIT_REASON_RDTSCP:
312 case EXIT_REASON_VMX_PREEMPT:
314 case EXIT_REASON_INVVPID:
316 case EXIT_REASON_WBINVD:
318 case EXIT_REASON_XSETBV:
320 case EXIT_REASON_APIC_WRITE:
323 snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
330 vmx_allow_x2apic_msrs(struct vmx *vmx)
337 * Allow readonly access to the following x2APIC MSRs from the guest.
339 error += guest_msr_ro(vmx, MSR_APIC_ID);
340 error += guest_msr_ro(vmx, MSR_APIC_VERSION);
341 error += guest_msr_ro(vmx, MSR_APIC_LDR);
342 error += guest_msr_ro(vmx, MSR_APIC_SVR);
344 for (i = 0; i < 8; i++)
345 error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
347 for (i = 0; i < 8; i++)
348 error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
350 for (i = 0; i < 8; i++)
351 error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
353 error += guest_msr_ro(vmx, MSR_APIC_ESR);
354 error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
355 error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
356 error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
357 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
358 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
359 error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
360 error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
361 error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
362 error += guest_msr_ro(vmx, MSR_APIC_ICR);
365 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
367 * These registers get special treatment described in the section
368 * "Virtualizing MSR-Based APIC Accesses".
370 error += guest_msr_rw(vmx, MSR_APIC_TPR);
371 error += guest_msr_rw(vmx, MSR_APIC_EOI);
372 error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
378 vmx_fix_cr0(u_long cr0)
381 return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
385 vmx_fix_cr4(u_long cr4)
388 return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
394 if (vpid < 0 || vpid > 0xffff)
395 panic("vpid_free: invalid vpid %d", vpid);
398 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
399 * the unit number allocator.
402 if (vpid > VM_MAXCPU)
403 free_unr(vpid_unr, vpid);
407 vpid_alloc(uint16_t *vpid, int num)
411 if (num <= 0 || num > VM_MAXCPU)
412 panic("invalid number of vpids requested: %d", num);
415 * If the "enable vpid" execution control is not enabled then the
416 * VPID is required to be 0 for all vcpus.
418 if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
419 for (i = 0; i < num; i++)
425 * Allocate a unique VPID for each vcpu from the unit number allocator.
427 for (i = 0; i < num; i++) {
428 x = alloc_unr(vpid_unr);
436 atomic_add_int(&vpid_alloc_failed, 1);
439 * If the unit number allocator does not have enough unique
440 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
442 * These VPIDs are not be unique across VMs but this does not
443 * affect correctness because the combined mappings are also
444 * tagged with the EP4TA which is unique for each VM.
446 * It is still sub-optimal because the invvpid will invalidate
447 * combined mappings for a particular VPID across all EP4TAs.
452 for (i = 0; i < num; i++)
461 * VPID 0 is required when the "enable VPID" execution control is
464 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
465 * unit number allocator does not have sufficient unique VPIDs to
466 * satisfy the allocation.
468 * The remaining VPIDs are managed by the unit number allocator.
470 vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
474 vmx_disable(void *arg __unused)
476 struct invvpid_desc invvpid_desc = { 0 };
477 struct invept_desc invept_desc = { 0 };
479 if (vmxon_enabled[curcpu]) {
481 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
483 * VMXON or VMXOFF are not required to invalidate any TLB
484 * caching structures. This prevents potential retention of
485 * cached information in the TLB between distinct VMX episodes.
487 invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
488 invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
491 load_cr4(rcr4() & ~CR4_VMXE);
499 lapic_ipi_free(pirvec);
501 if (vpid_unr != NULL) {
502 delete_unrhdr(vpid_unr);
506 if (nmi_flush_l1d_sw == 1)
507 nmi_flush_l1d_sw = 0;
509 smp_rendezvous(NULL, vmx_disable, NULL, NULL);
515 vmx_enable(void *arg __unused)
518 uint64_t feature_control;
520 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
521 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
522 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
523 wrmsr(MSR_IA32_FEATURE_CONTROL,
524 feature_control | IA32_FEATURE_CONTROL_VMX_EN |
525 IA32_FEATURE_CONTROL_LOCK);
528 load_cr4(rcr4() | CR4_VMXE);
530 *(uint32_t *)vmxon_region[curcpu] = vmx_revision();
531 error = vmxon(vmxon_region[curcpu]);
533 vmxon_enabled[curcpu] = 1;
540 if (vmxon_enabled[curcpu])
541 vmxon(vmxon_region[curcpu]);
547 int error, use_tpr_shadow;
548 uint64_t basic, fixed0, fixed1, feature_control;
549 uint32_t tmp, procbased2_vid_bits;
551 /* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
552 if (!(cpu_feature2 & CPUID2_VMX)) {
553 printf("vmx_init: processor does not support VMX operation\n");
558 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
559 * are set (bits 0 and 2 respectively).
561 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
562 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
563 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
564 printf("vmx_init: VMX operation disabled by BIOS\n");
569 * Verify capabilities MSR_VMX_BASIC:
570 * - bit 54 indicates support for INS/OUTS decoding
572 basic = rdmsr(MSR_VMX_BASIC);
573 if ((basic & (1UL << 54)) == 0) {
574 printf("vmx_init: processor does not support desired basic "
579 /* Check support for primary processor-based VM-execution controls */
580 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
581 MSR_VMX_TRUE_PROCBASED_CTLS,
582 PROCBASED_CTLS_ONE_SETTING,
583 PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
585 printf("vmx_init: processor does not support desired primary "
586 "processor-based controls\n");
590 /* Clear the processor-based ctl bits that are set on demand */
591 procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
593 /* Check support for secondary processor-based VM-execution controls */
594 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
595 MSR_VMX_PROCBASED_CTLS2,
596 PROCBASED_CTLS2_ONE_SETTING,
597 PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
599 printf("vmx_init: processor does not support desired secondary "
600 "processor-based controls\n");
604 /* Check support for VPID */
605 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
606 PROCBASED2_ENABLE_VPID, 0, &tmp);
608 procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
610 /* Check support for pin-based VM-execution controls */
611 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
612 MSR_VMX_TRUE_PINBASED_CTLS,
613 PINBASED_CTLS_ONE_SETTING,
614 PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
616 printf("vmx_init: processor does not support desired "
617 "pin-based controls\n");
621 /* Check support for VM-exit controls */
622 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
623 VM_EXIT_CTLS_ONE_SETTING,
624 VM_EXIT_CTLS_ZERO_SETTING,
627 printf("vmx_init: processor does not support desired "
632 /* Check support for VM-entry controls */
633 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
634 VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
637 printf("vmx_init: processor does not support desired "
643 * Check support for optional features by testing them
646 cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
647 MSR_VMX_TRUE_PROCBASED_CTLS,
648 PROCBASED_HLT_EXITING, 0,
651 cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
652 MSR_VMX_PROCBASED_CTLS,
656 cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
657 MSR_VMX_TRUE_PROCBASED_CTLS,
658 PROCBASED_PAUSE_EXITING, 0,
661 cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
662 MSR_VMX_PROCBASED_CTLS2,
663 PROCBASED2_UNRESTRICTED_GUEST, 0,
666 cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
667 MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
671 * Check support for virtual interrupt delivery.
673 procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
674 PROCBASED2_VIRTUALIZE_X2APIC_MODE |
675 PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
676 PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
678 use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
679 MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
682 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
683 procbased2_vid_bits, 0, &tmp);
684 if (error == 0 && use_tpr_shadow) {
685 virtual_interrupt_delivery = 1;
686 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
687 &virtual_interrupt_delivery);
690 if (virtual_interrupt_delivery) {
691 procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
692 procbased_ctls2 |= procbased2_vid_bits;
693 procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
696 * No need to emulate accesses to %CR8 if virtual
697 * interrupt delivery is enabled.
699 procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
700 procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
703 * Check for Posted Interrupts only if Virtual Interrupt
704 * Delivery is enabled.
706 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
707 MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
710 pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
711 &IDTVEC(justreturn));
714 printf("vmx_init: unable to allocate "
715 "posted interrupt vector\n");
718 posted_interrupts = 1;
719 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
725 if (posted_interrupts)
726 pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
729 error = ept_init(ipinum);
731 printf("vmx_init: ept initialization failed (%d)\n", error);
735 guest_l1d_flush = (cpu_ia32_arch_caps & IA32_ARCH_CAP_RDCL_NO) == 0;
736 TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
739 * L1D cache flush is enabled. Use IA32_FLUSH_CMD MSR when
740 * available. Otherwise fall back to the software flush
741 * method which loads enough data from the kernel text to
742 * flush existing L1D content, both on VMX entry and on NMI
745 if (guest_l1d_flush) {
746 if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
747 guest_l1d_flush_sw = 1;
748 TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
749 &guest_l1d_flush_sw);
751 if (guest_l1d_flush_sw) {
752 if (nmi_flush_l1d_sw <= 1)
753 nmi_flush_l1d_sw = 1;
755 msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
756 msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
761 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
763 fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
764 fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
765 cr0_ones_mask = fixed0 & fixed1;
766 cr0_zeros_mask = ~fixed0 & ~fixed1;
769 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
770 * if unrestricted guest execution is allowed.
772 if (cap_unrestricted_guest)
773 cr0_ones_mask &= ~(CR0_PG | CR0_PE);
776 * Do not allow the guest to set CR0_NW or CR0_CD.
778 cr0_zeros_mask |= (CR0_NW | CR0_CD);
780 fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
781 fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
782 cr4_ones_mask = fixed0 & fixed1;
783 cr4_zeros_mask = ~fixed0 & ~fixed1;
789 /* enable VMX operation */
790 smp_rendezvous(NULL, vmx_enable, NULL, NULL);
798 vmx_trigger_hostintr(int vector)
801 struct gate_descriptor *gd;
805 KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
806 "invalid vector %d", vector));
807 KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
809 KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
810 "has invalid type %d", vector, gd->gd_type));
811 KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
812 "has invalid dpl %d", vector, gd->gd_dpl));
813 KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
814 "for vector %d has invalid selector %d", vector, gd->gd_selector));
815 KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
816 "IST %d", vector, gd->gd_ist));
818 func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
823 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
825 int error, mask_ident, shadow_ident;
828 if (which != 0 && which != 4)
829 panic("vmx_setup_cr_shadow: unknown cr%d", which);
832 mask_ident = VMCS_CR0_MASK;
833 mask_value = cr0_ones_mask | cr0_zeros_mask;
834 shadow_ident = VMCS_CR0_SHADOW;
836 mask_ident = VMCS_CR4_MASK;
837 mask_value = cr4_ones_mask | cr4_zeros_mask;
838 shadow_ident = VMCS_CR4_SHADOW;
841 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
845 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
851 #define vmx_setup_cr0_shadow(vmcs,init) vmx_setup_cr_shadow(0, (vmcs), (init))
852 #define vmx_setup_cr4_shadow(vmcs,init) vmx_setup_cr_shadow(4, (vmcs), (init))
855 vmx_vminit(struct vm *vm, pmap_t pmap)
857 uint16_t vpid[VM_MAXCPU];
863 vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
864 if ((uintptr_t)vmx & PAGE_MASK) {
865 panic("malloc of struct vmx not aligned on %d byte boundary",
870 vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
873 * Clean up EPTP-tagged guest physical and combined mappings
875 * VMX transitions are not required to invalidate any guest physical
876 * mappings. So, it may be possible for stale guest physical mappings
877 * to be present in the processor TLBs.
879 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
881 ept_invalidate_mappings(vmx->eptp);
883 msr_bitmap_initialize(vmx->msr_bitmap);
886 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
887 * The guest FSBASE and GSBASE are saved and restored during
888 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
889 * always restored from the vmcs host state area on vm-exit.
891 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
892 * how they are saved/restored so can be directly accessed by the
895 * MSR_EFER is saved and restored in the guest VMCS area on a
896 * VM exit and entry respectively. It is also restored from the
897 * host VMCS area on a VM exit.
899 * The TSC MSR is exposed read-only. Writes are disallowed as
900 * that will impact the host TSC. If the guest does a write
901 * the "use TSC offsetting" execution control is enabled and the
902 * difference between the host TSC and the guest TSC is written
903 * into the TSC offset in the VMCS.
905 if (guest_msr_rw(vmx, MSR_GSBASE) ||
906 guest_msr_rw(vmx, MSR_FSBASE) ||
907 guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
908 guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
909 guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
910 guest_msr_rw(vmx, MSR_EFER) ||
911 guest_msr_ro(vmx, MSR_TSC))
912 panic("vmx_vminit: error setting guest msr access");
914 vpid_alloc(vpid, VM_MAXCPU);
916 if (virtual_interrupt_delivery) {
917 error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
918 APIC_ACCESS_ADDRESS);
919 /* XXX this should really return an error to the caller */
920 KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
923 for (i = 0; i < VM_MAXCPU; i++) {
924 vmcs = &vmx->vmcs[i];
925 vmcs->identifier = vmx_revision();
926 error = vmclear(vmcs);
928 panic("vmx_vminit: vmclear error %d on vcpu %d\n",
932 vmx_msr_guest_init(vmx, i);
934 error = vmcs_init(vmcs);
935 KASSERT(error == 0, ("vmcs_init error %d", error));
939 error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
940 error += vmwrite(VMCS_EPTP, vmx->eptp);
941 error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
942 error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
943 error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
944 error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
945 error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
946 error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
947 error += vmwrite(VMCS_VPID, vpid[i]);
949 if (guest_l1d_flush && !guest_l1d_flush_sw) {
950 vmcs_write(VMCS_ENTRY_MSR_LOAD, pmap_kextract(
951 (vm_offset_t)&msr_load_list[0]));
952 vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
953 nitems(msr_load_list));
954 vmcs_write(VMCS_EXIT_MSR_STORE, 0);
955 vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
958 /* exception bitmap */
959 if (vcpu_trace_exceptions(vm, i))
960 exc_bitmap = 0xffffffff;
962 exc_bitmap = 1 << IDT_MC;
963 error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
965 vmx->ctx[i].guest_dr6 = 0xffff0ff0;
966 error += vmwrite(VMCS_GUEST_DR7, 0x400);
968 if (virtual_interrupt_delivery) {
969 error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
970 error += vmwrite(VMCS_VIRTUAL_APIC,
971 vtophys(&vmx->apic_page[i]));
972 error += vmwrite(VMCS_EOI_EXIT0, 0);
973 error += vmwrite(VMCS_EOI_EXIT1, 0);
974 error += vmwrite(VMCS_EOI_EXIT2, 0);
975 error += vmwrite(VMCS_EOI_EXIT3, 0);
977 if (posted_interrupts) {
978 error += vmwrite(VMCS_PIR_VECTOR, pirvec);
979 error += vmwrite(VMCS_PIR_DESC,
980 vtophys(&vmx->pir_desc[i]));
983 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
986 vmx->cap[i].proc_ctls = procbased_ctls;
987 vmx->cap[i].proc_ctls2 = procbased_ctls2;
989 vmx->state[i].nextrip = ~0;
990 vmx->state[i].lastcpu = NOCPU;
991 vmx->state[i].vpid = vpid[i];
994 * Set up the CR0/4 shadows, and init the read shadow
995 * to the power-on register value from the Intel Sys Arch.
999 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
1001 panic("vmx_setup_cr0_shadow %d", error);
1003 error = vmx_setup_cr4_shadow(vmcs, 0);
1005 panic("vmx_setup_cr4_shadow %d", error);
1007 vmx->ctx[i].pmap = pmap;
1014 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
1018 func = vmxctx->guest_rax;
1020 handled = x86_emulate_cpuid(vm, vcpu,
1021 (uint32_t*)(&vmxctx->guest_rax),
1022 (uint32_t*)(&vmxctx->guest_rbx),
1023 (uint32_t*)(&vmxctx->guest_rcx),
1024 (uint32_t*)(&vmxctx->guest_rdx));
1028 static __inline void
1029 vmx_run_trace(struct vmx *vmx, int vcpu)
1032 VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
1036 static __inline void
1037 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
1041 VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
1042 handled ? "handled" : "unhandled",
1043 exit_reason_to_str(exit_reason), rip);
1047 static __inline void
1048 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1051 VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1055 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1056 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1059 * Invalidate guest mappings identified by its vpid from the TLB.
1061 static __inline void
1062 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1064 struct vmxstate *vmxstate;
1065 struct invvpid_desc invvpid_desc;
1067 vmxstate = &vmx->state[vcpu];
1068 if (vmxstate->vpid == 0)
1073 * Set the 'lastcpu' to an invalid host cpu.
1075 * This will invalidate TLB entries tagged with the vcpu's
1076 * vpid the next time it runs via vmx_set_pcpu_defaults().
1078 vmxstate->lastcpu = NOCPU;
1082 KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1083 "critical section", __func__, vcpu));
1086 * Invalidate all mappings tagged with 'vpid'
1088 * We do this because this vcpu was executing on a different host
1089 * cpu when it last ran. We do not track whether it invalidated
1090 * mappings associated with its 'vpid' during that run. So we must
1091 * assume that the mappings associated with 'vpid' on 'curcpu' are
1092 * stale and invalidate them.
1094 * Note that we incur this penalty only when the scheduler chooses to
1095 * move the thread associated with this vcpu between host cpus.
1097 * Note also that this will invalidate mappings tagged with 'vpid'
1100 if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1101 invvpid_desc._res1 = 0;
1102 invvpid_desc._res2 = 0;
1103 invvpid_desc.vpid = vmxstate->vpid;
1104 invvpid_desc.linear_addr = 0;
1105 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1106 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1109 * The invvpid can be skipped if an invept is going to
1110 * be performed before entering the guest. The invept
1111 * will invalidate combined mappings tagged with
1112 * 'vmx->eptp' for all vpids.
1114 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1119 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1121 struct vmxstate *vmxstate;
1123 vmxstate = &vmx->state[vcpu];
1124 if (vmxstate->lastcpu == curcpu)
1127 vmxstate->lastcpu = curcpu;
1129 vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1131 vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1132 vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1133 vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1134 vmx_invvpid(vmx, vcpu, pmap, 1);
1138 * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1140 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1142 static void __inline
1143 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1146 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1147 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1148 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1149 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1153 static void __inline
1154 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1157 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1158 ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1159 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1160 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1161 VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1164 static void __inline
1165 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1168 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1169 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1170 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1171 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1175 static void __inline
1176 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1179 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1180 ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1181 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1182 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1183 VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1187 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1191 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1192 vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1193 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1194 VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1197 error = vmwrite(VMCS_TSC_OFFSET, offset);
1202 #define NMI_BLOCKING (VMCS_INTERRUPTIBILITY_NMI_BLOCKING | \
1203 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1204 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING | \
1205 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1208 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1212 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1213 KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1214 "interruptibility-state %#x", gi));
1216 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1217 KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1218 "VM-entry interruption information %#x", info));
1221 * Inject the virtual NMI. The vector must be the NMI IDT entry
1222 * or the VMCS entry check will fail.
1224 info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1225 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1227 VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1229 /* Clear the request */
1230 vm_nmi_clear(vmx->vm, vcpu);
1234 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1237 int vector, need_nmi_exiting, extint_pending;
1238 uint64_t rflags, entryinfo;
1241 if (vmx->state[vcpu].nextrip != guestrip) {
1242 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1243 if (gi & HWINTR_BLOCKING) {
1244 VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1245 "cleared due to rip change: %#lx/%#lx",
1246 vmx->state[vcpu].nextrip, guestrip);
1247 gi &= ~HWINTR_BLOCKING;
1248 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1252 if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1253 KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1254 "intinfo is not valid: %#lx", __func__, entryinfo));
1256 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1257 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1258 "pending exception: %#lx/%#x", __func__, entryinfo, info));
1261 vector = info & 0xff;
1262 if (vector == IDT_BP || vector == IDT_OF) {
1264 * VT-x requires #BP and #OF to be injected as software
1267 info &= ~VMCS_INTR_T_MASK;
1268 info |= VMCS_INTR_T_SWEXCEPTION;
1271 if (info & VMCS_INTR_DEL_ERRCODE)
1272 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1274 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1277 if (vm_nmi_pending(vmx->vm, vcpu)) {
1279 * If there are no conditions blocking NMI injection then
1280 * inject it directly here otherwise enable "NMI window
1281 * exiting" to inject it as soon as we can.
1283 * We also check for STI_BLOCKING because some implementations
1284 * don't allow NMI injection in this case. If we are running
1285 * on a processor that doesn't have this restriction it will
1286 * immediately exit and the NMI will be injected in the
1287 * "NMI window exiting" handler.
1289 need_nmi_exiting = 1;
1290 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1291 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1292 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1293 if ((info & VMCS_INTR_VALID) == 0) {
1294 vmx_inject_nmi(vmx, vcpu);
1295 need_nmi_exiting = 0;
1297 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1298 "due to VM-entry intr info %#x", info);
1301 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1302 "Guest Interruptibility-state %#x", gi);
1305 if (need_nmi_exiting)
1306 vmx_set_nmi_window_exiting(vmx, vcpu);
1309 extint_pending = vm_extint_pending(vmx->vm, vcpu);
1311 if (!extint_pending && virtual_interrupt_delivery) {
1312 vmx_inject_pir(vlapic);
1317 * If interrupt-window exiting is already in effect then don't bother
1318 * checking for pending interrupts. This is just an optimization and
1319 * not needed for correctness.
1321 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1322 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1323 "pending int_window_exiting");
1327 if (!extint_pending) {
1328 /* Ask the local apic for a vector to inject */
1329 if (!vlapic_pending_intr(vlapic, &vector))
1333 * From the Intel SDM, Volume 3, Section "Maskable
1334 * Hardware Interrupts":
1335 * - maskable interrupt vectors [16,255] can be delivered
1336 * through the local APIC.
1338 KASSERT(vector >= 16 && vector <= 255,
1339 ("invalid vector %d from local APIC", vector));
1341 /* Ask the legacy pic for a vector to inject */
1342 vatpic_pending_intr(vmx->vm, &vector);
1345 * From the Intel SDM, Volume 3, Section "Maskable
1346 * Hardware Interrupts":
1347 * - maskable interrupt vectors [0,255] can be delivered
1348 * through the INTR pin.
1350 KASSERT(vector >= 0 && vector <= 255,
1351 ("invalid vector %d from INTR", vector));
1354 /* Check RFLAGS.IF and the interruptibility state of the guest */
1355 rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1356 if ((rflags & PSL_I) == 0) {
1357 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1358 "rflags %#lx", vector, rflags);
1362 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1363 if (gi & HWINTR_BLOCKING) {
1364 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1365 "Guest Interruptibility-state %#x", vector, gi);
1369 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1370 if (info & VMCS_INTR_VALID) {
1372 * This is expected and could happen for multiple reasons:
1373 * - A vectoring VM-entry was aborted due to astpending
1374 * - A VM-exit happened during event injection.
1375 * - An exception was injected above.
1376 * - An NMI was injected above or after "NMI window exiting"
1378 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1379 "VM-entry intr info %#x", vector, info);
1383 /* Inject the interrupt */
1384 info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1386 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1388 if (!extint_pending) {
1389 /* Update the Local APIC ISR */
1390 vlapic_intr_accepted(vlapic, vector);
1392 vm_extint_clear(vmx->vm, vcpu);
1393 vatpic_intr_accepted(vmx->vm, vector);
1396 * After we accepted the current ExtINT the PIC may
1397 * have posted another one. If that is the case, set
1398 * the Interrupt Window Exiting execution control so
1399 * we can inject that one too.
1401 * Also, interrupt window exiting allows us to inject any
1402 * pending APIC vector that was preempted by the ExtINT
1403 * as soon as possible. This applies both for the software
1404 * emulated vlapic and the hardware assisted virtual APIC.
1406 vmx_set_int_window_exiting(vmx, vcpu);
1409 VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1415 * Set the Interrupt Window Exiting execution control so we can inject
1416 * the interrupt as soon as blocking condition goes away.
1418 vmx_set_int_window_exiting(vmx, vcpu);
1422 * If the Virtual NMIs execution control is '1' then the logical processor
1423 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1424 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1425 * virtual-NMI blocking.
1427 * This unblocking occurs even if the IRET causes a fault. In this case the
1428 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1431 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1435 VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1436 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1437 gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1438 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1442 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1446 VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1447 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1448 gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1449 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1453 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1457 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1458 KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1459 ("NMI blocking is not in effect %#x", gi));
1463 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1465 struct vmxctx *vmxctx;
1467 const struct xsave_limits *limits;
1469 vmxctx = &vmx->ctx[vcpu];
1470 limits = vmm_get_xsave_limits();
1473 * Note that the processor raises a GP# fault on its own if
1474 * xsetbv is executed for CPL != 0, so we do not have to
1475 * emulate that fault here.
1478 /* Only xcr0 is supported. */
1479 if (vmxctx->guest_rcx != 0) {
1480 vm_inject_gp(vmx->vm, vcpu);
1484 /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1485 if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1486 vm_inject_ud(vmx->vm, vcpu);
1490 xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1491 if ((xcrval & ~limits->xcr0_allowed) != 0) {
1492 vm_inject_gp(vmx->vm, vcpu);
1496 if (!(xcrval & XFEATURE_ENABLED_X87)) {
1497 vm_inject_gp(vmx->vm, vcpu);
1501 /* AVX (YMM_Hi128) requires SSE. */
1502 if (xcrval & XFEATURE_ENABLED_AVX &&
1503 (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1504 vm_inject_gp(vmx->vm, vcpu);
1509 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1510 * ZMM_Hi256, and Hi16_ZMM.
1512 if (xcrval & XFEATURE_AVX512 &&
1513 (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1514 (XFEATURE_AVX512 | XFEATURE_AVX)) {
1515 vm_inject_gp(vmx->vm, vcpu);
1520 * Intel MPX requires both bound register state flags to be
1523 if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1524 ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1525 vm_inject_gp(vmx->vm, vcpu);
1530 * This runs "inside" vmrun() with the guest's FPU state, so
1531 * modifying xcr0 directly modifies the guest's xcr0, not the
1534 load_xcr(0, xcrval);
1539 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1541 const struct vmxctx *vmxctx;
1543 vmxctx = &vmx->ctx[vcpu];
1547 return (vmxctx->guest_rax);
1549 return (vmxctx->guest_rcx);
1551 return (vmxctx->guest_rdx);
1553 return (vmxctx->guest_rbx);
1555 return (vmcs_read(VMCS_GUEST_RSP));
1557 return (vmxctx->guest_rbp);
1559 return (vmxctx->guest_rsi);
1561 return (vmxctx->guest_rdi);
1563 return (vmxctx->guest_r8);
1565 return (vmxctx->guest_r9);
1567 return (vmxctx->guest_r10);
1569 return (vmxctx->guest_r11);
1571 return (vmxctx->guest_r12);
1573 return (vmxctx->guest_r13);
1575 return (vmxctx->guest_r14);
1577 return (vmxctx->guest_r15);
1579 panic("invalid vmx register %d", ident);
1584 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1586 struct vmxctx *vmxctx;
1588 vmxctx = &vmx->ctx[vcpu];
1592 vmxctx->guest_rax = regval;
1595 vmxctx->guest_rcx = regval;
1598 vmxctx->guest_rdx = regval;
1601 vmxctx->guest_rbx = regval;
1604 vmcs_write(VMCS_GUEST_RSP, regval);
1607 vmxctx->guest_rbp = regval;
1610 vmxctx->guest_rsi = regval;
1613 vmxctx->guest_rdi = regval;
1616 vmxctx->guest_r8 = regval;
1619 vmxctx->guest_r9 = regval;
1622 vmxctx->guest_r10 = regval;
1625 vmxctx->guest_r11 = regval;
1628 vmxctx->guest_r12 = regval;
1631 vmxctx->guest_r13 = regval;
1634 vmxctx->guest_r14 = regval;
1637 vmxctx->guest_r15 = regval;
1640 panic("invalid vmx register %d", ident);
1645 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1647 uint64_t crval, regval;
1649 /* We only handle mov to %cr0 at this time */
1650 if ((exitqual & 0xf0) != 0x00)
1653 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1655 vmcs_write(VMCS_CR0_SHADOW, regval);
1657 crval = regval | cr0_ones_mask;
1658 crval &= ~cr0_zeros_mask;
1659 vmcs_write(VMCS_GUEST_CR0, crval);
1661 if (regval & CR0_PG) {
1662 uint64_t efer, entry_ctls;
1665 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1666 * the "IA-32e mode guest" bit in VM-entry control must be
1669 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1670 if (efer & EFER_LME) {
1672 vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1673 entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1674 entry_ctls |= VM_ENTRY_GUEST_LMA;
1675 vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1683 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1685 uint64_t crval, regval;
1687 /* We only handle mov to %cr4 at this time */
1688 if ((exitqual & 0xf0) != 0x00)
1691 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1693 vmcs_write(VMCS_CR4_SHADOW, regval);
1695 crval = regval | cr4_ones_mask;
1696 crval &= ~cr4_zeros_mask;
1697 vmcs_write(VMCS_GUEST_CR4, crval);
1703 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1705 struct vlapic *vlapic;
1709 /* We only handle mov %cr8 to/from a register at this time. */
1710 if ((exitqual & 0xe0) != 0x00) {
1714 vlapic = vm_lapic(vmx->vm, vcpu);
1715 regnum = (exitqual >> 8) & 0xf;
1716 if (exitqual & 0x10) {
1717 cr8 = vlapic_get_cr8(vlapic);
1718 vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1720 cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1721 vlapic_set_cr8(vlapic, cr8);
1728 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1735 ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1736 return ((ssar >> 5) & 0x3);
1739 static enum vm_cpu_mode
1744 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1745 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1747 return (CPU_MODE_64BIT); /* CS.L = 1 */
1749 return (CPU_MODE_COMPATIBILITY);
1750 } else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1751 return (CPU_MODE_PROTECTED);
1753 return (CPU_MODE_REAL);
1757 static enum vm_paging_mode
1758 vmx_paging_mode(void)
1761 if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1762 return (PAGING_MODE_FLAT);
1763 if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1764 return (PAGING_MODE_32);
1765 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1766 return (PAGING_MODE_64);
1768 return (PAGING_MODE_PAE);
1772 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1776 enum vm_reg_name reg;
1778 reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1779 error = vmx_getreg(vmx, vcpuid, reg, &val);
1780 KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1785 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1791 error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1792 KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1800 inout_str_addrsize(uint32_t inst_info)
1804 size = (inst_info >> 7) & 0x7;
1807 return (2); /* 16 bit */
1809 return (4); /* 32 bit */
1811 return (8); /* 64 bit */
1813 panic("%s: invalid size encoding %d", __func__, size);
1818 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1819 struct vm_inout_str *vis)
1824 vis->seg_name = VM_REG_GUEST_ES;
1826 s = (inst_info >> 15) & 0x7;
1827 vis->seg_name = vm_segment_name(s);
1830 error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1831 KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1835 vmx_paging_info(struct vm_guest_paging *paging)
1837 paging->cr3 = vmcs_guest_cr3();
1838 paging->cpl = vmx_cpl();
1839 paging->cpu_mode = vmx_cpu_mode();
1840 paging->paging_mode = vmx_paging_mode();
1844 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1846 struct vm_guest_paging *paging;
1849 paging = &vmexit->u.inst_emul.paging;
1851 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1852 vmexit->inst_length = 0;
1853 vmexit->u.inst_emul.gpa = gpa;
1854 vmexit->u.inst_emul.gla = gla;
1855 vmx_paging_info(paging);
1856 switch (paging->cpu_mode) {
1858 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1859 vmexit->u.inst_emul.cs_d = 0;
1861 case CPU_MODE_PROTECTED:
1862 case CPU_MODE_COMPATIBILITY:
1863 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1864 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1865 vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1868 vmexit->u.inst_emul.cs_base = 0;
1869 vmexit->u.inst_emul.cs_d = 0;
1872 vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1876 ept_fault_type(uint64_t ept_qual)
1880 if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1881 fault_type = VM_PROT_WRITE;
1882 else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1883 fault_type = VM_PROT_EXECUTE;
1885 fault_type= VM_PROT_READ;
1887 return (fault_type);
1891 ept_emulation_fault(uint64_t ept_qual)
1895 /* EPT fault on an instruction fetch doesn't make sense here */
1896 if (ept_qual & EPT_VIOLATION_INST_FETCH)
1899 /* EPT fault must be a read fault or a write fault */
1900 read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1901 write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1902 if ((read | write) == 0)
1906 * The EPT violation must have been caused by accessing a
1907 * guest-physical address that is a translation of a guest-linear
1910 if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1911 (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1919 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1921 uint32_t proc_ctls2;
1923 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1924 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1928 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1930 uint32_t proc_ctls2;
1932 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1933 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1937 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1940 int error, handled, offset;
1941 uint32_t *apic_regs, vector;
1945 offset = APIC_WRITE_OFFSET(qual);
1947 if (!apic_access_virtualization(vmx, vcpuid)) {
1949 * In general there should not be any APIC write VM-exits
1950 * unless APIC-access virtualization is enabled.
1952 * However self-IPI virtualization can legitimately trigger
1953 * an APIC-write VM-exit so treat it specially.
1955 if (x2apic_virtualization(vmx, vcpuid) &&
1956 offset == APIC_OFFSET_SELF_IPI) {
1957 apic_regs = (uint32_t *)(vlapic->apic_page);
1958 vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1959 vlapic_self_ipi_handler(vlapic, vector);
1966 case APIC_OFFSET_ID:
1967 vlapic_id_write_handler(vlapic);
1969 case APIC_OFFSET_LDR:
1970 vlapic_ldr_write_handler(vlapic);
1972 case APIC_OFFSET_DFR:
1973 vlapic_dfr_write_handler(vlapic);
1975 case APIC_OFFSET_SVR:
1976 vlapic_svr_write_handler(vlapic);
1978 case APIC_OFFSET_ESR:
1979 vlapic_esr_write_handler(vlapic);
1981 case APIC_OFFSET_ICR_LOW:
1983 error = vlapic_icrlo_write_handler(vlapic, &retu);
1984 if (error != 0 || retu)
1985 handled = UNHANDLED;
1987 case APIC_OFFSET_CMCI_LVT:
1988 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1989 vlapic_lvt_write_handler(vlapic, offset);
1991 case APIC_OFFSET_TIMER_ICR:
1992 vlapic_icrtmr_write_handler(vlapic);
1994 case APIC_OFFSET_TIMER_DCR:
1995 vlapic_dcr_write_handler(vlapic);
1998 handled = UNHANDLED;
2005 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
2008 if (apic_access_virtualization(vmx, vcpuid) &&
2009 (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
2016 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2019 int access_type, offset, allowed;
2021 if (!apic_access_virtualization(vmx, vcpuid))
2024 qual = vmexit->u.vmx.exit_qualification;
2025 access_type = APIC_ACCESS_TYPE(qual);
2026 offset = APIC_ACCESS_OFFSET(qual);
2029 if (access_type == 0) {
2031 * Read data access to the following registers is expected.
2034 case APIC_OFFSET_APR:
2035 case APIC_OFFSET_PPR:
2036 case APIC_OFFSET_RRR:
2037 case APIC_OFFSET_CMCI_LVT:
2038 case APIC_OFFSET_TIMER_CCR:
2044 } else if (access_type == 1) {
2046 * Write data access to the following registers is expected.
2049 case APIC_OFFSET_VER:
2050 case APIC_OFFSET_APR:
2051 case APIC_OFFSET_PPR:
2052 case APIC_OFFSET_RRR:
2053 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2054 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2055 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2056 case APIC_OFFSET_CMCI_LVT:
2057 case APIC_OFFSET_TIMER_CCR:
2066 vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2071 * Regardless of whether the APIC-access is allowed this handler
2072 * always returns UNHANDLED:
2073 * - if the access is allowed then it is handled by emulating the
2074 * instruction that caused the VM-exit (outside the critical section)
2075 * - if the access is not allowed then it will be converted to an
2076 * exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2081 static enum task_switch_reason
2082 vmx_task_switch_reason(uint64_t qual)
2086 reason = (qual >> 30) & 0x3;
2095 return (TSR_IDT_GATE);
2097 panic("%s: invalid reason %d", __func__, reason);
2102 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2107 error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2109 error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2115 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2117 struct vmxctx *vmxctx;
2123 error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2125 error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2129 vmxctx = &vmx->ctx[vcpuid];
2130 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2131 KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2134 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2135 KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2142 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2144 int error, errcode, errcode_valid, handled, in;
2145 struct vmxctx *vmxctx;
2146 struct vlapic *vlapic;
2147 struct vm_inout_str *vis;
2148 struct vm_task_switch *ts;
2149 uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2150 uint32_t intr_type, intr_vec, reason;
2151 uint64_t exitintinfo, qual, gpa;
2154 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2155 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2157 handled = UNHANDLED;
2158 vmxctx = &vmx->ctx[vcpu];
2160 qual = vmexit->u.vmx.exit_qualification;
2161 reason = vmexit->u.vmx.exit_reason;
2162 vmexit->exitcode = VM_EXITCODE_BOGUS;
2164 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2167 * VM-entry failures during or after loading guest state.
2169 * These VM-exits are uncommon but must be handled specially
2170 * as most VM-exit fields are not populated as usual.
2172 if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2173 VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2174 __asm __volatile("int $18");
2179 * VM exits that can be triggered during event delivery need to
2180 * be handled specially by re-injecting the event if the IDT
2181 * vectoring information field's valid bit is set.
2183 * See "Information for VM Exits During Event Delivery" in Intel SDM
2186 idtvec_info = vmcs_idt_vectoring_info();
2187 if (idtvec_info & VMCS_IDT_VEC_VALID) {
2188 idtvec_info &= ~(1 << 12); /* clear undefined bit */
2189 exitintinfo = idtvec_info;
2190 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2191 idtvec_err = vmcs_idt_vectoring_err();
2192 exitintinfo |= (uint64_t)idtvec_err << 32;
2194 error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2195 KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2199 * If 'virtual NMIs' are being used and the VM-exit
2200 * happened while injecting an NMI during the previous
2201 * VM-entry, then clear "blocking by NMI" in the
2202 * Guest Interruptibility-State so the NMI can be
2203 * reinjected on the subsequent VM-entry.
2205 * However, if the NMI was being delivered through a task
2206 * gate, then the new task must start execution with NMIs
2207 * blocked so don't clear NMI blocking in this case.
2209 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2210 if (intr_type == VMCS_INTR_T_NMI) {
2211 if (reason != EXIT_REASON_TASK_SWITCH)
2212 vmx_clear_nmi_blocking(vmx, vcpu);
2214 vmx_assert_nmi_blocking(vmx, vcpu);
2218 * Update VM-entry instruction length if the event being
2219 * delivered was a software interrupt or software exception.
2221 if (intr_type == VMCS_INTR_T_SWINTR ||
2222 intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2223 intr_type == VMCS_INTR_T_SWEXCEPTION) {
2224 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2229 case EXIT_REASON_TASK_SWITCH:
2230 ts = &vmexit->u.task_switch;
2231 ts->tsssel = qual & 0xffff;
2232 ts->reason = vmx_task_switch_reason(qual);
2234 ts->errcode_valid = 0;
2235 vmx_paging_info(&ts->paging);
2237 * If the task switch was due to a CALL, JMP, IRET, software
2238 * interrupt (INT n) or software exception (INT3, INTO),
2239 * then the saved %rip references the instruction that caused
2240 * the task switch. The instruction length field in the VMCS
2241 * is valid in this case.
2243 * In all other cases (e.g., NMI, hardware exception) the
2244 * saved %rip is one that would have been saved in the old TSS
2245 * had the task switch completed normally so the instruction
2246 * length field is not needed in this case and is explicitly
2249 if (ts->reason == TSR_IDT_GATE) {
2250 KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2251 ("invalid idtvec_info %#x for IDT task switch",
2253 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2254 if (intr_type != VMCS_INTR_T_SWINTR &&
2255 intr_type != VMCS_INTR_T_SWEXCEPTION &&
2256 intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2257 /* Task switch triggered by external event */
2259 vmexit->inst_length = 0;
2260 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2261 ts->errcode_valid = 1;
2262 ts->errcode = vmcs_idt_vectoring_err();
2266 vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2267 VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2268 "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2269 ts->ext ? "external" : "internal",
2270 ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2272 case EXIT_REASON_CR_ACCESS:
2273 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2274 switch (qual & 0xf) {
2276 handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2279 handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2282 handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2286 case EXIT_REASON_RDMSR:
2287 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2289 ecx = vmxctx->guest_rcx;
2290 VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2291 error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2293 vmexit->exitcode = VM_EXITCODE_RDMSR;
2294 vmexit->u.msr.code = ecx;
2298 /* Return to userspace with a valid exitcode */
2299 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2300 ("emulate_rdmsr retu with bogus exitcode"));
2303 case EXIT_REASON_WRMSR:
2304 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2306 eax = vmxctx->guest_rax;
2307 ecx = vmxctx->guest_rcx;
2308 edx = vmxctx->guest_rdx;
2309 VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2310 ecx, (uint64_t)edx << 32 | eax);
2311 error = emulate_wrmsr(vmx, vcpu, ecx,
2312 (uint64_t)edx << 32 | eax, &retu);
2314 vmexit->exitcode = VM_EXITCODE_WRMSR;
2315 vmexit->u.msr.code = ecx;
2316 vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2320 /* Return to userspace with a valid exitcode */
2321 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2322 ("emulate_wrmsr retu with bogus exitcode"));
2325 case EXIT_REASON_HLT:
2326 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2327 vmexit->exitcode = VM_EXITCODE_HLT;
2328 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2330 case EXIT_REASON_MTF:
2331 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2332 vmexit->exitcode = VM_EXITCODE_MTRAP;
2333 vmexit->inst_length = 0;
2335 case EXIT_REASON_PAUSE:
2336 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2337 vmexit->exitcode = VM_EXITCODE_PAUSE;
2339 case EXIT_REASON_INTR_WINDOW:
2340 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2341 vmx_clear_int_window_exiting(vmx, vcpu);
2343 case EXIT_REASON_EXT_INTR:
2345 * External interrupts serve only to cause VM exits and allow
2346 * the host interrupt handler to run.
2348 * If this external interrupt triggers a virtual interrupt
2349 * to a VM, then that state will be recorded by the
2350 * host interrupt handler in the VM's softc. We will inject
2351 * this virtual interrupt during the subsequent VM enter.
2353 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2356 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2357 * This appears to be a bug in VMware Fusion?
2359 if (!(intr_info & VMCS_INTR_VALID))
2361 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2362 (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2363 ("VM exit interruption info invalid: %#x", intr_info));
2364 vmx_trigger_hostintr(intr_info & 0xff);
2367 * This is special. We want to treat this as an 'handled'
2368 * VM-exit but not increment the instruction pointer.
2370 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2372 case EXIT_REASON_NMI_WINDOW:
2373 /* Exit to allow the pending virtual NMI to be injected */
2374 if (vm_nmi_pending(vmx->vm, vcpu))
2375 vmx_inject_nmi(vmx, vcpu);
2376 vmx_clear_nmi_window_exiting(vmx, vcpu);
2377 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2379 case EXIT_REASON_INOUT:
2380 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2381 vmexit->exitcode = VM_EXITCODE_INOUT;
2382 vmexit->u.inout.bytes = (qual & 0x7) + 1;
2383 vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2384 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2385 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2386 vmexit->u.inout.port = (uint16_t)(qual >> 16);
2387 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2388 if (vmexit->u.inout.string) {
2389 inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2390 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2391 vis = &vmexit->u.inout_str;
2392 vmx_paging_info(&vis->paging);
2393 vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2394 vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2395 vis->index = inout_str_index(vmx, vcpu, in);
2396 vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2397 vis->addrsize = inout_str_addrsize(inst_info);
2398 inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2401 case EXIT_REASON_CPUID:
2402 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2403 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2405 case EXIT_REASON_EXCEPTION:
2406 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2407 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2408 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2409 ("VM exit interruption info invalid: %#x", intr_info));
2411 intr_vec = intr_info & 0xff;
2412 intr_type = intr_info & VMCS_INTR_T_MASK;
2415 * If Virtual NMIs control is 1 and the VM-exit is due to a
2416 * fault encountered during the execution of IRET then we must
2417 * restore the state of "virtual-NMI blocking" before resuming
2420 * See "Resuming Guest Software after Handling an Exception".
2421 * See "Information for VM Exits Due to Vectored Events".
2423 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2424 (intr_vec != IDT_DF) &&
2425 (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2426 vmx_restore_nmi_blocking(vmx, vcpu);
2429 * The NMI has already been handled in vmx_exit_handle_nmi().
2431 if (intr_type == VMCS_INTR_T_NMI)
2435 * Call the machine check handler by hand. Also don't reflect
2436 * the machine check back into the guest.
2438 if (intr_vec == IDT_MC) {
2439 VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2440 __asm __volatile("int $18");
2444 if (intr_vec == IDT_PF) {
2445 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2446 KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2451 * Software exceptions exhibit trap-like behavior. This in
2452 * turn requires populating the VM-entry instruction length
2453 * so that the %rip in the trap frame is past the INT3/INTO
2456 if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2457 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2459 /* Reflect all other exceptions back into the guest */
2460 errcode_valid = errcode = 0;
2461 if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2463 errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2465 VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2466 "the guest", intr_vec, errcode);
2467 error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2468 errcode_valid, errcode, 0);
2469 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2473 case EXIT_REASON_EPT_FAULT:
2475 * If 'gpa' lies within the address space allocated to
2476 * memory then this must be a nested page fault otherwise
2477 * this must be an instruction that accesses MMIO space.
2480 if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2481 apic_access_fault(vmx, vcpu, gpa)) {
2482 vmexit->exitcode = VM_EXITCODE_PAGING;
2483 vmexit->inst_length = 0;
2484 vmexit->u.paging.gpa = gpa;
2485 vmexit->u.paging.fault_type = ept_fault_type(qual);
2486 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2487 } else if (ept_emulation_fault(qual)) {
2488 vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2489 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2492 * If Virtual NMIs control is 1 and the VM-exit is due to an
2493 * EPT fault during the execution of IRET then we must restore
2494 * the state of "virtual-NMI blocking" before resuming.
2496 * See description of "NMI unblocking due to IRET" in
2497 * "Exit Qualification for EPT Violations".
2499 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2500 (qual & EXIT_QUAL_NMIUDTI) != 0)
2501 vmx_restore_nmi_blocking(vmx, vcpu);
2503 case EXIT_REASON_VIRTUALIZED_EOI:
2504 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2505 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2506 vmexit->inst_length = 0; /* trap-like */
2508 case EXIT_REASON_APIC_ACCESS:
2509 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2511 case EXIT_REASON_APIC_WRITE:
2513 * APIC-write VM exit is trap-like so the %rip is already
2514 * pointing to the next instruction.
2516 vmexit->inst_length = 0;
2517 vlapic = vm_lapic(vmx->vm, vcpu);
2518 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2520 case EXIT_REASON_XSETBV:
2521 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2523 case EXIT_REASON_MONITOR:
2524 vmexit->exitcode = VM_EXITCODE_MONITOR;
2526 case EXIT_REASON_MWAIT:
2527 vmexit->exitcode = VM_EXITCODE_MWAIT;
2530 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2536 * It is possible that control is returned to userland
2537 * even though we were able to handle the VM exit in the
2540 * In such a case we want to make sure that the userland
2541 * restarts guest execution at the instruction *after*
2542 * the one we just processed. Therefore we update the
2543 * guest rip in the VMCS and in 'vmexit'.
2545 vmexit->rip += vmexit->inst_length;
2546 vmexit->inst_length = 0;
2547 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2549 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2551 * If this VM exit was not claimed by anybody then
2552 * treat it as a generic VMX exit.
2554 vmexit->exitcode = VM_EXITCODE_VMX;
2555 vmexit->u.vmx.status = VM_SUCCESS;
2556 vmexit->u.vmx.inst_type = 0;
2557 vmexit->u.vmx.inst_error = 0;
2560 * The exitcode and collateral have been populated.
2561 * The VM exit will be processed further in userland.
2568 static __inline void
2569 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2572 KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2573 ("vmx_exit_inst_error: invalid inst_fail_status %d",
2574 vmxctx->inst_fail_status));
2576 vmexit->inst_length = 0;
2577 vmexit->exitcode = VM_EXITCODE_VMX;
2578 vmexit->u.vmx.status = vmxctx->inst_fail_status;
2579 vmexit->u.vmx.inst_error = vmcs_instruction_error();
2580 vmexit->u.vmx.exit_reason = ~0;
2581 vmexit->u.vmx.exit_qualification = ~0;
2584 case VMX_VMRESUME_ERROR:
2585 case VMX_VMLAUNCH_ERROR:
2586 case VMX_INVEPT_ERROR:
2587 vmexit->u.vmx.inst_type = rc;
2590 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2595 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2596 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2597 * sufficient to simply vector to the NMI handler via a software interrupt.
2598 * However, this must be done before maskable interrupts are enabled
2599 * otherwise the "iret" issued by an interrupt handler will incorrectly
2600 * clear NMI blocking.
2602 static __inline void
2603 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2607 KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2609 if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2612 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2613 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2614 ("VM exit interruption info invalid: %#x", intr_info));
2616 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2617 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2618 "to NMI has invalid vector: %#x", intr_info));
2619 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2620 __asm __volatile("int $2");
2624 static __inline void
2625 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2629 /* Save host control debug registers. */
2630 vmxctx->host_dr7 = rdr7();
2631 vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2634 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2635 * exceptions in the host based on the guest DRx values. The
2636 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2639 wrmsr(MSR_DEBUGCTLMSR, 0);
2642 * Disable single stepping the kernel to avoid corrupting the
2643 * guest DR6. A debugger might still be able to corrupt the
2644 * guest DR6 by setting a breakpoint after this point and then
2647 rflags = read_rflags();
2648 vmxctx->host_tf = rflags & PSL_T;
2649 write_rflags(rflags & ~PSL_T);
2651 /* Save host debug registers. */
2652 vmxctx->host_dr0 = rdr0();
2653 vmxctx->host_dr1 = rdr1();
2654 vmxctx->host_dr2 = rdr2();
2655 vmxctx->host_dr3 = rdr3();
2656 vmxctx->host_dr6 = rdr6();
2658 /* Restore guest debug registers. */
2659 load_dr0(vmxctx->guest_dr0);
2660 load_dr1(vmxctx->guest_dr1);
2661 load_dr2(vmxctx->guest_dr2);
2662 load_dr3(vmxctx->guest_dr3);
2663 load_dr6(vmxctx->guest_dr6);
2666 static __inline void
2667 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2670 /* Save guest debug registers. */
2671 vmxctx->guest_dr0 = rdr0();
2672 vmxctx->guest_dr1 = rdr1();
2673 vmxctx->guest_dr2 = rdr2();
2674 vmxctx->guest_dr3 = rdr3();
2675 vmxctx->guest_dr6 = rdr6();
2678 * Restore host debug registers. Restore DR7, DEBUGCTL, and
2681 load_dr0(vmxctx->host_dr0);
2682 load_dr1(vmxctx->host_dr1);
2683 load_dr2(vmxctx->host_dr2);
2684 load_dr3(vmxctx->host_dr3);
2685 load_dr6(vmxctx->host_dr6);
2686 wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2687 load_dr7(vmxctx->host_dr7);
2688 write_rflags(read_rflags() | vmxctx->host_tf);
2692 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2693 struct vm_eventinfo *evinfo)
2695 int rc, handled, launched;
2698 struct vmxctx *vmxctx;
2700 struct vm_exit *vmexit;
2701 struct vlapic *vlapic;
2702 uint32_t exit_reason;
2706 vmcs = &vmx->vmcs[vcpu];
2707 vmxctx = &vmx->ctx[vcpu];
2708 vlapic = vm_lapic(vm, vcpu);
2709 vmexit = vm_exitinfo(vm, vcpu);
2712 KASSERT(vmxctx->pmap == pmap,
2713 ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2715 vmx_msr_guest_enter(vmx, vcpu);
2721 * We do this every time because we may setup the virtual machine
2722 * from a different process than the one that actually runs it.
2724 * If the life of a virtual machine was spent entirely in the context
2725 * of a single process we could do this once in vmx_vminit().
2727 vmcs_write(VMCS_HOST_CR3, rcr3());
2729 vmcs_write(VMCS_GUEST_RIP, rip);
2730 vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2732 KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2733 "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2735 handled = UNHANDLED;
2737 * Interrupts are disabled from this point on until the
2738 * guest starts executing. This is done for the following
2741 * If an AST is asserted on this thread after the check below,
2742 * then the IPI_AST notification will not be lost, because it
2743 * will cause a VM exit due to external interrupt as soon as
2744 * the guest state is loaded.
2746 * A posted interrupt after 'vmx_inject_interrupts()' will
2747 * not be "lost" because it will be held pending in the host
2748 * APIC because interrupts are disabled. The pending interrupt
2749 * will be recognized as soon as the guest state is loaded.
2751 * The same reasoning applies to the IPI generated by
2752 * pmap_invalidate_ept().
2755 vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2758 * Check for vcpu suspension after injecting events because
2759 * vmx_inject_interrupts() can suspend the vcpu due to a
2762 if (vcpu_suspended(evinfo)) {
2764 vm_exit_suspended(vmx->vm, vcpu, rip);
2768 if (vcpu_rendezvous_pending(evinfo)) {
2770 vm_exit_rendezvous(vmx->vm, vcpu, rip);
2774 if (vcpu_reqidle(evinfo)) {
2776 vm_exit_reqidle(vmx->vm, vcpu, rip);
2780 if (vcpu_should_yield(vm, vcpu)) {
2782 vm_exit_astpending(vmx->vm, vcpu, rip);
2783 vmx_astpending_trace(vmx, vcpu, rip);
2788 vmx_run_trace(vmx, vcpu);
2789 vmx_dr_enter_guest(vmxctx);
2790 rc = vmx_enter_guest(vmxctx, vmx, launched);
2791 vmx_dr_leave_guest(vmxctx);
2793 /* Collect some information for VM exit processing */
2794 vmexit->rip = rip = vmcs_guest_rip();
2795 vmexit->inst_length = vmexit_instruction_length();
2796 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2797 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2799 /* Update 'nextrip' */
2800 vmx->state[vcpu].nextrip = rip;
2802 if (rc == VMX_GUEST_VMEXIT) {
2803 vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2805 handled = vmx_exit_process(vmx, vcpu, vmexit);
2808 vmx_exit_inst_error(vmxctx, rc, vmexit);
2811 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2816 * If a VM exit has been handled then the exitcode must be BOGUS
2817 * If a VM exit is not handled then the exitcode must not be BOGUS
2819 if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2820 (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2821 panic("Mismatch between handled (%d) and exitcode (%d)",
2822 handled, vmexit->exitcode);
2826 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2828 VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2832 vmx_msr_guest_exit(vmx, vcpu);
2838 vmx_vmcleanup(void *arg)
2841 struct vmx *vmx = arg;
2843 if (apic_access_virtualization(vmx, 0))
2844 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2846 for (i = 0; i < VM_MAXCPU; i++)
2847 vpid_free(vmx->state[i].vpid);
2855 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2859 case VM_REG_GUEST_RAX:
2860 return (&vmxctx->guest_rax);
2861 case VM_REG_GUEST_RBX:
2862 return (&vmxctx->guest_rbx);
2863 case VM_REG_GUEST_RCX:
2864 return (&vmxctx->guest_rcx);
2865 case VM_REG_GUEST_RDX:
2866 return (&vmxctx->guest_rdx);
2867 case VM_REG_GUEST_RSI:
2868 return (&vmxctx->guest_rsi);
2869 case VM_REG_GUEST_RDI:
2870 return (&vmxctx->guest_rdi);
2871 case VM_REG_GUEST_RBP:
2872 return (&vmxctx->guest_rbp);
2873 case VM_REG_GUEST_R8:
2874 return (&vmxctx->guest_r8);
2875 case VM_REG_GUEST_R9:
2876 return (&vmxctx->guest_r9);
2877 case VM_REG_GUEST_R10:
2878 return (&vmxctx->guest_r10);
2879 case VM_REG_GUEST_R11:
2880 return (&vmxctx->guest_r11);
2881 case VM_REG_GUEST_R12:
2882 return (&vmxctx->guest_r12);
2883 case VM_REG_GUEST_R13:
2884 return (&vmxctx->guest_r13);
2885 case VM_REG_GUEST_R14:
2886 return (&vmxctx->guest_r14);
2887 case VM_REG_GUEST_R15:
2888 return (&vmxctx->guest_r15);
2889 case VM_REG_GUEST_CR2:
2890 return (&vmxctx->guest_cr2);
2891 case VM_REG_GUEST_DR0:
2892 return (&vmxctx->guest_dr0);
2893 case VM_REG_GUEST_DR1:
2894 return (&vmxctx->guest_dr1);
2895 case VM_REG_GUEST_DR2:
2896 return (&vmxctx->guest_dr2);
2897 case VM_REG_GUEST_DR3:
2898 return (&vmxctx->guest_dr3);
2899 case VM_REG_GUEST_DR6:
2900 return (&vmxctx->guest_dr6);
2908 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2912 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2920 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2924 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2932 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2937 error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2938 VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2939 *retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2944 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2951 * Forcing the vcpu into an interrupt shadow is not supported.
2958 vmcs = &vmx->vmcs[vcpu];
2959 ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2960 error = vmcs_getreg(vmcs, running, ident, &gi);
2962 gi &= ~HWINTR_BLOCKING;
2963 error = vmcs_setreg(vmcs, running, ident, gi);
2966 VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2967 error ? "failed" : "succeeded");
2972 vmx_shadow_reg(int reg)
2979 case VM_REG_GUEST_CR0:
2980 shreg = VMCS_CR0_SHADOW;
2982 case VM_REG_GUEST_CR4:
2983 shreg = VMCS_CR4_SHADOW;
2993 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2995 int running, hostcpu;
2996 struct vmx *vmx = arg;
2998 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2999 if (running && hostcpu != curcpu)
3000 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
3002 if (reg == VM_REG_GUEST_INTR_SHADOW)
3003 return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
3005 if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
3008 return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
3012 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3014 int error, hostcpu, running, shadow;
3017 struct vmx *vmx = arg;
3019 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3020 if (running && hostcpu != curcpu)
3021 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
3023 if (reg == VM_REG_GUEST_INTR_SHADOW)
3024 return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
3026 if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
3029 error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
3033 * If the "load EFER" VM-entry control is 1 then the
3034 * value of EFER.LMA must be identical to "IA-32e mode guest"
3035 * bit in the VM-entry control.
3037 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
3038 (reg == VM_REG_GUEST_EFER)) {
3039 vmcs_getreg(&vmx->vmcs[vcpu], running,
3040 VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
3042 ctls |= VM_ENTRY_GUEST_LMA;
3044 ctls &= ~VM_ENTRY_GUEST_LMA;
3045 vmcs_setreg(&vmx->vmcs[vcpu], running,
3046 VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3049 shadow = vmx_shadow_reg(reg);
3052 * Store the unmodified value in the shadow
3054 error = vmcs_setreg(&vmx->vmcs[vcpu], running,
3055 VMCS_IDENT(shadow), val);
3058 if (reg == VM_REG_GUEST_CR3) {
3060 * Invalidate the guest vcpu's TLB mappings to emulate
3061 * the behavior of updating %cr3.
3063 * XXX the processor retains global mappings when %cr3
3064 * is updated but vmx_invvpid() does not.
3066 pmap = vmx->ctx[vcpu].pmap;
3067 vmx_invvpid(vmx, vcpu, pmap, running);
3075 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3077 int hostcpu, running;
3078 struct vmx *vmx = arg;
3080 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3081 if (running && hostcpu != curcpu)
3082 panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3084 return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
3088 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3090 int hostcpu, running;
3091 struct vmx *vmx = arg;
3093 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3094 if (running && hostcpu != curcpu)
3095 panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3097 return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
3101 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3103 struct vmx *vmx = arg;
3109 vcap = vmx->cap[vcpu].set;
3112 case VM_CAP_HALT_EXIT:
3116 case VM_CAP_PAUSE_EXIT:
3120 case VM_CAP_MTRAP_EXIT:
3121 if (cap_monitor_trap)
3124 case VM_CAP_UNRESTRICTED_GUEST:
3125 if (cap_unrestricted_guest)
3128 case VM_CAP_ENABLE_INVPCID:
3137 *retval = (vcap & (1 << type)) ? 1 : 0;
3143 vmx_setcap(void *arg, int vcpu, int type, int val)
3145 struct vmx *vmx = arg;
3146 struct vmcs *vmcs = &vmx->vmcs[vcpu];
3158 case VM_CAP_HALT_EXIT:
3159 if (cap_halt_exit) {
3161 pptr = &vmx->cap[vcpu].proc_ctls;
3163 flag = PROCBASED_HLT_EXITING;
3164 reg = VMCS_PRI_PROC_BASED_CTLS;
3167 case VM_CAP_MTRAP_EXIT:
3168 if (cap_monitor_trap) {
3170 pptr = &vmx->cap[vcpu].proc_ctls;
3172 flag = PROCBASED_MTF;
3173 reg = VMCS_PRI_PROC_BASED_CTLS;
3176 case VM_CAP_PAUSE_EXIT:
3177 if (cap_pause_exit) {
3179 pptr = &vmx->cap[vcpu].proc_ctls;
3181 flag = PROCBASED_PAUSE_EXITING;
3182 reg = VMCS_PRI_PROC_BASED_CTLS;
3185 case VM_CAP_UNRESTRICTED_GUEST:
3186 if (cap_unrestricted_guest) {
3188 pptr = &vmx->cap[vcpu].proc_ctls2;
3190 flag = PROCBASED2_UNRESTRICTED_GUEST;
3191 reg = VMCS_SEC_PROC_BASED_CTLS;
3194 case VM_CAP_ENABLE_INVPCID:
3197 pptr = &vmx->cap[vcpu].proc_ctls2;
3199 flag = PROCBASED2_ENABLE_INVPCID;
3200 reg = VMCS_SEC_PROC_BASED_CTLS;
3214 error = vmwrite(reg, baseval);
3221 * Update optional stored flags, and record
3229 vmx->cap[vcpu].set |= (1 << type);
3231 vmx->cap[vcpu].set &= ~(1 << type);
3240 struct vlapic vlapic;
3241 struct pir_desc *pir_desc;
3245 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg) \
3247 VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d", \
3248 level ? "level" : "edge", vector); \
3249 VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]); \
3250 VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]); \
3251 VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]); \
3252 VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]); \
3253 VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3257 * vlapic->ops handlers that utilize the APICv hardware assist described in
3258 * Chapter 29 of the Intel SDM.
3261 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3263 struct vlapic_vtx *vlapic_vtx;
3264 struct pir_desc *pir_desc;
3268 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3269 pir_desc = vlapic_vtx->pir_desc;
3272 * Keep track of interrupt requests in the PIR descriptor. This is
3273 * because the virtual APIC page pointed to by the VMCS cannot be
3274 * modified if the vcpu is running.
3277 mask = 1UL << (vector % 64);
3278 atomic_set_long(&pir_desc->pir[idx], mask);
3279 notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3281 VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3282 level, "vmx_set_intr_ready");
3287 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3289 struct vlapic_vtx *vlapic_vtx;
3290 struct pir_desc *pir_desc;
3291 struct LAPIC *lapic;
3292 uint64_t pending, pirval;
3297 * This function is only expected to be called from the 'HLT' exit
3298 * handler which does not care about the vector that is pending.
3300 KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3302 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3303 pir_desc = vlapic_vtx->pir_desc;
3305 pending = atomic_load_acq_long(&pir_desc->pending);
3307 return (0); /* common case */
3310 * If there is an interrupt pending then it will be recognized only
3311 * if its priority is greater than the processor priority.
3313 * Special case: if the processor priority is zero then any pending
3314 * interrupt will be recognized.
3316 lapic = vlapic->apic_page;
3317 ppr = lapic->ppr & 0xf0;
3321 VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3324 for (i = 3; i >= 0; i--) {
3325 pirval = pir_desc->pir[i];
3327 vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3335 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3338 panic("vmx_intr_accepted: not expected to be called");
3342 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3344 struct vlapic_vtx *vlapic_vtx;
3349 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3350 KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3351 ("vmx_set_tmr: vcpu cannot be running"));
3353 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3354 vmx = vlapic_vtx->vmx;
3355 vmcs = &vmx->vmcs[vlapic->vcpuid];
3356 mask = 1UL << (vector % 64);
3359 val = vmcs_read(VMCS_EOI_EXIT(vector));
3364 vmcs_write(VMCS_EOI_EXIT(vector), val);
3369 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3373 uint32_t proc_ctls2;
3376 vcpuid = vlapic->vcpuid;
3377 vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3378 vmcs = &vmx->vmcs[vcpuid];
3380 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3381 KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3382 ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3384 proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3385 proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3386 vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3389 vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3392 if (vlapic->vcpuid == 0) {
3394 * The nested page table mappings are shared by all vcpus
3395 * so unmap the APIC access page just once.
3397 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3398 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3402 * The MSR bitmap is shared by all vcpus so modify it only
3403 * once in the context of vcpu 0.
3405 error = vmx_allow_x2apic_msrs(vmx);
3406 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3412 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3415 ipi_cpu(hostcpu, pirvec);
3419 * Transfer the pending interrupts in the PIR descriptor to the IRR
3420 * in the virtual APIC page.
3423 vmx_inject_pir(struct vlapic *vlapic)
3425 struct vlapic_vtx *vlapic_vtx;
3426 struct pir_desc *pir_desc;
3427 struct LAPIC *lapic;
3428 uint64_t val, pirval;
3429 int rvi, pirbase = -1;
3430 uint16_t intr_status_old, intr_status_new;
3432 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3433 pir_desc = vlapic_vtx->pir_desc;
3434 if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3435 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3436 "no posted interrupt pending");
3442 lapic = vlapic->apic_page;
3444 val = atomic_readandclear_long(&pir_desc->pir[0]);
3447 lapic->irr1 |= val >> 32;
3452 val = atomic_readandclear_long(&pir_desc->pir[1]);
3455 lapic->irr3 |= val >> 32;
3460 val = atomic_readandclear_long(&pir_desc->pir[2]);
3463 lapic->irr5 |= val >> 32;
3468 val = atomic_readandclear_long(&pir_desc->pir[3]);
3471 lapic->irr7 |= val >> 32;
3476 VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3479 * Update RVI so the processor can evaluate pending virtual
3480 * interrupts on VM-entry.
3482 * It is possible for pirval to be 0 here, even though the
3483 * pending bit has been set. The scenario is:
3484 * CPU-Y is sending a posted interrupt to CPU-X, which
3485 * is running a guest and processing posted interrupts in h/w.
3486 * CPU-X will eventually exit and the state seen in s/w is
3487 * the pending bit set, but no PIR bits set.
3490 * (vm running) (host running)
3491 * rx posted interrupt
3494 * READ/CLEAR PIR bits
3497 * pending bit set, PIR 0
3500 rvi = pirbase + flsl(pirval) - 1;
3501 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3502 intr_status_new = (intr_status_old & 0xFF00) | rvi;
3503 if (intr_status_new > intr_status_old) {
3504 vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3505 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3506 "guest_intr_status changed from 0x%04x to 0x%04x",
3507 intr_status_old, intr_status_new);
3512 static struct vlapic *
3513 vmx_vlapic_init(void *arg, int vcpuid)
3516 struct vlapic *vlapic;
3517 struct vlapic_vtx *vlapic_vtx;
3521 vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3522 vlapic->vm = vmx->vm;
3523 vlapic->vcpuid = vcpuid;
3524 vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3526 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3527 vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3528 vlapic_vtx->vmx = vmx;
3530 if (virtual_interrupt_delivery) {
3531 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3532 vlapic->ops.pending_intr = vmx_pending_intr;
3533 vlapic->ops.intr_accepted = vmx_intr_accepted;
3534 vlapic->ops.set_tmr = vmx_set_tmr;
3535 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3538 if (posted_interrupts)
3539 vlapic->ops.post_intr = vmx_post_intr;
3541 vlapic_init(vlapic);
3547 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3550 vlapic_cleanup(vlapic);
3551 free(vlapic, M_VLAPIC);
3554 struct vmm_ops vmm_ops_intel = {