1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
25 #include <linux/objtool.h>
26 #include <linux/sched.h>
27 #include <linux/sched/smt.h>
28 #include <linux/slab.h>
29 #include <linux/tboot.h>
30 #include <linux/trace_events.h>
31 #include <linux/entry-kvm.h>
36 #include <asm/cpu_device_id.h>
37 #include <asm/debugreg.h>
39 #include <asm/fpu/api.h>
40 #include <asm/fpu/xstate.h>
41 #include <asm/idtentry.h>
43 #include <asm/irq_remapping.h>
44 #include <asm/kexec.h>
45 #include <asm/perf_event.h>
46 #include <asm/mmu_context.h>
47 #include <asm/mshyperv.h>
48 #include <asm/mwait.h>
49 #include <asm/spec-ctrl.h>
50 #include <asm/virtext.h>
53 #include "capabilities.h"
56 #include "kvm_onhyperv.h"
58 #include "kvm_cache_regs.h"
71 MODULE_AUTHOR("Qumranet");
72 MODULE_LICENSE("GPL");
75 static const struct x86_cpu_id vmx_cpu_id[] = {
76 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
79 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
82 bool __read_mostly enable_vpid = 1;
83 module_param_named(vpid, enable_vpid, bool, 0444);
85 static bool __read_mostly enable_vnmi = 1;
86 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
88 bool __read_mostly flexpriority_enabled = 1;
89 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
91 bool __read_mostly enable_ept = 1;
92 module_param_named(ept, enable_ept, bool, S_IRUGO);
94 bool __read_mostly enable_unrestricted_guest = 1;
95 module_param_named(unrestricted_guest,
96 enable_unrestricted_guest, bool, S_IRUGO);
98 bool __read_mostly enable_ept_ad_bits = 1;
99 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
101 static bool __read_mostly emulate_invalid_guest_state = true;
102 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
104 static bool __read_mostly fasteoi = 1;
105 module_param(fasteoi, bool, S_IRUGO);
107 module_param(enable_apicv, bool, S_IRUGO);
109 bool __read_mostly enable_ipiv = true;
110 module_param(enable_ipiv, bool, 0444);
113 * If nested=1, nested virtualization is supported, i.e., guests may use
114 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
115 * use VMX instructions.
117 static bool __read_mostly nested = 1;
118 module_param(nested, bool, S_IRUGO);
120 bool __read_mostly enable_pml = 1;
121 module_param_named(pml, enable_pml, bool, S_IRUGO);
123 static bool __read_mostly error_on_inconsistent_vmcs_config = true;
124 module_param(error_on_inconsistent_vmcs_config, bool, 0444);
126 static bool __read_mostly dump_invalid_vmcs = 0;
127 module_param(dump_invalid_vmcs, bool, 0644);
129 #define MSR_BITMAP_MODE_X2APIC 1
130 #define MSR_BITMAP_MODE_X2APIC_APICV 2
132 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
134 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
135 static int __read_mostly cpu_preemption_timer_multi;
136 static bool __read_mostly enable_preemption_timer = 1;
138 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
141 extern bool __read_mostly allow_smaller_maxphyaddr;
142 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
144 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
145 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
146 #define KVM_VM_CR0_ALWAYS_ON \
147 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
149 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
150 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
151 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
153 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
155 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
156 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
157 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
158 RTIT_STATUS_BYTECNT))
161 * List of MSRs that can be directly passed to the guest.
162 * In addition to these x2apic and PT MSRs are handled specially.
164 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
176 MSR_IA32_SYSENTER_CS,
177 MSR_IA32_SYSENTER_ESP,
178 MSR_IA32_SYSENTER_EIP,
180 MSR_CORE_C3_RESIDENCY,
181 MSR_CORE_C6_RESIDENCY,
182 MSR_CORE_C7_RESIDENCY,
186 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
187 * ple_gap: upper bound on the amount of time between two successive
188 * executions of PAUSE in a loop. Also indicate if ple enabled.
189 * According to test, this time is usually smaller than 128 cycles.
190 * ple_window: upper bound on the amount of time a guest is allowed to execute
191 * in a PAUSE loop. Tests indicate that most spinlocks are held for
192 * less than 2^12 cycles
193 * Time is measured based on a counter that runs at the same rate as the TSC,
194 * refer SDM volume 3b section 21.6.13 & 22.1.3.
196 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
197 module_param(ple_gap, uint, 0444);
199 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
200 module_param(ple_window, uint, 0444);
202 /* Default doubles per-vcpu window every exit. */
203 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
204 module_param(ple_window_grow, uint, 0444);
206 /* Default resets per-vcpu window every exit to ple_window. */
207 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
208 module_param(ple_window_shrink, uint, 0444);
210 /* Default is to compute the maximum so we can never overflow. */
211 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
212 module_param(ple_window_max, uint, 0444);
214 /* Default is SYSTEM mode, 1 for host-guest mode */
215 int __read_mostly pt_mode = PT_MODE_SYSTEM;
216 module_param(pt_mode, int, S_IRUGO);
218 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
219 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
220 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
222 /* Storage for pre module init parameter parsing */
223 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
225 static const struct {
228 } vmentry_l1d_param[] = {
229 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
230 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
231 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
232 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
233 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
234 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
237 #define L1D_CACHE_ORDER 4
238 static void *vmx_l1d_flush_pages;
240 /* Control for disabling CPU Fill buffer clear */
241 static bool __read_mostly vmx_fb_clear_ctrl_available;
243 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
248 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
249 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
254 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
258 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
261 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
262 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
263 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
268 /* If set to auto use the default l1tf mitigation method */
269 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
270 switch (l1tf_mitigation) {
271 case L1TF_MITIGATION_OFF:
272 l1tf = VMENTER_L1D_FLUSH_NEVER;
274 case L1TF_MITIGATION_FLUSH_NOWARN:
275 case L1TF_MITIGATION_FLUSH:
276 case L1TF_MITIGATION_FLUSH_NOSMT:
277 l1tf = VMENTER_L1D_FLUSH_COND;
279 case L1TF_MITIGATION_FULL:
280 case L1TF_MITIGATION_FULL_FORCE:
281 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
284 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
285 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
288 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
289 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
291 * This allocation for vmx_l1d_flush_pages is not tied to a VM
292 * lifetime and so should not be charged to a memcg.
294 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
297 vmx_l1d_flush_pages = page_address(page);
300 * Initialize each page with a different pattern in
301 * order to protect against KSM in the nested
302 * virtualization case.
304 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
305 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
310 l1tf_vmx_mitigation = l1tf;
312 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
313 static_branch_enable(&vmx_l1d_should_flush);
315 static_branch_disable(&vmx_l1d_should_flush);
317 if (l1tf == VMENTER_L1D_FLUSH_COND)
318 static_branch_enable(&vmx_l1d_flush_cond);
320 static_branch_disable(&vmx_l1d_flush_cond);
324 static int vmentry_l1d_flush_parse(const char *s)
329 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
330 if (vmentry_l1d_param[i].for_parse &&
331 sysfs_streq(s, vmentry_l1d_param[i].option))
338 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
342 l1tf = vmentry_l1d_flush_parse(s);
346 if (!boot_cpu_has(X86_BUG_L1TF))
350 * Has vmx_init() run already? If not then this is the pre init
351 * parameter parsing. In that case just store the value and let
352 * vmx_init() do the proper setup after enable_ept has been
355 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
356 vmentry_l1d_flush_param = l1tf;
360 mutex_lock(&vmx_l1d_flush_mutex);
361 ret = vmx_setup_l1d_flush(l1tf);
362 mutex_unlock(&vmx_l1d_flush_mutex);
366 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
368 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
369 return sprintf(s, "???\n");
371 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
374 static void vmx_setup_fb_clear_ctrl(void)
378 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
379 !boot_cpu_has_bug(X86_BUG_MDS) &&
380 !boot_cpu_has_bug(X86_BUG_TAA)) {
381 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
382 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
383 vmx_fb_clear_ctrl_available = true;
387 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
391 if (!vmx->disable_fb_clear)
394 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
396 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
397 /* Cache the MSR value to avoid reading it later */
398 vmx->msr_ia32_mcu_opt_ctrl = msr;
401 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
403 if (!vmx->disable_fb_clear)
406 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
407 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
410 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
412 vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
415 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
416 * at VMEntry. Skip the MSR read/write when a guest has no use case to
419 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
420 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
421 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
422 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
423 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
424 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
425 vmx->disable_fb_clear = false;
428 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
429 .set = vmentry_l1d_flush_set,
430 .get = vmentry_l1d_flush_get,
432 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
434 static u32 vmx_segment_access_rights(struct kvm_segment *var);
436 void vmx_vmexit(void);
438 #define vmx_insn_failed(fmt...) \
441 pr_warn_ratelimited(fmt); \
444 void vmread_error(unsigned long field, bool fault)
447 kvm_spurious_fault();
449 vmx_insn_failed("vmread failed: field=%lx\n", field);
452 noinline void vmwrite_error(unsigned long field, unsigned long value)
454 vmx_insn_failed("vmwrite failed: field=%lx val=%lx err=%u\n",
455 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
458 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
460 vmx_insn_failed("vmclear failed: %p/%llx err=%u\n",
461 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
464 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
466 vmx_insn_failed("vmptrld failed: %p/%llx err=%u\n",
467 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
470 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
472 vmx_insn_failed("invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
476 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
478 vmx_insn_failed("invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
482 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
483 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
485 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
486 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
488 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
490 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
491 static DEFINE_SPINLOCK(vmx_vpid_lock);
493 struct vmcs_config vmcs_config __ro_after_init;
494 struct vmx_capability vmx_capability __ro_after_init;
496 #define VMX_SEGMENT_FIELD(seg) \
497 [VCPU_SREG_##seg] = { \
498 .selector = GUEST_##seg##_SELECTOR, \
499 .base = GUEST_##seg##_BASE, \
500 .limit = GUEST_##seg##_LIMIT, \
501 .ar_bytes = GUEST_##seg##_AR_BYTES, \
504 static const struct kvm_vmx_segment_field {
509 } kvm_vmx_segment_fields[] = {
510 VMX_SEGMENT_FIELD(CS),
511 VMX_SEGMENT_FIELD(DS),
512 VMX_SEGMENT_FIELD(ES),
513 VMX_SEGMENT_FIELD(FS),
514 VMX_SEGMENT_FIELD(GS),
515 VMX_SEGMENT_FIELD(SS),
516 VMX_SEGMENT_FIELD(TR),
517 VMX_SEGMENT_FIELD(LDTR),
520 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
522 vmx->segment_cache.bitmask = 0;
525 static unsigned long host_idt_base;
527 #if IS_ENABLED(CONFIG_HYPERV)
528 static struct kvm_x86_ops vmx_x86_ops __initdata;
530 static bool __read_mostly enlightened_vmcs = true;
531 module_param(enlightened_vmcs, bool, 0444);
533 static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu)
535 struct hv_enlightened_vmcs *evmcs;
536 struct hv_partition_assist_pg **p_hv_pa_pg =
537 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
539 * Synthetic VM-Exit is not enabled in current code and so All
540 * evmcs in singe VM shares same assist page.
543 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
548 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
550 evmcs->partition_assist_page =
552 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
553 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
558 static __init void hv_init_evmcs(void)
562 if (!enlightened_vmcs)
566 * Enlightened VMCS usage should be recommended and the host needs
567 * to support eVMCS v1 or above.
569 if (ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
570 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
573 /* Check that we have assist pages on all online CPUs */
574 for_each_online_cpu(cpu) {
575 if (!hv_get_vp_assist_page(cpu)) {
576 enlightened_vmcs = false;
581 if (enlightened_vmcs) {
582 pr_info("Using Hyper-V Enlightened VMCS\n");
583 static_branch_enable(&__kvm_is_using_evmcs);
586 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
587 vmx_x86_ops.enable_l2_tlb_flush
588 = hv_enable_l2_tlb_flush;
591 enlightened_vmcs = false;
595 static void hv_reset_evmcs(void)
597 struct hv_vp_assist_page *vp_ap;
599 if (!kvm_is_using_evmcs())
603 * KVM should enable eVMCS if and only if all CPUs have a VP assist
604 * page, and should reject CPU onlining if eVMCS is enabled the CPU
605 * doesn't have a VP assist page allocated.
607 vp_ap = hv_get_vp_assist_page(smp_processor_id());
608 if (WARN_ON_ONCE(!vp_ap))
612 * Reset everything to support using non-enlightened VMCS access later
613 * (e.g. when we reload the module with enlightened_vmcs=0)
615 vp_ap->nested_control.features.directhypercall = 0;
616 vp_ap->current_nested_vmcs = 0;
617 vp_ap->enlighten_vmentry = 0;
620 #else /* IS_ENABLED(CONFIG_HYPERV) */
621 static void hv_init_evmcs(void) {}
622 static void hv_reset_evmcs(void) {}
623 #endif /* IS_ENABLED(CONFIG_HYPERV) */
626 * Comment's format: document - errata name - stepping - processor name.
628 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
630 static u32 vmx_preemption_cpu_tfms[] = {
631 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
633 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
634 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
635 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
637 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
639 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
640 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
642 * 320767.pdf - AAP86 - B1 -
643 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
646 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
648 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
650 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
652 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
653 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
654 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
656 /* Xeon E3-1220 V2 */
660 static inline bool cpu_has_broken_vmx_preemption_timer(void)
662 u32 eax = cpuid_eax(0x00000001), i;
664 /* Clear the reserved bits */
665 eax &= ~(0x3U << 14 | 0xfU << 28);
666 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
667 if (eax == vmx_preemption_cpu_tfms[i])
673 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
675 return flexpriority_enabled && lapic_in_kernel(vcpu);
678 static int possible_passthrough_msr_slot(u32 msr)
682 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
683 if (vmx_possible_passthrough_msrs[i] == msr)
689 static bool is_valid_passthrough_msr(u32 msr)
694 case 0x800 ... 0x8ff:
695 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
697 case MSR_IA32_RTIT_STATUS:
698 case MSR_IA32_RTIT_OUTPUT_BASE:
699 case MSR_IA32_RTIT_OUTPUT_MASK:
700 case MSR_IA32_RTIT_CR3_MATCH:
701 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
702 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
705 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
706 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
707 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
708 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
709 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
710 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
714 r = possible_passthrough_msr_slot(msr) != -ENOENT;
716 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
721 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
725 i = kvm_find_user_return_msr(msr);
727 return &vmx->guest_uret_msrs[i];
731 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
732 struct vmx_uret_msr *msr, u64 data)
734 unsigned int slot = msr - vmx->guest_uret_msrs;
737 if (msr->load_into_hardware) {
739 ret = kvm_set_user_return_msr(slot, data, msr->mask);
747 #ifdef CONFIG_KEXEC_CORE
748 static void crash_vmclear_local_loaded_vmcss(void)
750 int cpu = raw_smp_processor_id();
751 struct loaded_vmcs *v;
753 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
754 loaded_vmcss_on_cpu_link)
757 #endif /* CONFIG_KEXEC_CORE */
759 static void __loaded_vmcs_clear(void *arg)
761 struct loaded_vmcs *loaded_vmcs = arg;
762 int cpu = raw_smp_processor_id();
764 if (loaded_vmcs->cpu != cpu)
765 return; /* vcpu migration can race with cpu offline */
766 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
767 per_cpu(current_vmcs, cpu) = NULL;
769 vmcs_clear(loaded_vmcs->vmcs);
770 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
771 vmcs_clear(loaded_vmcs->shadow_vmcs);
773 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
776 * Ensure all writes to loaded_vmcs, including deleting it from its
777 * current percpu list, complete before setting loaded_vmcs->cpu to
778 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
779 * and add loaded_vmcs to its percpu list before it's deleted from this
780 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
784 loaded_vmcs->cpu = -1;
785 loaded_vmcs->launched = 0;
788 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
790 int cpu = loaded_vmcs->cpu;
793 smp_call_function_single(cpu,
794 __loaded_vmcs_clear, loaded_vmcs, 1);
797 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
801 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
803 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
804 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
805 vmx->segment_cache.bitmask = 0;
807 ret = vmx->segment_cache.bitmask & mask;
808 vmx->segment_cache.bitmask |= mask;
812 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
814 u16 *p = &vmx->segment_cache.seg[seg].selector;
816 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
817 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
821 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
823 ulong *p = &vmx->segment_cache.seg[seg].base;
825 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
826 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
830 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
832 u32 *p = &vmx->segment_cache.seg[seg].limit;
834 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
835 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
839 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
841 u32 *p = &vmx->segment_cache.seg[seg].ar;
843 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
844 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
848 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
852 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
853 (1u << DB_VECTOR) | (1u << AC_VECTOR);
855 * Guest access to VMware backdoor ports could legitimately
856 * trigger #GP because of TSS I/O permission bitmap.
857 * We intercept those #GP and allow access to them anyway
860 if (enable_vmware_backdoor)
861 eb |= (1u << GP_VECTOR);
862 if ((vcpu->guest_debug &
863 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
864 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
865 eb |= 1u << BP_VECTOR;
866 if (to_vmx(vcpu)->rmode.vm86_active)
868 if (!vmx_need_pf_intercept(vcpu))
869 eb &= ~(1u << PF_VECTOR);
871 /* When we are running a nested L2 guest and L1 specified for it a
872 * certain exception bitmap, we must trap the same exceptions and pass
873 * them to L1. When running L2, we will only handle the exceptions
874 * specified above if L1 did not want them.
876 if (is_guest_mode(vcpu))
877 eb |= get_vmcs12(vcpu)->exception_bitmap;
879 int mask = 0, match = 0;
881 if (enable_ept && (eb & (1u << PF_VECTOR))) {
883 * If EPT is enabled, #PF is currently only intercepted
884 * if MAXPHYADDR is smaller on the guest than on the
885 * host. In that case we only care about present,
886 * non-reserved faults. For vmcs02, however, PFEC_MASK
887 * and PFEC_MATCH are set in prepare_vmcs02_rare.
889 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
890 match = PFERR_PRESENT_MASK;
892 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
893 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
897 * Disabling xfd interception indicates that dynamic xfeatures
898 * might be used in the guest. Always trap #NM in this case
899 * to save guest xfd_err timely.
901 if (vcpu->arch.xfd_no_write_intercept)
902 eb |= (1u << NM_VECTOR);
904 vmcs_write32(EXCEPTION_BITMAP, eb);
908 * Check if MSR is intercepted for currently loaded MSR bitmap.
910 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
912 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
915 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
918 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
920 unsigned int flags = 0;
922 if (vmx->loaded_vmcs->launched)
923 flags |= VMX_RUN_VMRESUME;
926 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
927 * to change it directly without causing a vmexit. In that case read
928 * it after vmexit and store it in vmx->spec_ctrl.
930 if (!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL))
931 flags |= VMX_RUN_SAVE_SPEC_CTRL;
936 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
937 unsigned long entry, unsigned long exit)
939 vm_entry_controls_clearbit(vmx, entry);
940 vm_exit_controls_clearbit(vmx, exit);
943 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
947 for (i = 0; i < m->nr; ++i) {
948 if (m->val[i].index == msr)
954 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
957 struct msr_autoload *m = &vmx->msr_autoload;
961 if (cpu_has_load_ia32_efer()) {
962 clear_atomic_switch_msr_special(vmx,
963 VM_ENTRY_LOAD_IA32_EFER,
964 VM_EXIT_LOAD_IA32_EFER);
968 case MSR_CORE_PERF_GLOBAL_CTRL:
969 if (cpu_has_load_perf_global_ctrl()) {
970 clear_atomic_switch_msr_special(vmx,
971 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
972 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
977 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
981 m->guest.val[i] = m->guest.val[m->guest.nr];
982 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
985 i = vmx_find_loadstore_msr_slot(&m->host, msr);
990 m->host.val[i] = m->host.val[m->host.nr];
991 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
994 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
995 unsigned long entry, unsigned long exit,
996 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
997 u64 guest_val, u64 host_val)
999 vmcs_write64(guest_val_vmcs, guest_val);
1000 if (host_val_vmcs != HOST_IA32_EFER)
1001 vmcs_write64(host_val_vmcs, host_val);
1002 vm_entry_controls_setbit(vmx, entry);
1003 vm_exit_controls_setbit(vmx, exit);
1006 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1007 u64 guest_val, u64 host_val, bool entry_only)
1010 struct msr_autoload *m = &vmx->msr_autoload;
1014 if (cpu_has_load_ia32_efer()) {
1015 add_atomic_switch_msr_special(vmx,
1016 VM_ENTRY_LOAD_IA32_EFER,
1017 VM_EXIT_LOAD_IA32_EFER,
1020 guest_val, host_val);
1024 case MSR_CORE_PERF_GLOBAL_CTRL:
1025 if (cpu_has_load_perf_global_ctrl()) {
1026 add_atomic_switch_msr_special(vmx,
1027 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1028 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1029 GUEST_IA32_PERF_GLOBAL_CTRL,
1030 HOST_IA32_PERF_GLOBAL_CTRL,
1031 guest_val, host_val);
1035 case MSR_IA32_PEBS_ENABLE:
1036 /* PEBS needs a quiescent period after being disabled (to write
1037 * a record). Disabling PEBS through VMX MSR swapping doesn't
1038 * provide that period, so a CPU could write host's record into
1041 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1044 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1046 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1048 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1049 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1050 printk_once(KERN_WARNING "Not enough msr switch entries. "
1051 "Can't add msr %x\n", msr);
1056 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1058 m->guest.val[i].index = msr;
1059 m->guest.val[i].value = guest_val;
1066 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1068 m->host.val[j].index = msr;
1069 m->host.val[j].value = host_val;
1072 static bool update_transition_efer(struct vcpu_vmx *vmx)
1074 u64 guest_efer = vmx->vcpu.arch.efer;
1075 u64 ignore_bits = 0;
1078 /* Shadow paging assumes NX to be available. */
1080 guest_efer |= EFER_NX;
1083 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1085 ignore_bits |= EFER_SCE;
1086 #ifdef CONFIG_X86_64
1087 ignore_bits |= EFER_LMA | EFER_LME;
1088 /* SCE is meaningful only in long mode on Intel */
1089 if (guest_efer & EFER_LMA)
1090 ignore_bits &= ~(u64)EFER_SCE;
1094 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1095 * On CPUs that support "load IA32_EFER", always switch EFER
1096 * atomically, since it's faster than switching it manually.
1098 if (cpu_has_load_ia32_efer() ||
1099 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1100 if (!(guest_efer & EFER_LMA))
1101 guest_efer &= ~EFER_LME;
1102 if (guest_efer != host_efer)
1103 add_atomic_switch_msr(vmx, MSR_EFER,
1104 guest_efer, host_efer, false);
1106 clear_atomic_switch_msr(vmx, MSR_EFER);
1110 i = kvm_find_user_return_msr(MSR_EFER);
1114 clear_atomic_switch_msr(vmx, MSR_EFER);
1116 guest_efer &= ~ignore_bits;
1117 guest_efer |= host_efer & ignore_bits;
1119 vmx->guest_uret_msrs[i].data = guest_efer;
1120 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1125 #ifdef CONFIG_X86_32
1127 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1128 * VMCS rather than the segment table. KVM uses this helper to figure
1129 * out the current bases to poke them into the VMCS before entry.
1131 static unsigned long segment_base(u16 selector)
1133 struct desc_struct *table;
1136 if (!(selector & ~SEGMENT_RPL_MASK))
1139 table = get_current_gdt_ro();
1141 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1142 u16 ldt_selector = kvm_read_ldt();
1144 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1147 table = (struct desc_struct *)segment_base(ldt_selector);
1149 v = get_desc_base(&table[selector >> 3]);
1154 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1156 return vmx_pt_mode_is_host_guest() &&
1157 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1160 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1162 /* The base must be 128-byte aligned and a legal physical address. */
1163 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1166 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1170 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1171 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1172 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1173 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1174 for (i = 0; i < addr_range; i++) {
1175 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1176 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1180 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1184 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1185 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1186 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1187 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1188 for (i = 0; i < addr_range; i++) {
1189 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1190 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1194 static void pt_guest_enter(struct vcpu_vmx *vmx)
1196 if (vmx_pt_mode_is_system())
1200 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1201 * Save host state before VM entry.
1203 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1204 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1205 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1206 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1207 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1211 static void pt_guest_exit(struct vcpu_vmx *vmx)
1213 if (vmx_pt_mode_is_system())
1216 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1217 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1218 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1222 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1223 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1225 if (vmx->pt_desc.host.ctl)
1226 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1229 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1230 unsigned long fs_base, unsigned long gs_base)
1232 if (unlikely(fs_sel != host->fs_sel)) {
1234 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1236 vmcs_write16(HOST_FS_SELECTOR, 0);
1237 host->fs_sel = fs_sel;
1239 if (unlikely(gs_sel != host->gs_sel)) {
1241 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1243 vmcs_write16(HOST_GS_SELECTOR, 0);
1244 host->gs_sel = gs_sel;
1246 if (unlikely(fs_base != host->fs_base)) {
1247 vmcs_writel(HOST_FS_BASE, fs_base);
1248 host->fs_base = fs_base;
1250 if (unlikely(gs_base != host->gs_base)) {
1251 vmcs_writel(HOST_GS_BASE, gs_base);
1252 host->gs_base = gs_base;
1256 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1258 struct vcpu_vmx *vmx = to_vmx(vcpu);
1259 struct vmcs_host_state *host_state;
1260 #ifdef CONFIG_X86_64
1261 int cpu = raw_smp_processor_id();
1263 unsigned long fs_base, gs_base;
1267 vmx->req_immediate_exit = false;
1270 * Note that guest MSRs to be saved/restored can also be changed
1271 * when guest state is loaded. This happens when guest transitions
1272 * to/from long-mode by setting MSR_EFER.LMA.
1274 if (!vmx->guest_uret_msrs_loaded) {
1275 vmx->guest_uret_msrs_loaded = true;
1276 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1277 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1280 kvm_set_user_return_msr(i,
1281 vmx->guest_uret_msrs[i].data,
1282 vmx->guest_uret_msrs[i].mask);
1286 if (vmx->nested.need_vmcs12_to_shadow_sync)
1287 nested_sync_vmcs12_to_shadow(vcpu);
1289 if (vmx->guest_state_loaded)
1292 host_state = &vmx->loaded_vmcs->host_state;
1295 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1296 * allow segment selectors with cpl > 0 or ti == 1.
1298 host_state->ldt_sel = kvm_read_ldt();
1300 #ifdef CONFIG_X86_64
1301 savesegment(ds, host_state->ds_sel);
1302 savesegment(es, host_state->es_sel);
1304 gs_base = cpu_kernelmode_gs_base(cpu);
1305 if (likely(is_64bit_mm(current->mm))) {
1306 current_save_fsgs();
1307 fs_sel = current->thread.fsindex;
1308 gs_sel = current->thread.gsindex;
1309 fs_base = current->thread.fsbase;
1310 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1312 savesegment(fs, fs_sel);
1313 savesegment(gs, gs_sel);
1314 fs_base = read_msr(MSR_FS_BASE);
1315 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1318 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1320 savesegment(fs, fs_sel);
1321 savesegment(gs, gs_sel);
1322 fs_base = segment_base(fs_sel);
1323 gs_base = segment_base(gs_sel);
1326 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1327 vmx->guest_state_loaded = true;
1330 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1332 struct vmcs_host_state *host_state;
1334 if (!vmx->guest_state_loaded)
1337 host_state = &vmx->loaded_vmcs->host_state;
1339 ++vmx->vcpu.stat.host_state_reload;
1341 #ifdef CONFIG_X86_64
1342 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1344 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1345 kvm_load_ldt(host_state->ldt_sel);
1346 #ifdef CONFIG_X86_64
1347 load_gs_index(host_state->gs_sel);
1349 loadsegment(gs, host_state->gs_sel);
1352 if (host_state->fs_sel & 7)
1353 loadsegment(fs, host_state->fs_sel);
1354 #ifdef CONFIG_X86_64
1355 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1356 loadsegment(ds, host_state->ds_sel);
1357 loadsegment(es, host_state->es_sel);
1360 invalidate_tss_limit();
1361 #ifdef CONFIG_X86_64
1362 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1364 load_fixmap_gdt(raw_smp_processor_id());
1365 vmx->guest_state_loaded = false;
1366 vmx->guest_uret_msrs_loaded = false;
1369 #ifdef CONFIG_X86_64
1370 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1373 if (vmx->guest_state_loaded)
1374 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1376 return vmx->msr_guest_kernel_gs_base;
1379 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1382 if (vmx->guest_state_loaded)
1383 wrmsrl(MSR_KERNEL_GS_BASE, data);
1385 vmx->msr_guest_kernel_gs_base = data;
1389 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1390 struct loaded_vmcs *buddy)
1392 struct vcpu_vmx *vmx = to_vmx(vcpu);
1393 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1396 if (!already_loaded) {
1397 loaded_vmcs_clear(vmx->loaded_vmcs);
1398 local_irq_disable();
1401 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1402 * this cpu's percpu list, otherwise it may not yet be deleted
1403 * from its previous cpu's percpu list. Pairs with the
1404 * smb_wmb() in __loaded_vmcs_clear().
1408 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1409 &per_cpu(loaded_vmcss_on_cpu, cpu));
1413 prev = per_cpu(current_vmcs, cpu);
1414 if (prev != vmx->loaded_vmcs->vmcs) {
1415 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1416 vmcs_load(vmx->loaded_vmcs->vmcs);
1419 * No indirect branch prediction barrier needed when switching
1420 * the active VMCS within a vCPU, unless IBRS is advertised to
1421 * the vCPU. To minimize the number of IBPBs executed, KVM
1422 * performs IBPB on nested VM-Exit (a single nested transition
1423 * may switch the active VMCS multiple times).
1425 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1426 indirect_branch_prediction_barrier();
1429 if (!already_loaded) {
1430 void *gdt = get_current_gdt_ro();
1433 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1434 * TLB entries from its previous association with the vCPU.
1436 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1439 * Linux uses per-cpu TSS and GDT, so set these when switching
1440 * processors. See 22.2.4.
1442 vmcs_writel(HOST_TR_BASE,
1443 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1444 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1446 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1448 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1449 (unsigned long)(cpu_entry_stack(cpu) + 1));
1452 vmx->loaded_vmcs->cpu = cpu;
1457 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1458 * vcpu mutex is already taken.
1460 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1462 struct vcpu_vmx *vmx = to_vmx(vcpu);
1464 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1466 vmx_vcpu_pi_load(vcpu, cpu);
1468 vmx->host_debugctlmsr = get_debugctlmsr();
1471 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1473 vmx_vcpu_pi_put(vcpu);
1475 vmx_prepare_switch_to_host(to_vmx(vcpu));
1478 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1480 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1483 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1485 struct vcpu_vmx *vmx = to_vmx(vcpu);
1486 unsigned long rflags, save_rflags;
1488 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1489 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1490 rflags = vmcs_readl(GUEST_RFLAGS);
1491 if (vmx->rmode.vm86_active) {
1492 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1493 save_rflags = vmx->rmode.save_rflags;
1494 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1496 vmx->rflags = rflags;
1501 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1503 struct vcpu_vmx *vmx = to_vmx(vcpu);
1504 unsigned long old_rflags;
1506 if (is_unrestricted_guest(vcpu)) {
1507 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1508 vmx->rflags = rflags;
1509 vmcs_writel(GUEST_RFLAGS, rflags);
1513 old_rflags = vmx_get_rflags(vcpu);
1514 vmx->rflags = rflags;
1515 if (vmx->rmode.vm86_active) {
1516 vmx->rmode.save_rflags = rflags;
1517 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1519 vmcs_writel(GUEST_RFLAGS, rflags);
1521 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1522 vmx->emulation_required = vmx_emulation_required(vcpu);
1525 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1527 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1530 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1532 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1535 if (interruptibility & GUEST_INTR_STATE_STI)
1536 ret |= KVM_X86_SHADOW_INT_STI;
1537 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1538 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1543 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1545 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1546 u32 interruptibility = interruptibility_old;
1548 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1550 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1551 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1552 else if (mask & KVM_X86_SHADOW_INT_STI)
1553 interruptibility |= GUEST_INTR_STATE_STI;
1555 if ((interruptibility != interruptibility_old))
1556 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1559 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1561 struct vcpu_vmx *vmx = to_vmx(vcpu);
1562 unsigned long value;
1565 * Any MSR write that attempts to change bits marked reserved will
1568 if (data & vmx->pt_desc.ctl_bitmask)
1572 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1573 * result in a #GP unless the same write also clears TraceEn.
1575 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1576 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1580 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1581 * and FabricEn would cause #GP, if
1582 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1584 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1585 !(data & RTIT_CTL_FABRIC_EN) &&
1586 !intel_pt_validate_cap(vmx->pt_desc.caps,
1587 PT_CAP_single_range_output))
1591 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1592 * utilize encodings marked reserved will cause a #GP fault.
1594 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1595 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1596 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1597 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1599 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1600 PT_CAP_cycle_thresholds);
1601 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1602 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1603 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1605 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1606 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1607 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1608 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1612 * If ADDRx_CFG is reserved or the encodings is >2 will
1613 * cause a #GP fault.
1615 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1616 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1618 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1619 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1621 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1622 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1624 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1625 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1631 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1632 void *insn, int insn_len)
1635 * Emulation of instructions in SGX enclaves is impossible as RIP does
1636 * not point at the failing instruction, and even if it did, the code
1637 * stream is inaccessible. Inject #UD instead of exiting to userspace
1638 * so that guest userspace can't DoS the guest simply by triggering
1639 * emulation (enclaves are CPL3 only).
1641 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1642 kvm_queue_exception(vcpu, UD_VECTOR);
1648 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1650 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1651 unsigned long rip, orig_rip;
1655 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1656 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1657 * set when EPT misconfig occurs. In practice, real hardware updates
1658 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1659 * (namely Hyper-V) don't set it due to it being undefined behavior,
1660 * i.e. we end up advancing IP with some random value.
1662 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1663 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1664 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1667 * Emulating an enclave's instructions isn't supported as KVM
1668 * cannot access the enclave's memory or its true RIP, e.g. the
1669 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1670 * the RIP that actually triggered the VM-Exit. But, because
1671 * most instructions that cause VM-Exit will #UD in an enclave,
1672 * most instruction-based VM-Exits simply do not occur.
1674 * There are a few exceptions, notably the debug instructions
1675 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1676 * and generate #DB/#BP as expected, which KVM might intercept.
1677 * But again, the CPU does the dirty work and saves an instr
1678 * length of zero so VMMs don't shoot themselves in the foot.
1679 * WARN if KVM tries to skip a non-zero length instruction on
1680 * a VM-Exit from an enclave.
1685 WARN_ONCE(exit_reason.enclave_mode,
1686 "skipping instruction after SGX enclave VM-Exit");
1688 orig_rip = kvm_rip_read(vcpu);
1689 rip = orig_rip + instr_len;
1690 #ifdef CONFIG_X86_64
1692 * We need to mask out the high 32 bits of RIP if not in 64-bit
1693 * mode, but just finding out that we are in 64-bit mode is
1694 * quite expensive. Only do it if there was a carry.
1696 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1699 kvm_rip_write(vcpu, rip);
1701 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1706 /* skipping an emulated instruction also counts */
1707 vmx_set_interrupt_shadow(vcpu, 0);
1713 * Recognizes a pending MTF VM-exit and records the nested state for later
1716 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1718 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1719 struct vcpu_vmx *vmx = to_vmx(vcpu);
1721 if (!is_guest_mode(vcpu))
1725 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1726 * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps
1727 * or ICEBP (in the emulator proper), and skipping of ICEBP after an
1728 * intercepted #DB deliberately avoids single-step #DB and MTF updates
1729 * as ICEBP is higher priority than both. As instruction emulation is
1730 * completed at this point (i.e. KVM is at the instruction boundary),
1731 * any #DB exception pending delivery must be a debug-trap of lower
1732 * priority than MTF. Record the pending MTF state to be delivered in
1733 * vmx_check_nested_events().
1735 if (nested_cpu_has_mtf(vmcs12) &&
1736 (!vcpu->arch.exception.pending ||
1737 vcpu->arch.exception.vector == DB_VECTOR) &&
1738 (!vcpu->arch.exception_vmexit.pending ||
1739 vcpu->arch.exception_vmexit.vector == DB_VECTOR)) {
1740 vmx->nested.mtf_pending = true;
1741 kvm_make_request(KVM_REQ_EVENT, vcpu);
1743 vmx->nested.mtf_pending = false;
1747 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1749 vmx_update_emulated_instruction(vcpu);
1750 return skip_emulated_instruction(vcpu);
1753 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1756 * Ensure that we clear the HLT state in the VMCS. We don't need to
1757 * explicitly skip the instruction because if the HLT state is set,
1758 * then the instruction is already executing and RIP has already been
1761 if (kvm_hlt_in_guest(vcpu->kvm) &&
1762 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1763 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1766 static void vmx_inject_exception(struct kvm_vcpu *vcpu)
1768 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1769 u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
1770 struct vcpu_vmx *vmx = to_vmx(vcpu);
1772 kvm_deliver_exception_payload(vcpu, ex);
1774 if (ex->has_error_code) {
1776 * Despite the error code being architecturally defined as 32
1777 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1778 * VMX don't actually supporting setting bits 31:16. Hardware
1779 * will (should) never provide a bogus error code, but AMD CPUs
1780 * do generate error codes with bits 31:16 set, and so KVM's
1781 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1782 * the upper bits to avoid VM-Fail, losing information that
1783 * does't really exist is preferable to killing the VM.
1785 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
1786 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1789 if (vmx->rmode.vm86_active) {
1791 if (kvm_exception_is_soft(ex->vector))
1792 inc_eip = vcpu->arch.event_exit_inst_len;
1793 kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
1797 WARN_ON_ONCE(vmx->emulation_required);
1799 if (kvm_exception_is_soft(ex->vector)) {
1800 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1801 vmx->vcpu.arch.event_exit_inst_len);
1802 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1804 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1806 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1808 vmx_clear_hlt(vcpu);
1811 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1812 bool load_into_hardware)
1814 struct vmx_uret_msr *uret_msr;
1816 uret_msr = vmx_find_uret_msr(vmx, msr);
1820 uret_msr->load_into_hardware = load_into_hardware;
1824 * Configuring user return MSRs to automatically save, load, and restore MSRs
1825 * that need to be shoved into hardware when running the guest. Note, omitting
1826 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1827 * loaded into hardware when running the guest.
1829 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1831 #ifdef CONFIG_X86_64
1832 bool load_syscall_msrs;
1835 * The SYSCALL MSRs are only needed on long mode guests, and only
1836 * when EFER.SCE is set.
1838 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1839 (vmx->vcpu.arch.efer & EFER_SCE);
1841 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1842 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1843 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1845 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1847 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1848 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1849 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1852 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1853 * kernel and old userspace. If those guests run on a tsx=off host, do
1854 * allow guests to use TSX_CTRL, but don't change the value in hardware
1855 * so that TSX remains always disabled.
1857 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1860 * The set of MSRs to load may have changed, reload MSRs before the
1863 vmx->guest_uret_msrs_loaded = false;
1866 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1868 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1870 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1871 return vmcs12->tsc_offset;
1876 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1878 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1880 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1881 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1882 return vmcs12->tsc_multiplier;
1884 return kvm_caps.default_tsc_scaling_ratio;
1887 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1889 vmcs_write64(TSC_OFFSET, offset);
1892 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1894 vmcs_write64(TSC_MULTIPLIER, multiplier);
1898 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1899 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1900 * all guests if the "nested" module option is off, and can also be disabled
1901 * for a single guest by disabling its VMX cpuid bit.
1903 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1905 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1909 * Userspace is allowed to set any supported IA32_FEATURE_CONTROL regardless of
1910 * guest CPUID. Note, KVM allows userspace to set "VMX in SMX" to maintain
1911 * backwards compatibility even though KVM doesn't support emulating SMX. And
1912 * because userspace set "VMX in SMX", the guest must also be allowed to set it,
1913 * e.g. if the MSR is left unlocked and the guest does a RMW operation.
1915 #define KVM_SUPPORTED_FEATURE_CONTROL (FEAT_CTL_LOCKED | \
1916 FEAT_CTL_VMX_ENABLED_INSIDE_SMX | \
1917 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX | \
1918 FEAT_CTL_SGX_LC_ENABLED | \
1919 FEAT_CTL_SGX_ENABLED | \
1920 FEAT_CTL_LMCE_ENABLED)
1922 static inline bool is_vmx_feature_control_msr_valid(struct vcpu_vmx *vmx,
1923 struct msr_data *msr)
1925 uint64_t valid_bits;
1928 * Ensure KVM_SUPPORTED_FEATURE_CONTROL is updated when new bits are
1929 * exposed to the guest.
1931 WARN_ON_ONCE(vmx->msr_ia32_feature_control_valid_bits &
1932 ~KVM_SUPPORTED_FEATURE_CONTROL);
1934 if (!msr->host_initiated &&
1935 (vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED))
1938 if (msr->host_initiated)
1939 valid_bits = KVM_SUPPORTED_FEATURE_CONTROL;
1941 valid_bits = vmx->msr_ia32_feature_control_valid_bits;
1943 return !(msr->data & ~valid_bits);
1946 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1948 switch (msr->index) {
1949 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1952 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1954 return KVM_MSR_RET_INVALID;
1959 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1960 * Returns 0 on success, non-0 otherwise.
1961 * Assumes vcpu_load() was already called.
1963 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1965 struct vcpu_vmx *vmx = to_vmx(vcpu);
1966 struct vmx_uret_msr *msr;
1969 switch (msr_info->index) {
1970 #ifdef CONFIG_X86_64
1972 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1975 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1977 case MSR_KERNEL_GS_BASE:
1978 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1982 return kvm_get_msr_common(vcpu, msr_info);
1983 case MSR_IA32_TSX_CTRL:
1984 if (!msr_info->host_initiated &&
1985 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1988 case MSR_IA32_UMWAIT_CONTROL:
1989 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1992 msr_info->data = vmx->msr_ia32_umwait_control;
1994 case MSR_IA32_SPEC_CTRL:
1995 if (!msr_info->host_initiated &&
1996 !guest_has_spec_ctrl_msr(vcpu))
1999 msr_info->data = to_vmx(vcpu)->spec_ctrl;
2001 case MSR_IA32_SYSENTER_CS:
2002 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
2004 case MSR_IA32_SYSENTER_EIP:
2005 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
2007 case MSR_IA32_SYSENTER_ESP:
2008 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
2010 case MSR_IA32_BNDCFGS:
2011 if (!kvm_mpx_supported() ||
2012 (!msr_info->host_initiated &&
2013 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2015 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
2017 case MSR_IA32_MCG_EXT_CTL:
2018 if (!msr_info->host_initiated &&
2019 !(vmx->msr_ia32_feature_control &
2020 FEAT_CTL_LMCE_ENABLED))
2022 msr_info->data = vcpu->arch.mcg_ext_ctl;
2024 case MSR_IA32_FEAT_CTL:
2025 msr_info->data = vmx->msr_ia32_feature_control;
2027 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2028 if (!msr_info->host_initiated &&
2029 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
2031 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
2032 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
2034 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2035 if (!nested_vmx_allowed(vcpu))
2037 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
2041 * Enlightened VMCS v1 doesn't have certain VMCS fields but
2042 * instead of just ignoring the features, different Hyper-V
2043 * versions are either trying to use them and fail or do some
2044 * sanity checking and refuse to boot. Filter all unsupported
2047 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
2048 nested_evmcs_filter_control_msr(vcpu, msr_info->index,
2051 case MSR_IA32_RTIT_CTL:
2052 if (!vmx_pt_mode_is_host_guest())
2054 msr_info->data = vmx->pt_desc.guest.ctl;
2056 case MSR_IA32_RTIT_STATUS:
2057 if (!vmx_pt_mode_is_host_guest())
2059 msr_info->data = vmx->pt_desc.guest.status;
2061 case MSR_IA32_RTIT_CR3_MATCH:
2062 if (!vmx_pt_mode_is_host_guest() ||
2063 !intel_pt_validate_cap(vmx->pt_desc.caps,
2064 PT_CAP_cr3_filtering))
2066 msr_info->data = vmx->pt_desc.guest.cr3_match;
2068 case MSR_IA32_RTIT_OUTPUT_BASE:
2069 if (!vmx_pt_mode_is_host_guest() ||
2070 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2071 PT_CAP_topa_output) &&
2072 !intel_pt_validate_cap(vmx->pt_desc.caps,
2073 PT_CAP_single_range_output)))
2075 msr_info->data = vmx->pt_desc.guest.output_base;
2077 case MSR_IA32_RTIT_OUTPUT_MASK:
2078 if (!vmx_pt_mode_is_host_guest() ||
2079 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2080 PT_CAP_topa_output) &&
2081 !intel_pt_validate_cap(vmx->pt_desc.caps,
2082 PT_CAP_single_range_output)))
2084 msr_info->data = vmx->pt_desc.guest.output_mask;
2086 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2087 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2088 if (!vmx_pt_mode_is_host_guest() ||
2089 (index >= 2 * vmx->pt_desc.num_address_ranges))
2092 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
2094 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
2096 case MSR_IA32_DEBUGCTLMSR:
2097 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2101 msr = vmx_find_uret_msr(vmx, msr_info->index);
2103 msr_info->data = msr->data;
2106 return kvm_get_msr_common(vcpu, msr_info);
2112 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2115 #ifdef CONFIG_X86_64
2116 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2119 return (unsigned long)data;
2122 static u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated)
2126 if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) &&
2127 (host_initiated || guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT)))
2128 debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT;
2130 if ((kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT) &&
2131 (host_initiated || intel_pmu_lbr_is_enabled(vcpu)))
2132 debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI;
2138 * Writes msr value into the appropriate "register".
2139 * Returns 0 on success, non-0 otherwise.
2140 * Assumes vcpu_load() was already called.
2142 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2144 struct vcpu_vmx *vmx = to_vmx(vcpu);
2145 struct vmx_uret_msr *msr;
2147 u32 msr_index = msr_info->index;
2148 u64 data = msr_info->data;
2151 switch (msr_index) {
2153 ret = kvm_set_msr_common(vcpu, msr_info);
2155 #ifdef CONFIG_X86_64
2157 vmx_segment_cache_clear(vmx);
2158 vmcs_writel(GUEST_FS_BASE, data);
2161 vmx_segment_cache_clear(vmx);
2162 vmcs_writel(GUEST_GS_BASE, data);
2164 case MSR_KERNEL_GS_BASE:
2165 vmx_write_guest_kernel_gs_base(vmx, data);
2168 ret = kvm_set_msr_common(vcpu, msr_info);
2170 * Always intercepting WRMSR could incur non-negligible
2171 * overhead given xfd might be changed frequently in
2172 * guest context switch. Disable write interception
2173 * upon the first write with a non-zero value (indicating
2174 * potential usage on dynamic xfeatures). Also update
2175 * exception bitmap to trap #NM for proper virtualization
2179 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2181 vcpu->arch.xfd_no_write_intercept = true;
2182 vmx_update_exception_bitmap(vcpu);
2186 case MSR_IA32_SYSENTER_CS:
2187 if (is_guest_mode(vcpu))
2188 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2189 vmcs_write32(GUEST_SYSENTER_CS, data);
2191 case MSR_IA32_SYSENTER_EIP:
2192 if (is_guest_mode(vcpu)) {
2193 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2194 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2196 vmcs_writel(GUEST_SYSENTER_EIP, data);
2198 case MSR_IA32_SYSENTER_ESP:
2199 if (is_guest_mode(vcpu)) {
2200 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2201 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2203 vmcs_writel(GUEST_SYSENTER_ESP, data);
2205 case MSR_IA32_DEBUGCTLMSR: {
2208 invalid = data & ~vmx_get_supported_debugctl(vcpu, msr_info->host_initiated);
2209 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2210 kvm_pr_unimpl_wrmsr(vcpu, msr_index, data);
2211 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2212 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2218 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2219 VM_EXIT_SAVE_DEBUG_CONTROLS)
2220 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2222 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2223 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2224 (data & DEBUGCTLMSR_LBR))
2225 intel_pmu_create_guest_lbr_event(vcpu);
2228 case MSR_IA32_BNDCFGS:
2229 if (!kvm_mpx_supported() ||
2230 (!msr_info->host_initiated &&
2231 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2233 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2234 (data & MSR_IA32_BNDCFGS_RSVD))
2237 if (is_guest_mode(vcpu) &&
2238 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2239 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2240 get_vmcs12(vcpu)->guest_bndcfgs = data;
2242 vmcs_write64(GUEST_BNDCFGS, data);
2244 case MSR_IA32_UMWAIT_CONTROL:
2245 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2248 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2249 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2252 vmx->msr_ia32_umwait_control = data;
2254 case MSR_IA32_SPEC_CTRL:
2255 if (!msr_info->host_initiated &&
2256 !guest_has_spec_ctrl_msr(vcpu))
2259 if (kvm_spec_ctrl_test_value(data))
2262 vmx->spec_ctrl = data;
2268 * When it's written (to non-zero) for the first time, pass
2272 * The handling of the MSR bitmap for L2 guests is done in
2273 * nested_vmx_prepare_msr_bitmap. We should not touch the
2274 * vmcs02.msr_bitmap here since it gets completely overwritten
2275 * in the merging. We update the vmcs01 here for L1 as well
2276 * since it will end up touching the MSR anyway now.
2278 vmx_disable_intercept_for_msr(vcpu,
2282 case MSR_IA32_TSX_CTRL:
2283 if (!msr_info->host_initiated &&
2284 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2286 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2289 case MSR_IA32_CR_PAT:
2290 if (!kvm_pat_valid(data))
2293 if (is_guest_mode(vcpu) &&
2294 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2295 get_vmcs12(vcpu)->guest_ia32_pat = data;
2297 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2298 vmcs_write64(GUEST_IA32_PAT, data);
2299 vcpu->arch.pat = data;
2302 ret = kvm_set_msr_common(vcpu, msr_info);
2304 case MSR_IA32_MCG_EXT_CTL:
2305 if ((!msr_info->host_initiated &&
2306 !(to_vmx(vcpu)->msr_ia32_feature_control &
2307 FEAT_CTL_LMCE_ENABLED)) ||
2308 (data & ~MCG_EXT_CTL_LMCE_EN))
2310 vcpu->arch.mcg_ext_ctl = data;
2312 case MSR_IA32_FEAT_CTL:
2313 if (!is_vmx_feature_control_msr_valid(vmx, msr_info))
2316 vmx->msr_ia32_feature_control = data;
2317 if (msr_info->host_initiated && data == 0)
2318 vmx_leave_nested(vcpu);
2320 /* SGX may be enabled/disabled by guest's firmware */
2321 vmx_write_encls_bitmap(vcpu, NULL);
2323 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2325 * On real hardware, the LE hash MSRs are writable before
2326 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2327 * at which point SGX related bits in IA32_FEATURE_CONTROL
2330 * KVM does not emulate SGX activation for simplicity, so
2331 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2332 * is unlocked. This is technically not architectural
2333 * behavior, but it's close enough.
2335 if (!msr_info->host_initiated &&
2336 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2337 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2338 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2340 vmx->msr_ia32_sgxlepubkeyhash
2341 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2343 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2344 if (!msr_info->host_initiated)
2345 return 1; /* they are read-only */
2346 if (!nested_vmx_allowed(vcpu))
2348 return vmx_set_vmx_msr(vcpu, msr_index, data);
2349 case MSR_IA32_RTIT_CTL:
2350 if (!vmx_pt_mode_is_host_guest() ||
2351 vmx_rtit_ctl_check(vcpu, data) ||
2354 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2355 vmx->pt_desc.guest.ctl = data;
2356 pt_update_intercept_for_msr(vcpu);
2358 case MSR_IA32_RTIT_STATUS:
2359 if (!pt_can_write_msr(vmx))
2361 if (data & MSR_IA32_RTIT_STATUS_MASK)
2363 vmx->pt_desc.guest.status = data;
2365 case MSR_IA32_RTIT_CR3_MATCH:
2366 if (!pt_can_write_msr(vmx))
2368 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2369 PT_CAP_cr3_filtering))
2371 vmx->pt_desc.guest.cr3_match = data;
2373 case MSR_IA32_RTIT_OUTPUT_BASE:
2374 if (!pt_can_write_msr(vmx))
2376 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2377 PT_CAP_topa_output) &&
2378 !intel_pt_validate_cap(vmx->pt_desc.caps,
2379 PT_CAP_single_range_output))
2381 if (!pt_output_base_valid(vcpu, data))
2383 vmx->pt_desc.guest.output_base = data;
2385 case MSR_IA32_RTIT_OUTPUT_MASK:
2386 if (!pt_can_write_msr(vmx))
2388 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2389 PT_CAP_topa_output) &&
2390 !intel_pt_validate_cap(vmx->pt_desc.caps,
2391 PT_CAP_single_range_output))
2393 vmx->pt_desc.guest.output_mask = data;
2395 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2396 if (!pt_can_write_msr(vmx))
2398 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2399 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2401 if (is_noncanonical_address(data, vcpu))
2404 vmx->pt_desc.guest.addr_b[index / 2] = data;
2406 vmx->pt_desc.guest.addr_a[index / 2] = data;
2408 case MSR_IA32_PERF_CAPABILITIES:
2409 if (data && !vcpu_to_pmu(vcpu)->version)
2411 if (data & PMU_CAP_LBR_FMT) {
2412 if ((data & PMU_CAP_LBR_FMT) !=
2413 (kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT))
2415 if (!cpuid_model_is_consistent(vcpu))
2418 if (data & PERF_CAP_PEBS_FORMAT) {
2419 if ((data & PERF_CAP_PEBS_MASK) !=
2420 (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK))
2422 if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2424 if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2426 if (!cpuid_model_is_consistent(vcpu))
2429 ret = kvm_set_msr_common(vcpu, msr_info);
2434 msr = vmx_find_uret_msr(vmx, msr_index);
2436 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2438 ret = kvm_set_msr_common(vcpu, msr_info);
2441 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2442 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2443 vmx_update_fb_clear_dis(vcpu, vmx);
2448 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2450 unsigned long guest_owned_bits;
2452 kvm_register_mark_available(vcpu, reg);
2456 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2459 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2461 case VCPU_EXREG_PDPTR:
2463 ept_save_pdptrs(vcpu);
2465 case VCPU_EXREG_CR0:
2466 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2468 vcpu->arch.cr0 &= ~guest_owned_bits;
2469 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2471 case VCPU_EXREG_CR3:
2473 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2474 * CR3 is loaded into hardware, not the guest's CR3.
2476 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2477 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2479 case VCPU_EXREG_CR4:
2480 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2482 vcpu->arch.cr4 &= ~guest_owned_bits;
2483 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2486 KVM_BUG_ON(1, vcpu->kvm);
2492 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2493 * directly instead of going through cpu_has(), to ensure KVM is trapping
2494 * ENCLS whenever it's supported in hardware. It does not matter whether
2495 * the host OS supports or has enabled SGX.
2497 static bool cpu_has_sgx(void)
2499 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2503 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2504 * can't be used due to errata where VM Exit may incorrectly clear
2505 * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2506 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2508 static bool cpu_has_perf_global_ctrl_bug(void)
2510 if (boot_cpu_data.x86 == 0x6) {
2511 switch (boot_cpu_data.x86_model) {
2512 case INTEL_FAM6_NEHALEM_EP: /* AAK155 */
2513 case INTEL_FAM6_NEHALEM: /* AAP115 */
2514 case INTEL_FAM6_WESTMERE: /* AAT100 */
2515 case INTEL_FAM6_WESTMERE_EP: /* BC86,AAY89,BD102 */
2516 case INTEL_FAM6_NEHALEM_EX: /* BA97 */
2526 static int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt, u32 msr, u32 *result)
2528 u32 vmx_msr_low, vmx_msr_high;
2529 u32 ctl = ctl_min | ctl_opt;
2531 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2533 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2534 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2536 /* Ensure minimum (required) set of control bits are supported. */
2544 static u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2548 rdmsrl(msr, allowed);
2550 return ctl_opt & allowed;
2553 static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2554 struct vmx_capability *vmx_cap)
2556 u32 vmx_msr_low, vmx_msr_high;
2557 u32 _pin_based_exec_control = 0;
2558 u32 _cpu_based_exec_control = 0;
2559 u32 _cpu_based_2nd_exec_control = 0;
2560 u64 _cpu_based_3rd_exec_control = 0;
2561 u32 _vmexit_control = 0;
2562 u32 _vmentry_control = 0;
2567 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2568 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2569 * intercepts writes to PAT and EFER, i.e. never enables those controls.
2574 } const vmcs_entry_exit_pairs[] = {
2575 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2576 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
2577 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
2578 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
2579 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
2582 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2584 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2585 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2586 MSR_IA32_VMX_PROCBASED_CTLS,
2587 &_cpu_based_exec_control))
2589 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2590 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2591 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2592 MSR_IA32_VMX_PROCBASED_CTLS2,
2593 &_cpu_based_2nd_exec_control))
2596 #ifndef CONFIG_X86_64
2597 if (!(_cpu_based_2nd_exec_control &
2598 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2599 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2602 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2603 _cpu_based_2nd_exec_control &= ~(
2604 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2605 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2606 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2608 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2609 &vmx_cap->ept, &vmx_cap->vpid);
2611 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2613 pr_warn_once("EPT CAP should not exist if not support "
2614 "1-setting enable EPT VM-execution control\n");
2616 if (error_on_inconsistent_vmcs_config)
2621 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2623 pr_warn_once("VPID CAP should not exist if not support "
2624 "1-setting enable VPID VM-execution control\n");
2626 if (error_on_inconsistent_vmcs_config)
2633 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2635 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2636 _cpu_based_3rd_exec_control =
2637 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2638 MSR_IA32_VMX_PROCBASED_CTLS3);
2640 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2641 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2642 MSR_IA32_VMX_EXIT_CTLS,
2646 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2647 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2648 MSR_IA32_VMX_PINBASED_CTLS,
2649 &_pin_based_exec_control))
2652 if (cpu_has_broken_vmx_preemption_timer())
2653 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2654 if (!(_cpu_based_2nd_exec_control &
2655 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2656 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2658 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2659 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2660 MSR_IA32_VMX_ENTRY_CTLS,
2664 for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2665 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2666 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2668 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2671 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2672 _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2674 if (error_on_inconsistent_vmcs_config)
2677 _vmentry_control &= ~n_ctrl;
2678 _vmexit_control &= ~x_ctrl;
2681 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2683 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2684 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2687 #ifdef CONFIG_X86_64
2688 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2689 if (vmx_msr_high & (1u<<16))
2693 /* Require Write-Back (WB) memory type for VMCS accesses. */
2694 if (((vmx_msr_high >> 18) & 15) != 6)
2697 rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2699 vmcs_conf->size = vmx_msr_high & 0x1fff;
2700 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2702 vmcs_conf->revision_id = vmx_msr_low;
2704 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2705 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2706 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2707 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2708 vmcs_conf->vmexit_ctrl = _vmexit_control;
2709 vmcs_conf->vmentry_ctrl = _vmentry_control;
2710 vmcs_conf->misc = misc_msr;
2712 #if IS_ENABLED(CONFIG_HYPERV)
2713 if (enlightened_vmcs)
2714 evmcs_sanitize_exec_ctrls(vmcs_conf);
2720 static bool kvm_is_vmx_supported(void)
2722 int cpu = raw_smp_processor_id();
2724 if (!cpu_has_vmx()) {
2725 pr_err("VMX not supported by CPU %d\n", cpu);
2729 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2730 !this_cpu_has(X86_FEATURE_VMX)) {
2731 pr_err("VMX not enabled (by BIOS) in MSR_IA32_FEAT_CTL on CPU %d\n", cpu);
2738 static int vmx_check_processor_compat(void)
2740 int cpu = raw_smp_processor_id();
2741 struct vmcs_config vmcs_conf;
2742 struct vmx_capability vmx_cap;
2744 if (!kvm_is_vmx_supported())
2747 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0) {
2748 pr_err("Failed to setup VMCS config on CPU %d\n", cpu);
2752 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
2753 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config))) {
2754 pr_err("Inconsistent VMCS config on CPU %d\n", cpu);
2760 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2764 cr4_set_bits(X86_CR4_VMXE);
2766 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2767 _ASM_EXTABLE(1b, %l[fault])
2768 : : [vmxon_pointer] "m"(vmxon_pointer)
2773 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2774 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2775 cr4_clear_bits(X86_CR4_VMXE);
2780 static int vmx_hardware_enable(void)
2782 int cpu = raw_smp_processor_id();
2783 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2786 if (cr4_read_shadow() & X86_CR4_VMXE)
2790 * This can happen if we hot-added a CPU but failed to allocate
2791 * VP assist page for it.
2793 if (kvm_is_using_evmcs() && !hv_get_vp_assist_page(cpu))
2796 intel_pt_handle_vmx(1);
2798 r = kvm_cpu_vmxon(phys_addr);
2800 intel_pt_handle_vmx(0);
2810 static void vmclear_local_loaded_vmcss(void)
2812 int cpu = raw_smp_processor_id();
2813 struct loaded_vmcs *v, *n;
2815 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2816 loaded_vmcss_on_cpu_link)
2817 __loaded_vmcs_clear(v);
2820 static void vmx_hardware_disable(void)
2822 vmclear_local_loaded_vmcss();
2825 kvm_spurious_fault();
2829 intel_pt_handle_vmx(0);
2832 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2834 int node = cpu_to_node(cpu);
2838 pages = __alloc_pages_node(node, flags, 0);
2841 vmcs = page_address(pages);
2842 memset(vmcs, 0, vmcs_config.size);
2844 /* KVM supports Enlightened VMCS v1 only */
2845 if (kvm_is_using_evmcs())
2846 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2848 vmcs->hdr.revision_id = vmcs_config.revision_id;
2851 vmcs->hdr.shadow_vmcs = 1;
2855 void free_vmcs(struct vmcs *vmcs)
2857 free_page((unsigned long)vmcs);
2861 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2863 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2865 if (!loaded_vmcs->vmcs)
2867 loaded_vmcs_clear(loaded_vmcs);
2868 free_vmcs(loaded_vmcs->vmcs);
2869 loaded_vmcs->vmcs = NULL;
2870 if (loaded_vmcs->msr_bitmap)
2871 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2872 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2875 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2877 loaded_vmcs->vmcs = alloc_vmcs(false);
2878 if (!loaded_vmcs->vmcs)
2881 vmcs_clear(loaded_vmcs->vmcs);
2883 loaded_vmcs->shadow_vmcs = NULL;
2884 loaded_vmcs->hv_timer_soft_disabled = false;
2885 loaded_vmcs->cpu = -1;
2886 loaded_vmcs->launched = 0;
2888 if (cpu_has_vmx_msr_bitmap()) {
2889 loaded_vmcs->msr_bitmap = (unsigned long *)
2890 __get_free_page(GFP_KERNEL_ACCOUNT);
2891 if (!loaded_vmcs->msr_bitmap)
2893 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2896 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2897 memset(&loaded_vmcs->controls_shadow, 0,
2898 sizeof(struct vmcs_controls_shadow));
2903 free_loaded_vmcs(loaded_vmcs);
2907 static void free_kvm_area(void)
2911 for_each_possible_cpu(cpu) {
2912 free_vmcs(per_cpu(vmxarea, cpu));
2913 per_cpu(vmxarea, cpu) = NULL;
2917 static __init int alloc_kvm_area(void)
2921 for_each_possible_cpu(cpu) {
2924 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2931 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2932 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2933 * revision_id reported by MSR_IA32_VMX_BASIC.
2935 * However, even though not explicitly documented by
2936 * TLFS, VMXArea passed as VMXON argument should
2937 * still be marked with revision_id reported by
2940 if (kvm_is_using_evmcs())
2941 vmcs->hdr.revision_id = vmcs_config.revision_id;
2943 per_cpu(vmxarea, cpu) = vmcs;
2948 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2949 struct kvm_segment *save)
2951 if (!emulate_invalid_guest_state) {
2953 * CS and SS RPL should be equal during guest entry according
2954 * to VMX spec, but in reality it is not always so. Since vcpu
2955 * is in the middle of the transition from real mode to
2956 * protected mode it is safe to assume that RPL 0 is a good
2959 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2960 save->selector &= ~SEGMENT_RPL_MASK;
2961 save->dpl = save->selector & SEGMENT_RPL_MASK;
2964 __vmx_set_segment(vcpu, save, seg);
2967 static void enter_pmode(struct kvm_vcpu *vcpu)
2969 unsigned long flags;
2970 struct vcpu_vmx *vmx = to_vmx(vcpu);
2973 * Update real mode segment cache. It may be not up-to-date if segment
2974 * register was written while vcpu was in a guest mode.
2976 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2977 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2978 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2979 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2980 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2981 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2983 vmx->rmode.vm86_active = 0;
2985 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2987 flags = vmcs_readl(GUEST_RFLAGS);
2988 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2989 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2990 vmcs_writel(GUEST_RFLAGS, flags);
2992 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2993 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2995 vmx_update_exception_bitmap(vcpu);
2997 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2998 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2999 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3000 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3001 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3002 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3005 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3007 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3008 struct kvm_segment var = *save;
3011 if (seg == VCPU_SREG_CS)
3014 if (!emulate_invalid_guest_state) {
3015 var.selector = var.base >> 4;
3016 var.base = var.base & 0xffff0;
3026 if (save->base & 0xf)
3027 pr_warn_once("segment base is not paragraph aligned "
3028 "when entering protected mode (seg=%d)", seg);
3031 vmcs_write16(sf->selector, var.selector);
3032 vmcs_writel(sf->base, var.base);
3033 vmcs_write32(sf->limit, var.limit);
3034 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3037 static void enter_rmode(struct kvm_vcpu *vcpu)
3039 unsigned long flags;
3040 struct vcpu_vmx *vmx = to_vmx(vcpu);
3041 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
3043 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3044 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3045 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3046 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3047 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3048 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3049 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3051 vmx->rmode.vm86_active = 1;
3054 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3055 * vcpu. Warn the user that an update is overdue.
3057 if (!kvm_vmx->tss_addr)
3058 pr_warn_once("KVM_SET_TSS_ADDR needs to be called before running vCPU\n");
3060 vmx_segment_cache_clear(vmx);
3062 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
3063 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3064 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3066 flags = vmcs_readl(GUEST_RFLAGS);
3067 vmx->rmode.save_rflags = flags;
3069 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3071 vmcs_writel(GUEST_RFLAGS, flags);
3072 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3073 vmx_update_exception_bitmap(vcpu);
3075 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3076 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3077 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3078 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3079 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3080 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3083 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3085 struct vcpu_vmx *vmx = to_vmx(vcpu);
3087 /* Nothing to do if hardware doesn't support EFER. */
3088 if (!vmx_find_uret_msr(vmx, MSR_EFER))
3091 vcpu->arch.efer = efer;
3092 #ifdef CONFIG_X86_64
3093 if (efer & EFER_LMA)
3094 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
3096 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
3098 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
3102 vmx_setup_uret_msrs(vmx);
3106 #ifdef CONFIG_X86_64
3108 static void enter_lmode(struct kvm_vcpu *vcpu)
3112 vmx_segment_cache_clear(to_vmx(vcpu));
3114 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3115 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3116 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3118 vmcs_write32(GUEST_TR_AR_BYTES,
3119 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3120 | VMX_AR_TYPE_BUSY_64_TSS);
3122 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3125 static void exit_lmode(struct kvm_vcpu *vcpu)
3127 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3132 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3134 struct vcpu_vmx *vmx = to_vmx(vcpu);
3137 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3138 * the CPU is not required to invalidate guest-physical mappings on
3139 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3140 * associated with the root EPT structure and not any particular VPID
3141 * (INVVPID also isn't required to invalidate guest-physical mappings).
3145 } else if (enable_vpid) {
3146 if (cpu_has_vmx_invvpid_global()) {
3147 vpid_sync_vcpu_global();
3149 vpid_sync_vcpu_single(vmx->vpid);
3150 vpid_sync_vcpu_single(vmx->nested.vpid02);
3155 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3157 if (is_guest_mode(vcpu))
3158 return nested_get_vpid02(vcpu);
3159 return to_vmx(vcpu)->vpid;
3162 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3164 struct kvm_mmu *mmu = vcpu->arch.mmu;
3165 u64 root_hpa = mmu->root.hpa;
3167 /* No flush required if the current context is invalid. */
3168 if (!VALID_PAGE(root_hpa))
3172 ept_sync_context(construct_eptp(vcpu, root_hpa,
3173 mmu->root_role.level));
3175 vpid_sync_context(vmx_get_current_vpid(vcpu));
3178 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3181 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3182 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3184 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3187 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3190 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3191 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3192 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3193 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3194 * i.e. no explicit INVVPID is necessary.
3196 vpid_sync_context(vmx_get_current_vpid(vcpu));
3199 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3201 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3203 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3206 if (is_pae_paging(vcpu)) {
3207 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3208 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3209 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3210 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3214 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3216 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3218 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3221 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3222 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3223 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3224 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3226 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3229 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3230 CPU_BASED_CR3_STORE_EXITING)
3232 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3234 struct vcpu_vmx *vmx = to_vmx(vcpu);
3235 unsigned long hw_cr0, old_cr0_pg;
3238 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3240 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3241 if (is_unrestricted_guest(vcpu))
3242 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3244 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3246 hw_cr0 |= X86_CR0_WP;
3248 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3251 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3255 vmcs_writel(CR0_READ_SHADOW, cr0);
3256 vmcs_writel(GUEST_CR0, hw_cr0);
3257 vcpu->arch.cr0 = cr0;
3258 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3260 #ifdef CONFIG_X86_64
3261 if (vcpu->arch.efer & EFER_LME) {
3262 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3264 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3269 if (enable_ept && !is_unrestricted_guest(vcpu)) {
3271 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3272 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3273 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3274 * KVM's CR3 is installed.
3276 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3277 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3280 * When running with EPT but not unrestricted guest, KVM must
3281 * intercept CR3 accesses when paging is _disabled_. This is
3282 * necessary because restricted guests can't actually run with
3283 * paging disabled, and so KVM stuffs its own CR3 in order to
3284 * run the guest when identity mapped page tables.
3286 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3287 * update, it may be stale with respect to CR3 interception,
3288 * e.g. after nested VM-Enter.
3290 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3291 * stores to forward them to L1, even if KVM does not need to
3292 * intercept them to preserve its identity mapped page tables.
3294 if (!(cr0 & X86_CR0_PG)) {
3295 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3296 } else if (!is_guest_mode(vcpu)) {
3297 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3299 tmp = exec_controls_get(vmx);
3300 tmp &= ~CR3_EXITING_BITS;
3301 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3302 exec_controls_set(vmx, tmp);
3305 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3306 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3307 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3310 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3311 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3313 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3314 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3317 /* depends on vcpu->arch.cr0 to be set to a new value */
3318 vmx->emulation_required = vmx_emulation_required(vcpu);
3321 static int vmx_get_max_tdp_level(void)
3323 if (cpu_has_vmx_ept_5levels())
3328 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3330 u64 eptp = VMX_EPTP_MT_WB;
3332 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3334 if (enable_ept_ad_bits &&
3335 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3336 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3342 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3345 struct kvm *kvm = vcpu->kvm;
3346 bool update_guest_cr3 = true;
3347 unsigned long guest_cr3;
3351 eptp = construct_eptp(vcpu, root_hpa, root_level);
3352 vmcs_write64(EPT_POINTER, eptp);
3354 hv_track_root_tdp(vcpu, root_hpa);
3356 if (!enable_unrestricted_guest && !is_paging(vcpu))
3357 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3358 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3359 guest_cr3 = vcpu->arch.cr3;
3360 else /* vmcs.GUEST_CR3 is already up-to-date. */
3361 update_guest_cr3 = false;
3362 vmx_ept_load_pdptrs(vcpu);
3364 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3367 if (update_guest_cr3)
3368 vmcs_writel(GUEST_CR3, guest_cr3);
3372 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3375 * We operate under the default treatment of SMM, so VMX cannot be
3376 * enabled under SMM. Note, whether or not VMXE is allowed at all,
3377 * i.e. is a reserved bit, is handled by common x86 code.
3379 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3382 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3388 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3390 unsigned long old_cr4 = vcpu->arch.cr4;
3391 struct vcpu_vmx *vmx = to_vmx(vcpu);
3393 * Pass through host's Machine Check Enable value to hw_cr4, which
3394 * is in force while we are in guest mode. Do not let guests control
3395 * this bit, even if host CR4.MCE == 0.
3397 unsigned long hw_cr4;
3399 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3400 if (is_unrestricted_guest(vcpu))
3401 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3402 else if (vmx->rmode.vm86_active)
3403 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3405 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3407 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3408 if (cr4 & X86_CR4_UMIP) {
3409 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3410 hw_cr4 &= ~X86_CR4_UMIP;
3411 } else if (!is_guest_mode(vcpu) ||
3412 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3413 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3417 vcpu->arch.cr4 = cr4;
3418 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3420 if (!is_unrestricted_guest(vcpu)) {
3422 if (!is_paging(vcpu)) {
3423 hw_cr4 &= ~X86_CR4_PAE;
3424 hw_cr4 |= X86_CR4_PSE;
3425 } else if (!(cr4 & X86_CR4_PAE)) {
3426 hw_cr4 &= ~X86_CR4_PAE;
3431 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3432 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3433 * to be manually disabled when guest switches to non-paging
3436 * If !enable_unrestricted_guest, the CPU is always running
3437 * with CR0.PG=1 and CR4 needs to be modified.
3438 * If enable_unrestricted_guest, the CPU automatically
3439 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3441 if (!is_paging(vcpu))
3442 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3445 vmcs_writel(CR4_READ_SHADOW, cr4);
3446 vmcs_writel(GUEST_CR4, hw_cr4);
3448 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3449 kvm_update_cpuid_runtime(vcpu);
3452 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3454 struct vcpu_vmx *vmx = to_vmx(vcpu);
3457 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3458 *var = vmx->rmode.segs[seg];
3459 if (seg == VCPU_SREG_TR
3460 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3462 var->base = vmx_read_guest_seg_base(vmx, seg);
3463 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3466 var->base = vmx_read_guest_seg_base(vmx, seg);
3467 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3468 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3469 ar = vmx_read_guest_seg_ar(vmx, seg);
3470 var->unusable = (ar >> 16) & 1;
3471 var->type = ar & 15;
3472 var->s = (ar >> 4) & 1;
3473 var->dpl = (ar >> 5) & 3;
3475 * Some userspaces do not preserve unusable property. Since usable
3476 * segment has to be present according to VMX spec we can use present
3477 * property to amend userspace bug by making unusable segment always
3478 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3479 * segment as unusable.
3481 var->present = !var->unusable;
3482 var->avl = (ar >> 12) & 1;
3483 var->l = (ar >> 13) & 1;
3484 var->db = (ar >> 14) & 1;
3485 var->g = (ar >> 15) & 1;
3488 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3490 struct kvm_segment s;
3492 if (to_vmx(vcpu)->rmode.vm86_active) {
3493 vmx_get_segment(vcpu, &s, seg);
3496 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3499 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3501 struct vcpu_vmx *vmx = to_vmx(vcpu);
3503 if (unlikely(vmx->rmode.vm86_active))
3506 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3507 return VMX_AR_DPL(ar);
3511 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3515 ar = var->type & 15;
3516 ar |= (var->s & 1) << 4;
3517 ar |= (var->dpl & 3) << 5;
3518 ar |= (var->present & 1) << 7;
3519 ar |= (var->avl & 1) << 12;
3520 ar |= (var->l & 1) << 13;
3521 ar |= (var->db & 1) << 14;
3522 ar |= (var->g & 1) << 15;
3523 ar |= (var->unusable || !var->present) << 16;
3528 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3530 struct vcpu_vmx *vmx = to_vmx(vcpu);
3531 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3533 vmx_segment_cache_clear(vmx);
3535 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3536 vmx->rmode.segs[seg] = *var;
3537 if (seg == VCPU_SREG_TR)
3538 vmcs_write16(sf->selector, var->selector);
3540 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3544 vmcs_writel(sf->base, var->base);
3545 vmcs_write32(sf->limit, var->limit);
3546 vmcs_write16(sf->selector, var->selector);
3549 * Fix the "Accessed" bit in AR field of segment registers for older
3551 * IA32 arch specifies that at the time of processor reset the
3552 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3553 * is setting it to 0 in the userland code. This causes invalid guest
3554 * state vmexit when "unrestricted guest" mode is turned on.
3555 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3556 * tree. Newer qemu binaries with that qemu fix would not need this
3559 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3560 var->type |= 0x1; /* Accessed */
3562 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3565 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3567 __vmx_set_segment(vcpu, var, seg);
3569 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3572 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3574 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3576 *db = (ar >> 14) & 1;
3577 *l = (ar >> 13) & 1;
3580 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3582 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3583 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3586 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3588 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3589 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3592 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3594 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3595 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3598 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3600 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3601 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3604 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3606 struct kvm_segment var;
3609 vmx_get_segment(vcpu, &var, seg);
3611 if (seg == VCPU_SREG_CS)
3613 ar = vmx_segment_access_rights(&var);
3615 if (var.base != (var.selector << 4))
3617 if (var.limit != 0xffff)
3625 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3627 struct kvm_segment cs;
3628 unsigned int cs_rpl;
3630 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3631 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3635 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3639 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3640 if (cs.dpl > cs_rpl)
3643 if (cs.dpl != cs_rpl)
3649 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3653 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3655 struct kvm_segment ss;
3656 unsigned int ss_rpl;
3658 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3659 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3663 if (ss.type != 3 && ss.type != 7)
3667 if (ss.dpl != ss_rpl) /* DPL != RPL */
3675 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3677 struct kvm_segment var;
3680 vmx_get_segment(vcpu, &var, seg);
3681 rpl = var.selector & SEGMENT_RPL_MASK;
3689 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3690 if (var.dpl < rpl) /* DPL < RPL */
3694 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3700 static bool tr_valid(struct kvm_vcpu *vcpu)
3702 struct kvm_segment tr;
3704 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3708 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3710 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3718 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3720 struct kvm_segment ldtr;
3722 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3726 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3736 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3738 struct kvm_segment cs, ss;
3740 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3741 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3743 return ((cs.selector & SEGMENT_RPL_MASK) ==
3744 (ss.selector & SEGMENT_RPL_MASK));
3748 * Check if guest state is valid. Returns true if valid, false if
3750 * We assume that registers are always usable
3752 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3754 /* real mode guest state checks */
3755 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3756 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3758 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3760 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3762 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3764 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3766 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3769 /* protected mode guest state checks */
3770 if (!cs_ss_rpl_check(vcpu))
3772 if (!code_segment_valid(vcpu))
3774 if (!stack_segment_valid(vcpu))
3776 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3778 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3780 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3782 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3784 if (!tr_valid(vcpu))
3786 if (!ldtr_valid(vcpu))
3790 * - Add checks on RIP
3791 * - Add checks on RFLAGS
3797 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3799 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3803 for (i = 0; i < 3; i++) {
3804 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3808 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3809 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3813 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3819 static int init_rmode_identity_map(struct kvm *kvm)
3821 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3826 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3827 mutex_lock(&kvm->slots_lock);
3829 if (likely(kvm_vmx->ept_identity_pagetable_done))
3832 if (!kvm_vmx->ept_identity_map_addr)
3833 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3835 uaddr = __x86_set_memory_region(kvm,
3836 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3837 kvm_vmx->ept_identity_map_addr,
3839 if (IS_ERR(uaddr)) {
3844 /* Set up identity-mapping pagetable for EPT in real mode */
3845 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3846 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3847 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3848 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3853 kvm_vmx->ept_identity_pagetable_done = true;
3856 mutex_unlock(&kvm->slots_lock);
3860 static void seg_setup(int seg)
3862 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3865 vmcs_write16(sf->selector, 0);
3866 vmcs_writel(sf->base, 0);
3867 vmcs_write32(sf->limit, 0xffff);
3869 if (seg == VCPU_SREG_CS)
3870 ar |= 0x08; /* code segment */
3872 vmcs_write32(sf->ar_bytes, ar);
3875 int allocate_vpid(void)
3881 spin_lock(&vmx_vpid_lock);
3882 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3883 if (vpid < VMX_NR_VPIDS)
3884 __set_bit(vpid, vmx_vpid_bitmap);
3887 spin_unlock(&vmx_vpid_lock);
3891 void free_vpid(int vpid)
3893 if (!enable_vpid || vpid == 0)
3895 spin_lock(&vmx_vpid_lock);
3896 __clear_bit(vpid, vmx_vpid_bitmap);
3897 spin_unlock(&vmx_vpid_lock);
3900 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3903 * When KVM is a nested hypervisor on top of Hyper-V and uses
3904 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3905 * bitmap has changed.
3907 if (kvm_is_using_evmcs()) {
3908 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
3910 if (evmcs->hv_enlightenments_control.msr_bitmap)
3911 evmcs->hv_clean_fields &=
3912 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
3915 vmx->nested.force_msr_bitmap_recalc = true;
3918 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3920 struct vcpu_vmx *vmx = to_vmx(vcpu);
3921 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3923 if (!cpu_has_vmx_msr_bitmap())
3926 vmx_msr_bitmap_l01_changed(vmx);
3929 * Mark the desired intercept state in shadow bitmap, this is needed
3930 * for resync when the MSR filters change.
3932 if (is_valid_passthrough_msr(msr)) {
3933 int idx = possible_passthrough_msr_slot(msr);
3935 if (idx != -ENOENT) {
3936 if (type & MSR_TYPE_R)
3937 clear_bit(idx, vmx->shadow_msr_intercept.read);
3938 if (type & MSR_TYPE_W)
3939 clear_bit(idx, vmx->shadow_msr_intercept.write);
3943 if ((type & MSR_TYPE_R) &&
3944 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3945 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3946 type &= ~MSR_TYPE_R;
3949 if ((type & MSR_TYPE_W) &&
3950 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3951 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3952 type &= ~MSR_TYPE_W;
3955 if (type & MSR_TYPE_R)
3956 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3958 if (type & MSR_TYPE_W)
3959 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3962 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3964 struct vcpu_vmx *vmx = to_vmx(vcpu);
3965 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3967 if (!cpu_has_vmx_msr_bitmap())
3970 vmx_msr_bitmap_l01_changed(vmx);
3973 * Mark the desired intercept state in shadow bitmap, this is needed
3974 * for resync when the MSR filter changes.
3976 if (is_valid_passthrough_msr(msr)) {
3977 int idx = possible_passthrough_msr_slot(msr);
3979 if (idx != -ENOENT) {
3980 if (type & MSR_TYPE_R)
3981 set_bit(idx, vmx->shadow_msr_intercept.read);
3982 if (type & MSR_TYPE_W)
3983 set_bit(idx, vmx->shadow_msr_intercept.write);
3987 if (type & MSR_TYPE_R)
3988 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3990 if (type & MSR_TYPE_W)
3991 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3994 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
3997 * x2APIC indices for 64-bit accesses into the RDMSR and WRMSR halves
3998 * of the MSR bitmap. KVM emulates APIC registers up through 0x3f0,
3999 * i.e. MSR 0x83f, and so only needs to dynamically manipulate 64 bits.
4001 const int read_idx = APIC_BASE_MSR / BITS_PER_LONG_LONG;
4002 const int write_idx = read_idx + (0x800 / sizeof(u64));
4003 struct vcpu_vmx *vmx = to_vmx(vcpu);
4004 u64 *msr_bitmap = (u64 *)vmx->vmcs01.msr_bitmap;
4007 if (!cpu_has_vmx_msr_bitmap() || WARN_ON_ONCE(!lapic_in_kernel(vcpu)))
4010 if (cpu_has_secondary_exec_ctrls() &&
4011 (secondary_exec_controls_get(vmx) &
4012 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4013 mode = MSR_BITMAP_MODE_X2APIC;
4014 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4015 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4020 if (mode == vmx->x2apic_msr_bitmap_mode)
4023 vmx->x2apic_msr_bitmap_mode = mode;
4026 * Reset the bitmap for MSRs 0x800 - 0x83f. Leave AMD's uber-extended
4027 * registers (0x840 and above) intercepted, KVM doesn't support them.
4028 * Intercept all writes by default and poke holes as needed. Pass
4029 * through reads for all valid registers by default in x2APIC+APICv
4030 * mode, only the current timer count needs on-demand emulation by KVM.
4032 if (mode & MSR_BITMAP_MODE_X2APIC_APICV)
4033 msr_bitmap[read_idx] = ~kvm_lapic_readable_reg_mask(vcpu->arch.apic);
4035 msr_bitmap[read_idx] = ~0ull;
4036 msr_bitmap[write_idx] = ~0ull;
4039 * TPR reads and writes can be virtualized even if virtual interrupt
4040 * delivery is not in use.
4042 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
4043 !(mode & MSR_BITMAP_MODE_X2APIC));
4045 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
4046 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
4047 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
4048 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
4050 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
4054 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
4056 struct vcpu_vmx *vmx = to_vmx(vcpu);
4057 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
4060 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
4061 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
4062 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
4063 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
4064 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
4065 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
4066 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
4070 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
4072 struct vcpu_vmx *vmx = to_vmx(vcpu);
4077 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
4078 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
4079 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
4082 rvi = vmx_get_rvi();
4084 vapic_page = vmx->nested.virtual_apic_map.hva;
4085 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4087 return ((rvi & 0xf0) > (vppr & 0xf0));
4090 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4092 struct vcpu_vmx *vmx = to_vmx(vcpu);
4096 * Redo intercept permissions for MSRs that KVM is passing through to
4097 * the guest. Disabling interception will check the new MSR filter and
4098 * ensure that KVM enables interception if usersepace wants to filter
4099 * the MSR. MSRs that KVM is already intercepting don't need to be
4100 * refreshed since KVM is going to intercept them regardless of what
4103 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4104 u32 msr = vmx_possible_passthrough_msrs[i];
4106 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4107 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4109 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4110 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4113 /* PT MSRs can be passed through iff PT is exposed to the guest. */
4114 if (vmx_pt_mode_is_host_guest())
4115 pt_update_intercept_for_msr(vcpu);
4118 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4122 if (vcpu->mode == IN_GUEST_MODE) {
4124 * The vector of the virtual has already been set in the PIR.
4125 * Send a notification event to deliver the virtual interrupt
4126 * unless the vCPU is the currently running vCPU, i.e. the
4127 * event is being sent from a fastpath VM-Exit handler, in
4128 * which case the PIR will be synced to the vIRR before
4129 * re-entering the guest.
4131 * When the target is not the running vCPU, the following
4132 * possibilities emerge:
4134 * Case 1: vCPU stays in non-root mode. Sending a notification
4135 * event posts the interrupt to the vCPU.
4137 * Case 2: vCPU exits to root mode and is still runnable. The
4138 * PIR will be synced to the vIRR before re-entering the guest.
4139 * Sending a notification event is ok as the host IRQ handler
4140 * will ignore the spurious event.
4142 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4143 * has already synced PIR to vIRR and never blocks the vCPU if
4144 * the vIRR is not empty. Therefore, a blocked vCPU here does
4145 * not wait for any requested interrupts in PIR, and sending a
4146 * notification event also results in a benign, spurious event.
4149 if (vcpu != kvm_get_running_vcpu())
4150 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4155 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4156 * otherwise do nothing as KVM will grab the highest priority pending
4157 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4159 kvm_vcpu_wake_up(vcpu);
4162 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4165 struct vcpu_vmx *vmx = to_vmx(vcpu);
4167 if (is_guest_mode(vcpu) &&
4168 vector == vmx->nested.posted_intr_nv) {
4170 * If a posted intr is not recognized by hardware,
4171 * we will accomplish it in the next vmentry.
4173 vmx->nested.pi_pending = true;
4174 kvm_make_request(KVM_REQ_EVENT, vcpu);
4177 * This pairs with the smp_mb_*() after setting vcpu->mode in
4178 * vcpu_enter_guest() to guarantee the vCPU sees the event
4179 * request if triggering a posted interrupt "fails" because
4180 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4181 * the smb_wmb() in kvm_make_request() only ensures everything
4182 * done before making the request is visible when the request
4183 * is visible, it doesn't ensure ordering between the store to
4184 * vcpu->requests and the load from vcpu->mode.
4186 smp_mb__after_atomic();
4188 /* the PIR and ON have been set by L1. */
4189 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4195 * Send interrupt to vcpu via posted interrupt way.
4196 * 1. If target vcpu is running(non-root mode), send posted interrupt
4197 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4198 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4199 * interrupt from PIR in next vmentry.
4201 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4203 struct vcpu_vmx *vmx = to_vmx(vcpu);
4206 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4210 /* Note, this is called iff the local APIC is in-kernel. */
4211 if (!vcpu->arch.apic->apicv_active)
4214 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4217 /* If a previous notification has sent the IPI, nothing to do. */
4218 if (pi_test_and_set_on(&vmx->pi_desc))
4222 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4223 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4224 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4225 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4227 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4231 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4232 int trig_mode, int vector)
4234 struct kvm_vcpu *vcpu = apic->vcpu;
4236 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4237 kvm_lapic_set_irr(vector, apic);
4238 kvm_make_request(KVM_REQ_EVENT, vcpu);
4239 kvm_vcpu_kick(vcpu);
4241 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4247 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4248 * will not change in the lifetime of the guest.
4249 * Note that host-state that does change is set elsewhere. E.g., host-state
4250 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4252 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4256 unsigned long cr0, cr3, cr4;
4259 WARN_ON(cr0 & X86_CR0_TS);
4260 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4263 * Save the most likely value for this task's CR3 in the VMCS.
4264 * We can't use __get_current_cr3_fast() because we're not atomic.
4267 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4268 vmx->loaded_vmcs->host_state.cr3 = cr3;
4270 /* Save the most likely value for this task's CR4 in the VMCS. */
4271 cr4 = cr4_read_shadow();
4272 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4273 vmx->loaded_vmcs->host_state.cr4 = cr4;
4275 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4276 #ifdef CONFIG_X86_64
4278 * Load null selectors, so we can avoid reloading them in
4279 * vmx_prepare_switch_to_host(), in case userspace uses
4280 * the null selectors too (the expected case).
4282 vmcs_write16(HOST_DS_SELECTOR, 0);
4283 vmcs_write16(HOST_ES_SELECTOR, 0);
4285 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4286 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4288 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4289 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4291 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4293 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4295 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4296 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4299 * SYSENTER is used for 32-bit system calls on either 32-bit or
4300 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4301 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4302 * have already done so!).
4304 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4305 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4307 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4308 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4310 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4311 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4312 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4315 if (cpu_has_load_ia32_efer())
4316 vmcs_write64(HOST_IA32_EFER, host_efer);
4319 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4321 struct kvm_vcpu *vcpu = &vmx->vcpu;
4323 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4324 ~vcpu->arch.cr4_guest_rsvd_bits;
4326 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4327 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4329 if (is_guest_mode(&vmx->vcpu))
4330 vcpu->arch.cr4_guest_owned_bits &=
4331 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4332 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4335 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4337 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4339 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4340 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4343 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4345 if (!enable_preemption_timer)
4346 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4348 return pin_based_exec_ctrl;
4351 static u32 vmx_vmentry_ctrl(void)
4353 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4355 if (vmx_pt_mode_is_system())
4356 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4357 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4359 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4361 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4362 VM_ENTRY_LOAD_IA32_EFER |
4363 VM_ENTRY_IA32E_MODE);
4365 if (cpu_has_perf_global_ctrl_bug())
4366 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4368 return vmentry_ctrl;
4371 static u32 vmx_vmexit_ctrl(void)
4373 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4376 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4377 * nested virtualization and thus allowed to be set in vmcs12.
4379 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4380 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4382 if (vmx_pt_mode_is_system())
4383 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4384 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4386 if (cpu_has_perf_global_ctrl_bug())
4387 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4389 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4390 return vmexit_ctrl &
4391 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4394 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4396 struct vcpu_vmx *vmx = to_vmx(vcpu);
4398 if (is_guest_mode(vcpu)) {
4399 vmx->nested.update_vmcs01_apicv_status = true;
4403 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4405 if (kvm_vcpu_apicv_active(vcpu)) {
4406 secondary_exec_controls_setbit(vmx,
4407 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4408 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4410 tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4412 secondary_exec_controls_clearbit(vmx,
4413 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4414 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4416 tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4419 vmx_update_msr_bitmap_x2apic(vcpu);
4422 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4424 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4427 * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4428 * vmcs12 and propagated to vmcs02 when set in vmcs12.
4430 exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4431 CPU_BASED_USE_IO_BITMAPS |
4432 CPU_BASED_MONITOR_TRAP_FLAG |
4433 CPU_BASED_PAUSE_EXITING);
4435 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4436 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4437 CPU_BASED_NMI_WINDOW_EXITING);
4439 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4440 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4442 if (!cpu_need_tpr_shadow(&vmx->vcpu))
4443 exec_control &= ~CPU_BASED_TPR_SHADOW;
4445 #ifdef CONFIG_X86_64
4446 if (exec_control & CPU_BASED_TPR_SHADOW)
4447 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4448 CPU_BASED_CR8_STORE_EXITING);
4450 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4451 CPU_BASED_CR8_LOAD_EXITING;
4453 /* No need to intercept CR3 access or INVPLG when using EPT. */
4455 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4456 CPU_BASED_CR3_STORE_EXITING |
4457 CPU_BASED_INVLPG_EXITING);
4458 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4459 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4460 CPU_BASED_MONITOR_EXITING);
4461 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4462 exec_control &= ~CPU_BASED_HLT_EXITING;
4463 return exec_control;
4466 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4468 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4471 * IPI virtualization relies on APICv. Disable IPI virtualization if
4472 * APICv is inhibited.
4474 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4475 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4477 return exec_control;
4481 * Adjust a single secondary execution control bit to intercept/allow an
4482 * instruction in the guest. This is usually done based on whether or not a
4483 * feature has been exposed to the guest in order to correctly emulate faults.
4486 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4487 u32 control, bool enabled, bool exiting)
4490 * If the control is for an opt-in feature, clear the control if the
4491 * feature is not exposed to the guest, i.e. not enabled. If the
4492 * control is opt-out, i.e. an exiting control, clear the control if
4493 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4494 * disabled for the associated instruction. Note, the caller is
4495 * responsible presetting exec_control to set all supported bits.
4497 if (enabled == exiting)
4498 *exec_control &= ~control;
4501 * Update the nested MSR settings so that a nested VMM can/can't set
4502 * controls for features that are/aren't exposed to the guest.
4506 * All features that can be added or removed to VMX MSRs must
4507 * be supported in the first place for nested virtualization.
4509 if (WARN_ON_ONCE(!(vmcs_config.nested.secondary_ctls_high & control)))
4513 vmx->nested.msrs.secondary_ctls_high |= control;
4515 vmx->nested.msrs.secondary_ctls_high &= ~control;
4520 * Wrapper macro for the common case of adjusting a secondary execution control
4521 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4522 * verifies that the control is actually supported by KVM and hardware.
4524 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4528 if (cpu_has_vmx_##name()) { \
4529 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4530 X86_FEATURE_##feat_name); \
4531 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4532 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4536 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4537 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4538 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4540 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4541 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4543 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4545 struct kvm_vcpu *vcpu = &vmx->vcpu;
4547 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4549 if (vmx_pt_mode_is_system())
4550 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4551 if (!cpu_need_virtualize_apic_accesses(vcpu))
4552 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4554 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4556 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4557 enable_unrestricted_guest = 0;
4559 if (!enable_unrestricted_guest)
4560 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4561 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4562 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4563 if (!kvm_vcpu_apicv_active(vcpu))
4564 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4565 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4566 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4569 * KVM doesn't support VMFUNC for L1, but the control is set in KVM's
4570 * base configuration as KVM emulates VMFUNC[EPTP_SWITCHING] for L2.
4572 exec_control &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
4574 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4575 * in vmx_set_cr4. */
4576 exec_control &= ~SECONDARY_EXEC_DESC;
4578 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4580 We can NOT enable shadow_vmcs here because we don't have yet
4583 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4586 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4587 * it needs to be set here when dirty logging is already active, e.g.
4588 * if this vCPU was created after dirty logging was enabled.
4590 if (!enable_pml || !atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
4591 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4593 if (cpu_has_vmx_xsaves()) {
4594 /* Exposing XSAVES only when XSAVE is exposed */
4595 bool xsaves_enabled =
4596 boot_cpu_has(X86_FEATURE_XSAVE) &&
4597 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4598 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4600 vcpu->arch.xsaves_enabled = xsaves_enabled;
4602 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4603 SECONDARY_EXEC_XSAVES,
4604 xsaves_enabled, false);
4608 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4609 * feature is exposed to the guest. This creates a virtualization hole
4610 * if both are supported in hardware but only one is exposed to the
4611 * guest, but letting the guest execute RDTSCP or RDPID when either one
4612 * is advertised is preferable to emulating the advertised instruction
4613 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4615 if (cpu_has_vmx_rdtscp()) {
4616 bool rdpid_or_rdtscp_enabled =
4617 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4618 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4620 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4621 SECONDARY_EXEC_ENABLE_RDTSCP,
4622 rdpid_or_rdtscp_enabled, false);
4624 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4626 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4627 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4629 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4630 ENABLE_USR_WAIT_PAUSE, false);
4632 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4633 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4635 if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4636 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4638 return exec_control;
4641 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4643 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4646 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4649 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4651 if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4654 if (kvm_vmx->pid_table)
4657 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, vmx_get_pid_table_order(kvm));
4661 kvm_vmx->pid_table = (void *)page_address(pages);
4665 static int vmx_vcpu_precreate(struct kvm *kvm)
4667 return vmx_alloc_ipiv_pid_table(kvm);
4670 #define VMX_XSS_EXIT_BITMAP 0
4672 static void init_vmcs(struct vcpu_vmx *vmx)
4674 struct kvm *kvm = vmx->vcpu.kvm;
4675 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4678 nested_vmx_set_vmcs_shadowing_bitmap();
4680 if (cpu_has_vmx_msr_bitmap())
4681 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4683 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4686 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4688 exec_controls_set(vmx, vmx_exec_control(vmx));
4690 if (cpu_has_secondary_exec_ctrls())
4691 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4693 if (cpu_has_tertiary_exec_ctrls())
4694 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4696 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4697 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4698 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4699 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4700 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4702 vmcs_write16(GUEST_INTR_STATUS, 0);
4704 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4705 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4708 if (vmx_can_use_ipiv(&vmx->vcpu)) {
4709 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4710 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4713 if (!kvm_pause_in_guest(kvm)) {
4714 vmcs_write32(PLE_GAP, ple_gap);
4715 vmx->ple_window = ple_window;
4716 vmx->ple_window_dirty = true;
4719 if (kvm_notify_vmexit_enabled(kvm))
4720 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4722 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4723 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4724 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4726 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4727 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4728 vmx_set_constant_host_state(vmx);
4729 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4730 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4732 if (cpu_has_vmx_vmfunc())
4733 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4735 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4736 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4737 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4738 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4739 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4741 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4742 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4744 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4746 /* 22.2.1, 20.8.1 */
4747 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4749 vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4750 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4752 set_cr4_guest_host_mask(vmx);
4755 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4757 if (cpu_has_vmx_xsaves())
4758 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4761 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4762 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4765 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4767 if (vmx_pt_mode_is_host_guest()) {
4768 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4769 /* Bit[6~0] are forced to 1, writes are ignored. */
4770 vmx->pt_desc.guest.output_mask = 0x7F;
4771 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4774 vmcs_write32(GUEST_SYSENTER_CS, 0);
4775 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4776 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4777 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4779 if (cpu_has_vmx_tpr_shadow()) {
4780 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4781 if (cpu_need_tpr_shadow(&vmx->vcpu))
4782 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4783 __pa(vmx->vcpu.arch.apic->regs));
4784 vmcs_write32(TPR_THRESHOLD, 0);
4787 vmx_setup_uret_msrs(vmx);
4790 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4792 struct vcpu_vmx *vmx = to_vmx(vcpu);
4797 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4799 vcpu_setup_sgx_lepubkeyhash(vcpu);
4801 vmx->nested.posted_intr_nv = -1;
4802 vmx->nested.vmxon_ptr = INVALID_GPA;
4803 vmx->nested.current_vmptr = INVALID_GPA;
4804 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4806 vcpu->arch.microcode_version = 0x100000000ULL;
4807 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4810 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4811 * or POSTED_INTR_WAKEUP_VECTOR.
4813 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4814 vmx->pi_desc.sn = 1;
4817 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4819 struct vcpu_vmx *vmx = to_vmx(vcpu);
4822 __vmx_vcpu_reset(vcpu);
4824 vmx->rmode.vm86_active = 0;
4827 vmx->msr_ia32_umwait_control = 0;
4829 vmx->hv_deadline_tsc = -1;
4830 kvm_set_cr8(vcpu, 0);
4832 vmx_segment_cache_clear(vmx);
4833 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4835 seg_setup(VCPU_SREG_CS);
4836 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4837 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4839 seg_setup(VCPU_SREG_DS);
4840 seg_setup(VCPU_SREG_ES);
4841 seg_setup(VCPU_SREG_FS);
4842 seg_setup(VCPU_SREG_GS);
4843 seg_setup(VCPU_SREG_SS);
4845 vmcs_write16(GUEST_TR_SELECTOR, 0);
4846 vmcs_writel(GUEST_TR_BASE, 0);
4847 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4848 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4850 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4851 vmcs_writel(GUEST_LDTR_BASE, 0);
4852 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4853 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4855 vmcs_writel(GUEST_GDTR_BASE, 0);
4856 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4858 vmcs_writel(GUEST_IDTR_BASE, 0);
4859 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4861 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4862 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4863 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4864 if (kvm_mpx_supported())
4865 vmcs_write64(GUEST_BNDCFGS, 0);
4867 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4869 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4871 vpid_sync_context(vmx->vpid);
4873 vmx_update_fb_clear_dis(vcpu, vmx);
4876 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4878 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4881 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4884 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4885 vmx_enable_irq_window(vcpu);
4889 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4892 static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4894 struct vcpu_vmx *vmx = to_vmx(vcpu);
4896 int irq = vcpu->arch.interrupt.nr;
4898 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4900 ++vcpu->stat.irq_injections;
4901 if (vmx->rmode.vm86_active) {
4903 if (vcpu->arch.interrupt.soft)
4904 inc_eip = vcpu->arch.event_exit_inst_len;
4905 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4908 intr = irq | INTR_INFO_VALID_MASK;
4909 if (vcpu->arch.interrupt.soft) {
4910 intr |= INTR_TYPE_SOFT_INTR;
4911 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4912 vmx->vcpu.arch.event_exit_inst_len);
4914 intr |= INTR_TYPE_EXT_INTR;
4915 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4917 vmx_clear_hlt(vcpu);
4920 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4922 struct vcpu_vmx *vmx = to_vmx(vcpu);
4926 * Tracking the NMI-blocked state in software is built upon
4927 * finding the next open IRQ window. This, in turn, depends on
4928 * well-behaving guests: They have to keep IRQs disabled at
4929 * least as long as the NMI handler runs. Otherwise we may
4930 * cause NMI nesting, maybe breaking the guest. But as this is
4931 * highly unlikely, we can live with the residual risk.
4933 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4934 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4937 ++vcpu->stat.nmi_injections;
4938 vmx->loaded_vmcs->nmi_known_unmasked = false;
4940 if (vmx->rmode.vm86_active) {
4941 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4945 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4946 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4948 vmx_clear_hlt(vcpu);
4951 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4953 struct vcpu_vmx *vmx = to_vmx(vcpu);
4957 return vmx->loaded_vmcs->soft_vnmi_blocked;
4958 if (vmx->loaded_vmcs->nmi_known_unmasked)
4960 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4961 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4965 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4967 struct vcpu_vmx *vmx = to_vmx(vcpu);
4970 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4971 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4972 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4975 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4977 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4978 GUEST_INTR_STATE_NMI);
4980 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4981 GUEST_INTR_STATE_NMI);
4985 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4987 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4990 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4993 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4994 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4995 GUEST_INTR_STATE_NMI));
4998 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5000 if (to_vmx(vcpu)->nested.nested_run_pending)
5003 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
5004 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
5007 return !vmx_nmi_blocked(vcpu);
5010 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
5012 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5015 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
5016 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5017 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5020 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5022 if (to_vmx(vcpu)->nested.nested_run_pending)
5026 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
5027 * e.g. if the IRQ arrived asynchronously after checking nested events.
5029 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5032 return !vmx_interrupt_blocked(vcpu);
5035 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5039 if (enable_unrestricted_guest)
5042 mutex_lock(&kvm->slots_lock);
5043 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5045 mutex_unlock(&kvm->slots_lock);
5048 return PTR_ERR(ret);
5050 to_kvm_vmx(kvm)->tss_addr = addr;
5052 return init_rmode_tss(kvm, ret);
5055 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5057 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
5061 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5066 * Update instruction length as we may reinject the exception
5067 * from user space while in guest debugging mode.
5069 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5070 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5071 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5075 return !(vcpu->guest_debug &
5076 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
5090 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5091 int vec, u32 err_code)
5094 * Instruction with address size override prefix opcode 0x67
5095 * Cause the #SS fault with 0 error code in VM86 mode.
5097 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5098 if (kvm_emulate_instruction(vcpu, 0)) {
5099 if (vcpu->arch.halt_request) {
5100 vcpu->arch.halt_request = 0;
5101 return kvm_emulate_halt_noskip(vcpu);
5109 * Forward all other exceptions that are valid in real mode.
5110 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5111 * the required debugging infrastructure rework.
5113 kvm_queue_exception(vcpu, vec);
5117 static int handle_machine_check(struct kvm_vcpu *vcpu)
5119 /* handled by vmx_vcpu_run() */
5124 * If the host has split lock detection disabled, then #AC is
5125 * unconditionally injected into the guest, which is the pre split lock
5126 * detection behaviour.
5128 * If the host has split lock detection enabled then #AC is
5129 * only injected into the guest when:
5130 * - Guest CPL == 3 (user mode)
5131 * - Guest has #AC detection enabled in CR0
5132 * - Guest EFLAGS has AC bit set
5134 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5136 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5139 return vmx_get_cpl(vcpu) == 3 && kvm_is_cr0_bit_set(vcpu, X86_CR0_AM) &&
5140 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5143 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5145 struct vcpu_vmx *vmx = to_vmx(vcpu);
5146 struct kvm_run *kvm_run = vcpu->run;
5147 u32 intr_info, ex_no, error_code;
5148 unsigned long cr2, dr6;
5151 vect_info = vmx->idt_vectoring_info;
5152 intr_info = vmx_get_intr_info(vcpu);
5155 * Machine checks are handled by handle_exception_irqoff(), or by
5156 * vmx_vcpu_run() if a #MC occurs on VM-Entry. NMIs are handled by
5157 * vmx_vcpu_enter_exit().
5159 if (is_machine_check(intr_info) || is_nmi(intr_info))
5163 * Queue the exception here instead of in handle_nm_fault_irqoff().
5164 * This ensures the nested_vmx check is not skipped so vmexit can
5165 * be reflected to L1 (when it intercepts #NM) before reaching this
5168 if (is_nm_fault(intr_info)) {
5169 kvm_queue_exception(vcpu, NM_VECTOR);
5173 if (is_invalid_opcode(intr_info))
5174 return handle_ud(vcpu);
5177 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5178 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5180 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5181 WARN_ON_ONCE(!enable_vmware_backdoor);
5184 * VMware backdoor emulation on #GP interception only handles
5185 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5186 * error code on #GP.
5189 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5192 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5196 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5197 * MMIO, it is better to report an internal error.
5198 * See the comments in vmx_handle_exit.
5200 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5201 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5202 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5203 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5204 vcpu->run->internal.ndata = 4;
5205 vcpu->run->internal.data[0] = vect_info;
5206 vcpu->run->internal.data[1] = intr_info;
5207 vcpu->run->internal.data[2] = error_code;
5208 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5212 if (is_page_fault(intr_info)) {
5213 cr2 = vmx_get_exit_qual(vcpu);
5214 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5216 * EPT will cause page fault only if we need to
5217 * detect illegal GPAs.
5219 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5220 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5223 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5226 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5228 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5229 return handle_rmode_exception(vcpu, ex_no, error_code);
5233 dr6 = vmx_get_exit_qual(vcpu);
5234 if (!(vcpu->guest_debug &
5235 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5237 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5238 * instruction. ICEBP generates a trap-like #DB, but
5239 * despite its interception control being tied to #DB,
5240 * is an instruction intercept, i.e. the VM-Exit occurs
5241 * on the ICEBP itself. Use the inner "skip" helper to
5242 * avoid single-step #DB and MTF updates, as ICEBP is
5243 * higher priority. Note, skipping ICEBP still clears
5244 * STI and MOVSS blocking.
5246 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5247 * if single-step is enabled in RFLAGS and STI or MOVSS
5248 * blocking is active, as the CPU doesn't set the bit
5249 * on VM-Exit due to #DB interception. VM-Entry has a
5250 * consistency check that a single-step #DB is pending
5251 * in this scenario as the previous instruction cannot
5252 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5253 * don't modify RFLAGS), therefore the one instruction
5254 * delay when activating single-step breakpoints must
5255 * have already expired. Note, the CPU sets/clears BS
5256 * as appropriate for all other VM-Exits types.
5258 if (is_icebp(intr_info))
5259 WARN_ON(!skip_emulated_instruction(vcpu));
5260 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5261 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5262 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5263 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5264 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5266 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5269 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5270 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5274 * Update instruction length as we may reinject #BP from
5275 * user space while in guest debugging mode. Reading it for
5276 * #DB as well causes no harm, it is not used in that case.
5278 vmx->vcpu.arch.event_exit_inst_len =
5279 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5280 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5281 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5282 kvm_run->debug.arch.exception = ex_no;
5285 if (vmx_guest_inject_ac(vcpu)) {
5286 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5291 * Handle split lock. Depending on detection mode this will
5292 * either warn and disable split lock detection for this
5293 * task or force SIGBUS on it.
5295 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5299 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5300 kvm_run->ex.exception = ex_no;
5301 kvm_run->ex.error_code = error_code;
5307 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5309 ++vcpu->stat.irq_exits;
5313 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5315 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5316 vcpu->mmio_needed = 0;
5320 static int handle_io(struct kvm_vcpu *vcpu)
5322 unsigned long exit_qualification;
5323 int size, in, string;
5326 exit_qualification = vmx_get_exit_qual(vcpu);
5327 string = (exit_qualification & 16) != 0;
5329 ++vcpu->stat.io_exits;
5332 return kvm_emulate_instruction(vcpu, 0);
5334 port = exit_qualification >> 16;
5335 size = (exit_qualification & 7) + 1;
5336 in = (exit_qualification & 8) != 0;
5338 return kvm_fast_pio(vcpu, size, port, in);
5342 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5345 * Patch in the VMCALL instruction:
5347 hypercall[0] = 0x0f;
5348 hypercall[1] = 0x01;
5349 hypercall[2] = 0xc1;
5352 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5353 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5355 if (is_guest_mode(vcpu)) {
5356 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5357 unsigned long orig_val = val;
5360 * We get here when L2 changed cr0 in a way that did not change
5361 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5362 * but did change L0 shadowed bits. So we first calculate the
5363 * effective cr0 value that L1 would like to write into the
5364 * hardware. It consists of the L2-owned bits from the new
5365 * value combined with the L1-owned bits from L1's guest_cr0.
5367 val = (val & ~vmcs12->cr0_guest_host_mask) |
5368 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5370 if (!nested_guest_cr0_valid(vcpu, val))
5373 if (kvm_set_cr0(vcpu, val))
5375 vmcs_writel(CR0_READ_SHADOW, orig_val);
5378 if (to_vmx(vcpu)->nested.vmxon &&
5379 !nested_host_cr0_valid(vcpu, val))
5382 return kvm_set_cr0(vcpu, val);
5386 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5388 if (is_guest_mode(vcpu)) {
5389 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5390 unsigned long orig_val = val;
5392 /* analogously to handle_set_cr0 */
5393 val = (val & ~vmcs12->cr4_guest_host_mask) |
5394 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5395 if (kvm_set_cr4(vcpu, val))
5397 vmcs_writel(CR4_READ_SHADOW, orig_val);
5400 return kvm_set_cr4(vcpu, val);
5403 static int handle_desc(struct kvm_vcpu *vcpu)
5405 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5406 return kvm_emulate_instruction(vcpu, 0);
5409 static int handle_cr(struct kvm_vcpu *vcpu)
5411 unsigned long exit_qualification, val;
5417 exit_qualification = vmx_get_exit_qual(vcpu);
5418 cr = exit_qualification & 15;
5419 reg = (exit_qualification >> 8) & 15;
5420 switch ((exit_qualification >> 4) & 3) {
5421 case 0: /* mov to cr */
5422 val = kvm_register_read(vcpu, reg);
5423 trace_kvm_cr_write(cr, val);
5426 err = handle_set_cr0(vcpu, val);
5427 return kvm_complete_insn_gp(vcpu, err);
5429 WARN_ON_ONCE(enable_unrestricted_guest);
5431 err = kvm_set_cr3(vcpu, val);
5432 return kvm_complete_insn_gp(vcpu, err);
5434 err = handle_set_cr4(vcpu, val);
5435 return kvm_complete_insn_gp(vcpu, err);
5437 u8 cr8_prev = kvm_get_cr8(vcpu);
5439 err = kvm_set_cr8(vcpu, cr8);
5440 ret = kvm_complete_insn_gp(vcpu, err);
5441 if (lapic_in_kernel(vcpu))
5443 if (cr8_prev <= cr8)
5446 * TODO: we might be squashing a
5447 * KVM_GUESTDBG_SINGLESTEP-triggered
5448 * KVM_EXIT_DEBUG here.
5450 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5456 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5458 case 1: /*mov from cr*/
5461 WARN_ON_ONCE(enable_unrestricted_guest);
5463 val = kvm_read_cr3(vcpu);
5464 kvm_register_write(vcpu, reg, val);
5465 trace_kvm_cr_read(cr, val);
5466 return kvm_skip_emulated_instruction(vcpu);
5468 val = kvm_get_cr8(vcpu);
5469 kvm_register_write(vcpu, reg, val);
5470 trace_kvm_cr_read(cr, val);
5471 return kvm_skip_emulated_instruction(vcpu);
5475 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5476 trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
5477 kvm_lmsw(vcpu, val);
5479 return kvm_skip_emulated_instruction(vcpu);
5483 vcpu->run->exit_reason = 0;
5484 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5485 (int)(exit_qualification >> 4) & 3, cr);
5489 static int handle_dr(struct kvm_vcpu *vcpu)
5491 unsigned long exit_qualification;
5495 exit_qualification = vmx_get_exit_qual(vcpu);
5496 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5498 /* First, if DR does not exist, trigger UD */
5499 if (!kvm_require_dr(vcpu, dr))
5502 if (vmx_get_cpl(vcpu) > 0)
5505 dr7 = vmcs_readl(GUEST_DR7);
5508 * As the vm-exit takes precedence over the debug trap, we
5509 * need to emulate the latter, either for the host or the
5510 * guest debugging itself.
5512 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5513 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5514 vcpu->run->debug.arch.dr7 = dr7;
5515 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5516 vcpu->run->debug.arch.exception = DB_VECTOR;
5517 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5520 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5525 if (vcpu->guest_debug == 0) {
5526 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5529 * No more DR vmexits; force a reload of the debug registers
5530 * and reenter on this instruction. The next vmexit will
5531 * retrieve the full state of the debug registers.
5533 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5537 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5538 if (exit_qualification & TYPE_MOV_FROM_DR) {
5541 kvm_get_dr(vcpu, dr, &val);
5542 kvm_register_write(vcpu, reg, val);
5545 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5549 return kvm_complete_insn_gp(vcpu, err);
5552 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5554 get_debugreg(vcpu->arch.db[0], 0);
5555 get_debugreg(vcpu->arch.db[1], 1);
5556 get_debugreg(vcpu->arch.db[2], 2);
5557 get_debugreg(vcpu->arch.db[3], 3);
5558 get_debugreg(vcpu->arch.dr6, 6);
5559 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5561 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5562 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5565 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5566 * a stale dr6 from the guest.
5568 set_debugreg(DR6_RESERVED, 6);
5571 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5573 vmcs_writel(GUEST_DR7, val);
5576 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5578 kvm_apic_update_ppr(vcpu);
5582 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5584 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5586 kvm_make_request(KVM_REQ_EVENT, vcpu);
5588 ++vcpu->stat.irq_window_exits;
5592 static int handle_invlpg(struct kvm_vcpu *vcpu)
5594 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5596 kvm_mmu_invlpg(vcpu, exit_qualification);
5597 return kvm_skip_emulated_instruction(vcpu);
5600 static int handle_apic_access(struct kvm_vcpu *vcpu)
5602 if (likely(fasteoi)) {
5603 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5604 int access_type, offset;
5606 access_type = exit_qualification & APIC_ACCESS_TYPE;
5607 offset = exit_qualification & APIC_ACCESS_OFFSET;
5609 * Sane guest uses MOV to write EOI, with written value
5610 * not cared. So make a short-circuit here by avoiding
5611 * heavy instruction emulation.
5613 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5614 (offset == APIC_EOI)) {
5615 kvm_lapic_set_eoi(vcpu);
5616 return kvm_skip_emulated_instruction(vcpu);
5619 return kvm_emulate_instruction(vcpu, 0);
5622 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5624 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5625 int vector = exit_qualification & 0xff;
5627 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5628 kvm_apic_set_eoi_accelerated(vcpu, vector);
5632 static int handle_apic_write(struct kvm_vcpu *vcpu)
5634 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5637 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5638 * hardware has done any necessary aliasing, offset adjustments, etc...
5639 * for the access. I.e. the correct value has already been written to
5640 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5641 * retrieve the register value and emulate the access.
5643 u32 offset = exit_qualification & 0xff0;
5645 kvm_apic_write_nodecode(vcpu, offset);
5649 static int handle_task_switch(struct kvm_vcpu *vcpu)
5651 struct vcpu_vmx *vmx = to_vmx(vcpu);
5652 unsigned long exit_qualification;
5653 bool has_error_code = false;
5656 int reason, type, idt_v, idt_index;
5658 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5659 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5660 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5662 exit_qualification = vmx_get_exit_qual(vcpu);
5664 reason = (u32)exit_qualification >> 30;
5665 if (reason == TASK_SWITCH_GATE && idt_v) {
5667 case INTR_TYPE_NMI_INTR:
5668 vcpu->arch.nmi_injected = false;
5669 vmx_set_nmi_mask(vcpu, true);
5671 case INTR_TYPE_EXT_INTR:
5672 case INTR_TYPE_SOFT_INTR:
5673 kvm_clear_interrupt_queue(vcpu);
5675 case INTR_TYPE_HARD_EXCEPTION:
5676 if (vmx->idt_vectoring_info &
5677 VECTORING_INFO_DELIVER_CODE_MASK) {
5678 has_error_code = true;
5680 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5683 case INTR_TYPE_SOFT_EXCEPTION:
5684 kvm_clear_exception_queue(vcpu);
5690 tss_selector = exit_qualification;
5692 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5693 type != INTR_TYPE_EXT_INTR &&
5694 type != INTR_TYPE_NMI_INTR))
5695 WARN_ON(!skip_emulated_instruction(vcpu));
5698 * TODO: What about debug traps on tss switch?
5699 * Are we supposed to inject them and update dr6?
5701 return kvm_task_switch(vcpu, tss_selector,
5702 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5703 reason, has_error_code, error_code);
5706 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5708 unsigned long exit_qualification;
5712 exit_qualification = vmx_get_exit_qual(vcpu);
5715 * EPT violation happened while executing iret from NMI,
5716 * "blocked by NMI" bit has to be set before next VM entry.
5717 * There are errata that may cause this bit to not be set:
5720 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5722 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5723 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5725 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5726 trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5728 /* Is it a read fault? */
5729 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5730 ? PFERR_USER_MASK : 0;
5731 /* Is it a write fault? */
5732 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5733 ? PFERR_WRITE_MASK : 0;
5734 /* Is it a fetch fault? */
5735 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5736 ? PFERR_FETCH_MASK : 0;
5737 /* ept page table entry is present? */
5738 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5739 ? PFERR_PRESENT_MASK : 0;
5741 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5742 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5744 vcpu->arch.exit_qualification = exit_qualification;
5747 * Check that the GPA doesn't exceed physical memory limits, as that is
5748 * a guest page fault. We have to emulate the instruction here, because
5749 * if the illegal address is that of a paging structure, then
5750 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5751 * would also use advanced VM-exit information for EPT violations to
5752 * reconstruct the page fault error code.
5754 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5755 return kvm_emulate_instruction(vcpu, 0);
5757 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5760 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5764 if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5768 * A nested guest cannot optimize MMIO vmexits, because we have an
5769 * nGPA here instead of the required GPA.
5771 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5772 if (!is_guest_mode(vcpu) &&
5773 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5774 trace_kvm_fast_mmio(gpa);
5775 return kvm_skip_emulated_instruction(vcpu);
5778 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5781 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5783 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5786 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5787 ++vcpu->stat.nmi_window_exits;
5788 kvm_make_request(KVM_REQ_EVENT, vcpu);
5793 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5795 struct vcpu_vmx *vmx = to_vmx(vcpu);
5797 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5798 (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
5801 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5803 struct vcpu_vmx *vmx = to_vmx(vcpu);
5804 bool intr_window_requested;
5805 unsigned count = 130;
5807 intr_window_requested = exec_controls_get(vmx) &
5808 CPU_BASED_INTR_WINDOW_EXITING;
5810 while (vmx->emulation_required && count-- != 0) {
5811 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5812 return handle_interrupt_window(&vmx->vcpu);
5814 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5817 if (!kvm_emulate_instruction(vcpu, 0))
5820 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5821 kvm_prepare_emulation_failure_exit(vcpu);
5825 if (vcpu->arch.halt_request) {
5826 vcpu->arch.halt_request = 0;
5827 return kvm_emulate_halt_noskip(vcpu);
5831 * Note, return 1 and not 0, vcpu_run() will invoke
5832 * xfer_to_guest_mode() which will create a proper return
5835 if (__xfer_to_guest_mode_work_pending())
5842 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5844 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5845 kvm_prepare_emulation_failure_exit(vcpu);
5852 static void grow_ple_window(struct kvm_vcpu *vcpu)
5854 struct vcpu_vmx *vmx = to_vmx(vcpu);
5855 unsigned int old = vmx->ple_window;
5857 vmx->ple_window = __grow_ple_window(old, ple_window,
5861 if (vmx->ple_window != old) {
5862 vmx->ple_window_dirty = true;
5863 trace_kvm_ple_window_update(vcpu->vcpu_id,
5864 vmx->ple_window, old);
5868 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5870 struct vcpu_vmx *vmx = to_vmx(vcpu);
5871 unsigned int old = vmx->ple_window;
5873 vmx->ple_window = __shrink_ple_window(old, ple_window,
5877 if (vmx->ple_window != old) {
5878 vmx->ple_window_dirty = true;
5879 trace_kvm_ple_window_update(vcpu->vcpu_id,
5880 vmx->ple_window, old);
5885 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5886 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5888 static int handle_pause(struct kvm_vcpu *vcpu)
5890 if (!kvm_pause_in_guest(vcpu->kvm))
5891 grow_ple_window(vcpu);
5894 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5895 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5896 * never set PAUSE_EXITING and just set PLE if supported,
5897 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5899 kvm_vcpu_on_spin(vcpu, true);
5900 return kvm_skip_emulated_instruction(vcpu);
5903 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5908 static int handle_invpcid(struct kvm_vcpu *vcpu)
5910 u32 vmx_instruction_info;
5919 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5920 kvm_queue_exception(vcpu, UD_VECTOR);
5924 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5925 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5926 type = kvm_register_read(vcpu, gpr_index);
5928 /* According to the Intel instruction reference, the memory operand
5929 * is read even if it isn't needed (e.g., for type==all)
5931 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5932 vmx_instruction_info, false,
5933 sizeof(operand), &gva))
5936 return kvm_handle_invpcid(vcpu, type, gva);
5939 static int handle_pml_full(struct kvm_vcpu *vcpu)
5941 unsigned long exit_qualification;
5943 trace_kvm_pml_full(vcpu->vcpu_id);
5945 exit_qualification = vmx_get_exit_qual(vcpu);
5948 * PML buffer FULL happened while executing iret from NMI,
5949 * "blocked by NMI" bit has to be set before next VM entry.
5951 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5953 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5954 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5955 GUEST_INTR_STATE_NMI);
5958 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5959 * here.., and there's no userspace involvement needed for PML.
5964 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5966 struct vcpu_vmx *vmx = to_vmx(vcpu);
5968 if (!vmx->req_immediate_exit &&
5969 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5970 kvm_lapic_expired_hv_timer(vcpu);
5971 return EXIT_FASTPATH_REENTER_GUEST;
5974 return EXIT_FASTPATH_NONE;
5977 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5979 handle_fastpath_preemption_timer(vcpu);
5984 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5985 * are overwritten by nested_vmx_setup() when nested=1.
5987 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5989 kvm_queue_exception(vcpu, UD_VECTOR);
5993 #ifndef CONFIG_X86_SGX_KVM
5994 static int handle_encls(struct kvm_vcpu *vcpu)
5997 * SGX virtualization is disabled. There is no software enable bit for
5998 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5999 * the guest from executing ENCLS (when SGX is supported by hardware).
6001 kvm_queue_exception(vcpu, UD_VECTOR);
6004 #endif /* CONFIG_X86_SGX_KVM */
6006 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
6009 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
6010 * VM-Exits. Unconditionally set the flag here and leave the handling to
6011 * vmx_handle_exit().
6013 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
6017 static int handle_notify(struct kvm_vcpu *vcpu)
6019 unsigned long exit_qual = vmx_get_exit_qual(vcpu);
6020 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
6022 ++vcpu->stat.notify_window_exits;
6025 * Notify VM exit happened while executing iret from NMI,
6026 * "blocked by NMI" bit has to be set before next VM entry.
6028 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
6029 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6030 GUEST_INTR_STATE_NMI);
6032 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
6034 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
6035 vcpu->run->notify.flags = context_invalid ?
6036 KVM_NOTIFY_CONTEXT_INVALID : 0;
6044 * The exit handlers return 1 if the exit was handled fully and guest execution
6045 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
6046 * to be done to userspace and return 0.
6048 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6049 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
6050 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
6051 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
6052 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
6053 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
6054 [EXIT_REASON_CR_ACCESS] = handle_cr,
6055 [EXIT_REASON_DR_ACCESS] = handle_dr,
6056 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
6057 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
6058 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
6059 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
6060 [EXIT_REASON_HLT] = kvm_emulate_halt,
6061 [EXIT_REASON_INVD] = kvm_emulate_invd,
6062 [EXIT_REASON_INVLPG] = handle_invlpg,
6063 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
6064 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
6065 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
6066 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
6067 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
6068 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
6069 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
6070 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
6071 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
6072 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
6073 [EXIT_REASON_VMON] = handle_vmx_instruction,
6074 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
6075 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
6076 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
6077 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
6078 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
6079 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
6080 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
6081 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
6082 [EXIT_REASON_GDTR_IDTR] = handle_desc,
6083 [EXIT_REASON_LDTR_TR] = handle_desc,
6084 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
6085 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
6086 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
6087 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
6088 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
6089 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
6090 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
6091 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
6092 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
6093 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
6094 [EXIT_REASON_PML_FULL] = handle_pml_full,
6095 [EXIT_REASON_INVPCID] = handle_invpcid,
6096 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
6097 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
6098 [EXIT_REASON_ENCLS] = handle_encls,
6099 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
6100 [EXIT_REASON_NOTIFY] = handle_notify,
6103 static const int kvm_vmx_max_exit_handlers =
6104 ARRAY_SIZE(kvm_vmx_exit_handlers);
6106 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6107 u64 *info1, u64 *info2,
6108 u32 *intr_info, u32 *error_code)
6110 struct vcpu_vmx *vmx = to_vmx(vcpu);
6112 *reason = vmx->exit_reason.full;
6113 *info1 = vmx_get_exit_qual(vcpu);
6114 if (!(vmx->exit_reason.failed_vmentry)) {
6115 *info2 = vmx->idt_vectoring_info;
6116 *intr_info = vmx_get_intr_info(vcpu);
6117 if (is_exception_with_error_code(*intr_info))
6118 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6128 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6131 __free_page(vmx->pml_pg);
6136 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6138 struct vcpu_vmx *vmx = to_vmx(vcpu);
6142 pml_idx = vmcs_read16(GUEST_PML_INDEX);
6144 /* Do nothing if PML buffer is empty */
6145 if (pml_idx == (PML_ENTITY_NUM - 1))
6148 /* PML index always points to next available PML buffer entity */
6149 if (pml_idx >= PML_ENTITY_NUM)
6154 pml_buf = page_address(vmx->pml_pg);
6155 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6158 gpa = pml_buf[pml_idx];
6159 WARN_ON(gpa & (PAGE_SIZE - 1));
6160 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6163 /* reset PML index */
6164 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6167 static void vmx_dump_sel(char *name, uint32_t sel)
6169 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6170 name, vmcs_read16(sel),
6171 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6172 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6173 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6176 static void vmx_dump_dtsel(char *name, uint32_t limit)
6178 pr_err("%s limit=0x%08x, base=0x%016lx\n",
6179 name, vmcs_read32(limit),
6180 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6183 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6186 struct vmx_msr_entry *e;
6188 pr_err("MSR %s:\n", name);
6189 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6190 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6193 void dump_vmcs(struct kvm_vcpu *vcpu)
6195 struct vcpu_vmx *vmx = to_vmx(vcpu);
6196 u32 vmentry_ctl, vmexit_ctl;
6197 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6198 u64 tertiary_exec_control;
6202 if (!dump_invalid_vmcs) {
6203 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6207 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6208 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6209 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6210 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6211 cr4 = vmcs_readl(GUEST_CR4);
6213 if (cpu_has_secondary_exec_ctrls())
6214 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6216 secondary_exec_control = 0;
6218 if (cpu_has_tertiary_exec_ctrls())
6219 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6221 tertiary_exec_control = 0;
6223 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6224 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6225 pr_err("*** Guest State ***\n");
6226 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6227 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6228 vmcs_readl(CR0_GUEST_HOST_MASK));
6229 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6230 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6231 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6232 if (cpu_has_vmx_ept()) {
6233 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
6234 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6235 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
6236 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6238 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
6239 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6240 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
6241 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6242 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6243 vmcs_readl(GUEST_SYSENTER_ESP),
6244 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6245 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
6246 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
6247 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
6248 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
6249 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
6250 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
6251 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6252 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6253 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6254 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
6255 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6256 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6257 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6258 else if (efer_slot >= 0)
6259 pr_err("EFER= 0x%016llx (autoload)\n",
6260 vmx->msr_autoload.guest.val[efer_slot].value);
6261 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6262 pr_err("EFER= 0x%016llx (effective)\n",
6263 vcpu->arch.efer | (EFER_LMA | EFER_LME));
6265 pr_err("EFER= 0x%016llx (effective)\n",
6266 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6267 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6268 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6269 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
6270 vmcs_read64(GUEST_IA32_DEBUGCTL),
6271 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6272 if (cpu_has_load_perf_global_ctrl() &&
6273 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6274 pr_err("PerfGlobCtl = 0x%016llx\n",
6275 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6276 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6277 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6278 pr_err("Interruptibility = %08x ActivityState = %08x\n",
6279 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6280 vmcs_read32(GUEST_ACTIVITY_STATE));
6281 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6282 pr_err("InterruptStatus = %04x\n",
6283 vmcs_read16(GUEST_INTR_STATUS));
6284 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6285 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6286 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6287 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6289 pr_err("*** Host State ***\n");
6290 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6291 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6292 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6293 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6294 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6295 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6296 vmcs_read16(HOST_TR_SELECTOR));
6297 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6298 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6299 vmcs_readl(HOST_TR_BASE));
6300 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6301 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6302 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6303 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6304 vmcs_readl(HOST_CR4));
6305 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6306 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6307 vmcs_read32(HOST_IA32_SYSENTER_CS),
6308 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6309 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6310 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6311 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6312 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6313 if (cpu_has_load_perf_global_ctrl() &&
6314 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6315 pr_err("PerfGlobCtl = 0x%016llx\n",
6316 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6317 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6318 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6320 pr_err("*** Control State ***\n");
6321 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6322 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6323 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6324 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6325 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6326 vmcs_read32(EXCEPTION_BITMAP),
6327 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6328 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6329 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6330 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6331 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6332 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6333 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6334 vmcs_read32(VM_EXIT_INTR_INFO),
6335 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6336 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6337 pr_err(" reason=%08x qualification=%016lx\n",
6338 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6339 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6340 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6341 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6342 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6343 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6344 pr_err("TSC Multiplier = 0x%016llx\n",
6345 vmcs_read64(TSC_MULTIPLIER));
6346 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6347 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6348 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6349 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6351 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6352 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6353 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6354 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6356 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6357 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6358 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6359 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6360 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6361 pr_err("PLE Gap=%08x Window=%08x\n",
6362 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6363 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6364 pr_err("Virtual processor ID = 0x%04x\n",
6365 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6369 * The guest has exited. See if we can fix it or if we need userspace
6372 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6374 struct vcpu_vmx *vmx = to_vmx(vcpu);
6375 union vmx_exit_reason exit_reason = vmx->exit_reason;
6376 u32 vectoring_info = vmx->idt_vectoring_info;
6377 u16 exit_handler_index;
6380 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6381 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6382 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6383 * mode as if vcpus is in root mode, the PML buffer must has been
6384 * flushed already. Note, PML is never enabled in hardware while
6387 if (enable_pml && !is_guest_mode(vcpu))
6388 vmx_flush_pml_buffer(vcpu);
6391 * KVM should never reach this point with a pending nested VM-Enter.
6392 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6393 * invalid guest state should never happen as that means KVM knowingly
6394 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6396 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6399 if (is_guest_mode(vcpu)) {
6401 * PML is never enabled when running L2, bail immediately if a
6402 * PML full exit occurs as something is horribly wrong.
6404 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6405 goto unexpected_vmexit;
6408 * The host physical addresses of some pages of guest memory
6409 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6410 * Page). The CPU may write to these pages via their host
6411 * physical address while L2 is running, bypassing any
6412 * address-translation-based dirty tracking (e.g. EPT write
6415 * Mark them dirty on every exit from L2 to prevent them from
6416 * getting out of sync with dirty tracking.
6418 nested_mark_vmcs12_pages_dirty(vcpu);
6421 * Synthesize a triple fault if L2 state is invalid. In normal
6422 * operation, nested VM-Enter rejects any attempt to enter L2
6423 * with invalid state. However, those checks are skipped if
6424 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6425 * L2 state is invalid, it means either L1 modified SMRAM state
6426 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6427 * doing so is architecturally allowed in the RSM case, and is
6428 * the least awful solution for the userspace case without
6429 * risking false positives.
6431 if (vmx->emulation_required) {
6432 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6436 if (nested_vmx_reflect_vmexit(vcpu))
6440 /* If guest state is invalid, start emulating. L2 is handled above. */
6441 if (vmx->emulation_required)
6442 return handle_invalid_guest_state(vcpu);
6444 if (exit_reason.failed_vmentry) {
6446 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6447 vcpu->run->fail_entry.hardware_entry_failure_reason
6449 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6453 if (unlikely(vmx->fail)) {
6455 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6456 vcpu->run->fail_entry.hardware_entry_failure_reason
6457 = vmcs_read32(VM_INSTRUCTION_ERROR);
6458 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6464 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6465 * delivery event since it indicates guest is accessing MMIO.
6466 * The vm-exit can be triggered again after return to guest that
6467 * will cause infinite loop.
6469 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6470 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6471 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6472 exit_reason.basic != EXIT_REASON_PML_FULL &&
6473 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6474 exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6475 exit_reason.basic != EXIT_REASON_NOTIFY)) {
6478 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6479 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6480 vcpu->run->internal.data[0] = vectoring_info;
6481 vcpu->run->internal.data[1] = exit_reason.full;
6482 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6483 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6484 vcpu->run->internal.data[ndata++] =
6485 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6487 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6488 vcpu->run->internal.ndata = ndata;
6492 if (unlikely(!enable_vnmi &&
6493 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6494 if (!vmx_interrupt_blocked(vcpu)) {
6495 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6496 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6497 vcpu->arch.nmi_pending) {
6499 * This CPU don't support us in finding the end of an
6500 * NMI-blocked window if the guest runs with IRQs
6501 * disabled. So we pull the trigger after 1 s of
6502 * futile waiting, but inform the user about this.
6504 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6505 "state on VCPU %d after 1 s timeout\n",
6506 __func__, vcpu->vcpu_id);
6507 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6511 if (exit_fastpath != EXIT_FASTPATH_NONE)
6514 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6515 goto unexpected_vmexit;
6516 #ifdef CONFIG_RETPOLINE
6517 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6518 return kvm_emulate_wrmsr(vcpu);
6519 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6520 return handle_preemption_timer(vcpu);
6521 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6522 return handle_interrupt_window(vcpu);
6523 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6524 return handle_external_interrupt(vcpu);
6525 else if (exit_reason.basic == EXIT_REASON_HLT)
6526 return kvm_emulate_halt(vcpu);
6527 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6528 return handle_ept_misconfig(vcpu);
6531 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6532 kvm_vmx_max_exit_handlers);
6533 if (!kvm_vmx_exit_handlers[exit_handler_index])
6534 goto unexpected_vmexit;
6536 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6539 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6542 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6543 vcpu->run->internal.suberror =
6544 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6545 vcpu->run->internal.ndata = 2;
6546 vcpu->run->internal.data[0] = exit_reason.full;
6547 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6551 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6553 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6556 * Exit to user space when bus lock detected to inform that there is
6557 * a bus lock in guest.
6559 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6561 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6563 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6570 * Software based L1D cache flush which is used when microcode providing
6571 * the cache control MSR is not loaded.
6573 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6574 * flush it is required to read in 64 KiB because the replacement algorithm
6575 * is not exactly LRU. This could be sized at runtime via topology
6576 * information but as all relevant affected CPUs have 32KiB L1D cache size
6577 * there is no point in doing so.
6579 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6581 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6584 * This code is only executed when the flush mode is 'cond' or
6587 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6591 * Clear the per-vcpu flush bit, it gets set again
6592 * either from vcpu_run() or from one of the unsafe
6595 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6596 vcpu->arch.l1tf_flush_l1d = false;
6599 * Clear the per-cpu flush bit, it gets set again from
6600 * the interrupt handlers.
6602 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6603 kvm_clear_cpu_l1tf_flush_l1d();
6609 vcpu->stat.l1d_flush++;
6611 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6612 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6617 /* First ensure the pages are in the TLB */
6618 "xorl %%eax, %%eax\n"
6619 ".Lpopulate_tlb:\n\t"
6620 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6621 "addl $4096, %%eax\n\t"
6622 "cmpl %%eax, %[size]\n\t"
6623 "jne .Lpopulate_tlb\n\t"
6624 "xorl %%eax, %%eax\n\t"
6626 /* Now fill the cache */
6627 "xorl %%eax, %%eax\n"
6629 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6630 "addl $64, %%eax\n\t"
6631 "cmpl %%eax, %[size]\n\t"
6632 "jne .Lfill_cache\n\t"
6634 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6636 : "eax", "ebx", "ecx", "edx");
6639 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6641 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6644 if (is_guest_mode(vcpu) &&
6645 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6648 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6649 if (is_guest_mode(vcpu))
6650 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6652 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6655 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6657 struct vcpu_vmx *vmx = to_vmx(vcpu);
6658 u32 sec_exec_control;
6660 if (!lapic_in_kernel(vcpu))
6663 if (!flexpriority_enabled &&
6664 !cpu_has_vmx_virtualize_x2apic_mode())
6667 /* Postpone execution until vmcs01 is the current VMCS. */
6668 if (is_guest_mode(vcpu)) {
6669 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6673 sec_exec_control = secondary_exec_controls_get(vmx);
6674 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6675 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6677 switch (kvm_get_apic_mode(vcpu)) {
6678 case LAPIC_MODE_INVALID:
6679 WARN_ONCE(true, "Invalid local APIC state");
6681 case LAPIC_MODE_DISABLED:
6683 case LAPIC_MODE_XAPIC:
6684 if (flexpriority_enabled) {
6686 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6687 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6690 * Flush the TLB, reloading the APIC access page will
6691 * only do so if its physical address has changed, but
6692 * the guest may have inserted a non-APIC mapping into
6693 * the TLB while the APIC access page was disabled.
6695 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6698 case LAPIC_MODE_X2APIC:
6699 if (cpu_has_vmx_virtualize_x2apic_mode())
6701 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6704 secondary_exec_controls_set(vmx, sec_exec_control);
6706 vmx_update_msr_bitmap_x2apic(vcpu);
6709 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6713 /* Defer reload until vmcs01 is the current VMCS. */
6714 if (is_guest_mode(vcpu)) {
6715 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6719 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6720 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6723 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6724 if (is_error_page(page))
6727 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6728 vmx_flush_tlb_current(vcpu);
6731 * Do not pin apic access page in memory, the MMU notifier
6732 * will call us again if it is migrated or swapped out.
6737 static void vmx_hwapic_isr_update(int max_isr)
6745 status = vmcs_read16(GUEST_INTR_STATUS);
6747 if (max_isr != old) {
6749 status |= max_isr << 8;
6750 vmcs_write16(GUEST_INTR_STATUS, status);
6754 static void vmx_set_rvi(int vector)
6762 status = vmcs_read16(GUEST_INTR_STATUS);
6763 old = (u8)status & 0xff;
6764 if ((u8)vector != old) {
6766 status |= (u8)vector;
6767 vmcs_write16(GUEST_INTR_STATUS, status);
6771 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6774 * When running L2, updating RVI is only relevant when
6775 * vmcs12 virtual-interrupt-delivery enabled.
6776 * However, it can be enabled only when L1 also
6777 * intercepts external-interrupts and in that case
6778 * we should not update vmcs02 RVI but instead intercept
6779 * interrupt. Therefore, do nothing when running L2.
6781 if (!is_guest_mode(vcpu))
6782 vmx_set_rvi(max_irr);
6785 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6787 struct vcpu_vmx *vmx = to_vmx(vcpu);
6789 bool got_posted_interrupt;
6791 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6794 if (pi_test_on(&vmx->pi_desc)) {
6795 pi_clear_on(&vmx->pi_desc);
6797 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6798 * But on x86 this is just a compiler barrier anyway.
6800 smp_mb__after_atomic();
6801 got_posted_interrupt =
6802 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6804 max_irr = kvm_lapic_find_highest_irr(vcpu);
6805 got_posted_interrupt = false;
6809 * Newly recognized interrupts are injected via either virtual interrupt
6810 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6811 * disabled in two cases:
6813 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6814 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6815 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6816 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6817 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6819 * 2) If APICv is disabled for this vCPU, assigned devices may still
6820 * attempt to post interrupts. The posted interrupt vector will cause
6821 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6823 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6824 vmx_set_rvi(max_irr);
6825 else if (got_posted_interrupt)
6826 kvm_make_request(KVM_REQ_EVENT, vcpu);
6831 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6833 if (!kvm_vcpu_apicv_active(vcpu))
6836 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6837 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6838 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6839 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6842 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6844 struct vcpu_vmx *vmx = to_vmx(vcpu);
6846 pi_clear_on(&vmx->pi_desc);
6847 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6850 void vmx_do_interrupt_irqoff(unsigned long entry);
6851 void vmx_do_nmi_irqoff(void);
6853 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6856 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6857 * MSR value is not clobbered by the host activity before the guest
6858 * has chance to consume it.
6860 * Do not blindly read xfd_err here, since this exception might
6861 * be caused by L1 interception on a platform which doesn't
6862 * support xfd at all.
6864 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6865 * only when xfd contains a non-zero value.
6867 * Queuing exception is done in vmx_handle_exit. See comment there.
6869 if (vcpu->arch.guest_fpu.fpstate->xfd)
6870 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6873 static void handle_exception_irqoff(struct vcpu_vmx *vmx)
6875 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6877 /* if exit due to PF check for async PF */
6878 if (is_page_fault(intr_info))
6879 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6880 /* if exit due to NM, handle before interrupts are enabled */
6881 else if (is_nm_fault(intr_info))
6882 handle_nm_fault_irqoff(&vmx->vcpu);
6883 /* Handle machine checks before interrupts are enabled */
6884 else if (is_machine_check(intr_info))
6885 kvm_machine_check();
6888 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6890 u32 intr_info = vmx_get_intr_info(vcpu);
6891 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6892 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6894 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6895 "unexpected VM-Exit interrupt info: 0x%x", intr_info))
6898 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
6899 vmx_do_interrupt_irqoff(gate_offset(desc));
6900 kvm_after_interrupt(vcpu);
6902 vcpu->arch.at_instruction_boundary = true;
6905 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6907 struct vcpu_vmx *vmx = to_vmx(vcpu);
6909 if (vmx->emulation_required)
6912 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6913 handle_external_interrupt_irqoff(vcpu);
6914 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6915 handle_exception_irqoff(vmx);
6919 * The kvm parameter can be NULL (module initialization, or invocation before
6920 * VM creation). Be sure to check the kvm parameter before using it.
6922 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6925 case MSR_IA32_SMBASE:
6926 if (!IS_ENABLED(CONFIG_KVM_SMM))
6929 * We cannot do SMM unless we can run the guest in big
6932 return enable_unrestricted_guest || emulate_invalid_guest_state;
6933 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6935 case MSR_AMD64_VIRT_SPEC_CTRL:
6936 case MSR_AMD64_TSC_RATIO:
6937 /* This is AMD only. */
6944 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6949 bool idtv_info_valid;
6951 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6954 if (vmx->loaded_vmcs->nmi_known_unmasked)
6957 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6958 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6959 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6961 * SDM 3: 27.7.1.2 (September 2008)
6962 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6963 * a guest IRET fault.
6964 * SDM 3: 23.2.2 (September 2008)
6965 * Bit 12 is undefined in any of the following cases:
6966 * If the VM exit sets the valid bit in the IDT-vectoring
6967 * information field.
6968 * If the VM exit is due to a double fault.
6970 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6971 vector != DF_VECTOR && !idtv_info_valid)
6972 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6973 GUEST_INTR_STATE_NMI);
6975 vmx->loaded_vmcs->nmi_known_unmasked =
6976 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6977 & GUEST_INTR_STATE_NMI);
6978 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6979 vmx->loaded_vmcs->vnmi_blocked_time +=
6980 ktime_to_ns(ktime_sub(ktime_get(),
6981 vmx->loaded_vmcs->entry_time));
6984 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6985 u32 idt_vectoring_info,
6986 int instr_len_field,
6987 int error_code_field)
6991 bool idtv_info_valid;
6993 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6995 vcpu->arch.nmi_injected = false;
6996 kvm_clear_exception_queue(vcpu);
6997 kvm_clear_interrupt_queue(vcpu);
6999 if (!idtv_info_valid)
7002 kvm_make_request(KVM_REQ_EVENT, vcpu);
7004 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
7005 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
7008 case INTR_TYPE_NMI_INTR:
7009 vcpu->arch.nmi_injected = true;
7011 * SDM 3: 27.7.1.2 (September 2008)
7012 * Clear bit "block by NMI" before VM entry if a NMI
7015 vmx_set_nmi_mask(vcpu, false);
7017 case INTR_TYPE_SOFT_EXCEPTION:
7018 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7020 case INTR_TYPE_HARD_EXCEPTION:
7021 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
7022 u32 err = vmcs_read32(error_code_field);
7023 kvm_requeue_exception_e(vcpu, vector, err);
7025 kvm_requeue_exception(vcpu, vector);
7027 case INTR_TYPE_SOFT_INTR:
7028 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7030 case INTR_TYPE_EXT_INTR:
7031 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7038 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7040 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7041 VM_EXIT_INSTRUCTION_LEN,
7042 IDT_VECTORING_ERROR_CODE);
7045 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7047 __vmx_complete_interrupts(vcpu,
7048 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7049 VM_ENTRY_INSTRUCTION_LEN,
7050 VM_ENTRY_EXCEPTION_ERROR_CODE);
7052 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7055 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7058 struct perf_guest_switch_msr *msrs;
7059 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
7061 pmu->host_cross_mapped_mask = 0;
7062 if (pmu->pebs_enable & pmu->global_ctrl)
7063 intel_pmu_cross_mapped_check(pmu);
7065 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
7066 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
7070 for (i = 0; i < nr_msrs; i++)
7071 if (msrs[i].host == msrs[i].guest)
7072 clear_atomic_switch_msr(vmx, msrs[i].msr);
7074 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7075 msrs[i].host, false);
7078 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
7080 struct vcpu_vmx *vmx = to_vmx(vcpu);
7084 if (vmx->req_immediate_exit) {
7085 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
7086 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7087 } else if (vmx->hv_deadline_tsc != -1) {
7089 if (vmx->hv_deadline_tsc > tscl)
7090 /* set_hv_timer ensures the delta fits in 32-bits */
7091 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
7092 cpu_preemption_timer_multi);
7096 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7097 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7098 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7099 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7100 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7104 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7106 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7107 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7108 vmcs_writel(HOST_RSP, host_rsp);
7112 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7115 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7117 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7120 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7121 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7124 * If the guest/host SPEC_CTRL values differ, restore the host value.
7126 * For legacy IBRS, the IBRS bit always needs to be written after
7127 * transitioning from a less privileged predictor mode, regardless of
7128 * whether the guest/host values differ.
7130 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7131 vmx->spec_ctrl != hostval)
7132 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7137 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
7139 switch (to_vmx(vcpu)->exit_reason.basic) {
7140 case EXIT_REASON_MSR_WRITE:
7141 return handle_fastpath_set_msr_irqoff(vcpu);
7142 case EXIT_REASON_PREEMPTION_TIMER:
7143 return handle_fastpath_preemption_timer(vcpu);
7145 return EXIT_FASTPATH_NONE;
7149 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7152 struct vcpu_vmx *vmx = to_vmx(vcpu);
7154 guest_state_enter_irqoff();
7156 /* L1D Flush includes CPU buffer clear to mitigate MDS */
7157 if (static_branch_unlikely(&vmx_l1d_should_flush))
7158 vmx_l1d_flush(vcpu);
7159 else if (static_branch_unlikely(&mds_user_clear))
7160 mds_clear_cpu_buffers();
7161 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7162 kvm_arch_has_assigned_device(vcpu->kvm))
7163 mds_clear_cpu_buffers();
7165 vmx_disable_fb_clear(vmx);
7167 if (vcpu->arch.cr2 != native_read_cr2())
7168 native_write_cr2(vcpu->arch.cr2);
7170 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7173 vcpu->arch.cr2 = native_read_cr2();
7175 vmx_enable_fb_clear(vmx);
7177 if (unlikely(vmx->fail))
7178 vmx->exit_reason.full = 0xdead;
7180 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7182 if ((u16)vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
7183 is_nmi(vmx_get_intr_info(vcpu))) {
7184 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
7185 vmx_do_nmi_irqoff();
7186 kvm_after_interrupt(vcpu);
7189 guest_state_exit_irqoff();
7192 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
7194 struct vcpu_vmx *vmx = to_vmx(vcpu);
7195 unsigned long cr3, cr4;
7197 /* Record the guest's net vcpu time for enforced NMI injections. */
7198 if (unlikely(!enable_vnmi &&
7199 vmx->loaded_vmcs->soft_vnmi_blocked))
7200 vmx->loaded_vmcs->entry_time = ktime_get();
7203 * Don't enter VMX if guest state is invalid, let the exit handler
7204 * start emulation until we arrive back to a valid state. Synthesize a
7205 * consistency check VM-Exit due to invalid guest state and bail.
7207 if (unlikely(vmx->emulation_required)) {
7210 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7211 vmx->exit_reason.failed_vmentry = 1;
7212 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7213 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7214 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7215 vmx->exit_intr_info = 0;
7216 return EXIT_FASTPATH_NONE;
7219 trace_kvm_entry(vcpu);
7221 if (vmx->ple_window_dirty) {
7222 vmx->ple_window_dirty = false;
7223 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7227 * We did this in prepare_switch_to_guest, because it needs to
7228 * be within srcu_read_lock.
7230 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7232 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7233 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7234 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7235 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7236 vcpu->arch.regs_dirty = 0;
7239 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
7240 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7241 * it switches back to the current->mm, which can occur in KVM context
7242 * when switching to a temporary mm to patch kernel code, e.g. if KVM
7243 * toggles a static key while handling a VM-Exit.
7245 cr3 = __get_current_cr3_fast();
7246 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7247 vmcs_writel(HOST_CR3, cr3);
7248 vmx->loaded_vmcs->host_state.cr3 = cr3;
7251 cr4 = cr4_read_shadow();
7252 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7253 vmcs_writel(HOST_CR4, cr4);
7254 vmx->loaded_vmcs->host_state.cr4 = cr4;
7257 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
7258 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
7259 set_debugreg(vcpu->arch.dr6, 6);
7261 /* When single-stepping over STI and MOV SS, we must clear the
7262 * corresponding interruptibility bits in the guest state. Otherwise
7263 * vmentry fails as it then expects bit 14 (BS) in pending debug
7264 * exceptions being set, but that's not correct for the guest debugging
7266 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7267 vmx_set_interrupt_shadow(vcpu, 0);
7269 kvm_load_guest_xsave_state(vcpu);
7271 pt_guest_enter(vmx);
7273 atomic_switch_perf_msrs(vmx);
7274 if (intel_pmu_lbr_is_enabled(vcpu))
7275 vmx_passthrough_lbr_msrs(vcpu);
7277 if (enable_preemption_timer)
7278 vmx_update_hv_timer(vcpu);
7280 kvm_wait_lapic_expire(vcpu);
7282 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7283 vmx_vcpu_enter_exit(vcpu, __vmx_vcpu_run_flags(vmx));
7285 /* All fields are clean at this point */
7286 if (kvm_is_using_evmcs()) {
7287 current_evmcs->hv_clean_fields |=
7288 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7290 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7293 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7294 if (vmx->host_debugctlmsr)
7295 update_debugctlmsr(vmx->host_debugctlmsr);
7297 #ifndef CONFIG_X86_64
7299 * The sysexit path does not restore ds/es, so we must set them to
7300 * a reasonable value ourselves.
7302 * We can't defer this to vmx_prepare_switch_to_host() since that
7303 * function may be executed in interrupt context, which saves and
7304 * restore segments around it, nullifying its effect.
7306 loadsegment(ds, __USER_DS);
7307 loadsegment(es, __USER_DS);
7310 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7314 kvm_load_host_xsave_state(vcpu);
7316 if (is_guest_mode(vcpu)) {
7318 * Track VMLAUNCH/VMRESUME that have made past guest state
7321 if (vmx->nested.nested_run_pending &&
7322 !vmx->exit_reason.failed_vmentry)
7323 ++vcpu->stat.nested_run;
7325 vmx->nested.nested_run_pending = 0;
7328 vmx->idt_vectoring_info = 0;
7330 if (unlikely(vmx->fail))
7331 return EXIT_FASTPATH_NONE;
7333 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7334 kvm_machine_check();
7336 if (likely(!vmx->exit_reason.failed_vmentry))
7337 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7339 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7341 if (unlikely(vmx->exit_reason.failed_vmentry))
7342 return EXIT_FASTPATH_NONE;
7344 vmx->loaded_vmcs->launched = 1;
7346 vmx_recover_nmi_blocking(vmx);
7347 vmx_complete_interrupts(vmx);
7349 if (is_guest_mode(vcpu))
7350 return EXIT_FASTPATH_NONE;
7352 return vmx_exit_handlers_fastpath(vcpu);
7355 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7357 struct vcpu_vmx *vmx = to_vmx(vcpu);
7360 vmx_destroy_pml_buffer(vmx);
7361 free_vpid(vmx->vpid);
7362 nested_vmx_free_vcpu(vcpu);
7363 free_loaded_vmcs(vmx->loaded_vmcs);
7366 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7368 struct vmx_uret_msr *tsx_ctrl;
7369 struct vcpu_vmx *vmx;
7372 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7375 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7379 vmx->vpid = allocate_vpid();
7382 * If PML is turned on, failure on enabling PML just results in failure
7383 * of creating the vcpu, therefore we can simplify PML logic (by
7384 * avoiding dealing with cases, such as enabling PML partially on vcpus
7385 * for the guest), etc.
7388 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7393 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7394 vmx->guest_uret_msrs[i].mask = -1ull;
7395 if (boot_cpu_has(X86_FEATURE_RTM)) {
7397 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7398 * Keep the host value unchanged to avoid changing CPUID bits
7399 * under the host kernel's feet.
7401 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7403 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7406 err = alloc_loaded_vmcs(&vmx->vmcs01);
7411 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7412 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7413 * feature only for vmcs01, KVM currently isn't equipped to realize any
7414 * performance benefits from enabling it for vmcs02.
7416 if (kvm_is_using_evmcs() &&
7417 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7418 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7420 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7423 /* The MSR bitmap starts with all ones */
7424 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7425 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7427 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7428 #ifdef CONFIG_X86_64
7429 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7430 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7431 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7433 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7434 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7435 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7436 if (kvm_cstate_in_guest(vcpu->kvm)) {
7437 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7438 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7439 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7440 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7443 vmx->loaded_vmcs = &vmx->vmcs01;
7445 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7446 err = kvm_alloc_apic_access_page(vcpu->kvm);
7451 if (enable_ept && !enable_unrestricted_guest) {
7452 err = init_rmode_identity_map(vcpu->kvm);
7457 if (vmx_can_use_ipiv(vcpu))
7458 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7459 __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7464 free_loaded_vmcs(vmx->loaded_vmcs);
7466 vmx_destroy_pml_buffer(vmx);
7468 free_vpid(vmx->vpid);
7472 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7473 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7475 static int vmx_vm_init(struct kvm *kvm)
7478 kvm->arch.pause_in_guest = true;
7480 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7481 switch (l1tf_mitigation) {
7482 case L1TF_MITIGATION_OFF:
7483 case L1TF_MITIGATION_FLUSH_NOWARN:
7484 /* 'I explicitly don't care' is set */
7486 case L1TF_MITIGATION_FLUSH:
7487 case L1TF_MITIGATION_FLUSH_NOSMT:
7488 case L1TF_MITIGATION_FULL:
7490 * Warn upon starting the first VM in a potentially
7491 * insecure environment.
7493 if (sched_smt_active())
7494 pr_warn_once(L1TF_MSG_SMT);
7495 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7496 pr_warn_once(L1TF_MSG_L1D);
7498 case L1TF_MITIGATION_FULL_FORCE:
7499 /* Flush is enforced */
7506 static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7510 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7511 * memory aliases with conflicting memory types and sometimes MCEs.
7512 * We have to be careful as to what are honored and when.
7514 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7515 * UC. The effective memory type is UC or WC depending on guest PAT.
7516 * This was historically the source of MCEs and we want to be
7519 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7520 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7521 * EPT memory type is set to WB. The effective memory type is forced
7524 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7525 * EPT memory type is used to emulate guest CD/MTRR.
7529 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7531 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7532 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7534 if (kvm_read_cr0_bits(vcpu, X86_CR0_CD)) {
7535 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7536 cache = MTRR_TYPE_WRBACK;
7538 cache = MTRR_TYPE_UNCACHABLE;
7540 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7543 return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7546 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7549 * These bits in the secondary execution controls field
7550 * are dynamic, the others are mostly based on the hypervisor
7551 * architecture and the guest's CPUID. Do not touch the
7555 SECONDARY_EXEC_SHADOW_VMCS |
7556 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7557 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7558 SECONDARY_EXEC_DESC;
7560 u32 cur_ctl = secondary_exec_controls_get(vmx);
7562 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7566 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7567 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7569 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7571 struct vcpu_vmx *vmx = to_vmx(vcpu);
7572 struct kvm_cpuid_entry2 *entry;
7574 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7575 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7577 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7578 if (entry && (entry->_reg & (_cpuid_mask))) \
7579 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7582 entry = kvm_find_cpuid_entry(vcpu, 0x1);
7583 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7584 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7585 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7586 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7587 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7588 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7589 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7590 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7591 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7592 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7593 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7594 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7595 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7596 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7598 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7599 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7600 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7601 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7602 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7603 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7604 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7606 #undef cr4_fixed1_update
7609 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7611 struct vcpu_vmx *vmx = to_vmx(vcpu);
7612 struct kvm_cpuid_entry2 *best = NULL;
7615 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7616 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7619 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7620 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7621 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7622 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7625 /* Get the number of configurable Address Ranges for filtering */
7626 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7627 PT_CAP_num_address_ranges);
7629 /* Initialize and clear the no dependency bits */
7630 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7631 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7632 RTIT_CTL_BRANCH_EN);
7635 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7636 * will inject an #GP
7638 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7639 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7642 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7643 * PSBFreq can be set
7645 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7646 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7647 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7650 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7652 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7653 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7654 RTIT_CTL_MTC_RANGE);
7656 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7657 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7658 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7661 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7662 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7663 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7665 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7666 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7667 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7669 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7670 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7671 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7673 /* unmask address range configure area */
7674 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7675 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7678 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7680 struct vcpu_vmx *vmx = to_vmx(vcpu);
7682 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7683 vcpu->arch.xsaves_enabled = false;
7685 vmx_setup_uret_msrs(vmx);
7687 if (cpu_has_secondary_exec_ctrls())
7688 vmcs_set_secondary_exec_control(vmx,
7689 vmx_secondary_exec_control(vmx));
7691 if (nested_vmx_allowed(vcpu))
7692 vmx->msr_ia32_feature_control_valid_bits |=
7693 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7694 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7696 vmx->msr_ia32_feature_control_valid_bits &=
7697 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7698 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7700 if (nested_vmx_allowed(vcpu))
7701 nested_vmx_cr_fixed1_bits_update(vcpu);
7703 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7704 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7705 update_intel_pt_cfg(vcpu);
7707 if (boot_cpu_has(X86_FEATURE_RTM)) {
7708 struct vmx_uret_msr *msr;
7709 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7711 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7712 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7716 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7717 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7718 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7720 if (boot_cpu_has(X86_FEATURE_IBPB))
7721 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W,
7722 !guest_has_pred_cmd_msr(vcpu));
7724 if (boot_cpu_has(X86_FEATURE_FLUSH_L1D))
7725 vmx_set_intercept_for_msr(vcpu, MSR_IA32_FLUSH_CMD, MSR_TYPE_W,
7726 !guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D));
7728 set_cr4_guest_host_mask(vmx);
7730 vmx_write_encls_bitmap(vcpu, NULL);
7731 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7732 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7734 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7736 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7737 vmx->msr_ia32_feature_control_valid_bits |=
7738 FEAT_CTL_SGX_LC_ENABLED;
7740 vmx->msr_ia32_feature_control_valid_bits &=
7741 ~FEAT_CTL_SGX_LC_ENABLED;
7743 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7744 vmx_update_exception_bitmap(vcpu);
7747 static u64 vmx_get_perf_capabilities(void)
7749 u64 perf_cap = PMU_CAP_FW_WRITES;
7750 struct x86_pmu_lbr lbr;
7751 u64 host_perf_cap = 0;
7756 if (boot_cpu_has(X86_FEATURE_PDCM))
7757 rdmsrl(MSR_IA32_PERF_CAPABILITIES, host_perf_cap);
7759 x86_perf_get_lbr(&lbr);
7761 perf_cap |= host_perf_cap & PMU_CAP_LBR_FMT;
7763 if (vmx_pebs_supported()) {
7764 perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK;
7765 if ((perf_cap & PERF_CAP_PEBS_FORMAT) < 4)
7766 perf_cap &= ~PERF_CAP_PEBS_BASELINE;
7772 static __init void vmx_set_cpu_caps(void)
7778 kvm_cpu_cap_set(X86_FEATURE_VMX);
7781 if (kvm_mpx_supported())
7782 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7783 if (!cpu_has_vmx_invpcid())
7784 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7785 if (vmx_pt_mode_is_host_guest())
7786 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7787 if (vmx_pebs_supported()) {
7788 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7789 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7793 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7794 kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
7797 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7798 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7799 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7800 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7803 if (vmx_umip_emulated())
7804 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7807 kvm_caps.supported_xss = 0;
7808 if (!cpu_has_vmx_xsaves())
7809 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7811 /* CPUID 0x80000001 and 0x7 (RDPID) */
7812 if (!cpu_has_vmx_rdtscp()) {
7813 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7814 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7817 if (cpu_has_vmx_waitpkg())
7818 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7821 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7823 to_vmx(vcpu)->req_immediate_exit = true;
7826 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7827 struct x86_instruction_info *info)
7829 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7830 unsigned short port;
7834 if (info->intercept == x86_intercept_in ||
7835 info->intercept == x86_intercept_ins) {
7836 port = info->src_val;
7837 size = info->dst_bytes;
7839 port = info->dst_val;
7840 size = info->src_bytes;
7844 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7845 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7848 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7850 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7851 intercept = nested_cpu_has(vmcs12,
7852 CPU_BASED_UNCOND_IO_EXITING);
7854 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7856 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7857 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7860 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7861 struct x86_instruction_info *info,
7862 enum x86_intercept_stage stage,
7863 struct x86_exception *exception)
7865 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7867 switch (info->intercept) {
7869 * RDPID causes #UD if disabled through secondary execution controls.
7870 * Because it is marked as EmulateOnUD, we need to intercept it here.
7871 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7873 case x86_intercept_rdpid:
7874 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7875 exception->vector = UD_VECTOR;
7876 exception->error_code_valid = false;
7877 return X86EMUL_PROPAGATE_FAULT;
7881 case x86_intercept_in:
7882 case x86_intercept_ins:
7883 case x86_intercept_out:
7884 case x86_intercept_outs:
7885 return vmx_check_intercept_io(vcpu, info);
7887 case x86_intercept_lgdt:
7888 case x86_intercept_lidt:
7889 case x86_intercept_lldt:
7890 case x86_intercept_ltr:
7891 case x86_intercept_sgdt:
7892 case x86_intercept_sidt:
7893 case x86_intercept_sldt:
7894 case x86_intercept_str:
7895 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7896 return X86EMUL_CONTINUE;
7898 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7901 /* TODO: check more intercepts... */
7906 return X86EMUL_UNHANDLEABLE;
7909 #ifdef CONFIG_X86_64
7910 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7911 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7912 u64 divisor, u64 *result)
7914 u64 low = a << shift, high = a >> (64 - shift);
7916 /* To avoid the overflow on divq */
7917 if (high >= divisor)
7920 /* Low hold the result, high hold rem which is discarded */
7921 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7922 "rm" (divisor), "0" (low), "1" (high));
7928 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7931 struct vcpu_vmx *vmx;
7932 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7933 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7937 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7938 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7939 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7940 ktimer->timer_advance_ns);
7942 if (delta_tsc > lapic_timer_advance_cycles)
7943 delta_tsc -= lapic_timer_advance_cycles;
7947 /* Convert to host delta tsc if tsc scaling is enabled */
7948 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
7949 delta_tsc && u64_shl_div_u64(delta_tsc,
7950 kvm_caps.tsc_scaling_ratio_frac_bits,
7951 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7955 * If the delta tsc can't fit in the 32 bit after the multi shift,
7956 * we can't use the preemption timer.
7957 * It's possible that it fits on later vmentries, but checking
7958 * on every vmentry is costly so we just use an hrtimer.
7960 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7963 vmx->hv_deadline_tsc = tscl + delta_tsc;
7964 *expired = !delta_tsc;
7968 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7970 to_vmx(vcpu)->hv_deadline_tsc = -1;
7974 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7976 if (!kvm_pause_in_guest(vcpu->kvm))
7977 shrink_ple_window(vcpu);
7980 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7982 struct vcpu_vmx *vmx = to_vmx(vcpu);
7984 if (WARN_ON_ONCE(!enable_pml))
7987 if (is_guest_mode(vcpu)) {
7988 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7993 * Note, nr_memslots_dirty_logging can be changed concurrent with this
7994 * code, but in that case another update request will be made and so
7995 * the guest will never run with a stale PML value.
7997 if (atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
7998 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8000 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8003 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
8005 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
8006 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
8007 FEAT_CTL_LMCE_ENABLED;
8009 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
8010 ~FEAT_CTL_LMCE_ENABLED;
8013 #ifdef CONFIG_KVM_SMM
8014 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
8016 /* we need a nested vmexit to enter SMM, postpone if run is pending */
8017 if (to_vmx(vcpu)->nested.nested_run_pending)
8019 return !is_smm(vcpu);
8022 static int vmx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
8024 struct vcpu_vmx *vmx = to_vmx(vcpu);
8027 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
8028 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
8029 * SMI and RSM only modify state that is saved and restored via SMRAM.
8030 * E.g. most MSRs are left untouched, but many are modified by VM-Exit
8031 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
8033 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
8034 if (vmx->nested.smm.guest_mode)
8035 nested_vmx_vmexit(vcpu, -1, 0, 0);
8037 vmx->nested.smm.vmxon = vmx->nested.vmxon;
8038 vmx->nested.vmxon = false;
8039 vmx_clear_hlt(vcpu);
8043 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
8045 struct vcpu_vmx *vmx = to_vmx(vcpu);
8048 if (vmx->nested.smm.vmxon) {
8049 vmx->nested.vmxon = true;
8050 vmx->nested.smm.vmxon = false;
8053 if (vmx->nested.smm.guest_mode) {
8054 ret = nested_vmx_enter_non_root_mode(vcpu, false);
8058 vmx->nested.nested_run_pending = 1;
8059 vmx->nested.smm.guest_mode = false;
8064 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
8066 /* RSM will cause a vmexit anyway. */
8070 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
8072 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
8075 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
8077 if (is_guest_mode(vcpu)) {
8078 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
8080 if (hrtimer_try_to_cancel(timer) == 1)
8081 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
8085 static void vmx_hardware_unsetup(void)
8087 kvm_set_posted_intr_wakeup_handler(NULL);
8090 nested_vmx_hardware_unsetup();
8095 #define VMX_REQUIRED_APICV_INHIBITS \
8097 BIT(APICV_INHIBIT_REASON_DISABLE)| \
8098 BIT(APICV_INHIBIT_REASON_ABSENT) | \
8099 BIT(APICV_INHIBIT_REASON_HYPERV) | \
8100 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) | \
8101 BIT(APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED) | \
8102 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) | \
8103 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED) \
8106 static void vmx_vm_destroy(struct kvm *kvm)
8108 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
8110 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
8113 static struct kvm_x86_ops vmx_x86_ops __initdata = {
8114 .name = KBUILD_MODNAME,
8116 .check_processor_compatibility = vmx_check_processor_compat,
8118 .hardware_unsetup = vmx_hardware_unsetup,
8120 .hardware_enable = vmx_hardware_enable,
8121 .hardware_disable = vmx_hardware_disable,
8122 .has_emulated_msr = vmx_has_emulated_msr,
8124 .vm_size = sizeof(struct kvm_vmx),
8125 .vm_init = vmx_vm_init,
8126 .vm_destroy = vmx_vm_destroy,
8128 .vcpu_precreate = vmx_vcpu_precreate,
8129 .vcpu_create = vmx_vcpu_create,
8130 .vcpu_free = vmx_vcpu_free,
8131 .vcpu_reset = vmx_vcpu_reset,
8133 .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
8134 .vcpu_load = vmx_vcpu_load,
8135 .vcpu_put = vmx_vcpu_put,
8137 .update_exception_bitmap = vmx_update_exception_bitmap,
8138 .get_msr_feature = vmx_get_msr_feature,
8139 .get_msr = vmx_get_msr,
8140 .set_msr = vmx_set_msr,
8141 .get_segment_base = vmx_get_segment_base,
8142 .get_segment = vmx_get_segment,
8143 .set_segment = vmx_set_segment,
8144 .get_cpl = vmx_get_cpl,
8145 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8146 .set_cr0 = vmx_set_cr0,
8147 .is_valid_cr4 = vmx_is_valid_cr4,
8148 .set_cr4 = vmx_set_cr4,
8149 .set_efer = vmx_set_efer,
8150 .get_idt = vmx_get_idt,
8151 .set_idt = vmx_set_idt,
8152 .get_gdt = vmx_get_gdt,
8153 .set_gdt = vmx_set_gdt,
8154 .set_dr7 = vmx_set_dr7,
8155 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8156 .cache_reg = vmx_cache_reg,
8157 .get_rflags = vmx_get_rflags,
8158 .set_rflags = vmx_set_rflags,
8159 .get_if_flag = vmx_get_if_flag,
8161 .flush_tlb_all = vmx_flush_tlb_all,
8162 .flush_tlb_current = vmx_flush_tlb_current,
8163 .flush_tlb_gva = vmx_flush_tlb_gva,
8164 .flush_tlb_guest = vmx_flush_tlb_guest,
8166 .vcpu_pre_run = vmx_vcpu_pre_run,
8167 .vcpu_run = vmx_vcpu_run,
8168 .handle_exit = vmx_handle_exit,
8169 .skip_emulated_instruction = vmx_skip_emulated_instruction,
8170 .update_emulated_instruction = vmx_update_emulated_instruction,
8171 .set_interrupt_shadow = vmx_set_interrupt_shadow,
8172 .get_interrupt_shadow = vmx_get_interrupt_shadow,
8173 .patch_hypercall = vmx_patch_hypercall,
8174 .inject_irq = vmx_inject_irq,
8175 .inject_nmi = vmx_inject_nmi,
8176 .inject_exception = vmx_inject_exception,
8177 .cancel_injection = vmx_cancel_injection,
8178 .interrupt_allowed = vmx_interrupt_allowed,
8179 .nmi_allowed = vmx_nmi_allowed,
8180 .get_nmi_mask = vmx_get_nmi_mask,
8181 .set_nmi_mask = vmx_set_nmi_mask,
8182 .enable_nmi_window = vmx_enable_nmi_window,
8183 .enable_irq_window = vmx_enable_irq_window,
8184 .update_cr8_intercept = vmx_update_cr8_intercept,
8185 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
8186 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
8187 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
8188 .load_eoi_exitmap = vmx_load_eoi_exitmap,
8189 .apicv_post_state_restore = vmx_apicv_post_state_restore,
8190 .required_apicv_inhibits = VMX_REQUIRED_APICV_INHIBITS,
8191 .hwapic_irr_update = vmx_hwapic_irr_update,
8192 .hwapic_isr_update = vmx_hwapic_isr_update,
8193 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
8194 .sync_pir_to_irr = vmx_sync_pir_to_irr,
8195 .deliver_interrupt = vmx_deliver_interrupt,
8196 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
8198 .set_tss_addr = vmx_set_tss_addr,
8199 .set_identity_map_addr = vmx_set_identity_map_addr,
8200 .get_mt_mask = vmx_get_mt_mask,
8202 .get_exit_info = vmx_get_exit_info,
8204 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
8206 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8208 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
8209 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
8210 .write_tsc_offset = vmx_write_tsc_offset,
8211 .write_tsc_multiplier = vmx_write_tsc_multiplier,
8213 .load_mmu_pgd = vmx_load_mmu_pgd,
8215 .check_intercept = vmx_check_intercept,
8216 .handle_exit_irqoff = vmx_handle_exit_irqoff,
8218 .request_immediate_exit = vmx_request_immediate_exit,
8220 .sched_in = vmx_sched_in,
8222 .cpu_dirty_log_size = PML_ENTITY_NUM,
8223 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
8225 .nested_ops = &vmx_nested_ops,
8227 .pi_update_irte = vmx_pi_update_irte,
8228 .pi_start_assignment = vmx_pi_start_assignment,
8230 #ifdef CONFIG_X86_64
8231 .set_hv_timer = vmx_set_hv_timer,
8232 .cancel_hv_timer = vmx_cancel_hv_timer,
8235 .setup_mce = vmx_setup_mce,
8237 #ifdef CONFIG_KVM_SMM
8238 .smi_allowed = vmx_smi_allowed,
8239 .enter_smm = vmx_enter_smm,
8240 .leave_smm = vmx_leave_smm,
8241 .enable_smi_window = vmx_enable_smi_window,
8244 .can_emulate_instruction = vmx_can_emulate_instruction,
8245 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8246 .migrate_timers = vmx_migrate_timers,
8248 .msr_filter_changed = vmx_msr_filter_changed,
8249 .complete_emulated_msr = kvm_complete_insn_gp,
8251 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
8254 static unsigned int vmx_handle_intel_pt_intr(void)
8256 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8258 /* '0' on failure so that the !PT case can use a RET0 static call. */
8259 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8262 kvm_make_request(KVM_REQ_PMI, vcpu);
8263 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8264 (unsigned long *)&vcpu->arch.pmu.global_status);
8268 static __init void vmx_setup_user_return_msrs(void)
8272 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8273 * will emulate SYSCALL in legacy mode if the vendor string in guest
8274 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8275 * support this emulation, MSR_STAR is included in the list for i386,
8276 * but is never loaded into hardware. MSR_CSTAR is also never loaded
8277 * into hardware and is here purely for emulation purposes.
8279 const u32 vmx_uret_msrs_list[] = {
8280 #ifdef CONFIG_X86_64
8281 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8283 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8288 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8290 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8291 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8294 static void __init vmx_setup_me_spte_mask(void)
8299 * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
8300 * the former to avoid exposing shadow_phys_bits.
8302 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8303 * shadow_phys_bits. On MKTME and/or TDX capable systems,
8304 * boot_cpu_data.x86_phys_bits holds the actual physical address
8305 * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
8306 * reported by CPUID. Those bits between are KeyID bits.
8308 if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
8309 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8310 kvm_get_shadow_phys_bits() - 1);
8312 * Unlike SME, host kernel doesn't support setting up any
8313 * MKTME KeyID on Intel platforms. No memory encryption
8314 * bits should be included into the SPTE.
8316 kvm_mmu_set_me_spte_mask(0, me_mask);
8319 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8321 static __init int hardware_setup(void)
8323 unsigned long host_bndcfgs;
8328 host_idt_base = dt.address;
8330 vmx_setup_user_return_msrs();
8332 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8335 if (cpu_has_perf_global_ctrl_bug())
8336 pr_warn_once("VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8337 "does not work properly. Using workaround\n");
8339 if (boot_cpu_has(X86_FEATURE_NX))
8340 kvm_enable_efer_bits(EFER_NX);
8342 if (boot_cpu_has(X86_FEATURE_MPX)) {
8343 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8344 WARN_ONCE(host_bndcfgs, "BNDCFGS in host will be lost");
8347 if (!cpu_has_vmx_mpx())
8348 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8349 XFEATURE_MASK_BNDCSR);
8351 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8352 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8355 if (!cpu_has_vmx_ept() ||
8356 !cpu_has_vmx_ept_4levels() ||
8357 !cpu_has_vmx_ept_mt_wb() ||
8358 !cpu_has_vmx_invept_global())
8361 /* NX support is required for shadow paging. */
8362 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8363 pr_err_ratelimited("NX (Execute Disable) not supported\n");
8367 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8368 enable_ept_ad_bits = 0;
8370 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8371 enable_unrestricted_guest = 0;
8373 if (!cpu_has_vmx_flexpriority())
8374 flexpriority_enabled = 0;
8376 if (!cpu_has_virtual_nmis())
8379 #ifdef CONFIG_X86_SGX_KVM
8380 if (!cpu_has_vmx_encls_vmexit())
8385 * set_apic_access_page_addr() is used to reload apic access
8386 * page upon invalidation. No need to do anything if not
8387 * using the APIC_ACCESS_ADDR VMCS field.
8389 if (!flexpriority_enabled)
8390 vmx_x86_ops.set_apic_access_page_addr = NULL;
8392 if (!cpu_has_vmx_tpr_shadow())
8393 vmx_x86_ops.update_cr8_intercept = NULL;
8395 #if IS_ENABLED(CONFIG_HYPERV)
8396 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8398 vmx_x86_ops.flush_remote_tlbs = hv_flush_remote_tlbs;
8399 vmx_x86_ops.flush_remote_tlbs_range = hv_flush_remote_tlbs_range;
8403 if (!cpu_has_vmx_ple()) {
8406 ple_window_grow = 0;
8408 ple_window_shrink = 0;
8411 if (!cpu_has_vmx_apicv())
8414 vmx_x86_ops.sync_pir_to_irr = NULL;
8416 if (!enable_apicv || !cpu_has_vmx_ipiv())
8417 enable_ipiv = false;
8419 if (cpu_has_vmx_tsc_scaling())
8420 kvm_caps.has_tsc_control = true;
8422 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8423 kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8424 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8425 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8427 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8430 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8431 cpu_has_vmx_ept_execute_only());
8434 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8435 * bits to shadow_zero_check.
8437 vmx_setup_me_spte_mask();
8439 kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
8440 ept_caps_to_lpage_level(vmx_capability.ept));
8443 * Only enable PML when hardware supports PML feature, and both EPT
8444 * and EPT A/D bit features are enabled -- PML depends on them to work.
8446 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8450 vmx_x86_ops.cpu_dirty_log_size = 0;
8452 if (!cpu_has_vmx_preemption_timer())
8453 enable_preemption_timer = false;
8455 if (enable_preemption_timer) {
8456 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8458 cpu_preemption_timer_multi =
8459 vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8462 use_timer_freq = (u64)tsc_khz * 1000;
8463 use_timer_freq >>= cpu_preemption_timer_multi;
8466 * KVM "disables" the preemption timer by setting it to its max
8467 * value. Don't use the timer if it might cause spurious exits
8468 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8470 if (use_timer_freq > 0xffffffffu / 10)
8471 enable_preemption_timer = false;
8474 if (!enable_preemption_timer) {
8475 vmx_x86_ops.set_hv_timer = NULL;
8476 vmx_x86_ops.cancel_hv_timer = NULL;
8477 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8480 kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8481 kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8483 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8485 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8486 pt_mode = PT_MODE_SYSTEM;
8487 if (pt_mode == PT_MODE_HOST_GUEST)
8488 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8490 vmx_init_ops.handle_intel_pt_intr = NULL;
8492 setup_default_sgx_lepubkeyhash();
8495 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8497 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8504 r = alloc_kvm_area();
8506 nested_vmx_hardware_unsetup();
8508 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8513 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8514 .hardware_setup = hardware_setup,
8515 .handle_intel_pt_intr = NULL,
8517 .runtime_ops = &vmx_x86_ops,
8518 .pmu_ops = &intel_pmu_ops,
8521 static void vmx_cleanup_l1d_flush(void)
8523 if (vmx_l1d_flush_pages) {
8524 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8525 vmx_l1d_flush_pages = NULL;
8527 /* Restore state so sysfs ignores VMX */
8528 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8531 static void __vmx_exit(void)
8533 allow_smaller_maxphyaddr = false;
8535 #ifdef CONFIG_KEXEC_CORE
8536 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8539 vmx_cleanup_l1d_flush();
8542 static void vmx_exit(void)
8545 kvm_x86_vendor_exit();
8549 module_exit(vmx_exit);
8551 static int __init vmx_init(void)
8555 if (!kvm_is_vmx_supported())
8559 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
8560 * to unwind if a later step fails.
8564 r = kvm_x86_vendor_init(&vmx_init_ops);
8569 * Must be called after common x86 init so enable_ept is properly set
8570 * up. Hand the parameter mitigation value in which was stored in
8571 * the pre module init parser. If no parameter was given, it will
8572 * contain 'auto' which will be turned into the default 'cond'
8575 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8579 vmx_setup_fb_clear_ctrl();
8581 for_each_possible_cpu(cpu) {
8582 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8587 #ifdef CONFIG_KEXEC_CORE
8588 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8589 crash_vmclear_local_loaded_vmcss);
8591 vmx_check_vmcs12_offsets();
8594 * Shadow paging doesn't have a (further) performance penalty
8595 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8599 allow_smaller_maxphyaddr = true;
8602 * Common KVM initialization _must_ come last, after this, /dev/kvm is
8603 * exposed to userspace!
8605 r = kvm_init(sizeof(struct vcpu_vmx), __alignof__(struct vcpu_vmx),
8615 kvm_x86_vendor_exit();
8618 module_init(vmx_init);