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);
189 * Use the last page below 4GB as the APIC access address. This address is
190 * occupied by the boot firmware so it is guaranteed that it will not conflict
191 * with a page in system memory.
193 #define APIC_ACCESS_ADDRESS 0xFFFFF000
195 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
196 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
197 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
198 static void vmx_inject_pir(struct vlapic *vlapic);
202 exit_reason_to_str(int reason)
204 static char reasonbuf[32];
207 case EXIT_REASON_EXCEPTION:
209 case EXIT_REASON_EXT_INTR:
211 case EXIT_REASON_TRIPLE_FAULT:
212 return "triplefault";
213 case EXIT_REASON_INIT:
215 case EXIT_REASON_SIPI:
217 case EXIT_REASON_IO_SMI:
219 case EXIT_REASON_SMI:
221 case EXIT_REASON_INTR_WINDOW:
223 case EXIT_REASON_NMI_WINDOW:
225 case EXIT_REASON_TASK_SWITCH:
227 case EXIT_REASON_CPUID:
229 case EXIT_REASON_GETSEC:
231 case EXIT_REASON_HLT:
233 case EXIT_REASON_INVD:
235 case EXIT_REASON_INVLPG:
237 case EXIT_REASON_RDPMC:
239 case EXIT_REASON_RDTSC:
241 case EXIT_REASON_RSM:
243 case EXIT_REASON_VMCALL:
245 case EXIT_REASON_VMCLEAR:
247 case EXIT_REASON_VMLAUNCH:
249 case EXIT_REASON_VMPTRLD:
251 case EXIT_REASON_VMPTRST:
253 case EXIT_REASON_VMREAD:
255 case EXIT_REASON_VMRESUME:
257 case EXIT_REASON_VMWRITE:
259 case EXIT_REASON_VMXOFF:
261 case EXIT_REASON_VMXON:
263 case EXIT_REASON_CR_ACCESS:
265 case EXIT_REASON_DR_ACCESS:
267 case EXIT_REASON_INOUT:
269 case EXIT_REASON_RDMSR:
271 case EXIT_REASON_WRMSR:
273 case EXIT_REASON_INVAL_VMCS:
275 case EXIT_REASON_INVAL_MSR:
277 case EXIT_REASON_MWAIT:
279 case EXIT_REASON_MTF:
281 case EXIT_REASON_MONITOR:
283 case EXIT_REASON_PAUSE:
285 case EXIT_REASON_MCE_DURING_ENTRY:
286 return "mce-during-entry";
287 case EXIT_REASON_TPR:
289 case EXIT_REASON_APIC_ACCESS:
290 return "apic-access";
291 case EXIT_REASON_GDTR_IDTR:
293 case EXIT_REASON_LDTR_TR:
295 case EXIT_REASON_EPT_FAULT:
297 case EXIT_REASON_EPT_MISCONFIG:
298 return "eptmisconfig";
299 case EXIT_REASON_INVEPT:
301 case EXIT_REASON_RDTSCP:
303 case EXIT_REASON_VMX_PREEMPT:
305 case EXIT_REASON_INVVPID:
307 case EXIT_REASON_WBINVD:
309 case EXIT_REASON_XSETBV:
311 case EXIT_REASON_APIC_WRITE:
314 snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
321 vmx_allow_x2apic_msrs(struct vmx *vmx)
328 * Allow readonly access to the following x2APIC MSRs from the guest.
330 error += guest_msr_ro(vmx, MSR_APIC_ID);
331 error += guest_msr_ro(vmx, MSR_APIC_VERSION);
332 error += guest_msr_ro(vmx, MSR_APIC_LDR);
333 error += guest_msr_ro(vmx, MSR_APIC_SVR);
335 for (i = 0; i < 8; i++)
336 error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
338 for (i = 0; i < 8; i++)
339 error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
341 for (i = 0; i < 8; i++)
342 error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
344 error += guest_msr_ro(vmx, MSR_APIC_ESR);
345 error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
346 error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
347 error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
348 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
349 error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
350 error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
351 error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
352 error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
353 error += guest_msr_ro(vmx, MSR_APIC_ICR);
356 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
358 * These registers get special treatment described in the section
359 * "Virtualizing MSR-Based APIC Accesses".
361 error += guest_msr_rw(vmx, MSR_APIC_TPR);
362 error += guest_msr_rw(vmx, MSR_APIC_EOI);
363 error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
369 vmx_fix_cr0(u_long cr0)
372 return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
376 vmx_fix_cr4(u_long cr4)
379 return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
385 if (vpid < 0 || vpid > 0xffff)
386 panic("vpid_free: invalid vpid %d", vpid);
389 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
390 * the unit number allocator.
393 if (vpid > VM_MAXCPU)
394 free_unr(vpid_unr, vpid);
398 vpid_alloc(uint16_t *vpid, int num)
402 if (num <= 0 || num > VM_MAXCPU)
403 panic("invalid number of vpids requested: %d", num);
406 * If the "enable vpid" execution control is not enabled then the
407 * VPID is required to be 0 for all vcpus.
409 if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
410 for (i = 0; i < num; i++)
416 * Allocate a unique VPID for each vcpu from the unit number allocator.
418 for (i = 0; i < num; i++) {
419 x = alloc_unr(vpid_unr);
427 atomic_add_int(&vpid_alloc_failed, 1);
430 * If the unit number allocator does not have enough unique
431 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
433 * These VPIDs are not be unique across VMs but this does not
434 * affect correctness because the combined mappings are also
435 * tagged with the EP4TA which is unique for each VM.
437 * It is still sub-optimal because the invvpid will invalidate
438 * combined mappings for a particular VPID across all EP4TAs.
443 for (i = 0; i < num; i++)
452 * VPID 0 is required when the "enable VPID" execution control is
455 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
456 * unit number allocator does not have sufficient unique VPIDs to
457 * satisfy the allocation.
459 * The remaining VPIDs are managed by the unit number allocator.
461 vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
465 vmx_disable(void *arg __unused)
467 struct invvpid_desc invvpid_desc = { 0 };
468 struct invept_desc invept_desc = { 0 };
470 if (vmxon_enabled[curcpu]) {
472 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
474 * VMXON or VMXOFF are not required to invalidate any TLB
475 * caching structures. This prevents potential retention of
476 * cached information in the TLB between distinct VMX episodes.
478 invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
479 invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
482 load_cr4(rcr4() & ~CR4_VMXE);
490 lapic_ipi_free(pirvec);
492 if (vpid_unr != NULL) {
493 delete_unrhdr(vpid_unr);
497 smp_rendezvous(NULL, vmx_disable, NULL, NULL);
503 vmx_enable(void *arg __unused)
506 uint64_t feature_control;
508 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
509 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
510 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
511 wrmsr(MSR_IA32_FEATURE_CONTROL,
512 feature_control | IA32_FEATURE_CONTROL_VMX_EN |
513 IA32_FEATURE_CONTROL_LOCK);
516 load_cr4(rcr4() | CR4_VMXE);
518 *(uint32_t *)vmxon_region[curcpu] = vmx_revision();
519 error = vmxon(vmxon_region[curcpu]);
521 vmxon_enabled[curcpu] = 1;
528 if (vmxon_enabled[curcpu])
529 vmxon(vmxon_region[curcpu]);
535 int error, use_tpr_shadow;
536 uint64_t basic, fixed0, fixed1, feature_control;
537 uint32_t tmp, procbased2_vid_bits;
539 /* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
540 if (!(cpu_feature2 & CPUID2_VMX)) {
541 printf("vmx_init: processor does not support VMX operation\n");
546 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
547 * are set (bits 0 and 2 respectively).
549 feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
550 if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
551 (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
552 printf("vmx_init: VMX operation disabled by BIOS\n");
557 * Verify capabilities MSR_VMX_BASIC:
558 * - bit 54 indicates support for INS/OUTS decoding
560 basic = rdmsr(MSR_VMX_BASIC);
561 if ((basic & (1UL << 54)) == 0) {
562 printf("vmx_init: processor does not support desired basic "
567 /* Check support for primary processor-based VM-execution controls */
568 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
569 MSR_VMX_TRUE_PROCBASED_CTLS,
570 PROCBASED_CTLS_ONE_SETTING,
571 PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
573 printf("vmx_init: processor does not support desired primary "
574 "processor-based controls\n");
578 /* Clear the processor-based ctl bits that are set on demand */
579 procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
581 /* Check support for secondary processor-based VM-execution controls */
582 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
583 MSR_VMX_PROCBASED_CTLS2,
584 PROCBASED_CTLS2_ONE_SETTING,
585 PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
587 printf("vmx_init: processor does not support desired secondary "
588 "processor-based controls\n");
592 /* Check support for VPID */
593 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
594 PROCBASED2_ENABLE_VPID, 0, &tmp);
596 procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
598 /* Check support for pin-based VM-execution controls */
599 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
600 MSR_VMX_TRUE_PINBASED_CTLS,
601 PINBASED_CTLS_ONE_SETTING,
602 PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
604 printf("vmx_init: processor does not support desired "
605 "pin-based controls\n");
609 /* Check support for VM-exit controls */
610 error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
611 VM_EXIT_CTLS_ONE_SETTING,
612 VM_EXIT_CTLS_ZERO_SETTING,
615 printf("vmx_init: processor does not support desired "
620 /* Check support for VM-entry controls */
621 error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
622 VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
625 printf("vmx_init: processor does not support desired "
631 * Check support for optional features by testing them
634 cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
635 MSR_VMX_TRUE_PROCBASED_CTLS,
636 PROCBASED_HLT_EXITING, 0,
639 cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
640 MSR_VMX_PROCBASED_CTLS,
644 cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
645 MSR_VMX_TRUE_PROCBASED_CTLS,
646 PROCBASED_PAUSE_EXITING, 0,
649 cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
650 MSR_VMX_PROCBASED_CTLS2,
651 PROCBASED2_UNRESTRICTED_GUEST, 0,
654 cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
655 MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
659 * Check support for virtual interrupt delivery.
661 procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
662 PROCBASED2_VIRTUALIZE_X2APIC_MODE |
663 PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
664 PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
666 use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
667 MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
670 error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
671 procbased2_vid_bits, 0, &tmp);
672 if (error == 0 && use_tpr_shadow) {
673 virtual_interrupt_delivery = 1;
674 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
675 &virtual_interrupt_delivery);
678 if (virtual_interrupt_delivery) {
679 procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
680 procbased_ctls2 |= procbased2_vid_bits;
681 procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
684 * No need to emulate accesses to %CR8 if virtual
685 * interrupt delivery is enabled.
687 procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
688 procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
691 * Check for Posted Interrupts only if Virtual Interrupt
692 * Delivery is enabled.
694 error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
695 MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
698 pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
699 &IDTVEC(justreturn));
702 printf("vmx_init: unable to allocate "
703 "posted interrupt vector\n");
706 posted_interrupts = 1;
707 TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
713 if (posted_interrupts)
714 pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
717 error = ept_init(ipinum);
719 printf("vmx_init: ept initialization failed (%d)\n", error);
724 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
726 fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
727 fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
728 cr0_ones_mask = fixed0 & fixed1;
729 cr0_zeros_mask = ~fixed0 & ~fixed1;
732 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
733 * if unrestricted guest execution is allowed.
735 if (cap_unrestricted_guest)
736 cr0_ones_mask &= ~(CR0_PG | CR0_PE);
739 * Do not allow the guest to set CR0_NW or CR0_CD.
741 cr0_zeros_mask |= (CR0_NW | CR0_CD);
743 fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
744 fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
745 cr4_ones_mask = fixed0 & fixed1;
746 cr4_zeros_mask = ~fixed0 & ~fixed1;
752 /* enable VMX operation */
753 smp_rendezvous(NULL, vmx_enable, NULL, NULL);
761 vmx_trigger_hostintr(int vector)
764 struct gate_descriptor *gd;
768 KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
769 "invalid vector %d", vector));
770 KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
772 KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
773 "has invalid type %d", vector, gd->gd_type));
774 KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
775 "has invalid dpl %d", vector, gd->gd_dpl));
776 KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
777 "for vector %d has invalid selector %d", vector, gd->gd_selector));
778 KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
779 "IST %d", vector, gd->gd_ist));
781 func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
786 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
788 int error, mask_ident, shadow_ident;
791 if (which != 0 && which != 4)
792 panic("vmx_setup_cr_shadow: unknown cr%d", which);
795 mask_ident = VMCS_CR0_MASK;
796 mask_value = cr0_ones_mask | cr0_zeros_mask;
797 shadow_ident = VMCS_CR0_SHADOW;
799 mask_ident = VMCS_CR4_MASK;
800 mask_value = cr4_ones_mask | cr4_zeros_mask;
801 shadow_ident = VMCS_CR4_SHADOW;
804 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
808 error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
814 #define vmx_setup_cr0_shadow(vmcs,init) vmx_setup_cr_shadow(0, (vmcs), (init))
815 #define vmx_setup_cr4_shadow(vmcs,init) vmx_setup_cr_shadow(4, (vmcs), (init))
818 vmx_vminit(struct vm *vm, pmap_t pmap)
820 uint16_t vpid[VM_MAXCPU];
826 vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
827 if ((uintptr_t)vmx & PAGE_MASK) {
828 panic("malloc of struct vmx not aligned on %d byte boundary",
833 vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
836 * Clean up EPTP-tagged guest physical and combined mappings
838 * VMX transitions are not required to invalidate any guest physical
839 * mappings. So, it may be possible for stale guest physical mappings
840 * to be present in the processor TLBs.
842 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
844 ept_invalidate_mappings(vmx->eptp);
846 msr_bitmap_initialize(vmx->msr_bitmap);
849 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
850 * The guest FSBASE and GSBASE are saved and restored during
851 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
852 * always restored from the vmcs host state area on vm-exit.
854 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
855 * how they are saved/restored so can be directly accessed by the
858 * MSR_EFER is saved and restored in the guest VMCS area on a
859 * VM exit and entry respectively. It is also restored from the
860 * host VMCS area on a VM exit.
862 * The TSC MSR is exposed read-only. Writes are disallowed as
863 * that will impact the host TSC. If the guest does a write
864 * the "use TSC offsetting" execution control is enabled and the
865 * difference between the host TSC and the guest TSC is written
866 * into the TSC offset in the VMCS.
868 if (guest_msr_rw(vmx, MSR_GSBASE) ||
869 guest_msr_rw(vmx, MSR_FSBASE) ||
870 guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
871 guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
872 guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
873 guest_msr_rw(vmx, MSR_EFER) ||
874 guest_msr_ro(vmx, MSR_TSC))
875 panic("vmx_vminit: error setting guest msr access");
877 vpid_alloc(vpid, VM_MAXCPU);
879 if (virtual_interrupt_delivery) {
880 error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
881 APIC_ACCESS_ADDRESS);
882 /* XXX this should really return an error to the caller */
883 KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
886 for (i = 0; i < VM_MAXCPU; i++) {
887 vmcs = &vmx->vmcs[i];
888 vmcs->identifier = vmx_revision();
889 error = vmclear(vmcs);
891 panic("vmx_vminit: vmclear error %d on vcpu %d\n",
895 vmx_msr_guest_init(vmx, i);
897 error = vmcs_init(vmcs);
898 KASSERT(error == 0, ("vmcs_init error %d", error));
902 error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
903 error += vmwrite(VMCS_EPTP, vmx->eptp);
904 error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
905 error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
906 error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
907 error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
908 error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
909 error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
910 error += vmwrite(VMCS_VPID, vpid[i]);
912 /* exception bitmap */
913 if (vcpu_trace_exceptions(vm, i))
914 exc_bitmap = 0xffffffff;
916 exc_bitmap = 1 << IDT_MC;
917 error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
919 vmx->ctx[i].guest_dr6 = 0xffff0ff0;
920 error += vmwrite(VMCS_GUEST_DR7, 0x400);
922 if (virtual_interrupt_delivery) {
923 error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
924 error += vmwrite(VMCS_VIRTUAL_APIC,
925 vtophys(&vmx->apic_page[i]));
926 error += vmwrite(VMCS_EOI_EXIT0, 0);
927 error += vmwrite(VMCS_EOI_EXIT1, 0);
928 error += vmwrite(VMCS_EOI_EXIT2, 0);
929 error += vmwrite(VMCS_EOI_EXIT3, 0);
931 if (posted_interrupts) {
932 error += vmwrite(VMCS_PIR_VECTOR, pirvec);
933 error += vmwrite(VMCS_PIR_DESC,
934 vtophys(&vmx->pir_desc[i]));
937 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
940 vmx->cap[i].proc_ctls = procbased_ctls;
941 vmx->cap[i].proc_ctls2 = procbased_ctls2;
943 vmx->state[i].nextrip = ~0;
944 vmx->state[i].lastcpu = NOCPU;
945 vmx->state[i].vpid = vpid[i];
948 * Set up the CR0/4 shadows, and init the read shadow
949 * to the power-on register value from the Intel Sys Arch.
953 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
955 panic("vmx_setup_cr0_shadow %d", error);
957 error = vmx_setup_cr4_shadow(vmcs, 0);
959 panic("vmx_setup_cr4_shadow %d", error);
961 vmx->ctx[i].pmap = pmap;
968 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
972 func = vmxctx->guest_rax;
974 handled = x86_emulate_cpuid(vm, vcpu,
975 (uint32_t*)(&vmxctx->guest_rax),
976 (uint32_t*)(&vmxctx->guest_rbx),
977 (uint32_t*)(&vmxctx->guest_rcx),
978 (uint32_t*)(&vmxctx->guest_rdx));
983 vmx_run_trace(struct vmx *vmx, int vcpu)
986 VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
991 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
995 VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
996 handled ? "handled" : "unhandled",
997 exit_reason_to_str(exit_reason), rip);
1001 static __inline void
1002 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1005 VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1009 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1010 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1013 * Invalidate guest mappings identified by its vpid from the TLB.
1015 static __inline void
1016 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1018 struct vmxstate *vmxstate;
1019 struct invvpid_desc invvpid_desc;
1021 vmxstate = &vmx->state[vcpu];
1022 if (vmxstate->vpid == 0)
1027 * Set the 'lastcpu' to an invalid host cpu.
1029 * This will invalidate TLB entries tagged with the vcpu's
1030 * vpid the next time it runs via vmx_set_pcpu_defaults().
1032 vmxstate->lastcpu = NOCPU;
1036 KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1037 "critical section", __func__, vcpu));
1040 * Invalidate all mappings tagged with 'vpid'
1042 * We do this because this vcpu was executing on a different host
1043 * cpu when it last ran. We do not track whether it invalidated
1044 * mappings associated with its 'vpid' during that run. So we must
1045 * assume that the mappings associated with 'vpid' on 'curcpu' are
1046 * stale and invalidate them.
1048 * Note that we incur this penalty only when the scheduler chooses to
1049 * move the thread associated with this vcpu between host cpus.
1051 * Note also that this will invalidate mappings tagged with 'vpid'
1054 if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1055 invvpid_desc._res1 = 0;
1056 invvpid_desc._res2 = 0;
1057 invvpid_desc.vpid = vmxstate->vpid;
1058 invvpid_desc.linear_addr = 0;
1059 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1060 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1063 * The invvpid can be skipped if an invept is going to
1064 * be performed before entering the guest. The invept
1065 * will invalidate combined mappings tagged with
1066 * 'vmx->eptp' for all vpids.
1068 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1073 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1075 struct vmxstate *vmxstate;
1077 vmxstate = &vmx->state[vcpu];
1078 if (vmxstate->lastcpu == curcpu)
1081 vmxstate->lastcpu = curcpu;
1083 vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1085 vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1086 vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1087 vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1088 vmx_invvpid(vmx, vcpu, pmap, 1);
1092 * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1094 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1096 static void __inline
1097 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1100 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1101 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1102 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1103 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1107 static void __inline
1108 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1111 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1112 ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1113 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1114 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1115 VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1118 static void __inline
1119 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1122 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1123 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1124 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1125 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1129 static void __inline
1130 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1133 KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1134 ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1135 vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1136 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1137 VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1141 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1145 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1146 vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1147 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1148 VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1151 error = vmwrite(VMCS_TSC_OFFSET, offset);
1156 #define NMI_BLOCKING (VMCS_INTERRUPTIBILITY_NMI_BLOCKING | \
1157 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1158 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING | \
1159 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1162 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1166 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1167 KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1168 "interruptibility-state %#x", gi));
1170 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1171 KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1172 "VM-entry interruption information %#x", info));
1175 * Inject the virtual NMI. The vector must be the NMI IDT entry
1176 * or the VMCS entry check will fail.
1178 info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1179 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1181 VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1183 /* Clear the request */
1184 vm_nmi_clear(vmx->vm, vcpu);
1188 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1191 int vector, need_nmi_exiting, extint_pending;
1192 uint64_t rflags, entryinfo;
1195 if (vmx->state[vcpu].nextrip != guestrip) {
1196 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1197 if (gi & HWINTR_BLOCKING) {
1198 VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1199 "cleared due to rip change: %#lx/%#lx",
1200 vmx->state[vcpu].nextrip, guestrip);
1201 gi &= ~HWINTR_BLOCKING;
1202 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1206 if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1207 KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1208 "intinfo is not valid: %#lx", __func__, entryinfo));
1210 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1211 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1212 "pending exception: %#lx/%#x", __func__, entryinfo, info));
1215 vector = info & 0xff;
1216 if (vector == IDT_BP || vector == IDT_OF) {
1218 * VT-x requires #BP and #OF to be injected as software
1221 info &= ~VMCS_INTR_T_MASK;
1222 info |= VMCS_INTR_T_SWEXCEPTION;
1225 if (info & VMCS_INTR_DEL_ERRCODE)
1226 vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1228 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1231 if (vm_nmi_pending(vmx->vm, vcpu)) {
1233 * If there are no conditions blocking NMI injection then
1234 * inject it directly here otherwise enable "NMI window
1235 * exiting" to inject it as soon as we can.
1237 * We also check for STI_BLOCKING because some implementations
1238 * don't allow NMI injection in this case. If we are running
1239 * on a processor that doesn't have this restriction it will
1240 * immediately exit and the NMI will be injected in the
1241 * "NMI window exiting" handler.
1243 need_nmi_exiting = 1;
1244 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1245 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1246 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1247 if ((info & VMCS_INTR_VALID) == 0) {
1248 vmx_inject_nmi(vmx, vcpu);
1249 need_nmi_exiting = 0;
1251 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1252 "due to VM-entry intr info %#x", info);
1255 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1256 "Guest Interruptibility-state %#x", gi);
1259 if (need_nmi_exiting)
1260 vmx_set_nmi_window_exiting(vmx, vcpu);
1263 extint_pending = vm_extint_pending(vmx->vm, vcpu);
1265 if (!extint_pending && virtual_interrupt_delivery) {
1266 vmx_inject_pir(vlapic);
1271 * If interrupt-window exiting is already in effect then don't bother
1272 * checking for pending interrupts. This is just an optimization and
1273 * not needed for correctness.
1275 if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1276 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1277 "pending int_window_exiting");
1281 if (!extint_pending) {
1282 /* Ask the local apic for a vector to inject */
1283 if (!vlapic_pending_intr(vlapic, &vector))
1287 * From the Intel SDM, Volume 3, Section "Maskable
1288 * Hardware Interrupts":
1289 * - maskable interrupt vectors [16,255] can be delivered
1290 * through the local APIC.
1292 KASSERT(vector >= 16 && vector <= 255,
1293 ("invalid vector %d from local APIC", vector));
1295 /* Ask the legacy pic for a vector to inject */
1296 vatpic_pending_intr(vmx->vm, &vector);
1299 * From the Intel SDM, Volume 3, Section "Maskable
1300 * Hardware Interrupts":
1301 * - maskable interrupt vectors [0,255] can be delivered
1302 * through the INTR pin.
1304 KASSERT(vector >= 0 && vector <= 255,
1305 ("invalid vector %d from INTR", vector));
1308 /* Check RFLAGS.IF and the interruptibility state of the guest */
1309 rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1310 if ((rflags & PSL_I) == 0) {
1311 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1312 "rflags %#lx", vector, rflags);
1316 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1317 if (gi & HWINTR_BLOCKING) {
1318 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1319 "Guest Interruptibility-state %#x", vector, gi);
1323 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1324 if (info & VMCS_INTR_VALID) {
1326 * This is expected and could happen for multiple reasons:
1327 * - A vectoring VM-entry was aborted due to astpending
1328 * - A VM-exit happened during event injection.
1329 * - An exception was injected above.
1330 * - An NMI was injected above or after "NMI window exiting"
1332 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1333 "VM-entry intr info %#x", vector, info);
1337 /* Inject the interrupt */
1338 info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1340 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1342 if (!extint_pending) {
1343 /* Update the Local APIC ISR */
1344 vlapic_intr_accepted(vlapic, vector);
1346 vm_extint_clear(vmx->vm, vcpu);
1347 vatpic_intr_accepted(vmx->vm, vector);
1350 * After we accepted the current ExtINT the PIC may
1351 * have posted another one. If that is the case, set
1352 * the Interrupt Window Exiting execution control so
1353 * we can inject that one too.
1355 * Also, interrupt window exiting allows us to inject any
1356 * pending APIC vector that was preempted by the ExtINT
1357 * as soon as possible. This applies both for the software
1358 * emulated vlapic and the hardware assisted virtual APIC.
1360 vmx_set_int_window_exiting(vmx, vcpu);
1363 VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1369 * Set the Interrupt Window Exiting execution control so we can inject
1370 * the interrupt as soon as blocking condition goes away.
1372 vmx_set_int_window_exiting(vmx, vcpu);
1376 * If the Virtual NMIs execution control is '1' then the logical processor
1377 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1378 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1379 * virtual-NMI blocking.
1381 * This unblocking occurs even if the IRET causes a fault. In this case the
1382 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1385 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1389 VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1390 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1391 gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1392 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1396 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1400 VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1401 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1402 gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1403 vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1407 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1411 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1412 KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1413 ("NMI blocking is not in effect %#x", gi));
1417 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1419 struct vmxctx *vmxctx;
1421 const struct xsave_limits *limits;
1423 vmxctx = &vmx->ctx[vcpu];
1424 limits = vmm_get_xsave_limits();
1427 * Note that the processor raises a GP# fault on its own if
1428 * xsetbv is executed for CPL != 0, so we do not have to
1429 * emulate that fault here.
1432 /* Only xcr0 is supported. */
1433 if (vmxctx->guest_rcx != 0) {
1434 vm_inject_gp(vmx->vm, vcpu);
1438 /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1439 if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1440 vm_inject_ud(vmx->vm, vcpu);
1444 xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1445 if ((xcrval & ~limits->xcr0_allowed) != 0) {
1446 vm_inject_gp(vmx->vm, vcpu);
1450 if (!(xcrval & XFEATURE_ENABLED_X87)) {
1451 vm_inject_gp(vmx->vm, vcpu);
1455 /* AVX (YMM_Hi128) requires SSE. */
1456 if (xcrval & XFEATURE_ENABLED_AVX &&
1457 (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1458 vm_inject_gp(vmx->vm, vcpu);
1463 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1464 * ZMM_Hi256, and Hi16_ZMM.
1466 if (xcrval & XFEATURE_AVX512 &&
1467 (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1468 (XFEATURE_AVX512 | XFEATURE_AVX)) {
1469 vm_inject_gp(vmx->vm, vcpu);
1474 * Intel MPX requires both bound register state flags to be
1477 if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1478 ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1479 vm_inject_gp(vmx->vm, vcpu);
1484 * This runs "inside" vmrun() with the guest's FPU state, so
1485 * modifying xcr0 directly modifies the guest's xcr0, not the
1488 load_xcr(0, xcrval);
1493 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1495 const struct vmxctx *vmxctx;
1497 vmxctx = &vmx->ctx[vcpu];
1501 return (vmxctx->guest_rax);
1503 return (vmxctx->guest_rcx);
1505 return (vmxctx->guest_rdx);
1507 return (vmxctx->guest_rbx);
1509 return (vmcs_read(VMCS_GUEST_RSP));
1511 return (vmxctx->guest_rbp);
1513 return (vmxctx->guest_rsi);
1515 return (vmxctx->guest_rdi);
1517 return (vmxctx->guest_r8);
1519 return (vmxctx->guest_r9);
1521 return (vmxctx->guest_r10);
1523 return (vmxctx->guest_r11);
1525 return (vmxctx->guest_r12);
1527 return (vmxctx->guest_r13);
1529 return (vmxctx->guest_r14);
1531 return (vmxctx->guest_r15);
1533 panic("invalid vmx register %d", ident);
1538 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1540 struct vmxctx *vmxctx;
1542 vmxctx = &vmx->ctx[vcpu];
1546 vmxctx->guest_rax = regval;
1549 vmxctx->guest_rcx = regval;
1552 vmxctx->guest_rdx = regval;
1555 vmxctx->guest_rbx = regval;
1558 vmcs_write(VMCS_GUEST_RSP, regval);
1561 vmxctx->guest_rbp = regval;
1564 vmxctx->guest_rsi = regval;
1567 vmxctx->guest_rdi = regval;
1570 vmxctx->guest_r8 = regval;
1573 vmxctx->guest_r9 = regval;
1576 vmxctx->guest_r10 = regval;
1579 vmxctx->guest_r11 = regval;
1582 vmxctx->guest_r12 = regval;
1585 vmxctx->guest_r13 = regval;
1588 vmxctx->guest_r14 = regval;
1591 vmxctx->guest_r15 = regval;
1594 panic("invalid vmx register %d", ident);
1599 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1601 uint64_t crval, regval;
1603 /* We only handle mov to %cr0 at this time */
1604 if ((exitqual & 0xf0) != 0x00)
1607 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1609 vmcs_write(VMCS_CR0_SHADOW, regval);
1611 crval = regval | cr0_ones_mask;
1612 crval &= ~cr0_zeros_mask;
1613 vmcs_write(VMCS_GUEST_CR0, crval);
1615 if (regval & CR0_PG) {
1616 uint64_t efer, entry_ctls;
1619 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1620 * the "IA-32e mode guest" bit in VM-entry control must be
1623 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1624 if (efer & EFER_LME) {
1626 vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1627 entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1628 entry_ctls |= VM_ENTRY_GUEST_LMA;
1629 vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1637 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1639 uint64_t crval, regval;
1641 /* We only handle mov to %cr4 at this time */
1642 if ((exitqual & 0xf0) != 0x00)
1645 regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1647 vmcs_write(VMCS_CR4_SHADOW, regval);
1649 crval = regval | cr4_ones_mask;
1650 crval &= ~cr4_zeros_mask;
1651 vmcs_write(VMCS_GUEST_CR4, crval);
1657 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1659 struct vlapic *vlapic;
1663 /* We only handle mov %cr8 to/from a register at this time. */
1664 if ((exitqual & 0xe0) != 0x00) {
1668 vlapic = vm_lapic(vmx->vm, vcpu);
1669 regnum = (exitqual >> 8) & 0xf;
1670 if (exitqual & 0x10) {
1671 cr8 = vlapic_get_cr8(vlapic);
1672 vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1674 cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1675 vlapic_set_cr8(vlapic, cr8);
1682 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1689 ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1690 return ((ssar >> 5) & 0x3);
1693 static enum vm_cpu_mode
1698 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1699 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1701 return (CPU_MODE_64BIT); /* CS.L = 1 */
1703 return (CPU_MODE_COMPATIBILITY);
1704 } else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1705 return (CPU_MODE_PROTECTED);
1707 return (CPU_MODE_REAL);
1711 static enum vm_paging_mode
1712 vmx_paging_mode(void)
1715 if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1716 return (PAGING_MODE_FLAT);
1717 if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1718 return (PAGING_MODE_32);
1719 if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1720 return (PAGING_MODE_64);
1722 return (PAGING_MODE_PAE);
1726 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1730 enum vm_reg_name reg;
1732 reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1733 error = vmx_getreg(vmx, vcpuid, reg, &val);
1734 KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1739 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1745 error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1746 KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1754 inout_str_addrsize(uint32_t inst_info)
1758 size = (inst_info >> 7) & 0x7;
1761 return (2); /* 16 bit */
1763 return (4); /* 32 bit */
1765 return (8); /* 64 bit */
1767 panic("%s: invalid size encoding %d", __func__, size);
1772 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1773 struct vm_inout_str *vis)
1778 vis->seg_name = VM_REG_GUEST_ES;
1780 s = (inst_info >> 15) & 0x7;
1781 vis->seg_name = vm_segment_name(s);
1784 error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1785 KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1789 vmx_paging_info(struct vm_guest_paging *paging)
1791 paging->cr3 = vmcs_guest_cr3();
1792 paging->cpl = vmx_cpl();
1793 paging->cpu_mode = vmx_cpu_mode();
1794 paging->paging_mode = vmx_paging_mode();
1798 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1800 struct vm_guest_paging *paging;
1803 paging = &vmexit->u.inst_emul.paging;
1805 vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1806 vmexit->inst_length = 0;
1807 vmexit->u.inst_emul.gpa = gpa;
1808 vmexit->u.inst_emul.gla = gla;
1809 vmx_paging_info(paging);
1810 switch (paging->cpu_mode) {
1812 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1813 vmexit->u.inst_emul.cs_d = 0;
1815 case CPU_MODE_PROTECTED:
1816 case CPU_MODE_COMPATIBILITY:
1817 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1818 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1819 vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1822 vmexit->u.inst_emul.cs_base = 0;
1823 vmexit->u.inst_emul.cs_d = 0;
1826 vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1830 ept_fault_type(uint64_t ept_qual)
1834 if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1835 fault_type = VM_PROT_WRITE;
1836 else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1837 fault_type = VM_PROT_EXECUTE;
1839 fault_type= VM_PROT_READ;
1841 return (fault_type);
1845 ept_emulation_fault(uint64_t ept_qual)
1849 /* EPT fault on an instruction fetch doesn't make sense here */
1850 if (ept_qual & EPT_VIOLATION_INST_FETCH)
1853 /* EPT fault must be a read fault or a write fault */
1854 read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1855 write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1856 if ((read | write) == 0)
1860 * The EPT violation must have been caused by accessing a
1861 * guest-physical address that is a translation of a guest-linear
1864 if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1865 (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1873 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1875 uint32_t proc_ctls2;
1877 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1878 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1882 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1884 uint32_t proc_ctls2;
1886 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1887 return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1891 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1894 int error, handled, offset;
1895 uint32_t *apic_regs, vector;
1899 offset = APIC_WRITE_OFFSET(qual);
1901 if (!apic_access_virtualization(vmx, vcpuid)) {
1903 * In general there should not be any APIC write VM-exits
1904 * unless APIC-access virtualization is enabled.
1906 * However self-IPI virtualization can legitimately trigger
1907 * an APIC-write VM-exit so treat it specially.
1909 if (x2apic_virtualization(vmx, vcpuid) &&
1910 offset == APIC_OFFSET_SELF_IPI) {
1911 apic_regs = (uint32_t *)(vlapic->apic_page);
1912 vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1913 vlapic_self_ipi_handler(vlapic, vector);
1920 case APIC_OFFSET_ID:
1921 vlapic_id_write_handler(vlapic);
1923 case APIC_OFFSET_LDR:
1924 vlapic_ldr_write_handler(vlapic);
1926 case APIC_OFFSET_DFR:
1927 vlapic_dfr_write_handler(vlapic);
1929 case APIC_OFFSET_SVR:
1930 vlapic_svr_write_handler(vlapic);
1932 case APIC_OFFSET_ESR:
1933 vlapic_esr_write_handler(vlapic);
1935 case APIC_OFFSET_ICR_LOW:
1937 error = vlapic_icrlo_write_handler(vlapic, &retu);
1938 if (error != 0 || retu)
1939 handled = UNHANDLED;
1941 case APIC_OFFSET_CMCI_LVT:
1942 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1943 vlapic_lvt_write_handler(vlapic, offset);
1945 case APIC_OFFSET_TIMER_ICR:
1946 vlapic_icrtmr_write_handler(vlapic);
1948 case APIC_OFFSET_TIMER_DCR:
1949 vlapic_dcr_write_handler(vlapic);
1952 handled = UNHANDLED;
1959 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1962 if (apic_access_virtualization(vmx, vcpuid) &&
1963 (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1970 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1973 int access_type, offset, allowed;
1975 if (!apic_access_virtualization(vmx, vcpuid))
1978 qual = vmexit->u.vmx.exit_qualification;
1979 access_type = APIC_ACCESS_TYPE(qual);
1980 offset = APIC_ACCESS_OFFSET(qual);
1983 if (access_type == 0) {
1985 * Read data access to the following registers is expected.
1988 case APIC_OFFSET_APR:
1989 case APIC_OFFSET_PPR:
1990 case APIC_OFFSET_RRR:
1991 case APIC_OFFSET_CMCI_LVT:
1992 case APIC_OFFSET_TIMER_CCR:
1998 } else if (access_type == 1) {
2000 * Write data access to the following registers is expected.
2003 case APIC_OFFSET_VER:
2004 case APIC_OFFSET_APR:
2005 case APIC_OFFSET_PPR:
2006 case APIC_OFFSET_RRR:
2007 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2008 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2009 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2010 case APIC_OFFSET_CMCI_LVT:
2011 case APIC_OFFSET_TIMER_CCR:
2020 vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2025 * Regardless of whether the APIC-access is allowed this handler
2026 * always returns UNHANDLED:
2027 * - if the access is allowed then it is handled by emulating the
2028 * instruction that caused the VM-exit (outside the critical section)
2029 * - if the access is not allowed then it will be converted to an
2030 * exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2035 static enum task_switch_reason
2036 vmx_task_switch_reason(uint64_t qual)
2040 reason = (qual >> 30) & 0x3;
2049 return (TSR_IDT_GATE);
2051 panic("%s: invalid reason %d", __func__, reason);
2056 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2061 error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2063 error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2069 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2071 struct vmxctx *vmxctx;
2077 error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2079 error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2083 vmxctx = &vmx->ctx[vcpuid];
2084 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2085 KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2088 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2089 KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2096 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2098 int error, errcode, errcode_valid, handled, in;
2099 struct vmxctx *vmxctx;
2100 struct vlapic *vlapic;
2101 struct vm_inout_str *vis;
2102 struct vm_task_switch *ts;
2103 uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2104 uint32_t intr_type, intr_vec, reason;
2105 uint64_t exitintinfo, qual, gpa;
2108 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2109 CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2111 handled = UNHANDLED;
2112 vmxctx = &vmx->ctx[vcpu];
2114 qual = vmexit->u.vmx.exit_qualification;
2115 reason = vmexit->u.vmx.exit_reason;
2116 vmexit->exitcode = VM_EXITCODE_BOGUS;
2118 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2121 * VM-entry failures during or after loading guest state.
2123 * These VM-exits are uncommon but must be handled specially
2124 * as most VM-exit fields are not populated as usual.
2126 if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2127 VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2128 __asm __volatile("int $18");
2133 * VM exits that can be triggered during event delivery need to
2134 * be handled specially by re-injecting the event if the IDT
2135 * vectoring information field's valid bit is set.
2137 * See "Information for VM Exits During Event Delivery" in Intel SDM
2140 idtvec_info = vmcs_idt_vectoring_info();
2141 if (idtvec_info & VMCS_IDT_VEC_VALID) {
2142 idtvec_info &= ~(1 << 12); /* clear undefined bit */
2143 exitintinfo = idtvec_info;
2144 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2145 idtvec_err = vmcs_idt_vectoring_err();
2146 exitintinfo |= (uint64_t)idtvec_err << 32;
2148 error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2149 KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2153 * If 'virtual NMIs' are being used and the VM-exit
2154 * happened while injecting an NMI during the previous
2155 * VM-entry, then clear "blocking by NMI" in the
2156 * Guest Interruptibility-State so the NMI can be
2157 * reinjected on the subsequent VM-entry.
2159 * However, if the NMI was being delivered through a task
2160 * gate, then the new task must start execution with NMIs
2161 * blocked so don't clear NMI blocking in this case.
2163 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2164 if (intr_type == VMCS_INTR_T_NMI) {
2165 if (reason != EXIT_REASON_TASK_SWITCH)
2166 vmx_clear_nmi_blocking(vmx, vcpu);
2168 vmx_assert_nmi_blocking(vmx, vcpu);
2172 * Update VM-entry instruction length if the event being
2173 * delivered was a software interrupt or software exception.
2175 if (intr_type == VMCS_INTR_T_SWINTR ||
2176 intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2177 intr_type == VMCS_INTR_T_SWEXCEPTION) {
2178 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2183 case EXIT_REASON_TASK_SWITCH:
2184 ts = &vmexit->u.task_switch;
2185 ts->tsssel = qual & 0xffff;
2186 ts->reason = vmx_task_switch_reason(qual);
2188 ts->errcode_valid = 0;
2189 vmx_paging_info(&ts->paging);
2191 * If the task switch was due to a CALL, JMP, IRET, software
2192 * interrupt (INT n) or software exception (INT3, INTO),
2193 * then the saved %rip references the instruction that caused
2194 * the task switch. The instruction length field in the VMCS
2195 * is valid in this case.
2197 * In all other cases (e.g., NMI, hardware exception) the
2198 * saved %rip is one that would have been saved in the old TSS
2199 * had the task switch completed normally so the instruction
2200 * length field is not needed in this case and is explicitly
2203 if (ts->reason == TSR_IDT_GATE) {
2204 KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2205 ("invalid idtvec_info %#x for IDT task switch",
2207 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2208 if (intr_type != VMCS_INTR_T_SWINTR &&
2209 intr_type != VMCS_INTR_T_SWEXCEPTION &&
2210 intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2211 /* Task switch triggered by external event */
2213 vmexit->inst_length = 0;
2214 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2215 ts->errcode_valid = 1;
2216 ts->errcode = vmcs_idt_vectoring_err();
2220 vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2221 VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2222 "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2223 ts->ext ? "external" : "internal",
2224 ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2226 case EXIT_REASON_CR_ACCESS:
2227 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2228 switch (qual & 0xf) {
2230 handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2233 handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2236 handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2240 case EXIT_REASON_RDMSR:
2241 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2243 ecx = vmxctx->guest_rcx;
2244 VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2245 error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2247 vmexit->exitcode = VM_EXITCODE_RDMSR;
2248 vmexit->u.msr.code = ecx;
2252 /* Return to userspace with a valid exitcode */
2253 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2254 ("emulate_rdmsr retu with bogus exitcode"));
2257 case EXIT_REASON_WRMSR:
2258 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2260 eax = vmxctx->guest_rax;
2261 ecx = vmxctx->guest_rcx;
2262 edx = vmxctx->guest_rdx;
2263 VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2264 ecx, (uint64_t)edx << 32 | eax);
2265 error = emulate_wrmsr(vmx, vcpu, ecx,
2266 (uint64_t)edx << 32 | eax, &retu);
2268 vmexit->exitcode = VM_EXITCODE_WRMSR;
2269 vmexit->u.msr.code = ecx;
2270 vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2274 /* Return to userspace with a valid exitcode */
2275 KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2276 ("emulate_wrmsr retu with bogus exitcode"));
2279 case EXIT_REASON_HLT:
2280 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2281 vmexit->exitcode = VM_EXITCODE_HLT;
2282 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2284 case EXIT_REASON_MTF:
2285 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2286 vmexit->exitcode = VM_EXITCODE_MTRAP;
2287 vmexit->inst_length = 0;
2289 case EXIT_REASON_PAUSE:
2290 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2291 vmexit->exitcode = VM_EXITCODE_PAUSE;
2293 case EXIT_REASON_INTR_WINDOW:
2294 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2295 vmx_clear_int_window_exiting(vmx, vcpu);
2297 case EXIT_REASON_EXT_INTR:
2299 * External interrupts serve only to cause VM exits and allow
2300 * the host interrupt handler to run.
2302 * If this external interrupt triggers a virtual interrupt
2303 * to a VM, then that state will be recorded by the
2304 * host interrupt handler in the VM's softc. We will inject
2305 * this virtual interrupt during the subsequent VM enter.
2307 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2310 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2311 * This appears to be a bug in VMware Fusion?
2313 if (!(intr_info & VMCS_INTR_VALID))
2315 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2316 (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2317 ("VM exit interruption info invalid: %#x", intr_info));
2318 vmx_trigger_hostintr(intr_info & 0xff);
2321 * This is special. We want to treat this as an 'handled'
2322 * VM-exit but not increment the instruction pointer.
2324 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2326 case EXIT_REASON_NMI_WINDOW:
2327 /* Exit to allow the pending virtual NMI to be injected */
2328 if (vm_nmi_pending(vmx->vm, vcpu))
2329 vmx_inject_nmi(vmx, vcpu);
2330 vmx_clear_nmi_window_exiting(vmx, vcpu);
2331 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2333 case EXIT_REASON_INOUT:
2334 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2335 vmexit->exitcode = VM_EXITCODE_INOUT;
2336 vmexit->u.inout.bytes = (qual & 0x7) + 1;
2337 vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2338 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2339 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2340 vmexit->u.inout.port = (uint16_t)(qual >> 16);
2341 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2342 if (vmexit->u.inout.string) {
2343 inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2344 vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2345 vis = &vmexit->u.inout_str;
2346 vmx_paging_info(&vis->paging);
2347 vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2348 vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2349 vis->index = inout_str_index(vmx, vcpu, in);
2350 vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2351 vis->addrsize = inout_str_addrsize(inst_info);
2352 inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2355 case EXIT_REASON_CPUID:
2356 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2357 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2359 case EXIT_REASON_EXCEPTION:
2360 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2361 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2362 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2363 ("VM exit interruption info invalid: %#x", intr_info));
2365 intr_vec = intr_info & 0xff;
2366 intr_type = intr_info & VMCS_INTR_T_MASK;
2369 * If Virtual NMIs control is 1 and the VM-exit is due to a
2370 * fault encountered during the execution of IRET then we must
2371 * restore the state of "virtual-NMI blocking" before resuming
2374 * See "Resuming Guest Software after Handling an Exception".
2375 * See "Information for VM Exits Due to Vectored Events".
2377 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2378 (intr_vec != IDT_DF) &&
2379 (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2380 vmx_restore_nmi_blocking(vmx, vcpu);
2383 * The NMI has already been handled in vmx_exit_handle_nmi().
2385 if (intr_type == VMCS_INTR_T_NMI)
2389 * Call the machine check handler by hand. Also don't reflect
2390 * the machine check back into the guest.
2392 if (intr_vec == IDT_MC) {
2393 VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2394 __asm __volatile("int $18");
2398 if (intr_vec == IDT_PF) {
2399 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2400 KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2405 * Software exceptions exhibit trap-like behavior. This in
2406 * turn requires populating the VM-entry instruction length
2407 * so that the %rip in the trap frame is past the INT3/INTO
2410 if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2411 vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2413 /* Reflect all other exceptions back into the guest */
2414 errcode_valid = errcode = 0;
2415 if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2417 errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2419 VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2420 "the guest", intr_vec, errcode);
2421 error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2422 errcode_valid, errcode, 0);
2423 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2427 case EXIT_REASON_EPT_FAULT:
2429 * If 'gpa' lies within the address space allocated to
2430 * memory then this must be a nested page fault otherwise
2431 * this must be an instruction that accesses MMIO space.
2434 if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2435 apic_access_fault(vmx, vcpu, gpa)) {
2436 vmexit->exitcode = VM_EXITCODE_PAGING;
2437 vmexit->inst_length = 0;
2438 vmexit->u.paging.gpa = gpa;
2439 vmexit->u.paging.fault_type = ept_fault_type(qual);
2440 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2441 } else if (ept_emulation_fault(qual)) {
2442 vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2443 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2446 * If Virtual NMIs control is 1 and the VM-exit is due to an
2447 * EPT fault during the execution of IRET then we must restore
2448 * the state of "virtual-NMI blocking" before resuming.
2450 * See description of "NMI unblocking due to IRET" in
2451 * "Exit Qualification for EPT Violations".
2453 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2454 (qual & EXIT_QUAL_NMIUDTI) != 0)
2455 vmx_restore_nmi_blocking(vmx, vcpu);
2457 case EXIT_REASON_VIRTUALIZED_EOI:
2458 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2459 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2460 vmexit->inst_length = 0; /* trap-like */
2462 case EXIT_REASON_APIC_ACCESS:
2463 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2465 case EXIT_REASON_APIC_WRITE:
2467 * APIC-write VM exit is trap-like so the %rip is already
2468 * pointing to the next instruction.
2470 vmexit->inst_length = 0;
2471 vlapic = vm_lapic(vmx->vm, vcpu);
2472 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2474 case EXIT_REASON_XSETBV:
2475 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2477 case EXIT_REASON_MONITOR:
2478 vmexit->exitcode = VM_EXITCODE_MONITOR;
2480 case EXIT_REASON_MWAIT:
2481 vmexit->exitcode = VM_EXITCODE_MWAIT;
2484 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2490 * It is possible that control is returned to userland
2491 * even though we were able to handle the VM exit in the
2494 * In such a case we want to make sure that the userland
2495 * restarts guest execution at the instruction *after*
2496 * the one we just processed. Therefore we update the
2497 * guest rip in the VMCS and in 'vmexit'.
2499 vmexit->rip += vmexit->inst_length;
2500 vmexit->inst_length = 0;
2501 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2503 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2505 * If this VM exit was not claimed by anybody then
2506 * treat it as a generic VMX exit.
2508 vmexit->exitcode = VM_EXITCODE_VMX;
2509 vmexit->u.vmx.status = VM_SUCCESS;
2510 vmexit->u.vmx.inst_type = 0;
2511 vmexit->u.vmx.inst_error = 0;
2514 * The exitcode and collateral have been populated.
2515 * The VM exit will be processed further in userland.
2522 static __inline void
2523 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2526 KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2527 ("vmx_exit_inst_error: invalid inst_fail_status %d",
2528 vmxctx->inst_fail_status));
2530 vmexit->inst_length = 0;
2531 vmexit->exitcode = VM_EXITCODE_VMX;
2532 vmexit->u.vmx.status = vmxctx->inst_fail_status;
2533 vmexit->u.vmx.inst_error = vmcs_instruction_error();
2534 vmexit->u.vmx.exit_reason = ~0;
2535 vmexit->u.vmx.exit_qualification = ~0;
2538 case VMX_VMRESUME_ERROR:
2539 case VMX_VMLAUNCH_ERROR:
2540 case VMX_INVEPT_ERROR:
2541 vmexit->u.vmx.inst_type = rc;
2544 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2549 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2550 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2551 * sufficient to simply vector to the NMI handler via a software interrupt.
2552 * However, this must be done before maskable interrupts are enabled
2553 * otherwise the "iret" issued by an interrupt handler will incorrectly
2554 * clear NMI blocking.
2556 static __inline void
2557 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2561 KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2563 if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2566 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2567 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2568 ("VM exit interruption info invalid: %#x", intr_info));
2570 if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2571 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2572 "to NMI has invalid vector: %#x", intr_info));
2573 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2574 __asm __volatile("int $2");
2578 static __inline void
2579 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2583 /* Save host control debug registers. */
2584 vmxctx->host_dr7 = rdr7();
2585 vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2588 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2589 * exceptions in the host based on the guest DRx values. The
2590 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2593 wrmsr(MSR_DEBUGCTLMSR, 0);
2596 * Disable single stepping the kernel to avoid corrupting the
2597 * guest DR6. A debugger might still be able to corrupt the
2598 * guest DR6 by setting a breakpoint after this point and then
2601 rflags = read_rflags();
2602 vmxctx->host_tf = rflags & PSL_T;
2603 write_rflags(rflags & ~PSL_T);
2605 /* Save host debug registers. */
2606 vmxctx->host_dr0 = rdr0();
2607 vmxctx->host_dr1 = rdr1();
2608 vmxctx->host_dr2 = rdr2();
2609 vmxctx->host_dr3 = rdr3();
2610 vmxctx->host_dr6 = rdr6();
2612 /* Restore guest debug registers. */
2613 load_dr0(vmxctx->guest_dr0);
2614 load_dr1(vmxctx->guest_dr1);
2615 load_dr2(vmxctx->guest_dr2);
2616 load_dr3(vmxctx->guest_dr3);
2617 load_dr6(vmxctx->guest_dr6);
2620 static __inline void
2621 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2624 /* Save guest debug registers. */
2625 vmxctx->guest_dr0 = rdr0();
2626 vmxctx->guest_dr1 = rdr1();
2627 vmxctx->guest_dr2 = rdr2();
2628 vmxctx->guest_dr3 = rdr3();
2629 vmxctx->guest_dr6 = rdr6();
2632 * Restore host debug registers. Restore DR7, DEBUGCTL, and
2635 load_dr0(vmxctx->host_dr0);
2636 load_dr1(vmxctx->host_dr1);
2637 load_dr2(vmxctx->host_dr2);
2638 load_dr3(vmxctx->host_dr3);
2639 load_dr6(vmxctx->host_dr6);
2640 wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2641 load_dr7(vmxctx->host_dr7);
2642 write_rflags(read_rflags() | vmxctx->host_tf);
2646 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2647 struct vm_eventinfo *evinfo)
2649 int rc, handled, launched;
2652 struct vmxctx *vmxctx;
2654 struct vm_exit *vmexit;
2655 struct vlapic *vlapic;
2656 uint32_t exit_reason;
2660 vmcs = &vmx->vmcs[vcpu];
2661 vmxctx = &vmx->ctx[vcpu];
2662 vlapic = vm_lapic(vm, vcpu);
2663 vmexit = vm_exitinfo(vm, vcpu);
2666 KASSERT(vmxctx->pmap == pmap,
2667 ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2669 vmx_msr_guest_enter(vmx, vcpu);
2675 * We do this every time because we may setup the virtual machine
2676 * from a different process than the one that actually runs it.
2678 * If the life of a virtual machine was spent entirely in the context
2679 * of a single process we could do this once in vmx_vminit().
2681 vmcs_write(VMCS_HOST_CR3, rcr3());
2683 vmcs_write(VMCS_GUEST_RIP, rip);
2684 vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2686 KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2687 "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2689 handled = UNHANDLED;
2691 * Interrupts are disabled from this point on until the
2692 * guest starts executing. This is done for the following
2695 * If an AST is asserted on this thread after the check below,
2696 * then the IPI_AST notification will not be lost, because it
2697 * will cause a VM exit due to external interrupt as soon as
2698 * the guest state is loaded.
2700 * A posted interrupt after 'vmx_inject_interrupts()' will
2701 * not be "lost" because it will be held pending in the host
2702 * APIC because interrupts are disabled. The pending interrupt
2703 * will be recognized as soon as the guest state is loaded.
2705 * The same reasoning applies to the IPI generated by
2706 * pmap_invalidate_ept().
2709 vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2712 * Check for vcpu suspension after injecting events because
2713 * vmx_inject_interrupts() can suspend the vcpu due to a
2716 if (vcpu_suspended(evinfo)) {
2718 vm_exit_suspended(vmx->vm, vcpu, rip);
2722 if (vcpu_rendezvous_pending(evinfo)) {
2724 vm_exit_rendezvous(vmx->vm, vcpu, rip);
2728 if (vcpu_reqidle(evinfo)) {
2730 vm_exit_reqidle(vmx->vm, vcpu, rip);
2734 if (vcpu_should_yield(vm, vcpu)) {
2736 vm_exit_astpending(vmx->vm, vcpu, rip);
2737 vmx_astpending_trace(vmx, vcpu, rip);
2742 vmx_run_trace(vmx, vcpu);
2743 vmx_dr_enter_guest(vmxctx);
2744 rc = vmx_enter_guest(vmxctx, vmx, launched);
2745 vmx_dr_leave_guest(vmxctx);
2747 /* Collect some information for VM exit processing */
2748 vmexit->rip = rip = vmcs_guest_rip();
2749 vmexit->inst_length = vmexit_instruction_length();
2750 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2751 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2753 /* Update 'nextrip' */
2754 vmx->state[vcpu].nextrip = rip;
2756 if (rc == VMX_GUEST_VMEXIT) {
2757 vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2759 handled = vmx_exit_process(vmx, vcpu, vmexit);
2762 vmx_exit_inst_error(vmxctx, rc, vmexit);
2765 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2770 * If a VM exit has been handled then the exitcode must be BOGUS
2771 * If a VM exit is not handled then the exitcode must not be BOGUS
2773 if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2774 (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2775 panic("Mismatch between handled (%d) and exitcode (%d)",
2776 handled, vmexit->exitcode);
2780 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2782 VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2786 vmx_msr_guest_exit(vmx, vcpu);
2792 vmx_vmcleanup(void *arg)
2795 struct vmx *vmx = arg;
2797 if (apic_access_virtualization(vmx, 0))
2798 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2800 for (i = 0; i < VM_MAXCPU; i++)
2801 vpid_free(vmx->state[i].vpid);
2809 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2813 case VM_REG_GUEST_RAX:
2814 return (&vmxctx->guest_rax);
2815 case VM_REG_GUEST_RBX:
2816 return (&vmxctx->guest_rbx);
2817 case VM_REG_GUEST_RCX:
2818 return (&vmxctx->guest_rcx);
2819 case VM_REG_GUEST_RDX:
2820 return (&vmxctx->guest_rdx);
2821 case VM_REG_GUEST_RSI:
2822 return (&vmxctx->guest_rsi);
2823 case VM_REG_GUEST_RDI:
2824 return (&vmxctx->guest_rdi);
2825 case VM_REG_GUEST_RBP:
2826 return (&vmxctx->guest_rbp);
2827 case VM_REG_GUEST_R8:
2828 return (&vmxctx->guest_r8);
2829 case VM_REG_GUEST_R9:
2830 return (&vmxctx->guest_r9);
2831 case VM_REG_GUEST_R10:
2832 return (&vmxctx->guest_r10);
2833 case VM_REG_GUEST_R11:
2834 return (&vmxctx->guest_r11);
2835 case VM_REG_GUEST_R12:
2836 return (&vmxctx->guest_r12);
2837 case VM_REG_GUEST_R13:
2838 return (&vmxctx->guest_r13);
2839 case VM_REG_GUEST_R14:
2840 return (&vmxctx->guest_r14);
2841 case VM_REG_GUEST_R15:
2842 return (&vmxctx->guest_r15);
2843 case VM_REG_GUEST_CR2:
2844 return (&vmxctx->guest_cr2);
2845 case VM_REG_GUEST_DR0:
2846 return (&vmxctx->guest_dr0);
2847 case VM_REG_GUEST_DR1:
2848 return (&vmxctx->guest_dr1);
2849 case VM_REG_GUEST_DR2:
2850 return (&vmxctx->guest_dr2);
2851 case VM_REG_GUEST_DR3:
2852 return (&vmxctx->guest_dr3);
2853 case VM_REG_GUEST_DR6:
2854 return (&vmxctx->guest_dr6);
2862 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2866 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2874 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2878 if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2886 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2891 error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2892 VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2893 *retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2898 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2905 * Forcing the vcpu into an interrupt shadow is not supported.
2912 vmcs = &vmx->vmcs[vcpu];
2913 ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2914 error = vmcs_getreg(vmcs, running, ident, &gi);
2916 gi &= ~HWINTR_BLOCKING;
2917 error = vmcs_setreg(vmcs, running, ident, gi);
2920 VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2921 error ? "failed" : "succeeded");
2926 vmx_shadow_reg(int reg)
2933 case VM_REG_GUEST_CR0:
2934 shreg = VMCS_CR0_SHADOW;
2936 case VM_REG_GUEST_CR4:
2937 shreg = VMCS_CR4_SHADOW;
2947 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2949 int running, hostcpu;
2950 struct vmx *vmx = arg;
2952 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2953 if (running && hostcpu != curcpu)
2954 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2956 if (reg == VM_REG_GUEST_INTR_SHADOW)
2957 return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2959 if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2962 return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2966 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2968 int error, hostcpu, running, shadow;
2971 struct vmx *vmx = arg;
2973 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2974 if (running && hostcpu != curcpu)
2975 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2977 if (reg == VM_REG_GUEST_INTR_SHADOW)
2978 return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2980 if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2983 error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2987 * If the "load EFER" VM-entry control is 1 then the
2988 * value of EFER.LMA must be identical to "IA-32e mode guest"
2989 * bit in the VM-entry control.
2991 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2992 (reg == VM_REG_GUEST_EFER)) {
2993 vmcs_getreg(&vmx->vmcs[vcpu], running,
2994 VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2996 ctls |= VM_ENTRY_GUEST_LMA;
2998 ctls &= ~VM_ENTRY_GUEST_LMA;
2999 vmcs_setreg(&vmx->vmcs[vcpu], running,
3000 VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3003 shadow = vmx_shadow_reg(reg);
3006 * Store the unmodified value in the shadow
3008 error = vmcs_setreg(&vmx->vmcs[vcpu], running,
3009 VMCS_IDENT(shadow), val);
3012 if (reg == VM_REG_GUEST_CR3) {
3014 * Invalidate the guest vcpu's TLB mappings to emulate
3015 * the behavior of updating %cr3.
3017 * XXX the processor retains global mappings when %cr3
3018 * is updated but vmx_invvpid() does not.
3020 pmap = vmx->ctx[vcpu].pmap;
3021 vmx_invvpid(vmx, vcpu, pmap, running);
3029 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3031 int hostcpu, running;
3032 struct vmx *vmx = arg;
3034 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3035 if (running && hostcpu != curcpu)
3036 panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3038 return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
3042 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3044 int hostcpu, running;
3045 struct vmx *vmx = arg;
3047 running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3048 if (running && hostcpu != curcpu)
3049 panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3051 return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
3055 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3057 struct vmx *vmx = arg;
3063 vcap = vmx->cap[vcpu].set;
3066 case VM_CAP_HALT_EXIT:
3070 case VM_CAP_PAUSE_EXIT:
3074 case VM_CAP_MTRAP_EXIT:
3075 if (cap_monitor_trap)
3078 case VM_CAP_UNRESTRICTED_GUEST:
3079 if (cap_unrestricted_guest)
3082 case VM_CAP_ENABLE_INVPCID:
3091 *retval = (vcap & (1 << type)) ? 1 : 0;
3097 vmx_setcap(void *arg, int vcpu, int type, int val)
3099 struct vmx *vmx = arg;
3100 struct vmcs *vmcs = &vmx->vmcs[vcpu];
3112 case VM_CAP_HALT_EXIT:
3113 if (cap_halt_exit) {
3115 pptr = &vmx->cap[vcpu].proc_ctls;
3117 flag = PROCBASED_HLT_EXITING;
3118 reg = VMCS_PRI_PROC_BASED_CTLS;
3121 case VM_CAP_MTRAP_EXIT:
3122 if (cap_monitor_trap) {
3124 pptr = &vmx->cap[vcpu].proc_ctls;
3126 flag = PROCBASED_MTF;
3127 reg = VMCS_PRI_PROC_BASED_CTLS;
3130 case VM_CAP_PAUSE_EXIT:
3131 if (cap_pause_exit) {
3133 pptr = &vmx->cap[vcpu].proc_ctls;
3135 flag = PROCBASED_PAUSE_EXITING;
3136 reg = VMCS_PRI_PROC_BASED_CTLS;
3139 case VM_CAP_UNRESTRICTED_GUEST:
3140 if (cap_unrestricted_guest) {
3142 pptr = &vmx->cap[vcpu].proc_ctls2;
3144 flag = PROCBASED2_UNRESTRICTED_GUEST;
3145 reg = VMCS_SEC_PROC_BASED_CTLS;
3148 case VM_CAP_ENABLE_INVPCID:
3151 pptr = &vmx->cap[vcpu].proc_ctls2;
3153 flag = PROCBASED2_ENABLE_INVPCID;
3154 reg = VMCS_SEC_PROC_BASED_CTLS;
3168 error = vmwrite(reg, baseval);
3175 * Update optional stored flags, and record
3183 vmx->cap[vcpu].set |= (1 << type);
3185 vmx->cap[vcpu].set &= ~(1 << type);
3194 struct vlapic vlapic;
3195 struct pir_desc *pir_desc;
3199 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg) \
3201 VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d", \
3202 level ? "level" : "edge", vector); \
3203 VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]); \
3204 VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]); \
3205 VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]); \
3206 VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]); \
3207 VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3211 * vlapic->ops handlers that utilize the APICv hardware assist described in
3212 * Chapter 29 of the Intel SDM.
3215 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3217 struct vlapic_vtx *vlapic_vtx;
3218 struct pir_desc *pir_desc;
3222 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3223 pir_desc = vlapic_vtx->pir_desc;
3226 * Keep track of interrupt requests in the PIR descriptor. This is
3227 * because the virtual APIC page pointed to by the VMCS cannot be
3228 * modified if the vcpu is running.
3231 mask = 1UL << (vector % 64);
3232 atomic_set_long(&pir_desc->pir[idx], mask);
3233 notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3235 VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3236 level, "vmx_set_intr_ready");
3241 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3243 struct vlapic_vtx *vlapic_vtx;
3244 struct pir_desc *pir_desc;
3245 struct LAPIC *lapic;
3246 uint64_t pending, pirval;
3251 * This function is only expected to be called from the 'HLT' exit
3252 * handler which does not care about the vector that is pending.
3254 KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3256 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3257 pir_desc = vlapic_vtx->pir_desc;
3259 pending = atomic_load_acq_long(&pir_desc->pending);
3261 return (0); /* common case */
3264 * If there is an interrupt pending then it will be recognized only
3265 * if its priority is greater than the processor priority.
3267 * Special case: if the processor priority is zero then any pending
3268 * interrupt will be recognized.
3270 lapic = vlapic->apic_page;
3271 ppr = lapic->ppr & 0xf0;
3275 VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3278 for (i = 3; i >= 0; i--) {
3279 pirval = pir_desc->pir[i];
3281 vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3289 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3292 panic("vmx_intr_accepted: not expected to be called");
3296 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3298 struct vlapic_vtx *vlapic_vtx;
3303 KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3304 KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3305 ("vmx_set_tmr: vcpu cannot be running"));
3307 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3308 vmx = vlapic_vtx->vmx;
3309 vmcs = &vmx->vmcs[vlapic->vcpuid];
3310 mask = 1UL << (vector % 64);
3313 val = vmcs_read(VMCS_EOI_EXIT(vector));
3318 vmcs_write(VMCS_EOI_EXIT(vector), val);
3323 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3327 uint32_t proc_ctls2;
3330 vcpuid = vlapic->vcpuid;
3331 vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3332 vmcs = &vmx->vmcs[vcpuid];
3334 proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3335 KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3336 ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3338 proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3339 proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3340 vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3343 vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3346 if (vlapic->vcpuid == 0) {
3348 * The nested page table mappings are shared by all vcpus
3349 * so unmap the APIC access page just once.
3351 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3352 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3356 * The MSR bitmap is shared by all vcpus so modify it only
3357 * once in the context of vcpu 0.
3359 error = vmx_allow_x2apic_msrs(vmx);
3360 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3366 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3369 ipi_cpu(hostcpu, pirvec);
3373 * Transfer the pending interrupts in the PIR descriptor to the IRR
3374 * in the virtual APIC page.
3377 vmx_inject_pir(struct vlapic *vlapic)
3379 struct vlapic_vtx *vlapic_vtx;
3380 struct pir_desc *pir_desc;
3381 struct LAPIC *lapic;
3382 uint64_t val, pirval;
3383 int rvi, pirbase = -1;
3384 uint16_t intr_status_old, intr_status_new;
3386 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3387 pir_desc = vlapic_vtx->pir_desc;
3388 if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3389 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3390 "no posted interrupt pending");
3396 lapic = vlapic->apic_page;
3398 val = atomic_readandclear_long(&pir_desc->pir[0]);
3401 lapic->irr1 |= val >> 32;
3406 val = atomic_readandclear_long(&pir_desc->pir[1]);
3409 lapic->irr3 |= val >> 32;
3414 val = atomic_readandclear_long(&pir_desc->pir[2]);
3417 lapic->irr5 |= val >> 32;
3422 val = atomic_readandclear_long(&pir_desc->pir[3]);
3425 lapic->irr7 |= val >> 32;
3430 VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3433 * Update RVI so the processor can evaluate pending virtual
3434 * interrupts on VM-entry.
3436 * It is possible for pirval to be 0 here, even though the
3437 * pending bit has been set. The scenario is:
3438 * CPU-Y is sending a posted interrupt to CPU-X, which
3439 * is running a guest and processing posted interrupts in h/w.
3440 * CPU-X will eventually exit and the state seen in s/w is
3441 * the pending bit set, but no PIR bits set.
3444 * (vm running) (host running)
3445 * rx posted interrupt
3448 * READ/CLEAR PIR bits
3451 * pending bit set, PIR 0
3454 rvi = pirbase + flsl(pirval) - 1;
3455 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3456 intr_status_new = (intr_status_old & 0xFF00) | rvi;
3457 if (intr_status_new > intr_status_old) {
3458 vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3459 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3460 "guest_intr_status changed from 0x%04x to 0x%04x",
3461 intr_status_old, intr_status_new);
3466 static struct vlapic *
3467 vmx_vlapic_init(void *arg, int vcpuid)
3470 struct vlapic *vlapic;
3471 struct vlapic_vtx *vlapic_vtx;
3475 vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3476 vlapic->vm = vmx->vm;
3477 vlapic->vcpuid = vcpuid;
3478 vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3480 vlapic_vtx = (struct vlapic_vtx *)vlapic;
3481 vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3482 vlapic_vtx->vmx = vmx;
3484 if (virtual_interrupt_delivery) {
3485 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3486 vlapic->ops.pending_intr = vmx_pending_intr;
3487 vlapic->ops.intr_accepted = vmx_intr_accepted;
3488 vlapic->ops.set_tmr = vmx_set_tmr;
3489 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3492 if (posted_interrupts)
3493 vlapic->ops.post_intr = vmx_post_intr;
3495 vlapic_init(vlapic);
3501 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3504 vlapic_cleanup(vlapic);
3505 free(vlapic, M_VLAPIC);
3508 struct vmm_ops vmm_ops_intel = {