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>
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/api.h>
39 #include <asm/fpu/xstate.h>
40 #include <asm/idtentry.h>
42 #include <asm/irq_remapping.h>
43 #include <asm/kexec.h>
44 #include <asm/perf_event.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/mwait.h>
48 #include <asm/spec-ctrl.h>
49 #include <asm/virtext.h>
52 #include "capabilities.h"
56 #include "kvm_onhyperv.h"
58 #include "kvm_cache_regs.h"
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
74 static const struct x86_cpu_id vmx_cpu_id[] = {
75 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
78 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
81 bool __read_mostly enable_vpid = 1;
82 module_param_named(vpid, enable_vpid, bool, 0444);
84 static bool __read_mostly enable_vnmi = 1;
85 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
87 bool __read_mostly flexpriority_enabled = 1;
88 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
90 bool __read_mostly enable_ept = 1;
91 module_param_named(ept, enable_ept, bool, S_IRUGO);
93 bool __read_mostly enable_unrestricted_guest = 1;
94 module_param_named(unrestricted_guest,
95 enable_unrestricted_guest, bool, S_IRUGO);
97 bool __read_mostly enable_ept_ad_bits = 1;
98 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
100 static bool __read_mostly emulate_invalid_guest_state = true;
101 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
103 static bool __read_mostly fasteoi = 1;
104 module_param(fasteoi, bool, S_IRUGO);
106 module_param(enable_apicv, bool, S_IRUGO);
109 * If nested=1, nested virtualization is supported, i.e., guests may use
110 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
111 * use VMX instructions.
113 static bool __read_mostly nested = 1;
114 module_param(nested, bool, S_IRUGO);
116 bool __read_mostly enable_pml = 1;
117 module_param_named(pml, enable_pml, bool, S_IRUGO);
119 static bool __read_mostly dump_invalid_vmcs = 0;
120 module_param(dump_invalid_vmcs, bool, 0644);
122 #define MSR_BITMAP_MODE_X2APIC 1
123 #define MSR_BITMAP_MODE_X2APIC_APICV 2
125 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
127 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
128 static int __read_mostly cpu_preemption_timer_multi;
129 static bool __read_mostly enable_preemption_timer = 1;
131 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
134 extern bool __read_mostly allow_smaller_maxphyaddr;
135 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
137 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
138 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
139 #define KVM_VM_CR0_ALWAYS_ON \
140 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
142 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
143 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
144 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
146 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
148 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
149 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
150 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
151 RTIT_STATUS_BYTECNT))
154 * List of MSRs that can be directly passed to the guest.
155 * In addition to these x2apic and PT MSRs are handled specially.
157 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
168 MSR_IA32_SYSENTER_CS,
169 MSR_IA32_SYSENTER_ESP,
170 MSR_IA32_SYSENTER_EIP,
172 MSR_CORE_C3_RESIDENCY,
173 MSR_CORE_C6_RESIDENCY,
174 MSR_CORE_C7_RESIDENCY,
178 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
179 * ple_gap: upper bound on the amount of time between two successive
180 * executions of PAUSE in a loop. Also indicate if ple enabled.
181 * According to test, this time is usually smaller than 128 cycles.
182 * ple_window: upper bound on the amount of time a guest is allowed to execute
183 * in a PAUSE loop. Tests indicate that most spinlocks are held for
184 * less than 2^12 cycles
185 * Time is measured based on a counter that runs at the same rate as the TSC,
186 * refer SDM volume 3b section 21.6.13 & 22.1.3.
188 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
189 module_param(ple_gap, uint, 0444);
191 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
192 module_param(ple_window, uint, 0444);
194 /* Default doubles per-vcpu window every exit. */
195 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
196 module_param(ple_window_grow, uint, 0444);
198 /* Default resets per-vcpu window every exit to ple_window. */
199 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
200 module_param(ple_window_shrink, uint, 0444);
202 /* Default is to compute the maximum so we can never overflow. */
203 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
204 module_param(ple_window_max, uint, 0444);
206 /* Default is SYSTEM mode, 1 for host-guest mode */
207 int __read_mostly pt_mode = PT_MODE_SYSTEM;
208 module_param(pt_mode, int, S_IRUGO);
210 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
211 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
212 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
214 /* Storage for pre module init parameter parsing */
215 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
217 static const struct {
220 } vmentry_l1d_param[] = {
221 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
222 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
223 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
224 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
225 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
226 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
229 #define L1D_CACHE_ORDER 4
230 static void *vmx_l1d_flush_pages;
232 /* Control for disabling CPU Fill buffer clear */
233 static bool __read_mostly vmx_fb_clear_ctrl_available;
235 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
240 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
241 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
246 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
250 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
253 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
254 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
255 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
260 /* If set to auto use the default l1tf mitigation method */
261 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
262 switch (l1tf_mitigation) {
263 case L1TF_MITIGATION_OFF:
264 l1tf = VMENTER_L1D_FLUSH_NEVER;
266 case L1TF_MITIGATION_FLUSH_NOWARN:
267 case L1TF_MITIGATION_FLUSH:
268 case L1TF_MITIGATION_FLUSH_NOSMT:
269 l1tf = VMENTER_L1D_FLUSH_COND;
271 case L1TF_MITIGATION_FULL:
272 case L1TF_MITIGATION_FULL_FORCE:
273 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
276 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
277 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
280 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
281 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
283 * This allocation for vmx_l1d_flush_pages is not tied to a VM
284 * lifetime and so should not be charged to a memcg.
286 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
289 vmx_l1d_flush_pages = page_address(page);
292 * Initialize each page with a different pattern in
293 * order to protect against KSM in the nested
294 * virtualization case.
296 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
297 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
302 l1tf_vmx_mitigation = l1tf;
304 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
305 static_branch_enable(&vmx_l1d_should_flush);
307 static_branch_disable(&vmx_l1d_should_flush);
309 if (l1tf == VMENTER_L1D_FLUSH_COND)
310 static_branch_enable(&vmx_l1d_flush_cond);
312 static_branch_disable(&vmx_l1d_flush_cond);
316 static int vmentry_l1d_flush_parse(const char *s)
321 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
322 if (vmentry_l1d_param[i].for_parse &&
323 sysfs_streq(s, vmentry_l1d_param[i].option))
330 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
334 l1tf = vmentry_l1d_flush_parse(s);
338 if (!boot_cpu_has(X86_BUG_L1TF))
342 * Has vmx_init() run already? If not then this is the pre init
343 * parameter parsing. In that case just store the value and let
344 * vmx_init() do the proper setup after enable_ept has been
347 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
348 vmentry_l1d_flush_param = l1tf;
352 mutex_lock(&vmx_l1d_flush_mutex);
353 ret = vmx_setup_l1d_flush(l1tf);
354 mutex_unlock(&vmx_l1d_flush_mutex);
358 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
360 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
361 return sprintf(s, "???\n");
363 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
366 static void vmx_setup_fb_clear_ctrl(void)
370 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
371 !boot_cpu_has_bug(X86_BUG_MDS) &&
372 !boot_cpu_has_bug(X86_BUG_TAA)) {
373 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
374 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
375 vmx_fb_clear_ctrl_available = true;
379 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
383 if (!vmx->disable_fb_clear)
386 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
388 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
389 /* Cache the MSR value to avoid reading it later */
390 vmx->msr_ia32_mcu_opt_ctrl = msr;
393 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
395 if (!vmx->disable_fb_clear)
398 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
399 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
402 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
404 vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
407 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
408 * at VMEntry. Skip the MSR read/write when a guest has no use case to
411 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
412 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
413 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
414 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
415 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
416 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
417 vmx->disable_fb_clear = false;
420 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
421 .set = vmentry_l1d_flush_set,
422 .get = vmentry_l1d_flush_get,
424 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
426 static u32 vmx_segment_access_rights(struct kvm_segment *var);
428 void vmx_vmexit(void);
430 #define vmx_insn_failed(fmt...) \
433 pr_warn_ratelimited(fmt); \
436 asmlinkage void vmread_error(unsigned long field, bool fault)
439 kvm_spurious_fault();
441 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
444 noinline void vmwrite_error(unsigned long field, unsigned long value)
446 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
447 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
450 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
452 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
455 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
457 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
460 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
462 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
466 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
468 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
472 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
473 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
475 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
476 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
478 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
480 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
481 static DEFINE_SPINLOCK(vmx_vpid_lock);
483 struct vmcs_config vmcs_config;
484 struct vmx_capability vmx_capability;
486 #define VMX_SEGMENT_FIELD(seg) \
487 [VCPU_SREG_##seg] = { \
488 .selector = GUEST_##seg##_SELECTOR, \
489 .base = GUEST_##seg##_BASE, \
490 .limit = GUEST_##seg##_LIMIT, \
491 .ar_bytes = GUEST_##seg##_AR_BYTES, \
494 static const struct kvm_vmx_segment_field {
499 } kvm_vmx_segment_fields[] = {
500 VMX_SEGMENT_FIELD(CS),
501 VMX_SEGMENT_FIELD(DS),
502 VMX_SEGMENT_FIELD(ES),
503 VMX_SEGMENT_FIELD(FS),
504 VMX_SEGMENT_FIELD(GS),
505 VMX_SEGMENT_FIELD(SS),
506 VMX_SEGMENT_FIELD(TR),
507 VMX_SEGMENT_FIELD(LDTR),
510 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
512 vmx->segment_cache.bitmask = 0;
515 static unsigned long host_idt_base;
517 #if IS_ENABLED(CONFIG_HYPERV)
518 static bool __read_mostly enlightened_vmcs = true;
519 module_param(enlightened_vmcs, bool, 0444);
521 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
523 struct hv_enlightened_vmcs *evmcs;
524 struct hv_partition_assist_pg **p_hv_pa_pg =
525 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
527 * Synthetic VM-Exit is not enabled in current code and so All
528 * evmcs in singe VM shares same assist page.
531 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
536 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
538 evmcs->partition_assist_page =
540 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
541 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
546 #endif /* IS_ENABLED(CONFIG_HYPERV) */
549 * Comment's format: document - errata name - stepping - processor name.
551 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
553 static u32 vmx_preemption_cpu_tfms[] = {
554 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
556 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
557 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
558 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
560 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
562 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
563 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
565 * 320767.pdf - AAP86 - B1 -
566 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
569 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
571 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
573 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
575 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
576 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
577 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
579 /* Xeon E3-1220 V2 */
583 static inline bool cpu_has_broken_vmx_preemption_timer(void)
585 u32 eax = cpuid_eax(0x00000001), i;
587 /* Clear the reserved bits */
588 eax &= ~(0x3U << 14 | 0xfU << 28);
589 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
590 if (eax == vmx_preemption_cpu_tfms[i])
596 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
598 return flexpriority_enabled && lapic_in_kernel(vcpu);
601 static int possible_passthrough_msr_slot(u32 msr)
605 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
606 if (vmx_possible_passthrough_msrs[i] == msr)
612 static bool is_valid_passthrough_msr(u32 msr)
617 case 0x800 ... 0x8ff:
618 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
620 case MSR_IA32_RTIT_STATUS:
621 case MSR_IA32_RTIT_OUTPUT_BASE:
622 case MSR_IA32_RTIT_OUTPUT_MASK:
623 case MSR_IA32_RTIT_CR3_MATCH:
624 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
625 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
628 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
629 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
630 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
631 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
632 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
633 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
637 r = possible_passthrough_msr_slot(msr) != -ENOENT;
639 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
644 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
648 i = kvm_find_user_return_msr(msr);
650 return &vmx->guest_uret_msrs[i];
654 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
655 struct vmx_uret_msr *msr, u64 data)
657 unsigned int slot = msr - vmx->guest_uret_msrs;
660 if (msr->load_into_hardware) {
662 ret = kvm_set_user_return_msr(slot, data, msr->mask);
670 #ifdef CONFIG_KEXEC_CORE
671 static void crash_vmclear_local_loaded_vmcss(void)
673 int cpu = raw_smp_processor_id();
674 struct loaded_vmcs *v;
676 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
677 loaded_vmcss_on_cpu_link)
680 #endif /* CONFIG_KEXEC_CORE */
682 static void __loaded_vmcs_clear(void *arg)
684 struct loaded_vmcs *loaded_vmcs = arg;
685 int cpu = raw_smp_processor_id();
687 if (loaded_vmcs->cpu != cpu)
688 return; /* vcpu migration can race with cpu offline */
689 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
690 per_cpu(current_vmcs, cpu) = NULL;
692 vmcs_clear(loaded_vmcs->vmcs);
693 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
694 vmcs_clear(loaded_vmcs->shadow_vmcs);
696 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
699 * Ensure all writes to loaded_vmcs, including deleting it from its
700 * current percpu list, complete before setting loaded_vmcs->cpu to
701 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
702 * and add loaded_vmcs to its percpu list before it's deleted from this
703 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
707 loaded_vmcs->cpu = -1;
708 loaded_vmcs->launched = 0;
711 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
713 int cpu = loaded_vmcs->cpu;
716 smp_call_function_single(cpu,
717 __loaded_vmcs_clear, loaded_vmcs, 1);
720 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
724 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
726 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
727 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
728 vmx->segment_cache.bitmask = 0;
730 ret = vmx->segment_cache.bitmask & mask;
731 vmx->segment_cache.bitmask |= mask;
735 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
737 u16 *p = &vmx->segment_cache.seg[seg].selector;
739 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
740 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
744 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
746 ulong *p = &vmx->segment_cache.seg[seg].base;
748 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
749 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
753 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
755 u32 *p = &vmx->segment_cache.seg[seg].limit;
757 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
758 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
762 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
764 u32 *p = &vmx->segment_cache.seg[seg].ar;
766 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
767 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
771 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
775 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
776 (1u << DB_VECTOR) | (1u << AC_VECTOR);
778 * Guest access to VMware backdoor ports could legitimately
779 * trigger #GP because of TSS I/O permission bitmap.
780 * We intercept those #GP and allow access to them anyway
783 if (enable_vmware_backdoor)
784 eb |= (1u << GP_VECTOR);
785 if ((vcpu->guest_debug &
786 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
787 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
788 eb |= 1u << BP_VECTOR;
789 if (to_vmx(vcpu)->rmode.vm86_active)
791 if (!vmx_need_pf_intercept(vcpu))
792 eb &= ~(1u << PF_VECTOR);
794 /* When we are running a nested L2 guest and L1 specified for it a
795 * certain exception bitmap, we must trap the same exceptions and pass
796 * them to L1. When running L2, we will only handle the exceptions
797 * specified above if L1 did not want them.
799 if (is_guest_mode(vcpu))
800 eb |= get_vmcs12(vcpu)->exception_bitmap;
802 int mask = 0, match = 0;
804 if (enable_ept && (eb & (1u << PF_VECTOR))) {
806 * If EPT is enabled, #PF is currently only intercepted
807 * if MAXPHYADDR is smaller on the guest than on the
808 * host. In that case we only care about present,
809 * non-reserved faults. For vmcs02, however, PFEC_MASK
810 * and PFEC_MATCH are set in prepare_vmcs02_rare.
812 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
813 match = PFERR_PRESENT_MASK;
815 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
816 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
820 * Disabling xfd interception indicates that dynamic xfeatures
821 * might be used in the guest. Always trap #NM in this case
822 * to save guest xfd_err timely.
824 if (vcpu->arch.xfd_no_write_intercept)
825 eb |= (1u << NM_VECTOR);
827 vmcs_write32(EXCEPTION_BITMAP, eb);
831 * Check if MSR is intercepted for currently loaded MSR bitmap.
833 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
835 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
838 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap,
842 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
844 unsigned int flags = 0;
846 if (vmx->loaded_vmcs->launched)
847 flags |= VMX_RUN_VMRESUME;
852 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
853 unsigned long entry, unsigned long exit)
855 vm_entry_controls_clearbit(vmx, entry);
856 vm_exit_controls_clearbit(vmx, exit);
859 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
863 for (i = 0; i < m->nr; ++i) {
864 if (m->val[i].index == msr)
870 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
873 struct msr_autoload *m = &vmx->msr_autoload;
877 if (cpu_has_load_ia32_efer()) {
878 clear_atomic_switch_msr_special(vmx,
879 VM_ENTRY_LOAD_IA32_EFER,
880 VM_EXIT_LOAD_IA32_EFER);
884 case MSR_CORE_PERF_GLOBAL_CTRL:
885 if (cpu_has_load_perf_global_ctrl()) {
886 clear_atomic_switch_msr_special(vmx,
887 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
888 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
893 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
897 m->guest.val[i] = m->guest.val[m->guest.nr];
898 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
901 i = vmx_find_loadstore_msr_slot(&m->host, msr);
906 m->host.val[i] = m->host.val[m->host.nr];
907 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
910 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
911 unsigned long entry, unsigned long exit,
912 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
913 u64 guest_val, u64 host_val)
915 vmcs_write64(guest_val_vmcs, guest_val);
916 if (host_val_vmcs != HOST_IA32_EFER)
917 vmcs_write64(host_val_vmcs, host_val);
918 vm_entry_controls_setbit(vmx, entry);
919 vm_exit_controls_setbit(vmx, exit);
922 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
923 u64 guest_val, u64 host_val, bool entry_only)
926 struct msr_autoload *m = &vmx->msr_autoload;
930 if (cpu_has_load_ia32_efer()) {
931 add_atomic_switch_msr_special(vmx,
932 VM_ENTRY_LOAD_IA32_EFER,
933 VM_EXIT_LOAD_IA32_EFER,
936 guest_val, host_val);
940 case MSR_CORE_PERF_GLOBAL_CTRL:
941 if (cpu_has_load_perf_global_ctrl()) {
942 add_atomic_switch_msr_special(vmx,
943 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
944 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
945 GUEST_IA32_PERF_GLOBAL_CTRL,
946 HOST_IA32_PERF_GLOBAL_CTRL,
947 guest_val, host_val);
951 case MSR_IA32_PEBS_ENABLE:
952 /* PEBS needs a quiescent period after being disabled (to write
953 * a record). Disabling PEBS through VMX MSR swapping doesn't
954 * provide that period, so a CPU could write host's record into
957 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
960 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
962 j = vmx_find_loadstore_msr_slot(&m->host, msr);
964 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
965 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
966 printk_once(KERN_WARNING "Not enough msr switch entries. "
967 "Can't add msr %x\n", msr);
972 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
974 m->guest.val[i].index = msr;
975 m->guest.val[i].value = guest_val;
982 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
984 m->host.val[j].index = msr;
985 m->host.val[j].value = host_val;
988 static bool update_transition_efer(struct vcpu_vmx *vmx)
990 u64 guest_efer = vmx->vcpu.arch.efer;
994 /* Shadow paging assumes NX to be available. */
996 guest_efer |= EFER_NX;
999 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1001 ignore_bits |= EFER_SCE;
1002 #ifdef CONFIG_X86_64
1003 ignore_bits |= EFER_LMA | EFER_LME;
1004 /* SCE is meaningful only in long mode on Intel */
1005 if (guest_efer & EFER_LMA)
1006 ignore_bits &= ~(u64)EFER_SCE;
1010 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1011 * On CPUs that support "load IA32_EFER", always switch EFER
1012 * atomically, since it's faster than switching it manually.
1014 if (cpu_has_load_ia32_efer() ||
1015 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1016 if (!(guest_efer & EFER_LMA))
1017 guest_efer &= ~EFER_LME;
1018 if (guest_efer != host_efer)
1019 add_atomic_switch_msr(vmx, MSR_EFER,
1020 guest_efer, host_efer, false);
1022 clear_atomic_switch_msr(vmx, MSR_EFER);
1026 i = kvm_find_user_return_msr(MSR_EFER);
1030 clear_atomic_switch_msr(vmx, MSR_EFER);
1032 guest_efer &= ~ignore_bits;
1033 guest_efer |= host_efer & ignore_bits;
1035 vmx->guest_uret_msrs[i].data = guest_efer;
1036 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1041 #ifdef CONFIG_X86_32
1043 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1044 * VMCS rather than the segment table. KVM uses this helper to figure
1045 * out the current bases to poke them into the VMCS before entry.
1047 static unsigned long segment_base(u16 selector)
1049 struct desc_struct *table;
1052 if (!(selector & ~SEGMENT_RPL_MASK))
1055 table = get_current_gdt_ro();
1057 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1058 u16 ldt_selector = kvm_read_ldt();
1060 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1063 table = (struct desc_struct *)segment_base(ldt_selector);
1065 v = get_desc_base(&table[selector >> 3]);
1070 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1072 return vmx_pt_mode_is_host_guest() &&
1073 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1076 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1078 /* The base must be 128-byte aligned and a legal physical address. */
1079 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1082 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1086 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1087 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1088 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1089 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1090 for (i = 0; i < addr_range; i++) {
1091 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1092 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1096 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1100 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1101 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1102 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1103 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1104 for (i = 0; i < addr_range; i++) {
1105 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1106 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1110 static void pt_guest_enter(struct vcpu_vmx *vmx)
1112 if (vmx_pt_mode_is_system())
1116 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1117 * Save host state before VM entry.
1119 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1120 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1121 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1122 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1123 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1127 static void pt_guest_exit(struct vcpu_vmx *vmx)
1129 if (vmx_pt_mode_is_system())
1132 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1133 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1134 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1138 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1139 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1141 if (vmx->pt_desc.host.ctl)
1142 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1145 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1146 unsigned long fs_base, unsigned long gs_base)
1148 if (unlikely(fs_sel != host->fs_sel)) {
1150 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1152 vmcs_write16(HOST_FS_SELECTOR, 0);
1153 host->fs_sel = fs_sel;
1155 if (unlikely(gs_sel != host->gs_sel)) {
1157 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1159 vmcs_write16(HOST_GS_SELECTOR, 0);
1160 host->gs_sel = gs_sel;
1162 if (unlikely(fs_base != host->fs_base)) {
1163 vmcs_writel(HOST_FS_BASE, fs_base);
1164 host->fs_base = fs_base;
1166 if (unlikely(gs_base != host->gs_base)) {
1167 vmcs_writel(HOST_GS_BASE, gs_base);
1168 host->gs_base = gs_base;
1172 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1174 struct vcpu_vmx *vmx = to_vmx(vcpu);
1175 struct vmcs_host_state *host_state;
1176 #ifdef CONFIG_X86_64
1177 int cpu = raw_smp_processor_id();
1179 unsigned long fs_base, gs_base;
1183 vmx->req_immediate_exit = false;
1186 * Note that guest MSRs to be saved/restored can also be changed
1187 * when guest state is loaded. This happens when guest transitions
1188 * to/from long-mode by setting MSR_EFER.LMA.
1190 if (!vmx->guest_uret_msrs_loaded) {
1191 vmx->guest_uret_msrs_loaded = true;
1192 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1193 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1196 kvm_set_user_return_msr(i,
1197 vmx->guest_uret_msrs[i].data,
1198 vmx->guest_uret_msrs[i].mask);
1202 if (vmx->nested.need_vmcs12_to_shadow_sync)
1203 nested_sync_vmcs12_to_shadow(vcpu);
1205 if (vmx->guest_state_loaded)
1208 host_state = &vmx->loaded_vmcs->host_state;
1211 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1212 * allow segment selectors with cpl > 0 or ti == 1.
1214 host_state->ldt_sel = kvm_read_ldt();
1216 #ifdef CONFIG_X86_64
1217 savesegment(ds, host_state->ds_sel);
1218 savesegment(es, host_state->es_sel);
1220 gs_base = cpu_kernelmode_gs_base(cpu);
1221 if (likely(is_64bit_mm(current->mm))) {
1222 current_save_fsgs();
1223 fs_sel = current->thread.fsindex;
1224 gs_sel = current->thread.gsindex;
1225 fs_base = current->thread.fsbase;
1226 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1228 savesegment(fs, fs_sel);
1229 savesegment(gs, gs_sel);
1230 fs_base = read_msr(MSR_FS_BASE);
1231 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1234 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1236 savesegment(fs, fs_sel);
1237 savesegment(gs, gs_sel);
1238 fs_base = segment_base(fs_sel);
1239 gs_base = segment_base(gs_sel);
1242 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1243 vmx->guest_state_loaded = true;
1246 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1248 struct vmcs_host_state *host_state;
1250 if (!vmx->guest_state_loaded)
1253 host_state = &vmx->loaded_vmcs->host_state;
1255 ++vmx->vcpu.stat.host_state_reload;
1257 #ifdef CONFIG_X86_64
1258 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1260 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1261 kvm_load_ldt(host_state->ldt_sel);
1262 #ifdef CONFIG_X86_64
1263 load_gs_index(host_state->gs_sel);
1265 loadsegment(gs, host_state->gs_sel);
1268 if (host_state->fs_sel & 7)
1269 loadsegment(fs, host_state->fs_sel);
1270 #ifdef CONFIG_X86_64
1271 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1272 loadsegment(ds, host_state->ds_sel);
1273 loadsegment(es, host_state->es_sel);
1276 invalidate_tss_limit();
1277 #ifdef CONFIG_X86_64
1278 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1280 load_fixmap_gdt(raw_smp_processor_id());
1281 vmx->guest_state_loaded = false;
1282 vmx->guest_uret_msrs_loaded = false;
1285 #ifdef CONFIG_X86_64
1286 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1289 if (vmx->guest_state_loaded)
1290 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1292 return vmx->msr_guest_kernel_gs_base;
1295 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1298 if (vmx->guest_state_loaded)
1299 wrmsrl(MSR_KERNEL_GS_BASE, data);
1301 vmx->msr_guest_kernel_gs_base = data;
1305 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1306 struct loaded_vmcs *buddy)
1308 struct vcpu_vmx *vmx = to_vmx(vcpu);
1309 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1312 if (!already_loaded) {
1313 loaded_vmcs_clear(vmx->loaded_vmcs);
1314 local_irq_disable();
1317 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1318 * this cpu's percpu list, otherwise it may not yet be deleted
1319 * from its previous cpu's percpu list. Pairs with the
1320 * smb_wmb() in __loaded_vmcs_clear().
1324 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1325 &per_cpu(loaded_vmcss_on_cpu, cpu));
1329 prev = per_cpu(current_vmcs, cpu);
1330 if (prev != vmx->loaded_vmcs->vmcs) {
1331 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1332 vmcs_load(vmx->loaded_vmcs->vmcs);
1335 * No indirect branch prediction barrier needed when switching
1336 * the active VMCS within a guest, e.g. on nested VM-Enter.
1337 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1339 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1340 indirect_branch_prediction_barrier();
1343 if (!already_loaded) {
1344 void *gdt = get_current_gdt_ro();
1347 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1348 * TLB entries from its previous association with the vCPU.
1350 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1353 * Linux uses per-cpu TSS and GDT, so set these when switching
1354 * processors. See 22.2.4.
1356 vmcs_writel(HOST_TR_BASE,
1357 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1358 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1360 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1362 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1363 (unsigned long)(cpu_entry_stack(cpu) + 1));
1366 vmx->loaded_vmcs->cpu = cpu;
1371 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1372 * vcpu mutex is already taken.
1374 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1376 struct vcpu_vmx *vmx = to_vmx(vcpu);
1378 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1380 vmx_vcpu_pi_load(vcpu, cpu);
1382 vmx->host_debugctlmsr = get_debugctlmsr();
1385 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1387 vmx_vcpu_pi_put(vcpu);
1389 vmx_prepare_switch_to_host(to_vmx(vcpu));
1392 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1394 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1397 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1399 struct vcpu_vmx *vmx = to_vmx(vcpu);
1400 unsigned long rflags, save_rflags;
1402 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1403 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1404 rflags = vmcs_readl(GUEST_RFLAGS);
1405 if (vmx->rmode.vm86_active) {
1406 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1407 save_rflags = vmx->rmode.save_rflags;
1408 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1410 vmx->rflags = rflags;
1415 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1417 struct vcpu_vmx *vmx = to_vmx(vcpu);
1418 unsigned long old_rflags;
1420 if (is_unrestricted_guest(vcpu)) {
1421 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1422 vmx->rflags = rflags;
1423 vmcs_writel(GUEST_RFLAGS, rflags);
1427 old_rflags = vmx_get_rflags(vcpu);
1428 vmx->rflags = rflags;
1429 if (vmx->rmode.vm86_active) {
1430 vmx->rmode.save_rflags = rflags;
1431 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1433 vmcs_writel(GUEST_RFLAGS, rflags);
1435 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1436 vmx->emulation_required = vmx_emulation_required(vcpu);
1439 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1441 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1444 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1446 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1449 if (interruptibility & GUEST_INTR_STATE_STI)
1450 ret |= KVM_X86_SHADOW_INT_STI;
1451 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1452 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1457 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1459 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1460 u32 interruptibility = interruptibility_old;
1462 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1464 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1465 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1466 else if (mask & KVM_X86_SHADOW_INT_STI)
1467 interruptibility |= GUEST_INTR_STATE_STI;
1469 if ((interruptibility != interruptibility_old))
1470 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1473 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1475 struct vcpu_vmx *vmx = to_vmx(vcpu);
1476 unsigned long value;
1479 * Any MSR write that attempts to change bits marked reserved will
1482 if (data & vmx->pt_desc.ctl_bitmask)
1486 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1487 * result in a #GP unless the same write also clears TraceEn.
1489 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1490 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1494 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1495 * and FabricEn would cause #GP, if
1496 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1498 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1499 !(data & RTIT_CTL_FABRIC_EN) &&
1500 !intel_pt_validate_cap(vmx->pt_desc.caps,
1501 PT_CAP_single_range_output))
1505 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1506 * utilize encodings marked reserved will cause a #GP fault.
1508 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1509 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1510 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1511 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1513 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1514 PT_CAP_cycle_thresholds);
1515 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1516 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1517 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1519 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1520 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1521 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1522 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1526 * If ADDRx_CFG is reserved or the encodings is >2 will
1527 * cause a #GP fault.
1529 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1530 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1532 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1533 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1535 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1536 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1538 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1539 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1545 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1546 void *insn, int insn_len)
1549 * Emulation of instructions in SGX enclaves is impossible as RIP does
1550 * not point at the failing instruction, and even if it did, the code
1551 * stream is inaccessible. Inject #UD instead of exiting to userspace
1552 * so that guest userspace can't DoS the guest simply by triggering
1553 * emulation (enclaves are CPL3 only).
1555 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1556 kvm_queue_exception(vcpu, UD_VECTOR);
1562 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1564 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1565 unsigned long rip, orig_rip;
1569 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1570 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1571 * set when EPT misconfig occurs. In practice, real hardware updates
1572 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1573 * (namely Hyper-V) don't set it due to it being undefined behavior,
1574 * i.e. we end up advancing IP with some random value.
1576 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1577 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1578 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1581 * Emulating an enclave's instructions isn't supported as KVM
1582 * cannot access the enclave's memory or its true RIP, e.g. the
1583 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1584 * the RIP that actually triggered the VM-Exit. But, because
1585 * most instructions that cause VM-Exit will #UD in an enclave,
1586 * most instruction-based VM-Exits simply do not occur.
1588 * There are a few exceptions, notably the debug instructions
1589 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1590 * and generate #DB/#BP as expected, which KVM might intercept.
1591 * But again, the CPU does the dirty work and saves an instr
1592 * length of zero so VMMs don't shoot themselves in the foot.
1593 * WARN if KVM tries to skip a non-zero length instruction on
1594 * a VM-Exit from an enclave.
1599 WARN(exit_reason.enclave_mode,
1600 "KVM: skipping instruction after SGX enclave VM-Exit");
1602 orig_rip = kvm_rip_read(vcpu);
1603 rip = orig_rip + instr_len;
1604 #ifdef CONFIG_X86_64
1606 * We need to mask out the high 32 bits of RIP if not in 64-bit
1607 * mode, but just finding out that we are in 64-bit mode is
1608 * quite expensive. Only do it if there was a carry.
1610 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1613 kvm_rip_write(vcpu, rip);
1615 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1620 /* skipping an emulated instruction also counts */
1621 vmx_set_interrupt_shadow(vcpu, 0);
1627 * Recognizes a pending MTF VM-exit and records the nested state for later
1630 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1632 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1633 struct vcpu_vmx *vmx = to_vmx(vcpu);
1635 if (!is_guest_mode(vcpu))
1639 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1640 * T-bit traps. As instruction emulation is completed (i.e. at the
1641 * instruction boundary), any #DB exception pending delivery must be a
1642 * debug-trap. Record the pending MTF state to be delivered in
1643 * vmx_check_nested_events().
1645 if (nested_cpu_has_mtf(vmcs12) &&
1646 (!vcpu->arch.exception.pending ||
1647 vcpu->arch.exception.nr == DB_VECTOR))
1648 vmx->nested.mtf_pending = true;
1650 vmx->nested.mtf_pending = false;
1653 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1655 vmx_update_emulated_instruction(vcpu);
1656 return skip_emulated_instruction(vcpu);
1659 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1662 * Ensure that we clear the HLT state in the VMCS. We don't need to
1663 * explicitly skip the instruction because if the HLT state is set,
1664 * then the instruction is already executing and RIP has already been
1667 if (kvm_hlt_in_guest(vcpu->kvm) &&
1668 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1669 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1672 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1674 struct vcpu_vmx *vmx = to_vmx(vcpu);
1675 unsigned nr = vcpu->arch.exception.nr;
1676 bool has_error_code = vcpu->arch.exception.has_error_code;
1677 u32 error_code = vcpu->arch.exception.error_code;
1678 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1680 kvm_deliver_exception_payload(vcpu);
1682 if (has_error_code) {
1683 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1684 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1687 if (vmx->rmode.vm86_active) {
1689 if (kvm_exception_is_soft(nr))
1690 inc_eip = vcpu->arch.event_exit_inst_len;
1691 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1695 WARN_ON_ONCE(vmx->emulation_required);
1697 if (kvm_exception_is_soft(nr)) {
1698 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1699 vmx->vcpu.arch.event_exit_inst_len);
1700 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1702 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1704 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1706 vmx_clear_hlt(vcpu);
1709 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1710 bool load_into_hardware)
1712 struct vmx_uret_msr *uret_msr;
1714 uret_msr = vmx_find_uret_msr(vmx, msr);
1718 uret_msr->load_into_hardware = load_into_hardware;
1722 * Configuring user return MSRs to automatically save, load, and restore MSRs
1723 * that need to be shoved into hardware when running the guest. Note, omitting
1724 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1725 * loaded into hardware when running the guest.
1727 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1729 #ifdef CONFIG_X86_64
1730 bool load_syscall_msrs;
1733 * The SYSCALL MSRs are only needed on long mode guests, and only
1734 * when EFER.SCE is set.
1736 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1737 (vmx->vcpu.arch.efer & EFER_SCE);
1739 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1740 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1741 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1743 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1745 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1746 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1747 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1750 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1751 * kernel and old userspace. If those guests run on a tsx=off host, do
1752 * allow guests to use TSX_CTRL, but don't change the value in hardware
1753 * so that TSX remains always disabled.
1755 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1758 * The set of MSRs to load may have changed, reload MSRs before the
1761 vmx->guest_uret_msrs_loaded = false;
1764 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1766 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1768 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1769 return vmcs12->tsc_offset;
1774 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1776 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1778 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1779 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1780 return vmcs12->tsc_multiplier;
1782 return kvm_default_tsc_scaling_ratio;
1785 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1787 vmcs_write64(TSC_OFFSET, offset);
1790 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1792 vmcs_write64(TSC_MULTIPLIER, multiplier);
1796 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1797 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1798 * all guests if the "nested" module option is off, and can also be disabled
1799 * for a single guest by disabling its VMX cpuid bit.
1801 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1803 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1806 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1809 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1811 return !(val & ~valid_bits);
1814 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1816 switch (msr->index) {
1817 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1820 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1821 case MSR_IA32_PERF_CAPABILITIES:
1822 msr->data = vmx_get_perf_capabilities();
1825 return KVM_MSR_RET_INVALID;
1830 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1831 * Returns 0 on success, non-0 otherwise.
1832 * Assumes vcpu_load() was already called.
1834 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1836 struct vcpu_vmx *vmx = to_vmx(vcpu);
1837 struct vmx_uret_msr *msr;
1840 switch (msr_info->index) {
1841 #ifdef CONFIG_X86_64
1843 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1846 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1848 case MSR_KERNEL_GS_BASE:
1849 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1853 return kvm_get_msr_common(vcpu, msr_info);
1854 case MSR_IA32_TSX_CTRL:
1855 if (!msr_info->host_initiated &&
1856 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1859 case MSR_IA32_UMWAIT_CONTROL:
1860 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1863 msr_info->data = vmx->msr_ia32_umwait_control;
1865 case MSR_IA32_SPEC_CTRL:
1866 if (!msr_info->host_initiated &&
1867 !guest_has_spec_ctrl_msr(vcpu))
1870 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1872 case MSR_IA32_SYSENTER_CS:
1873 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1875 case MSR_IA32_SYSENTER_EIP:
1876 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1878 case MSR_IA32_SYSENTER_ESP:
1879 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1881 case MSR_IA32_BNDCFGS:
1882 if (!kvm_mpx_supported() ||
1883 (!msr_info->host_initiated &&
1884 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1886 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1888 case MSR_IA32_MCG_EXT_CTL:
1889 if (!msr_info->host_initiated &&
1890 !(vmx->msr_ia32_feature_control &
1891 FEAT_CTL_LMCE_ENABLED))
1893 msr_info->data = vcpu->arch.mcg_ext_ctl;
1895 case MSR_IA32_FEAT_CTL:
1896 msr_info->data = vmx->msr_ia32_feature_control;
1898 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1899 if (!msr_info->host_initiated &&
1900 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1902 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1903 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1905 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1906 if (!nested_vmx_allowed(vcpu))
1908 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1912 * Enlightened VMCS v1 doesn't have certain VMCS fields but
1913 * instead of just ignoring the features, different Hyper-V
1914 * versions are either trying to use them and fail or do some
1915 * sanity checking and refuse to boot. Filter all unsupported
1918 if (!msr_info->host_initiated &&
1919 vmx->nested.enlightened_vmcs_enabled)
1920 nested_evmcs_filter_control_msr(msr_info->index,
1923 case MSR_IA32_RTIT_CTL:
1924 if (!vmx_pt_mode_is_host_guest())
1926 msr_info->data = vmx->pt_desc.guest.ctl;
1928 case MSR_IA32_RTIT_STATUS:
1929 if (!vmx_pt_mode_is_host_guest())
1931 msr_info->data = vmx->pt_desc.guest.status;
1933 case MSR_IA32_RTIT_CR3_MATCH:
1934 if (!vmx_pt_mode_is_host_guest() ||
1935 !intel_pt_validate_cap(vmx->pt_desc.caps,
1936 PT_CAP_cr3_filtering))
1938 msr_info->data = vmx->pt_desc.guest.cr3_match;
1940 case MSR_IA32_RTIT_OUTPUT_BASE:
1941 if (!vmx_pt_mode_is_host_guest() ||
1942 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1943 PT_CAP_topa_output) &&
1944 !intel_pt_validate_cap(vmx->pt_desc.caps,
1945 PT_CAP_single_range_output)))
1947 msr_info->data = vmx->pt_desc.guest.output_base;
1949 case MSR_IA32_RTIT_OUTPUT_MASK:
1950 if (!vmx_pt_mode_is_host_guest() ||
1951 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1952 PT_CAP_topa_output) &&
1953 !intel_pt_validate_cap(vmx->pt_desc.caps,
1954 PT_CAP_single_range_output)))
1956 msr_info->data = vmx->pt_desc.guest.output_mask;
1958 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1959 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1960 if (!vmx_pt_mode_is_host_guest() ||
1961 (index >= 2 * vmx->pt_desc.num_address_ranges))
1964 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1966 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1968 case MSR_IA32_DEBUGCTLMSR:
1969 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1973 msr = vmx_find_uret_msr(vmx, msr_info->index);
1975 msr_info->data = msr->data;
1978 return kvm_get_msr_common(vcpu, msr_info);
1984 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1987 #ifdef CONFIG_X86_64
1988 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1991 return (unsigned long)data;
1994 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
1996 u64 debugctl = vmx_supported_debugctl();
1998 if (!intel_pmu_lbr_is_enabled(vcpu))
1999 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2001 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
2002 debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
2008 * Writes msr value into the appropriate "register".
2009 * Returns 0 on success, non-0 otherwise.
2010 * Assumes vcpu_load() was already called.
2012 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2014 struct vcpu_vmx *vmx = to_vmx(vcpu);
2015 struct vmx_uret_msr *msr;
2017 u32 msr_index = msr_info->index;
2018 u64 data = msr_info->data;
2021 switch (msr_index) {
2023 ret = kvm_set_msr_common(vcpu, msr_info);
2025 #ifdef CONFIG_X86_64
2027 vmx_segment_cache_clear(vmx);
2028 vmcs_writel(GUEST_FS_BASE, data);
2031 vmx_segment_cache_clear(vmx);
2032 vmcs_writel(GUEST_GS_BASE, data);
2034 case MSR_KERNEL_GS_BASE:
2035 vmx_write_guest_kernel_gs_base(vmx, data);
2038 ret = kvm_set_msr_common(vcpu, msr_info);
2040 * Always intercepting WRMSR could incur non-negligible
2041 * overhead given xfd might be changed frequently in
2042 * guest context switch. Disable write interception
2043 * upon the first write with a non-zero value (indicating
2044 * potential usage on dynamic xfeatures). Also update
2045 * exception bitmap to trap #NM for proper virtualization
2049 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2051 vcpu->arch.xfd_no_write_intercept = true;
2052 vmx_update_exception_bitmap(vcpu);
2056 case MSR_IA32_SYSENTER_CS:
2057 if (is_guest_mode(vcpu))
2058 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2059 vmcs_write32(GUEST_SYSENTER_CS, data);
2061 case MSR_IA32_SYSENTER_EIP:
2062 if (is_guest_mode(vcpu)) {
2063 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2064 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2066 vmcs_writel(GUEST_SYSENTER_EIP, data);
2068 case MSR_IA32_SYSENTER_ESP:
2069 if (is_guest_mode(vcpu)) {
2070 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2071 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2073 vmcs_writel(GUEST_SYSENTER_ESP, data);
2075 case MSR_IA32_DEBUGCTLMSR: {
2076 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2077 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2078 if (report_ignored_msrs)
2079 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2081 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2082 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2088 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2089 VM_EXIT_SAVE_DEBUG_CONTROLS)
2090 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2092 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2093 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2094 (data & DEBUGCTLMSR_LBR))
2095 intel_pmu_create_guest_lbr_event(vcpu);
2098 case MSR_IA32_BNDCFGS:
2099 if (!kvm_mpx_supported() ||
2100 (!msr_info->host_initiated &&
2101 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2103 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2104 (data & MSR_IA32_BNDCFGS_RSVD))
2106 vmcs_write64(GUEST_BNDCFGS, data);
2108 case MSR_IA32_UMWAIT_CONTROL:
2109 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2112 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2113 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2116 vmx->msr_ia32_umwait_control = data;
2118 case MSR_IA32_SPEC_CTRL:
2119 if (!msr_info->host_initiated &&
2120 !guest_has_spec_ctrl_msr(vcpu))
2123 if (kvm_spec_ctrl_test_value(data))
2126 vmx->spec_ctrl = data;
2132 * When it's written (to non-zero) for the first time, pass
2136 * The handling of the MSR bitmap for L2 guests is done in
2137 * nested_vmx_prepare_msr_bitmap. We should not touch the
2138 * vmcs02.msr_bitmap here since it gets completely overwritten
2139 * in the merging. We update the vmcs01 here for L1 as well
2140 * since it will end up touching the MSR anyway now.
2142 vmx_disable_intercept_for_msr(vcpu,
2146 case MSR_IA32_TSX_CTRL:
2147 if (!msr_info->host_initiated &&
2148 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2150 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2153 case MSR_IA32_PRED_CMD:
2154 if (!msr_info->host_initiated &&
2155 !guest_has_pred_cmd_msr(vcpu))
2158 if (data & ~PRED_CMD_IBPB)
2160 if (!boot_cpu_has(X86_FEATURE_IBPB))
2165 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2169 * When it's written (to non-zero) for the first time, pass
2173 * The handling of the MSR bitmap for L2 guests is done in
2174 * nested_vmx_prepare_msr_bitmap. We should not touch the
2175 * vmcs02.msr_bitmap here since it gets completely overwritten
2178 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2180 case MSR_IA32_CR_PAT:
2181 if (!kvm_pat_valid(data))
2184 if (is_guest_mode(vcpu) &&
2185 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2186 get_vmcs12(vcpu)->guest_ia32_pat = data;
2188 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2189 vmcs_write64(GUEST_IA32_PAT, data);
2190 vcpu->arch.pat = data;
2193 ret = kvm_set_msr_common(vcpu, msr_info);
2195 case MSR_IA32_MCG_EXT_CTL:
2196 if ((!msr_info->host_initiated &&
2197 !(to_vmx(vcpu)->msr_ia32_feature_control &
2198 FEAT_CTL_LMCE_ENABLED)) ||
2199 (data & ~MCG_EXT_CTL_LMCE_EN))
2201 vcpu->arch.mcg_ext_ctl = data;
2203 case MSR_IA32_FEAT_CTL:
2204 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2205 (to_vmx(vcpu)->msr_ia32_feature_control &
2206 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2208 vmx->msr_ia32_feature_control = data;
2209 if (msr_info->host_initiated && data == 0)
2210 vmx_leave_nested(vcpu);
2212 /* SGX may be enabled/disabled by guest's firmware */
2213 vmx_write_encls_bitmap(vcpu, NULL);
2215 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2217 * On real hardware, the LE hash MSRs are writable before
2218 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2219 * at which point SGX related bits in IA32_FEATURE_CONTROL
2222 * KVM does not emulate SGX activation for simplicity, so
2223 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2224 * is unlocked. This is technically not architectural
2225 * behavior, but it's close enough.
2227 if (!msr_info->host_initiated &&
2228 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2229 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2230 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2232 vmx->msr_ia32_sgxlepubkeyhash
2233 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2235 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2236 if (!msr_info->host_initiated)
2237 return 1; /* they are read-only */
2238 if (!nested_vmx_allowed(vcpu))
2240 return vmx_set_vmx_msr(vcpu, msr_index, data);
2241 case MSR_IA32_RTIT_CTL:
2242 if (!vmx_pt_mode_is_host_guest() ||
2243 vmx_rtit_ctl_check(vcpu, data) ||
2246 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2247 vmx->pt_desc.guest.ctl = data;
2248 pt_update_intercept_for_msr(vcpu);
2250 case MSR_IA32_RTIT_STATUS:
2251 if (!pt_can_write_msr(vmx))
2253 if (data & MSR_IA32_RTIT_STATUS_MASK)
2255 vmx->pt_desc.guest.status = data;
2257 case MSR_IA32_RTIT_CR3_MATCH:
2258 if (!pt_can_write_msr(vmx))
2260 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2261 PT_CAP_cr3_filtering))
2263 vmx->pt_desc.guest.cr3_match = data;
2265 case MSR_IA32_RTIT_OUTPUT_BASE:
2266 if (!pt_can_write_msr(vmx))
2268 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2269 PT_CAP_topa_output) &&
2270 !intel_pt_validate_cap(vmx->pt_desc.caps,
2271 PT_CAP_single_range_output))
2273 if (!pt_output_base_valid(vcpu, data))
2275 vmx->pt_desc.guest.output_base = data;
2277 case MSR_IA32_RTIT_OUTPUT_MASK:
2278 if (!pt_can_write_msr(vmx))
2280 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2281 PT_CAP_topa_output) &&
2282 !intel_pt_validate_cap(vmx->pt_desc.caps,
2283 PT_CAP_single_range_output))
2285 vmx->pt_desc.guest.output_mask = data;
2287 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2288 if (!pt_can_write_msr(vmx))
2290 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2291 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2293 if (is_noncanonical_address(data, vcpu))
2296 vmx->pt_desc.guest.addr_b[index / 2] = data;
2298 vmx->pt_desc.guest.addr_a[index / 2] = data;
2300 case MSR_IA32_PERF_CAPABILITIES:
2301 if (data && !vcpu_to_pmu(vcpu)->version)
2303 if (data & PMU_CAP_LBR_FMT) {
2304 if ((data & PMU_CAP_LBR_FMT) !=
2305 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2307 if (!intel_pmu_lbr_is_compatible(vcpu))
2310 ret = kvm_set_msr_common(vcpu, msr_info);
2315 msr = vmx_find_uret_msr(vmx, msr_index);
2317 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2319 ret = kvm_set_msr_common(vcpu, msr_info);
2322 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2323 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2324 vmx_update_fb_clear_dis(vcpu, vmx);
2329 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2331 unsigned long guest_owned_bits;
2333 kvm_register_mark_available(vcpu, reg);
2337 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2340 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2342 case VCPU_EXREG_PDPTR:
2344 ept_save_pdptrs(vcpu);
2346 case VCPU_EXREG_CR0:
2347 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2349 vcpu->arch.cr0 &= ~guest_owned_bits;
2350 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2352 case VCPU_EXREG_CR3:
2354 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2355 * CR3 is loaded into hardware, not the guest's CR3.
2357 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2358 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2360 case VCPU_EXREG_CR4:
2361 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2363 vcpu->arch.cr4 &= ~guest_owned_bits;
2364 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2367 KVM_BUG_ON(1, vcpu->kvm);
2372 static __init int cpu_has_kvm_support(void)
2374 return cpu_has_vmx();
2377 static __init int vmx_disabled_by_bios(void)
2379 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2380 !boot_cpu_has(X86_FEATURE_VMX);
2383 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2387 cr4_set_bits(X86_CR4_VMXE);
2389 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2390 _ASM_EXTABLE(1b, %l[fault])
2391 : : [vmxon_pointer] "m"(vmxon_pointer)
2396 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2397 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2398 cr4_clear_bits(X86_CR4_VMXE);
2403 static int vmx_hardware_enable(void)
2405 int cpu = raw_smp_processor_id();
2406 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2409 if (cr4_read_shadow() & X86_CR4_VMXE)
2413 * This can happen if we hot-added a CPU but failed to allocate
2414 * VP assist page for it.
2416 if (static_branch_unlikely(&enable_evmcs) &&
2417 !hv_get_vp_assist_page(cpu))
2420 intel_pt_handle_vmx(1);
2422 r = kvm_cpu_vmxon(phys_addr);
2424 intel_pt_handle_vmx(0);
2434 static void vmclear_local_loaded_vmcss(void)
2436 int cpu = raw_smp_processor_id();
2437 struct loaded_vmcs *v, *n;
2439 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2440 loaded_vmcss_on_cpu_link)
2441 __loaded_vmcs_clear(v);
2444 static void vmx_hardware_disable(void)
2446 vmclear_local_loaded_vmcss();
2449 kvm_spurious_fault();
2451 intel_pt_handle_vmx(0);
2455 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2456 * directly instead of going through cpu_has(), to ensure KVM is trapping
2457 * ENCLS whenever it's supported in hardware. It does not matter whether
2458 * the host OS supports or has enabled SGX.
2460 static bool cpu_has_sgx(void)
2462 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2465 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2466 u32 msr, u32 *result)
2468 u32 vmx_msr_low, vmx_msr_high;
2469 u32 ctl = ctl_min | ctl_opt;
2471 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2473 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2474 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2476 /* Ensure minimum (required) set of control bits are supported. */
2484 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2485 struct vmx_capability *vmx_cap)
2487 u32 vmx_msr_low, vmx_msr_high;
2488 u32 min, opt, min2, opt2;
2489 u32 _pin_based_exec_control = 0;
2490 u32 _cpu_based_exec_control = 0;
2491 u32 _cpu_based_2nd_exec_control = 0;
2492 u32 _vmexit_control = 0;
2493 u32 _vmentry_control = 0;
2495 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2496 min = CPU_BASED_HLT_EXITING |
2497 #ifdef CONFIG_X86_64
2498 CPU_BASED_CR8_LOAD_EXITING |
2499 CPU_BASED_CR8_STORE_EXITING |
2501 CPU_BASED_CR3_LOAD_EXITING |
2502 CPU_BASED_CR3_STORE_EXITING |
2503 CPU_BASED_UNCOND_IO_EXITING |
2504 CPU_BASED_MOV_DR_EXITING |
2505 CPU_BASED_USE_TSC_OFFSETTING |
2506 CPU_BASED_MWAIT_EXITING |
2507 CPU_BASED_MONITOR_EXITING |
2508 CPU_BASED_INVLPG_EXITING |
2509 CPU_BASED_RDPMC_EXITING;
2511 opt = CPU_BASED_TPR_SHADOW |
2512 CPU_BASED_USE_MSR_BITMAPS |
2513 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2514 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2515 &_cpu_based_exec_control) < 0)
2517 #ifdef CONFIG_X86_64
2518 if (_cpu_based_exec_control & CPU_BASED_TPR_SHADOW)
2519 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2520 ~CPU_BASED_CR8_STORE_EXITING;
2522 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2524 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2525 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2526 SECONDARY_EXEC_WBINVD_EXITING |
2527 SECONDARY_EXEC_ENABLE_VPID |
2528 SECONDARY_EXEC_ENABLE_EPT |
2529 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2530 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2531 SECONDARY_EXEC_DESC |
2532 SECONDARY_EXEC_ENABLE_RDTSCP |
2533 SECONDARY_EXEC_ENABLE_INVPCID |
2534 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2535 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2536 SECONDARY_EXEC_SHADOW_VMCS |
2537 SECONDARY_EXEC_XSAVES |
2538 SECONDARY_EXEC_RDSEED_EXITING |
2539 SECONDARY_EXEC_RDRAND_EXITING |
2540 SECONDARY_EXEC_ENABLE_PML |
2541 SECONDARY_EXEC_TSC_SCALING |
2542 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2543 SECONDARY_EXEC_PT_USE_GPA |
2544 SECONDARY_EXEC_PT_CONCEAL_VMX |
2545 SECONDARY_EXEC_ENABLE_VMFUNC |
2546 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2548 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2549 if (adjust_vmx_controls(min2, opt2,
2550 MSR_IA32_VMX_PROCBASED_CTLS2,
2551 &_cpu_based_2nd_exec_control) < 0)
2554 #ifndef CONFIG_X86_64
2555 if (!(_cpu_based_2nd_exec_control &
2556 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2557 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2560 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2561 _cpu_based_2nd_exec_control &= ~(
2562 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2563 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2564 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2566 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2567 &vmx_cap->ept, &vmx_cap->vpid);
2569 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2570 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2572 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2573 CPU_BASED_CR3_STORE_EXITING |
2574 CPU_BASED_INVLPG_EXITING);
2575 } else if (vmx_cap->ept) {
2577 pr_warn_once("EPT CAP should not exist if not support "
2578 "1-setting enable EPT VM-execution control\n");
2580 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2583 pr_warn_once("VPID CAP should not exist if not support "
2584 "1-setting enable VPID VM-execution control\n");
2587 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2588 #ifdef CONFIG_X86_64
2589 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2591 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2592 VM_EXIT_LOAD_IA32_PAT |
2593 VM_EXIT_LOAD_IA32_EFER |
2594 VM_EXIT_CLEAR_BNDCFGS |
2595 VM_EXIT_PT_CONCEAL_PIP |
2596 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2597 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2598 &_vmexit_control) < 0)
2601 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2602 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2603 PIN_BASED_VMX_PREEMPTION_TIMER;
2604 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2605 &_pin_based_exec_control) < 0)
2608 if (cpu_has_broken_vmx_preemption_timer())
2609 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2610 if (!(_cpu_based_2nd_exec_control &
2611 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2612 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2614 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2615 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2616 VM_ENTRY_LOAD_IA32_PAT |
2617 VM_ENTRY_LOAD_IA32_EFER |
2618 VM_ENTRY_LOAD_BNDCFGS |
2619 VM_ENTRY_PT_CONCEAL_PIP |
2620 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2621 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2622 &_vmentry_control) < 0)
2626 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2627 * can't be used due to an errata where VM Exit may incorrectly clear
2628 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2629 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2631 if (boot_cpu_data.x86 == 0x6) {
2632 switch (boot_cpu_data.x86_model) {
2633 case 26: /* AAK155 */
2634 case 30: /* AAP115 */
2635 case 37: /* AAT100 */
2636 case 44: /* BC86,AAY89,BD102 */
2638 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2639 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2640 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2641 "does not work properly. Using workaround\n");
2649 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2651 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2652 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2655 #ifdef CONFIG_X86_64
2656 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2657 if (vmx_msr_high & (1u<<16))
2661 /* Require Write-Back (WB) memory type for VMCS accesses. */
2662 if (((vmx_msr_high >> 18) & 15) != 6)
2665 vmcs_conf->size = vmx_msr_high & 0x1fff;
2666 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2668 vmcs_conf->revision_id = vmx_msr_low;
2670 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2671 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2672 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2673 vmcs_conf->vmexit_ctrl = _vmexit_control;
2674 vmcs_conf->vmentry_ctrl = _vmentry_control;
2676 #if IS_ENABLED(CONFIG_HYPERV)
2677 if (enlightened_vmcs)
2678 evmcs_sanitize_exec_ctrls(vmcs_conf);
2684 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2686 int node = cpu_to_node(cpu);
2690 pages = __alloc_pages_node(node, flags, 0);
2693 vmcs = page_address(pages);
2694 memset(vmcs, 0, vmcs_config.size);
2696 /* KVM supports Enlightened VMCS v1 only */
2697 if (static_branch_unlikely(&enable_evmcs))
2698 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2700 vmcs->hdr.revision_id = vmcs_config.revision_id;
2703 vmcs->hdr.shadow_vmcs = 1;
2707 void free_vmcs(struct vmcs *vmcs)
2709 free_page((unsigned long)vmcs);
2713 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2715 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2717 if (!loaded_vmcs->vmcs)
2719 loaded_vmcs_clear(loaded_vmcs);
2720 free_vmcs(loaded_vmcs->vmcs);
2721 loaded_vmcs->vmcs = NULL;
2722 if (loaded_vmcs->msr_bitmap)
2723 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2724 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2727 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2729 loaded_vmcs->vmcs = alloc_vmcs(false);
2730 if (!loaded_vmcs->vmcs)
2733 vmcs_clear(loaded_vmcs->vmcs);
2735 loaded_vmcs->shadow_vmcs = NULL;
2736 loaded_vmcs->hv_timer_soft_disabled = false;
2737 loaded_vmcs->cpu = -1;
2738 loaded_vmcs->launched = 0;
2740 if (cpu_has_vmx_msr_bitmap()) {
2741 loaded_vmcs->msr_bitmap = (unsigned long *)
2742 __get_free_page(GFP_KERNEL_ACCOUNT);
2743 if (!loaded_vmcs->msr_bitmap)
2745 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2748 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2749 memset(&loaded_vmcs->controls_shadow, 0,
2750 sizeof(struct vmcs_controls_shadow));
2755 free_loaded_vmcs(loaded_vmcs);
2759 static void free_kvm_area(void)
2763 for_each_possible_cpu(cpu) {
2764 free_vmcs(per_cpu(vmxarea, cpu));
2765 per_cpu(vmxarea, cpu) = NULL;
2769 static __init int alloc_kvm_area(void)
2773 for_each_possible_cpu(cpu) {
2776 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2783 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2784 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2785 * revision_id reported by MSR_IA32_VMX_BASIC.
2787 * However, even though not explicitly documented by
2788 * TLFS, VMXArea passed as VMXON argument should
2789 * still be marked with revision_id reported by
2792 if (static_branch_unlikely(&enable_evmcs))
2793 vmcs->hdr.revision_id = vmcs_config.revision_id;
2795 per_cpu(vmxarea, cpu) = vmcs;
2800 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2801 struct kvm_segment *save)
2803 if (!emulate_invalid_guest_state) {
2805 * CS and SS RPL should be equal during guest entry according
2806 * to VMX spec, but in reality it is not always so. Since vcpu
2807 * is in the middle of the transition from real mode to
2808 * protected mode it is safe to assume that RPL 0 is a good
2811 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2812 save->selector &= ~SEGMENT_RPL_MASK;
2813 save->dpl = save->selector & SEGMENT_RPL_MASK;
2816 __vmx_set_segment(vcpu, save, seg);
2819 static void enter_pmode(struct kvm_vcpu *vcpu)
2821 unsigned long flags;
2822 struct vcpu_vmx *vmx = to_vmx(vcpu);
2825 * Update real mode segment cache. It may be not up-to-date if segment
2826 * register was written while vcpu was in a guest mode.
2828 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2829 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2830 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2831 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2832 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2833 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2835 vmx->rmode.vm86_active = 0;
2837 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2839 flags = vmcs_readl(GUEST_RFLAGS);
2840 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2841 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2842 vmcs_writel(GUEST_RFLAGS, flags);
2844 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2845 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2847 vmx_update_exception_bitmap(vcpu);
2849 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2850 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2851 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2852 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2853 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2854 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2857 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2859 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2860 struct kvm_segment var = *save;
2863 if (seg == VCPU_SREG_CS)
2866 if (!emulate_invalid_guest_state) {
2867 var.selector = var.base >> 4;
2868 var.base = var.base & 0xffff0;
2878 if (save->base & 0xf)
2879 printk_once(KERN_WARNING "kvm: segment base is not "
2880 "paragraph aligned when entering "
2881 "protected mode (seg=%d)", seg);
2884 vmcs_write16(sf->selector, var.selector);
2885 vmcs_writel(sf->base, var.base);
2886 vmcs_write32(sf->limit, var.limit);
2887 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2890 static void enter_rmode(struct kvm_vcpu *vcpu)
2892 unsigned long flags;
2893 struct vcpu_vmx *vmx = to_vmx(vcpu);
2894 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2896 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2897 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2898 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2899 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2900 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2901 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2902 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2904 vmx->rmode.vm86_active = 1;
2907 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2908 * vcpu. Warn the user that an update is overdue.
2910 if (!kvm_vmx->tss_addr)
2911 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2912 "called before entering vcpu\n");
2914 vmx_segment_cache_clear(vmx);
2916 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2917 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2918 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2920 flags = vmcs_readl(GUEST_RFLAGS);
2921 vmx->rmode.save_rflags = flags;
2923 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2925 vmcs_writel(GUEST_RFLAGS, flags);
2926 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2927 vmx_update_exception_bitmap(vcpu);
2929 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2930 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2931 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2932 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2933 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2934 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2937 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2939 struct vcpu_vmx *vmx = to_vmx(vcpu);
2941 /* Nothing to do if hardware doesn't support EFER. */
2942 if (!vmx_find_uret_msr(vmx, MSR_EFER))
2945 vcpu->arch.efer = efer;
2946 if (efer & EFER_LMA)
2947 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
2949 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
2951 vmx_setup_uret_msrs(vmx);
2955 #ifdef CONFIG_X86_64
2957 static void enter_lmode(struct kvm_vcpu *vcpu)
2961 vmx_segment_cache_clear(to_vmx(vcpu));
2963 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2964 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2965 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2967 vmcs_write32(GUEST_TR_AR_BYTES,
2968 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2969 | VMX_AR_TYPE_BUSY_64_TSS);
2971 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2974 static void exit_lmode(struct kvm_vcpu *vcpu)
2976 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2981 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2983 struct vcpu_vmx *vmx = to_vmx(vcpu);
2986 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2987 * the CPU is not required to invalidate guest-physical mappings on
2988 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2989 * associated with the root EPT structure and not any particular VPID
2990 * (INVVPID also isn't required to invalidate guest-physical mappings).
2994 } else if (enable_vpid) {
2995 if (cpu_has_vmx_invvpid_global()) {
2996 vpid_sync_vcpu_global();
2998 vpid_sync_vcpu_single(vmx->vpid);
2999 vpid_sync_vcpu_single(vmx->nested.vpid02);
3004 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3006 if (is_guest_mode(vcpu))
3007 return nested_get_vpid02(vcpu);
3008 return to_vmx(vcpu)->vpid;
3011 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3013 struct kvm_mmu *mmu = vcpu->arch.mmu;
3014 u64 root_hpa = mmu->root.hpa;
3016 /* No flush required if the current context is invalid. */
3017 if (!VALID_PAGE(root_hpa))
3021 ept_sync_context(construct_eptp(vcpu, root_hpa,
3022 mmu->root_role.level));
3024 vpid_sync_context(vmx_get_current_vpid(vcpu));
3027 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3030 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3031 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3033 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3036 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3039 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3040 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3041 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3042 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3043 * i.e. no explicit INVVPID is necessary.
3045 vpid_sync_context(vmx_get_current_vpid(vcpu));
3048 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3050 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3052 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3055 if (is_pae_paging(vcpu)) {
3056 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3057 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3058 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3059 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3063 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3065 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3067 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3070 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3071 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3072 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3073 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3075 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3078 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3079 CPU_BASED_CR3_STORE_EXITING)
3081 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3083 struct vcpu_vmx *vmx = to_vmx(vcpu);
3084 unsigned long hw_cr0, old_cr0_pg;
3087 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3089 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3090 if (is_unrestricted_guest(vcpu))
3091 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3093 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3095 hw_cr0 |= X86_CR0_WP;
3097 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3100 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3104 vmcs_writel(CR0_READ_SHADOW, cr0);
3105 vmcs_writel(GUEST_CR0, hw_cr0);
3106 vcpu->arch.cr0 = cr0;
3107 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3109 #ifdef CONFIG_X86_64
3110 if (vcpu->arch.efer & EFER_LME) {
3111 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3113 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3118 if (enable_ept && !is_unrestricted_guest(vcpu)) {
3120 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3121 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3122 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3123 * KVM's CR3 is installed.
3125 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3126 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3129 * When running with EPT but not unrestricted guest, KVM must
3130 * intercept CR3 accesses when paging is _disabled_. This is
3131 * necessary because restricted guests can't actually run with
3132 * paging disabled, and so KVM stuffs its own CR3 in order to
3133 * run the guest when identity mapped page tables.
3135 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3136 * update, it may be stale with respect to CR3 interception,
3137 * e.g. after nested VM-Enter.
3139 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3140 * stores to forward them to L1, even if KVM does not need to
3141 * intercept them to preserve its identity mapped page tables.
3143 if (!(cr0 & X86_CR0_PG)) {
3144 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3145 } else if (!is_guest_mode(vcpu)) {
3146 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3148 tmp = exec_controls_get(vmx);
3149 tmp &= ~CR3_EXITING_BITS;
3150 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3151 exec_controls_set(vmx, tmp);
3154 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3155 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3156 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3159 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3160 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3162 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3163 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3166 /* depends on vcpu->arch.cr0 to be set to a new value */
3167 vmx->emulation_required = vmx_emulation_required(vcpu);
3170 static int vmx_get_max_tdp_level(void)
3172 if (cpu_has_vmx_ept_5levels())
3177 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3179 u64 eptp = VMX_EPTP_MT_WB;
3181 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3183 if (enable_ept_ad_bits &&
3184 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3185 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3191 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3194 struct kvm *kvm = vcpu->kvm;
3195 bool update_guest_cr3 = true;
3196 unsigned long guest_cr3;
3200 eptp = construct_eptp(vcpu, root_hpa, root_level);
3201 vmcs_write64(EPT_POINTER, eptp);
3203 hv_track_root_tdp(vcpu, root_hpa);
3205 if (!enable_unrestricted_guest && !is_paging(vcpu))
3206 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3207 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3208 guest_cr3 = vcpu->arch.cr3;
3209 else /* vmcs.GUEST_CR3 is already up-to-date. */
3210 update_guest_cr3 = false;
3211 vmx_ept_load_pdptrs(vcpu);
3213 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3216 if (update_guest_cr3)
3217 vmcs_writel(GUEST_CR3, guest_cr3);
3221 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3224 * We operate under the default treatment of SMM, so VMX cannot be
3225 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3226 * handled by kvm_is_valid_cr4().
3228 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3231 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3237 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3239 unsigned long old_cr4 = vcpu->arch.cr4;
3240 struct vcpu_vmx *vmx = to_vmx(vcpu);
3242 * Pass through host's Machine Check Enable value to hw_cr4, which
3243 * is in force while we are in guest mode. Do not let guests control
3244 * this bit, even if host CR4.MCE == 0.
3246 unsigned long hw_cr4;
3248 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3249 if (is_unrestricted_guest(vcpu))
3250 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3251 else if (vmx->rmode.vm86_active)
3252 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3254 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3256 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3257 if (cr4 & X86_CR4_UMIP) {
3258 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3259 hw_cr4 &= ~X86_CR4_UMIP;
3260 } else if (!is_guest_mode(vcpu) ||
3261 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3262 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3266 vcpu->arch.cr4 = cr4;
3267 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3269 if (!is_unrestricted_guest(vcpu)) {
3271 if (!is_paging(vcpu)) {
3272 hw_cr4 &= ~X86_CR4_PAE;
3273 hw_cr4 |= X86_CR4_PSE;
3274 } else if (!(cr4 & X86_CR4_PAE)) {
3275 hw_cr4 &= ~X86_CR4_PAE;
3280 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3281 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3282 * to be manually disabled when guest switches to non-paging
3285 * If !enable_unrestricted_guest, the CPU is always running
3286 * with CR0.PG=1 and CR4 needs to be modified.
3287 * If enable_unrestricted_guest, the CPU automatically
3288 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3290 if (!is_paging(vcpu))
3291 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3294 vmcs_writel(CR4_READ_SHADOW, cr4);
3295 vmcs_writel(GUEST_CR4, hw_cr4);
3297 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3298 kvm_update_cpuid_runtime(vcpu);
3301 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3303 struct vcpu_vmx *vmx = to_vmx(vcpu);
3306 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3307 *var = vmx->rmode.segs[seg];
3308 if (seg == VCPU_SREG_TR
3309 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3311 var->base = vmx_read_guest_seg_base(vmx, seg);
3312 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3315 var->base = vmx_read_guest_seg_base(vmx, seg);
3316 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3317 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3318 ar = vmx_read_guest_seg_ar(vmx, seg);
3319 var->unusable = (ar >> 16) & 1;
3320 var->type = ar & 15;
3321 var->s = (ar >> 4) & 1;
3322 var->dpl = (ar >> 5) & 3;
3324 * Some userspaces do not preserve unusable property. Since usable
3325 * segment has to be present according to VMX spec we can use present
3326 * property to amend userspace bug by making unusable segment always
3327 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3328 * segment as unusable.
3330 var->present = !var->unusable;
3331 var->avl = (ar >> 12) & 1;
3332 var->l = (ar >> 13) & 1;
3333 var->db = (ar >> 14) & 1;
3334 var->g = (ar >> 15) & 1;
3337 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3339 struct kvm_segment s;
3341 if (to_vmx(vcpu)->rmode.vm86_active) {
3342 vmx_get_segment(vcpu, &s, seg);
3345 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3348 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3350 struct vcpu_vmx *vmx = to_vmx(vcpu);
3352 if (unlikely(vmx->rmode.vm86_active))
3355 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3356 return VMX_AR_DPL(ar);
3360 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3364 if (var->unusable || !var->present)
3367 ar = var->type & 15;
3368 ar |= (var->s & 1) << 4;
3369 ar |= (var->dpl & 3) << 5;
3370 ar |= (var->present & 1) << 7;
3371 ar |= (var->avl & 1) << 12;
3372 ar |= (var->l & 1) << 13;
3373 ar |= (var->db & 1) << 14;
3374 ar |= (var->g & 1) << 15;
3380 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3382 struct vcpu_vmx *vmx = to_vmx(vcpu);
3383 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3385 vmx_segment_cache_clear(vmx);
3387 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3388 vmx->rmode.segs[seg] = *var;
3389 if (seg == VCPU_SREG_TR)
3390 vmcs_write16(sf->selector, var->selector);
3392 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3396 vmcs_writel(sf->base, var->base);
3397 vmcs_write32(sf->limit, var->limit);
3398 vmcs_write16(sf->selector, var->selector);
3401 * Fix the "Accessed" bit in AR field of segment registers for older
3403 * IA32 arch specifies that at the time of processor reset the
3404 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3405 * is setting it to 0 in the userland code. This causes invalid guest
3406 * state vmexit when "unrestricted guest" mode is turned on.
3407 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3408 * tree. Newer qemu binaries with that qemu fix would not need this
3411 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3412 var->type |= 0x1; /* Accessed */
3414 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3417 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3419 __vmx_set_segment(vcpu, var, seg);
3421 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3424 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3426 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3428 *db = (ar >> 14) & 1;
3429 *l = (ar >> 13) & 1;
3432 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3434 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3435 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3438 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3440 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3441 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3444 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3446 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3447 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3450 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3452 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3453 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3456 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3458 struct kvm_segment var;
3461 vmx_get_segment(vcpu, &var, seg);
3463 if (seg == VCPU_SREG_CS)
3465 ar = vmx_segment_access_rights(&var);
3467 if (var.base != (var.selector << 4))
3469 if (var.limit != 0xffff)
3477 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3479 struct kvm_segment cs;
3480 unsigned int cs_rpl;
3482 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3483 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3487 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3491 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3492 if (cs.dpl > cs_rpl)
3495 if (cs.dpl != cs_rpl)
3501 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3505 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3507 struct kvm_segment ss;
3508 unsigned int ss_rpl;
3510 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3511 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3515 if (ss.type != 3 && ss.type != 7)
3519 if (ss.dpl != ss_rpl) /* DPL != RPL */
3527 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3529 struct kvm_segment var;
3532 vmx_get_segment(vcpu, &var, seg);
3533 rpl = var.selector & SEGMENT_RPL_MASK;
3541 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3542 if (var.dpl < rpl) /* DPL < RPL */
3546 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3552 static bool tr_valid(struct kvm_vcpu *vcpu)
3554 struct kvm_segment tr;
3556 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3560 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3562 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3570 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3572 struct kvm_segment ldtr;
3574 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3578 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3588 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3590 struct kvm_segment cs, ss;
3592 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3593 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3595 return ((cs.selector & SEGMENT_RPL_MASK) ==
3596 (ss.selector & SEGMENT_RPL_MASK));
3600 * Check if guest state is valid. Returns true if valid, false if
3602 * We assume that registers are always usable
3604 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3606 /* real mode guest state checks */
3607 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3608 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3610 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3612 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3614 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3616 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3618 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3621 /* protected mode guest state checks */
3622 if (!cs_ss_rpl_check(vcpu))
3624 if (!code_segment_valid(vcpu))
3626 if (!stack_segment_valid(vcpu))
3628 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3630 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3632 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3634 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3636 if (!tr_valid(vcpu))
3638 if (!ldtr_valid(vcpu))
3642 * - Add checks on RIP
3643 * - Add checks on RFLAGS
3649 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3651 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3655 for (i = 0; i < 3; i++) {
3656 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3660 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3661 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3665 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3671 static int init_rmode_identity_map(struct kvm *kvm)
3673 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3678 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3679 mutex_lock(&kvm->slots_lock);
3681 if (likely(kvm_vmx->ept_identity_pagetable_done))
3684 if (!kvm_vmx->ept_identity_map_addr)
3685 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3687 uaddr = __x86_set_memory_region(kvm,
3688 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3689 kvm_vmx->ept_identity_map_addr,
3691 if (IS_ERR(uaddr)) {
3696 /* Set up identity-mapping pagetable for EPT in real mode */
3697 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3698 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3699 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3700 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3705 kvm_vmx->ept_identity_pagetable_done = true;
3708 mutex_unlock(&kvm->slots_lock);
3712 static void seg_setup(int seg)
3714 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3717 vmcs_write16(sf->selector, 0);
3718 vmcs_writel(sf->base, 0);
3719 vmcs_write32(sf->limit, 0xffff);
3721 if (seg == VCPU_SREG_CS)
3722 ar |= 0x08; /* code segment */
3724 vmcs_write32(sf->ar_bytes, ar);
3727 static int alloc_apic_access_page(struct kvm *kvm)
3733 mutex_lock(&kvm->slots_lock);
3734 if (kvm->arch.apic_access_memslot_enabled)
3736 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3737 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3743 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3744 if (is_error_page(page)) {
3750 * Do not pin the page in memory, so that memory hot-unplug
3751 * is able to migrate it.
3754 kvm->arch.apic_access_memslot_enabled = true;
3756 mutex_unlock(&kvm->slots_lock);
3760 int allocate_vpid(void)
3766 spin_lock(&vmx_vpid_lock);
3767 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3768 if (vpid < VMX_NR_VPIDS)
3769 __set_bit(vpid, vmx_vpid_bitmap);
3772 spin_unlock(&vmx_vpid_lock);
3776 void free_vpid(int vpid)
3778 if (!enable_vpid || vpid == 0)
3780 spin_lock(&vmx_vpid_lock);
3781 __clear_bit(vpid, vmx_vpid_bitmap);
3782 spin_unlock(&vmx_vpid_lock);
3785 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3788 * When KVM is a nested hypervisor on top of Hyper-V and uses
3789 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3790 * bitmap has changed.
3792 if (static_branch_unlikely(&enable_evmcs))
3793 evmcs_touch_msr_bitmap();
3795 vmx->nested.force_msr_bitmap_recalc = true;
3798 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3800 struct vcpu_vmx *vmx = to_vmx(vcpu);
3801 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3803 if (!cpu_has_vmx_msr_bitmap())
3806 vmx_msr_bitmap_l01_changed(vmx);
3809 * Mark the desired intercept state in shadow bitmap, this is needed
3810 * for resync when the MSR filters change.
3812 if (is_valid_passthrough_msr(msr)) {
3813 int idx = possible_passthrough_msr_slot(msr);
3815 if (idx != -ENOENT) {
3816 if (type & MSR_TYPE_R)
3817 clear_bit(idx, vmx->shadow_msr_intercept.read);
3818 if (type & MSR_TYPE_W)
3819 clear_bit(idx, vmx->shadow_msr_intercept.write);
3823 if ((type & MSR_TYPE_R) &&
3824 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3825 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3826 type &= ~MSR_TYPE_R;
3829 if ((type & MSR_TYPE_W) &&
3830 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3831 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3832 type &= ~MSR_TYPE_W;
3835 if (type & MSR_TYPE_R)
3836 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3838 if (type & MSR_TYPE_W)
3839 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3842 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3844 struct vcpu_vmx *vmx = to_vmx(vcpu);
3845 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3847 if (!cpu_has_vmx_msr_bitmap())
3850 vmx_msr_bitmap_l01_changed(vmx);
3853 * Mark the desired intercept state in shadow bitmap, this is needed
3854 * for resync when the MSR filter changes.
3856 if (is_valid_passthrough_msr(msr)) {
3857 int idx = possible_passthrough_msr_slot(msr);
3859 if (idx != -ENOENT) {
3860 if (type & MSR_TYPE_R)
3861 set_bit(idx, vmx->shadow_msr_intercept.read);
3862 if (type & MSR_TYPE_W)
3863 set_bit(idx, vmx->shadow_msr_intercept.write);
3867 if (type & MSR_TYPE_R)
3868 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3870 if (type & MSR_TYPE_W)
3871 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3874 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3876 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3877 unsigned long read_intercept;
3880 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3882 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3883 unsigned int read_idx = msr / BITS_PER_LONG;
3884 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3886 msr_bitmap[read_idx] = read_intercept;
3887 msr_bitmap[write_idx] = ~0ul;
3891 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
3893 struct vcpu_vmx *vmx = to_vmx(vcpu);
3896 if (!cpu_has_vmx_msr_bitmap())
3899 if (cpu_has_secondary_exec_ctrls() &&
3900 (secondary_exec_controls_get(vmx) &
3901 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3902 mode = MSR_BITMAP_MODE_X2APIC;
3903 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3904 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3909 if (mode == vmx->x2apic_msr_bitmap_mode)
3912 vmx->x2apic_msr_bitmap_mode = mode;
3914 vmx_reset_x2apic_msrs(vcpu, mode);
3917 * TPR reads and writes can be virtualized even if virtual interrupt
3918 * delivery is not in use.
3920 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3921 !(mode & MSR_BITMAP_MODE_X2APIC));
3923 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3924 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3925 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3926 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3930 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3932 struct vcpu_vmx *vmx = to_vmx(vcpu);
3933 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3936 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3937 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3938 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3939 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3940 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
3941 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3942 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3946 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3948 struct vcpu_vmx *vmx = to_vmx(vcpu);
3953 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3954 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3955 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3958 rvi = vmx_get_rvi();
3960 vapic_page = vmx->nested.virtual_apic_map.hva;
3961 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3963 return ((rvi & 0xf0) > (vppr & 0xf0));
3966 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3968 struct vcpu_vmx *vmx = to_vmx(vcpu);
3972 * Set intercept permissions for all potentially passed through MSRs
3973 * again. They will automatically get filtered through the MSR filter,
3974 * so we are back in sync after this.
3976 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3977 u32 msr = vmx_possible_passthrough_msrs[i];
3978 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3979 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3981 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3982 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
3985 pt_update_intercept_for_msr(vcpu);
3988 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3992 if (vcpu->mode == IN_GUEST_MODE) {
3994 * The vector of the virtual has already been set in the PIR.
3995 * Send a notification event to deliver the virtual interrupt
3996 * unless the vCPU is the currently running vCPU, i.e. the
3997 * event is being sent from a fastpath VM-Exit handler, in
3998 * which case the PIR will be synced to the vIRR before
3999 * re-entering the guest.
4001 * When the target is not the running vCPU, the following
4002 * possibilities emerge:
4004 * Case 1: vCPU stays in non-root mode. Sending a notification
4005 * event posts the interrupt to the vCPU.
4007 * Case 2: vCPU exits to root mode and is still runnable. The
4008 * PIR will be synced to the vIRR before re-entering the guest.
4009 * Sending a notification event is ok as the host IRQ handler
4010 * will ignore the spurious event.
4012 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4013 * has already synced PIR to vIRR and never blocks the vCPU if
4014 * the vIRR is not empty. Therefore, a blocked vCPU here does
4015 * not wait for any requested interrupts in PIR, and sending a
4016 * notification event also results in a benign, spurious event.
4019 if (vcpu != kvm_get_running_vcpu())
4020 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4025 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4026 * otherwise do nothing as KVM will grab the highest priority pending
4027 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4029 kvm_vcpu_wake_up(vcpu);
4032 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4035 struct vcpu_vmx *vmx = to_vmx(vcpu);
4037 if (is_guest_mode(vcpu) &&
4038 vector == vmx->nested.posted_intr_nv) {
4040 * If a posted intr is not recognized by hardware,
4041 * we will accomplish it in the next vmentry.
4043 vmx->nested.pi_pending = true;
4044 kvm_make_request(KVM_REQ_EVENT, vcpu);
4047 * This pairs with the smp_mb_*() after setting vcpu->mode in
4048 * vcpu_enter_guest() to guarantee the vCPU sees the event
4049 * request if triggering a posted interrupt "fails" because
4050 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4051 * the smb_wmb() in kvm_make_request() only ensures everything
4052 * done before making the request is visible when the request
4053 * is visible, it doesn't ensure ordering between the store to
4054 * vcpu->requests and the load from vcpu->mode.
4056 smp_mb__after_atomic();
4058 /* the PIR and ON have been set by L1. */
4059 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4065 * Send interrupt to vcpu via posted interrupt way.
4066 * 1. If target vcpu is running(non-root mode), send posted interrupt
4067 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4068 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4069 * interrupt from PIR in next vmentry.
4071 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4073 struct vcpu_vmx *vmx = to_vmx(vcpu);
4076 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4080 if (!vcpu->arch.apicv_active)
4083 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4086 /* If a previous notification has sent the IPI, nothing to do. */
4087 if (pi_test_and_set_on(&vmx->pi_desc))
4091 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4092 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4093 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4094 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4096 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4100 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4101 int trig_mode, int vector)
4103 struct kvm_vcpu *vcpu = apic->vcpu;
4105 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4106 kvm_lapic_set_irr(vector, apic);
4107 kvm_make_request(KVM_REQ_EVENT, vcpu);
4108 kvm_vcpu_kick(vcpu);
4110 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4116 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4117 * will not change in the lifetime of the guest.
4118 * Note that host-state that does change is set elsewhere. E.g., host-state
4119 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4121 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4125 unsigned long cr0, cr3, cr4;
4128 WARN_ON(cr0 & X86_CR0_TS);
4129 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4132 * Save the most likely value for this task's CR3 in the VMCS.
4133 * We can't use __get_current_cr3_fast() because we're not atomic.
4136 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4137 vmx->loaded_vmcs->host_state.cr3 = cr3;
4139 /* Save the most likely value for this task's CR4 in the VMCS. */
4140 cr4 = cr4_read_shadow();
4141 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4142 vmx->loaded_vmcs->host_state.cr4 = cr4;
4144 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4145 #ifdef CONFIG_X86_64
4147 * Load null selectors, so we can avoid reloading them in
4148 * vmx_prepare_switch_to_host(), in case userspace uses
4149 * the null selectors too (the expected case).
4151 vmcs_write16(HOST_DS_SELECTOR, 0);
4152 vmcs_write16(HOST_ES_SELECTOR, 0);
4154 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4155 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4157 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4158 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4160 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4162 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4164 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4165 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4168 * SYSENTER is used for 32-bit system calls on either 32-bit or
4169 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4170 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4171 * have already done so!).
4173 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4174 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4176 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4177 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4179 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4180 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4181 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4184 if (cpu_has_load_ia32_efer())
4185 vmcs_write64(HOST_IA32_EFER, host_efer);
4188 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4190 struct kvm_vcpu *vcpu = &vmx->vcpu;
4192 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4193 ~vcpu->arch.cr4_guest_rsvd_bits;
4195 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4196 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4198 if (is_guest_mode(&vmx->vcpu))
4199 vcpu->arch.cr4_guest_owned_bits &=
4200 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4201 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4204 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4206 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4208 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4209 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4212 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4214 if (!enable_preemption_timer)
4215 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4217 return pin_based_exec_ctrl;
4220 static u32 vmx_vmentry_ctrl(void)
4222 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4224 if (vmx_pt_mode_is_system())
4225 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4226 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4227 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4228 return vmentry_ctrl &
4229 ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL | VM_ENTRY_LOAD_IA32_EFER);
4232 static u32 vmx_vmexit_ctrl(void)
4234 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4236 if (vmx_pt_mode_is_system())
4237 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4238 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4239 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4240 return vmexit_ctrl &
4241 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4244 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4246 struct vcpu_vmx *vmx = to_vmx(vcpu);
4248 if (is_guest_mode(vcpu)) {
4249 vmx->nested.update_vmcs01_apicv_status = true;
4253 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4254 if (cpu_has_secondary_exec_ctrls()) {
4255 if (kvm_vcpu_apicv_active(vcpu))
4256 secondary_exec_controls_setbit(vmx,
4257 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4258 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4260 secondary_exec_controls_clearbit(vmx,
4261 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4262 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4265 vmx_update_msr_bitmap_x2apic(vcpu);
4268 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4270 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4272 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4273 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4275 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4276 exec_control &= ~CPU_BASED_TPR_SHADOW;
4277 #ifdef CONFIG_X86_64
4278 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4279 CPU_BASED_CR8_LOAD_EXITING;
4283 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4284 CPU_BASED_CR3_LOAD_EXITING |
4285 CPU_BASED_INVLPG_EXITING;
4286 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4287 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4288 CPU_BASED_MONITOR_EXITING);
4289 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4290 exec_control &= ~CPU_BASED_HLT_EXITING;
4291 return exec_control;
4295 * Adjust a single secondary execution control bit to intercept/allow an
4296 * instruction in the guest. This is usually done based on whether or not a
4297 * feature has been exposed to the guest in order to correctly emulate faults.
4300 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4301 u32 control, bool enabled, bool exiting)
4304 * If the control is for an opt-in feature, clear the control if the
4305 * feature is not exposed to the guest, i.e. not enabled. If the
4306 * control is opt-out, i.e. an exiting control, clear the control if
4307 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4308 * disabled for the associated instruction. Note, the caller is
4309 * responsible presetting exec_control to set all supported bits.
4311 if (enabled == exiting)
4312 *exec_control &= ~control;
4315 * Update the nested MSR settings so that a nested VMM can/can't set
4316 * controls for features that are/aren't exposed to the guest.
4320 vmx->nested.msrs.secondary_ctls_high |= control;
4322 vmx->nested.msrs.secondary_ctls_high &= ~control;
4327 * Wrapper macro for the common case of adjusting a secondary execution control
4328 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4329 * verifies that the control is actually supported by KVM and hardware.
4331 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4335 if (cpu_has_vmx_##name()) { \
4336 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4337 X86_FEATURE_##feat_name); \
4338 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4339 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4343 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4344 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4345 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4347 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4348 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4350 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4352 struct kvm_vcpu *vcpu = &vmx->vcpu;
4354 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4356 if (vmx_pt_mode_is_system())
4357 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4358 if (!cpu_need_virtualize_apic_accesses(vcpu))
4359 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4361 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4363 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4364 enable_unrestricted_guest = 0;
4366 if (!enable_unrestricted_guest)
4367 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4368 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4369 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4370 if (!kvm_vcpu_apicv_active(vcpu))
4371 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4372 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4373 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4375 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4376 * in vmx_set_cr4. */
4377 exec_control &= ~SECONDARY_EXEC_DESC;
4379 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4381 We can NOT enable shadow_vmcs here because we don't have yet
4384 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4387 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4388 * it needs to be set here when dirty logging is already active, e.g.
4389 * if this vCPU was created after dirty logging was enabled.
4391 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4392 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4394 if (cpu_has_vmx_xsaves()) {
4395 /* Exposing XSAVES only when XSAVE is exposed */
4396 bool xsaves_enabled =
4397 boot_cpu_has(X86_FEATURE_XSAVE) &&
4398 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4399 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4401 vcpu->arch.xsaves_enabled = xsaves_enabled;
4403 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4404 SECONDARY_EXEC_XSAVES,
4405 xsaves_enabled, false);
4409 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4410 * feature is exposed to the guest. This creates a virtualization hole
4411 * if both are supported in hardware but only one is exposed to the
4412 * guest, but letting the guest execute RDTSCP or RDPID when either one
4413 * is advertised is preferable to emulating the advertised instruction
4414 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4416 if (cpu_has_vmx_rdtscp()) {
4417 bool rdpid_or_rdtscp_enabled =
4418 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4419 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4421 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4422 SECONDARY_EXEC_ENABLE_RDTSCP,
4423 rdpid_or_rdtscp_enabled, false);
4425 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4427 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4428 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4430 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4431 ENABLE_USR_WAIT_PAUSE, false);
4433 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4434 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4436 return exec_control;
4439 #define VMX_XSS_EXIT_BITMAP 0
4441 static void init_vmcs(struct vcpu_vmx *vmx)
4444 nested_vmx_set_vmcs_shadowing_bitmap();
4446 if (cpu_has_vmx_msr_bitmap())
4447 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4449 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4452 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4454 exec_controls_set(vmx, vmx_exec_control(vmx));
4456 if (cpu_has_secondary_exec_ctrls())
4457 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4459 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4460 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4461 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4462 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4463 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4465 vmcs_write16(GUEST_INTR_STATUS, 0);
4467 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4468 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4471 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4472 vmcs_write32(PLE_GAP, ple_gap);
4473 vmx->ple_window = ple_window;
4474 vmx->ple_window_dirty = true;
4477 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4478 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4479 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4481 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4482 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4483 vmx_set_constant_host_state(vmx);
4484 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4485 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4487 if (cpu_has_vmx_vmfunc())
4488 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4490 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4491 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4492 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4493 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4494 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4496 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4497 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4499 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4501 /* 22.2.1, 20.8.1 */
4502 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4504 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4505 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4507 set_cr4_guest_host_mask(vmx);
4510 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4512 if (cpu_has_vmx_xsaves())
4513 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4516 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4517 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4520 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4522 if (vmx_pt_mode_is_host_guest()) {
4523 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4524 /* Bit[6~0] are forced to 1, writes are ignored. */
4525 vmx->pt_desc.guest.output_mask = 0x7F;
4526 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4529 vmcs_write32(GUEST_SYSENTER_CS, 0);
4530 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4531 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4532 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4534 if (cpu_has_vmx_tpr_shadow()) {
4535 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4536 if (cpu_need_tpr_shadow(&vmx->vcpu))
4537 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4538 __pa(vmx->vcpu.arch.apic->regs));
4539 vmcs_write32(TPR_THRESHOLD, 0);
4542 vmx_setup_uret_msrs(vmx);
4545 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4547 struct vcpu_vmx *vmx = to_vmx(vcpu);
4552 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4554 vcpu_setup_sgx_lepubkeyhash(vcpu);
4556 vmx->nested.posted_intr_nv = -1;
4557 vmx->nested.vmxon_ptr = INVALID_GPA;
4558 vmx->nested.current_vmptr = INVALID_GPA;
4559 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4561 vcpu->arch.microcode_version = 0x100000000ULL;
4562 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4565 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4566 * or POSTED_INTR_WAKEUP_VECTOR.
4568 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4569 vmx->pi_desc.sn = 1;
4572 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4574 struct vcpu_vmx *vmx = to_vmx(vcpu);
4577 __vmx_vcpu_reset(vcpu);
4579 vmx->rmode.vm86_active = 0;
4582 vmx->msr_ia32_umwait_control = 0;
4584 vmx->hv_deadline_tsc = -1;
4585 kvm_set_cr8(vcpu, 0);
4587 vmx_segment_cache_clear(vmx);
4588 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4590 seg_setup(VCPU_SREG_CS);
4591 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4592 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4594 seg_setup(VCPU_SREG_DS);
4595 seg_setup(VCPU_SREG_ES);
4596 seg_setup(VCPU_SREG_FS);
4597 seg_setup(VCPU_SREG_GS);
4598 seg_setup(VCPU_SREG_SS);
4600 vmcs_write16(GUEST_TR_SELECTOR, 0);
4601 vmcs_writel(GUEST_TR_BASE, 0);
4602 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4603 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4605 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4606 vmcs_writel(GUEST_LDTR_BASE, 0);
4607 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4608 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4610 vmcs_writel(GUEST_GDTR_BASE, 0);
4611 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4613 vmcs_writel(GUEST_IDTR_BASE, 0);
4614 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4616 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4617 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4618 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4619 if (kvm_mpx_supported())
4620 vmcs_write64(GUEST_BNDCFGS, 0);
4622 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4624 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4626 vpid_sync_context(vmx->vpid);
4628 vmx_update_fb_clear_dis(vcpu, vmx);
4631 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4633 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4636 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4639 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4640 vmx_enable_irq_window(vcpu);
4644 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4647 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4649 struct vcpu_vmx *vmx = to_vmx(vcpu);
4651 int irq = vcpu->arch.interrupt.nr;
4653 trace_kvm_inj_virq(irq);
4655 ++vcpu->stat.irq_injections;
4656 if (vmx->rmode.vm86_active) {
4658 if (vcpu->arch.interrupt.soft)
4659 inc_eip = vcpu->arch.event_exit_inst_len;
4660 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4663 intr = irq | INTR_INFO_VALID_MASK;
4664 if (vcpu->arch.interrupt.soft) {
4665 intr |= INTR_TYPE_SOFT_INTR;
4666 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4667 vmx->vcpu.arch.event_exit_inst_len);
4669 intr |= INTR_TYPE_EXT_INTR;
4670 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4672 vmx_clear_hlt(vcpu);
4675 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4677 struct vcpu_vmx *vmx = to_vmx(vcpu);
4681 * Tracking the NMI-blocked state in software is built upon
4682 * finding the next open IRQ window. This, in turn, depends on
4683 * well-behaving guests: They have to keep IRQs disabled at
4684 * least as long as the NMI handler runs. Otherwise we may
4685 * cause NMI nesting, maybe breaking the guest. But as this is
4686 * highly unlikely, we can live with the residual risk.
4688 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4689 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4692 ++vcpu->stat.nmi_injections;
4693 vmx->loaded_vmcs->nmi_known_unmasked = false;
4695 if (vmx->rmode.vm86_active) {
4696 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4700 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4701 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4703 vmx_clear_hlt(vcpu);
4706 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4708 struct vcpu_vmx *vmx = to_vmx(vcpu);
4712 return vmx->loaded_vmcs->soft_vnmi_blocked;
4713 if (vmx->loaded_vmcs->nmi_known_unmasked)
4715 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4716 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4720 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4722 struct vcpu_vmx *vmx = to_vmx(vcpu);
4725 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4726 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4727 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4730 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4732 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4733 GUEST_INTR_STATE_NMI);
4735 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4736 GUEST_INTR_STATE_NMI);
4740 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4742 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4745 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4748 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4749 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4750 GUEST_INTR_STATE_NMI));
4753 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4755 if (to_vmx(vcpu)->nested.nested_run_pending)
4758 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4759 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4762 return !vmx_nmi_blocked(vcpu);
4765 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4767 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4770 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4771 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4772 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4775 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4777 if (to_vmx(vcpu)->nested.nested_run_pending)
4781 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4782 * e.g. if the IRQ arrived asynchronously after checking nested events.
4784 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4787 return !vmx_interrupt_blocked(vcpu);
4790 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4794 if (enable_unrestricted_guest)
4797 mutex_lock(&kvm->slots_lock);
4798 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4800 mutex_unlock(&kvm->slots_lock);
4803 return PTR_ERR(ret);
4805 to_kvm_vmx(kvm)->tss_addr = addr;
4807 return init_rmode_tss(kvm, ret);
4810 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4812 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4816 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4821 * Update instruction length as we may reinject the exception
4822 * from user space while in guest debugging mode.
4824 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4825 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4826 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4830 return !(vcpu->guest_debug &
4831 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4845 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4846 int vec, u32 err_code)
4849 * Instruction with address size override prefix opcode 0x67
4850 * Cause the #SS fault with 0 error code in VM86 mode.
4852 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4853 if (kvm_emulate_instruction(vcpu, 0)) {
4854 if (vcpu->arch.halt_request) {
4855 vcpu->arch.halt_request = 0;
4856 return kvm_emulate_halt_noskip(vcpu);
4864 * Forward all other exceptions that are valid in real mode.
4865 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4866 * the required debugging infrastructure rework.
4868 kvm_queue_exception(vcpu, vec);
4872 static int handle_machine_check(struct kvm_vcpu *vcpu)
4874 /* handled by vmx_vcpu_run() */
4879 * If the host has split lock detection disabled, then #AC is
4880 * unconditionally injected into the guest, which is the pre split lock
4881 * detection behaviour.
4883 * If the host has split lock detection enabled then #AC is
4884 * only injected into the guest when:
4885 * - Guest CPL == 3 (user mode)
4886 * - Guest has #AC detection enabled in CR0
4887 * - Guest EFLAGS has AC bit set
4889 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
4891 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4894 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4895 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4898 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4900 struct vcpu_vmx *vmx = to_vmx(vcpu);
4901 struct kvm_run *kvm_run = vcpu->run;
4902 u32 intr_info, ex_no, error_code;
4903 unsigned long cr2, dr6;
4906 vect_info = vmx->idt_vectoring_info;
4907 intr_info = vmx_get_intr_info(vcpu);
4909 if (is_machine_check(intr_info) || is_nmi(intr_info))
4910 return 1; /* handled by handle_exception_nmi_irqoff() */
4913 * Queue the exception here instead of in handle_nm_fault_irqoff().
4914 * This ensures the nested_vmx check is not skipped so vmexit can
4915 * be reflected to L1 (when it intercepts #NM) before reaching this
4918 if (is_nm_fault(intr_info)) {
4919 kvm_queue_exception(vcpu, NM_VECTOR);
4923 if (is_invalid_opcode(intr_info))
4924 return handle_ud(vcpu);
4927 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4928 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4930 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4931 WARN_ON_ONCE(!enable_vmware_backdoor);
4934 * VMware backdoor emulation on #GP interception only handles
4935 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4936 * error code on #GP.
4939 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4942 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4946 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4947 * MMIO, it is better to report an internal error.
4948 * See the comments in vmx_handle_exit.
4950 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4951 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4952 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4953 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4954 vcpu->run->internal.ndata = 4;
4955 vcpu->run->internal.data[0] = vect_info;
4956 vcpu->run->internal.data[1] = intr_info;
4957 vcpu->run->internal.data[2] = error_code;
4958 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4962 if (is_page_fault(intr_info)) {
4963 cr2 = vmx_get_exit_qual(vcpu);
4964 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4966 * EPT will cause page fault only if we need to
4967 * detect illegal GPAs.
4969 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4970 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4973 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4976 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4978 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4979 return handle_rmode_exception(vcpu, ex_no, error_code);
4983 dr6 = vmx_get_exit_qual(vcpu);
4984 if (!(vcpu->guest_debug &
4985 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4987 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
4988 * instruction. ICEBP generates a trap-like #DB, but
4989 * despite its interception control being tied to #DB,
4990 * is an instruction intercept, i.e. the VM-Exit occurs
4991 * on the ICEBP itself. Note, skipping ICEBP also
4992 * clears STI and MOVSS blocking.
4994 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
4995 * if single-step is enabled in RFLAGS and STI or MOVSS
4996 * blocking is active, as the CPU doesn't set the bit
4997 * on VM-Exit due to #DB interception. VM-Entry has a
4998 * consistency check that a single-step #DB is pending
4999 * in this scenario as the previous instruction cannot
5000 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5001 * don't modify RFLAGS), therefore the one instruction
5002 * delay when activating single-step breakpoints must
5003 * have already expired. Note, the CPU sets/clears BS
5004 * as appropriate for all other VM-Exits types.
5006 if (is_icebp(intr_info))
5007 WARN_ON(!skip_emulated_instruction(vcpu));
5008 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5009 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5010 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5011 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5012 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5014 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5017 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5018 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5022 * Update instruction length as we may reinject #BP from
5023 * user space while in guest debugging mode. Reading it for
5024 * #DB as well causes no harm, it is not used in that case.
5026 vmx->vcpu.arch.event_exit_inst_len =
5027 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5028 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5029 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5030 kvm_run->debug.arch.exception = ex_no;
5033 if (vmx_guest_inject_ac(vcpu)) {
5034 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5039 * Handle split lock. Depending on detection mode this will
5040 * either warn and disable split lock detection for this
5041 * task or force SIGBUS on it.
5043 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5047 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5048 kvm_run->ex.exception = ex_no;
5049 kvm_run->ex.error_code = error_code;
5055 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5057 ++vcpu->stat.irq_exits;
5061 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5063 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5064 vcpu->mmio_needed = 0;
5068 static int handle_io(struct kvm_vcpu *vcpu)
5070 unsigned long exit_qualification;
5071 int size, in, string;
5074 exit_qualification = vmx_get_exit_qual(vcpu);
5075 string = (exit_qualification & 16) != 0;
5077 ++vcpu->stat.io_exits;
5080 return kvm_emulate_instruction(vcpu, 0);
5082 port = exit_qualification >> 16;
5083 size = (exit_qualification & 7) + 1;
5084 in = (exit_qualification & 8) != 0;
5086 return kvm_fast_pio(vcpu, size, port, in);
5090 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5093 * Patch in the VMCALL instruction:
5095 hypercall[0] = 0x0f;
5096 hypercall[1] = 0x01;
5097 hypercall[2] = 0xc1;
5100 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5101 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5103 if (is_guest_mode(vcpu)) {
5104 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5105 unsigned long orig_val = val;
5108 * We get here when L2 changed cr0 in a way that did not change
5109 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5110 * but did change L0 shadowed bits. So we first calculate the
5111 * effective cr0 value that L1 would like to write into the
5112 * hardware. It consists of the L2-owned bits from the new
5113 * value combined with the L1-owned bits from L1's guest_cr0.
5115 val = (val & ~vmcs12->cr0_guest_host_mask) |
5116 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5118 if (!nested_guest_cr0_valid(vcpu, val))
5121 if (kvm_set_cr0(vcpu, val))
5123 vmcs_writel(CR0_READ_SHADOW, orig_val);
5126 if (to_vmx(vcpu)->nested.vmxon &&
5127 !nested_host_cr0_valid(vcpu, val))
5130 return kvm_set_cr0(vcpu, val);
5134 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5136 if (is_guest_mode(vcpu)) {
5137 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5138 unsigned long orig_val = val;
5140 /* analogously to handle_set_cr0 */
5141 val = (val & ~vmcs12->cr4_guest_host_mask) |
5142 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5143 if (kvm_set_cr4(vcpu, val))
5145 vmcs_writel(CR4_READ_SHADOW, orig_val);
5148 return kvm_set_cr4(vcpu, val);
5151 static int handle_desc(struct kvm_vcpu *vcpu)
5153 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5154 return kvm_emulate_instruction(vcpu, 0);
5157 static int handle_cr(struct kvm_vcpu *vcpu)
5159 unsigned long exit_qualification, val;
5165 exit_qualification = vmx_get_exit_qual(vcpu);
5166 cr = exit_qualification & 15;
5167 reg = (exit_qualification >> 8) & 15;
5168 switch ((exit_qualification >> 4) & 3) {
5169 case 0: /* mov to cr */
5170 val = kvm_register_read(vcpu, reg);
5171 trace_kvm_cr_write(cr, val);
5174 err = handle_set_cr0(vcpu, val);
5175 return kvm_complete_insn_gp(vcpu, err);
5177 WARN_ON_ONCE(enable_unrestricted_guest);
5179 err = kvm_set_cr3(vcpu, val);
5180 return kvm_complete_insn_gp(vcpu, err);
5182 err = handle_set_cr4(vcpu, val);
5183 return kvm_complete_insn_gp(vcpu, err);
5185 u8 cr8_prev = kvm_get_cr8(vcpu);
5187 err = kvm_set_cr8(vcpu, cr8);
5188 ret = kvm_complete_insn_gp(vcpu, err);
5189 if (lapic_in_kernel(vcpu))
5191 if (cr8_prev <= cr8)
5194 * TODO: we might be squashing a
5195 * KVM_GUESTDBG_SINGLESTEP-triggered
5196 * KVM_EXIT_DEBUG here.
5198 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5204 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5206 case 1: /*mov from cr*/
5209 WARN_ON_ONCE(enable_unrestricted_guest);
5211 val = kvm_read_cr3(vcpu);
5212 kvm_register_write(vcpu, reg, val);
5213 trace_kvm_cr_read(cr, val);
5214 return kvm_skip_emulated_instruction(vcpu);
5216 val = kvm_get_cr8(vcpu);
5217 kvm_register_write(vcpu, reg, val);
5218 trace_kvm_cr_read(cr, val);
5219 return kvm_skip_emulated_instruction(vcpu);
5223 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5224 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5225 kvm_lmsw(vcpu, val);
5227 return kvm_skip_emulated_instruction(vcpu);
5231 vcpu->run->exit_reason = 0;
5232 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5233 (int)(exit_qualification >> 4) & 3, cr);
5237 static int handle_dr(struct kvm_vcpu *vcpu)
5239 unsigned long exit_qualification;
5243 exit_qualification = vmx_get_exit_qual(vcpu);
5244 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5246 /* First, if DR does not exist, trigger UD */
5247 if (!kvm_require_dr(vcpu, dr))
5250 if (vmx_get_cpl(vcpu) > 0)
5253 dr7 = vmcs_readl(GUEST_DR7);
5256 * As the vm-exit takes precedence over the debug trap, we
5257 * need to emulate the latter, either for the host or the
5258 * guest debugging itself.
5260 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5261 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5262 vcpu->run->debug.arch.dr7 = dr7;
5263 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5264 vcpu->run->debug.arch.exception = DB_VECTOR;
5265 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5268 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5273 if (vcpu->guest_debug == 0) {
5274 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5277 * No more DR vmexits; force a reload of the debug registers
5278 * and reenter on this instruction. The next vmexit will
5279 * retrieve the full state of the debug registers.
5281 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5285 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5286 if (exit_qualification & TYPE_MOV_FROM_DR) {
5289 kvm_get_dr(vcpu, dr, &val);
5290 kvm_register_write(vcpu, reg, val);
5293 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5297 return kvm_complete_insn_gp(vcpu, err);
5300 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5302 get_debugreg(vcpu->arch.db[0], 0);
5303 get_debugreg(vcpu->arch.db[1], 1);
5304 get_debugreg(vcpu->arch.db[2], 2);
5305 get_debugreg(vcpu->arch.db[3], 3);
5306 get_debugreg(vcpu->arch.dr6, 6);
5307 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5309 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5310 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5313 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5314 * a stale dr6 from the guest.
5316 set_debugreg(DR6_RESERVED, 6);
5319 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5321 vmcs_writel(GUEST_DR7, val);
5324 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5326 kvm_apic_update_ppr(vcpu);
5330 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5332 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5334 kvm_make_request(KVM_REQ_EVENT, vcpu);
5336 ++vcpu->stat.irq_window_exits;
5340 static int handle_invlpg(struct kvm_vcpu *vcpu)
5342 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5344 kvm_mmu_invlpg(vcpu, exit_qualification);
5345 return kvm_skip_emulated_instruction(vcpu);
5348 static int handle_apic_access(struct kvm_vcpu *vcpu)
5350 if (likely(fasteoi)) {
5351 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5352 int access_type, offset;
5354 access_type = exit_qualification & APIC_ACCESS_TYPE;
5355 offset = exit_qualification & APIC_ACCESS_OFFSET;
5357 * Sane guest uses MOV to write EOI, with written value
5358 * not cared. So make a short-circuit here by avoiding
5359 * heavy instruction emulation.
5361 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5362 (offset == APIC_EOI)) {
5363 kvm_lapic_set_eoi(vcpu);
5364 return kvm_skip_emulated_instruction(vcpu);
5367 return kvm_emulate_instruction(vcpu, 0);
5370 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5372 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5373 int vector = exit_qualification & 0xff;
5375 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5376 kvm_apic_set_eoi_accelerated(vcpu, vector);
5380 static int handle_apic_write(struct kvm_vcpu *vcpu)
5382 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5385 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5386 * hardware has done any necessary aliasing, offset adjustments, etc...
5387 * for the access. I.e. the correct value has already been written to
5388 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5389 * retrieve the register value and emulate the access.
5391 u32 offset = exit_qualification & 0xff0;
5393 kvm_apic_write_nodecode(vcpu, offset);
5397 static int handle_task_switch(struct kvm_vcpu *vcpu)
5399 struct vcpu_vmx *vmx = to_vmx(vcpu);
5400 unsigned long exit_qualification;
5401 bool has_error_code = false;
5404 int reason, type, idt_v, idt_index;
5406 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5407 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5408 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5410 exit_qualification = vmx_get_exit_qual(vcpu);
5412 reason = (u32)exit_qualification >> 30;
5413 if (reason == TASK_SWITCH_GATE && idt_v) {
5415 case INTR_TYPE_NMI_INTR:
5416 vcpu->arch.nmi_injected = false;
5417 vmx_set_nmi_mask(vcpu, true);
5419 case INTR_TYPE_EXT_INTR:
5420 case INTR_TYPE_SOFT_INTR:
5421 kvm_clear_interrupt_queue(vcpu);
5423 case INTR_TYPE_HARD_EXCEPTION:
5424 if (vmx->idt_vectoring_info &
5425 VECTORING_INFO_DELIVER_CODE_MASK) {
5426 has_error_code = true;
5428 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5431 case INTR_TYPE_SOFT_EXCEPTION:
5432 kvm_clear_exception_queue(vcpu);
5438 tss_selector = exit_qualification;
5440 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5441 type != INTR_TYPE_EXT_INTR &&
5442 type != INTR_TYPE_NMI_INTR))
5443 WARN_ON(!skip_emulated_instruction(vcpu));
5446 * TODO: What about debug traps on tss switch?
5447 * Are we supposed to inject them and update dr6?
5449 return kvm_task_switch(vcpu, tss_selector,
5450 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5451 reason, has_error_code, error_code);
5454 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5456 unsigned long exit_qualification;
5460 exit_qualification = vmx_get_exit_qual(vcpu);
5463 * EPT violation happened while executing iret from NMI,
5464 * "blocked by NMI" bit has to be set before next VM entry.
5465 * There are errata that may cause this bit to not be set:
5468 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5470 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5471 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5473 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5474 trace_kvm_page_fault(gpa, exit_qualification);
5476 /* Is it a read fault? */
5477 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5478 ? PFERR_USER_MASK : 0;
5479 /* Is it a write fault? */
5480 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5481 ? PFERR_WRITE_MASK : 0;
5482 /* Is it a fetch fault? */
5483 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5484 ? PFERR_FETCH_MASK : 0;
5485 /* ept page table entry is present? */
5486 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5487 ? PFERR_PRESENT_MASK : 0;
5489 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5490 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5492 vcpu->arch.exit_qualification = exit_qualification;
5495 * Check that the GPA doesn't exceed physical memory limits, as that is
5496 * a guest page fault. We have to emulate the instruction here, because
5497 * if the illegal address is that of a paging structure, then
5498 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5499 * would also use advanced VM-exit information for EPT violations to
5500 * reconstruct the page fault error code.
5502 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5503 return kvm_emulate_instruction(vcpu, 0);
5505 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5508 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5512 if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5516 * A nested guest cannot optimize MMIO vmexits, because we have an
5517 * nGPA here instead of the required GPA.
5519 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5520 if (!is_guest_mode(vcpu) &&
5521 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5522 trace_kvm_fast_mmio(gpa);
5523 return kvm_skip_emulated_instruction(vcpu);
5526 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5529 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5531 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5534 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5535 ++vcpu->stat.nmi_window_exits;
5536 kvm_make_request(KVM_REQ_EVENT, vcpu);
5541 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5543 struct vcpu_vmx *vmx = to_vmx(vcpu);
5545 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5546 (vcpu->arch.exception.pending || vcpu->arch.exception.injected);
5549 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5551 struct vcpu_vmx *vmx = to_vmx(vcpu);
5552 bool intr_window_requested;
5553 unsigned count = 130;
5555 intr_window_requested = exec_controls_get(vmx) &
5556 CPU_BASED_INTR_WINDOW_EXITING;
5558 while (vmx->emulation_required && count-- != 0) {
5559 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5560 return handle_interrupt_window(&vmx->vcpu);
5562 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5565 if (!kvm_emulate_instruction(vcpu, 0))
5568 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5569 kvm_prepare_emulation_failure_exit(vcpu);
5573 if (vcpu->arch.halt_request) {
5574 vcpu->arch.halt_request = 0;
5575 return kvm_emulate_halt_noskip(vcpu);
5579 * Note, return 1 and not 0, vcpu_run() will invoke
5580 * xfer_to_guest_mode() which will create a proper return
5583 if (__xfer_to_guest_mode_work_pending())
5590 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5592 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5593 kvm_prepare_emulation_failure_exit(vcpu);
5600 static void grow_ple_window(struct kvm_vcpu *vcpu)
5602 struct vcpu_vmx *vmx = to_vmx(vcpu);
5603 unsigned int old = vmx->ple_window;
5605 vmx->ple_window = __grow_ple_window(old, ple_window,
5609 if (vmx->ple_window != old) {
5610 vmx->ple_window_dirty = true;
5611 trace_kvm_ple_window_update(vcpu->vcpu_id,
5612 vmx->ple_window, old);
5616 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5618 struct vcpu_vmx *vmx = to_vmx(vcpu);
5619 unsigned int old = vmx->ple_window;
5621 vmx->ple_window = __shrink_ple_window(old, ple_window,
5625 if (vmx->ple_window != old) {
5626 vmx->ple_window_dirty = true;
5627 trace_kvm_ple_window_update(vcpu->vcpu_id,
5628 vmx->ple_window, old);
5633 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5634 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5636 static int handle_pause(struct kvm_vcpu *vcpu)
5638 if (!kvm_pause_in_guest(vcpu->kvm))
5639 grow_ple_window(vcpu);
5642 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5643 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5644 * never set PAUSE_EXITING and just set PLE if supported,
5645 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5647 kvm_vcpu_on_spin(vcpu, true);
5648 return kvm_skip_emulated_instruction(vcpu);
5651 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5656 static int handle_invpcid(struct kvm_vcpu *vcpu)
5658 u32 vmx_instruction_info;
5667 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5668 kvm_queue_exception(vcpu, UD_VECTOR);
5672 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5673 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5674 type = kvm_register_read(vcpu, gpr_index);
5676 /* According to the Intel instruction reference, the memory operand
5677 * is read even if it isn't needed (e.g., for type==all)
5679 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5680 vmx_instruction_info, false,
5681 sizeof(operand), &gva))
5684 return kvm_handle_invpcid(vcpu, type, gva);
5687 static int handle_pml_full(struct kvm_vcpu *vcpu)
5689 unsigned long exit_qualification;
5691 trace_kvm_pml_full(vcpu->vcpu_id);
5693 exit_qualification = vmx_get_exit_qual(vcpu);
5696 * PML buffer FULL happened while executing iret from NMI,
5697 * "blocked by NMI" bit has to be set before next VM entry.
5699 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5701 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5702 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5703 GUEST_INTR_STATE_NMI);
5706 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5707 * here.., and there's no userspace involvement needed for PML.
5712 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5714 struct vcpu_vmx *vmx = to_vmx(vcpu);
5716 if (!vmx->req_immediate_exit &&
5717 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5718 kvm_lapic_expired_hv_timer(vcpu);
5719 return EXIT_FASTPATH_REENTER_GUEST;
5722 return EXIT_FASTPATH_NONE;
5725 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5727 handle_fastpath_preemption_timer(vcpu);
5732 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5733 * are overwritten by nested_vmx_setup() when nested=1.
5735 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5737 kvm_queue_exception(vcpu, UD_VECTOR);
5741 #ifndef CONFIG_X86_SGX_KVM
5742 static int handle_encls(struct kvm_vcpu *vcpu)
5745 * SGX virtualization is disabled. There is no software enable bit for
5746 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5747 * the guest from executing ENCLS (when SGX is supported by hardware).
5749 kvm_queue_exception(vcpu, UD_VECTOR);
5752 #endif /* CONFIG_X86_SGX_KVM */
5754 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5757 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
5758 * VM-Exits. Unconditionally set the flag here and leave the handling to
5759 * vmx_handle_exit().
5761 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
5766 * The exit handlers return 1 if the exit was handled fully and guest execution
5767 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5768 * to be done to userspace and return 0.
5770 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5771 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5772 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5773 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5774 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5775 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5776 [EXIT_REASON_CR_ACCESS] = handle_cr,
5777 [EXIT_REASON_DR_ACCESS] = handle_dr,
5778 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5779 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5780 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5781 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5782 [EXIT_REASON_HLT] = kvm_emulate_halt,
5783 [EXIT_REASON_INVD] = kvm_emulate_invd,
5784 [EXIT_REASON_INVLPG] = handle_invlpg,
5785 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5786 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5787 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5788 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5789 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5790 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5791 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5792 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5793 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5794 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5795 [EXIT_REASON_VMON] = handle_vmx_instruction,
5796 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5797 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5798 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5799 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5800 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5801 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5802 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5803 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5804 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5805 [EXIT_REASON_LDTR_TR] = handle_desc,
5806 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5807 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5808 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5809 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5810 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5811 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5812 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5813 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5814 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5815 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5816 [EXIT_REASON_PML_FULL] = handle_pml_full,
5817 [EXIT_REASON_INVPCID] = handle_invpcid,
5818 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5819 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5820 [EXIT_REASON_ENCLS] = handle_encls,
5821 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5824 static const int kvm_vmx_max_exit_handlers =
5825 ARRAY_SIZE(kvm_vmx_exit_handlers);
5827 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
5828 u64 *info1, u64 *info2,
5829 u32 *intr_info, u32 *error_code)
5831 struct vcpu_vmx *vmx = to_vmx(vcpu);
5833 *reason = vmx->exit_reason.full;
5834 *info1 = vmx_get_exit_qual(vcpu);
5835 if (!(vmx->exit_reason.failed_vmentry)) {
5836 *info2 = vmx->idt_vectoring_info;
5837 *intr_info = vmx_get_intr_info(vcpu);
5838 if (is_exception_with_error_code(*intr_info))
5839 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5849 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5852 __free_page(vmx->pml_pg);
5857 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5859 struct vcpu_vmx *vmx = to_vmx(vcpu);
5863 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5865 /* Do nothing if PML buffer is empty */
5866 if (pml_idx == (PML_ENTITY_NUM - 1))
5869 /* PML index always points to next available PML buffer entity */
5870 if (pml_idx >= PML_ENTITY_NUM)
5875 pml_buf = page_address(vmx->pml_pg);
5876 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5879 gpa = pml_buf[pml_idx];
5880 WARN_ON(gpa & (PAGE_SIZE - 1));
5881 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5884 /* reset PML index */
5885 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5888 static void vmx_dump_sel(char *name, uint32_t sel)
5890 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5891 name, vmcs_read16(sel),
5892 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5893 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5894 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5897 static void vmx_dump_dtsel(char *name, uint32_t limit)
5899 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5900 name, vmcs_read32(limit),
5901 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5904 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
5907 struct vmx_msr_entry *e;
5909 pr_err("MSR %s:\n", name);
5910 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
5911 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
5914 void dump_vmcs(struct kvm_vcpu *vcpu)
5916 struct vcpu_vmx *vmx = to_vmx(vcpu);
5917 u32 vmentry_ctl, vmexit_ctl;
5918 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5922 if (!dump_invalid_vmcs) {
5923 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5927 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5928 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5929 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5930 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5931 cr4 = vmcs_readl(GUEST_CR4);
5932 secondary_exec_control = 0;
5933 if (cpu_has_secondary_exec_ctrls())
5934 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5936 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
5937 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
5938 pr_err("*** Guest State ***\n");
5939 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5940 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5941 vmcs_readl(CR0_GUEST_HOST_MASK));
5942 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5943 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5944 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5945 if (cpu_has_vmx_ept()) {
5946 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5947 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5948 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5949 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5951 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5952 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5953 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5954 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5955 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5956 vmcs_readl(GUEST_SYSENTER_ESP),
5957 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5958 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5959 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5960 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5961 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5962 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5963 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5964 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5965 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5966 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5967 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5968 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
5969 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
5970 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
5971 else if (efer_slot >= 0)
5972 pr_err("EFER= 0x%016llx (autoload)\n",
5973 vmx->msr_autoload.guest.val[efer_slot].value);
5974 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
5975 pr_err("EFER= 0x%016llx (effective)\n",
5976 vcpu->arch.efer | (EFER_LMA | EFER_LME));
5978 pr_err("EFER= 0x%016llx (effective)\n",
5979 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
5980 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
5981 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
5982 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5983 vmcs_read64(GUEST_IA32_DEBUGCTL),
5984 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5985 if (cpu_has_load_perf_global_ctrl() &&
5986 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5987 pr_err("PerfGlobCtl = 0x%016llx\n",
5988 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5989 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5990 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5991 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5992 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5993 vmcs_read32(GUEST_ACTIVITY_STATE));
5994 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5995 pr_err("InterruptStatus = %04x\n",
5996 vmcs_read16(GUEST_INTR_STATUS));
5997 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
5998 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
5999 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6000 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6002 pr_err("*** Host State ***\n");
6003 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6004 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6005 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6006 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6007 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6008 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6009 vmcs_read16(HOST_TR_SELECTOR));
6010 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6011 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6012 vmcs_readl(HOST_TR_BASE));
6013 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6014 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6015 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6016 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6017 vmcs_readl(HOST_CR4));
6018 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6019 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6020 vmcs_read32(HOST_IA32_SYSENTER_CS),
6021 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6022 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6023 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6024 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6025 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6026 if (cpu_has_load_perf_global_ctrl() &&
6027 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6028 pr_err("PerfGlobCtl = 0x%016llx\n",
6029 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6030 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6031 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6033 pr_err("*** Control State ***\n");
6034 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
6035 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
6036 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
6037 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6038 vmcs_read32(EXCEPTION_BITMAP),
6039 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6040 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6041 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6042 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6043 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6044 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6045 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6046 vmcs_read32(VM_EXIT_INTR_INFO),
6047 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6048 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6049 pr_err(" reason=%08x qualification=%016lx\n",
6050 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6051 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6052 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6053 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6054 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6055 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6056 pr_err("TSC Multiplier = 0x%016llx\n",
6057 vmcs_read64(TSC_MULTIPLIER));
6058 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6059 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6060 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6061 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6063 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6064 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6065 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6066 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6068 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6069 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6070 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6071 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6072 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6073 pr_err("PLE Gap=%08x Window=%08x\n",
6074 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6075 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6076 pr_err("Virtual processor ID = 0x%04x\n",
6077 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6081 * The guest has exited. See if we can fix it or if we need userspace
6084 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6086 struct vcpu_vmx *vmx = to_vmx(vcpu);
6087 union vmx_exit_reason exit_reason = vmx->exit_reason;
6088 u32 vectoring_info = vmx->idt_vectoring_info;
6089 u16 exit_handler_index;
6092 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6093 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6094 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6095 * mode as if vcpus is in root mode, the PML buffer must has been
6096 * flushed already. Note, PML is never enabled in hardware while
6099 if (enable_pml && !is_guest_mode(vcpu))
6100 vmx_flush_pml_buffer(vcpu);
6103 * KVM should never reach this point with a pending nested VM-Enter.
6104 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6105 * invalid guest state should never happen as that means KVM knowingly
6106 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6108 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6111 if (is_guest_mode(vcpu)) {
6113 * PML is never enabled when running L2, bail immediately if a
6114 * PML full exit occurs as something is horribly wrong.
6116 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6117 goto unexpected_vmexit;
6120 * The host physical addresses of some pages of guest memory
6121 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6122 * Page). The CPU may write to these pages via their host
6123 * physical address while L2 is running, bypassing any
6124 * address-translation-based dirty tracking (e.g. EPT write
6127 * Mark them dirty on every exit from L2 to prevent them from
6128 * getting out of sync with dirty tracking.
6130 nested_mark_vmcs12_pages_dirty(vcpu);
6133 * Synthesize a triple fault if L2 state is invalid. In normal
6134 * operation, nested VM-Enter rejects any attempt to enter L2
6135 * with invalid state. However, those checks are skipped if
6136 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6137 * L2 state is invalid, it means either L1 modified SMRAM state
6138 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6139 * doing so is architecturally allowed in the RSM case, and is
6140 * the least awful solution for the userspace case without
6141 * risking false positives.
6143 if (vmx->emulation_required) {
6144 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6148 if (nested_vmx_reflect_vmexit(vcpu))
6152 /* If guest state is invalid, start emulating. L2 is handled above. */
6153 if (vmx->emulation_required)
6154 return handle_invalid_guest_state(vcpu);
6156 if (exit_reason.failed_vmentry) {
6158 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6159 vcpu->run->fail_entry.hardware_entry_failure_reason
6161 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6165 if (unlikely(vmx->fail)) {
6167 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6168 vcpu->run->fail_entry.hardware_entry_failure_reason
6169 = vmcs_read32(VM_INSTRUCTION_ERROR);
6170 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6176 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6177 * delivery event since it indicates guest is accessing MMIO.
6178 * The vm-exit can be triggered again after return to guest that
6179 * will cause infinite loop.
6181 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6182 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6183 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6184 exit_reason.basic != EXIT_REASON_PML_FULL &&
6185 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6186 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6189 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6190 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6191 vcpu->run->internal.data[0] = vectoring_info;
6192 vcpu->run->internal.data[1] = exit_reason.full;
6193 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6194 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6195 vcpu->run->internal.data[ndata++] =
6196 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6198 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6199 vcpu->run->internal.ndata = ndata;
6203 if (unlikely(!enable_vnmi &&
6204 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6205 if (!vmx_interrupt_blocked(vcpu)) {
6206 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6207 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6208 vcpu->arch.nmi_pending) {
6210 * This CPU don't support us in finding the end of an
6211 * NMI-blocked window if the guest runs with IRQs
6212 * disabled. So we pull the trigger after 1 s of
6213 * futile waiting, but inform the user about this.
6215 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6216 "state on VCPU %d after 1 s timeout\n",
6217 __func__, vcpu->vcpu_id);
6218 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6222 if (exit_fastpath != EXIT_FASTPATH_NONE)
6225 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6226 goto unexpected_vmexit;
6227 #ifdef CONFIG_RETPOLINE
6228 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6229 return kvm_emulate_wrmsr(vcpu);
6230 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6231 return handle_preemption_timer(vcpu);
6232 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6233 return handle_interrupt_window(vcpu);
6234 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6235 return handle_external_interrupt(vcpu);
6236 else if (exit_reason.basic == EXIT_REASON_HLT)
6237 return kvm_emulate_halt(vcpu);
6238 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6239 return handle_ept_misconfig(vcpu);
6242 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6243 kvm_vmx_max_exit_handlers);
6244 if (!kvm_vmx_exit_handlers[exit_handler_index])
6245 goto unexpected_vmexit;
6247 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6250 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6253 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6254 vcpu->run->internal.suberror =
6255 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6256 vcpu->run->internal.ndata = 2;
6257 vcpu->run->internal.data[0] = exit_reason.full;
6258 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6262 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6264 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6267 * Exit to user space when bus lock detected to inform that there is
6268 * a bus lock in guest.
6270 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6272 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6274 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6281 * Software based L1D cache flush which is used when microcode providing
6282 * the cache control MSR is not loaded.
6284 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6285 * flush it is required to read in 64 KiB because the replacement algorithm
6286 * is not exactly LRU. This could be sized at runtime via topology
6287 * information but as all relevant affected CPUs have 32KiB L1D cache size
6288 * there is no point in doing so.
6290 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6292 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6295 * This code is only executed when the flush mode is 'cond' or
6298 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6302 * Clear the per-vcpu flush bit, it gets set again
6303 * either from vcpu_run() or from one of the unsafe
6306 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6307 vcpu->arch.l1tf_flush_l1d = false;
6310 * Clear the per-cpu flush bit, it gets set again from
6311 * the interrupt handlers.
6313 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6314 kvm_clear_cpu_l1tf_flush_l1d();
6320 vcpu->stat.l1d_flush++;
6322 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6323 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6328 /* First ensure the pages are in the TLB */
6329 "xorl %%eax, %%eax\n"
6330 ".Lpopulate_tlb:\n\t"
6331 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6332 "addl $4096, %%eax\n\t"
6333 "cmpl %%eax, %[size]\n\t"
6334 "jne .Lpopulate_tlb\n\t"
6335 "xorl %%eax, %%eax\n\t"
6337 /* Now fill the cache */
6338 "xorl %%eax, %%eax\n"
6340 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6341 "addl $64, %%eax\n\t"
6342 "cmpl %%eax, %[size]\n\t"
6343 "jne .Lfill_cache\n\t"
6345 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6347 : "eax", "ebx", "ecx", "edx");
6350 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6352 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6355 if (is_guest_mode(vcpu) &&
6356 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6359 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6360 if (is_guest_mode(vcpu))
6361 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6363 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6366 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6368 struct vcpu_vmx *vmx = to_vmx(vcpu);
6369 u32 sec_exec_control;
6371 if (!lapic_in_kernel(vcpu))
6374 if (!flexpriority_enabled &&
6375 !cpu_has_vmx_virtualize_x2apic_mode())
6378 /* Postpone execution until vmcs01 is the current VMCS. */
6379 if (is_guest_mode(vcpu)) {
6380 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6384 sec_exec_control = secondary_exec_controls_get(vmx);
6385 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6386 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6388 switch (kvm_get_apic_mode(vcpu)) {
6389 case LAPIC_MODE_INVALID:
6390 WARN_ONCE(true, "Invalid local APIC state");
6392 case LAPIC_MODE_DISABLED:
6394 case LAPIC_MODE_XAPIC:
6395 if (flexpriority_enabled) {
6397 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6398 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6401 * Flush the TLB, reloading the APIC access page will
6402 * only do so if its physical address has changed, but
6403 * the guest may have inserted a non-APIC mapping into
6404 * the TLB while the APIC access page was disabled.
6406 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6409 case LAPIC_MODE_X2APIC:
6410 if (cpu_has_vmx_virtualize_x2apic_mode())
6412 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6415 secondary_exec_controls_set(vmx, sec_exec_control);
6417 vmx_update_msr_bitmap_x2apic(vcpu);
6420 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6424 /* Defer reload until vmcs01 is the current VMCS. */
6425 if (is_guest_mode(vcpu)) {
6426 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6430 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6431 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6434 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6435 if (is_error_page(page))
6438 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6439 vmx_flush_tlb_current(vcpu);
6442 * Do not pin apic access page in memory, the MMU notifier
6443 * will call us again if it is migrated or swapped out.
6448 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6456 status = vmcs_read16(GUEST_INTR_STATUS);
6458 if (max_isr != old) {
6460 status |= max_isr << 8;
6461 vmcs_write16(GUEST_INTR_STATUS, status);
6465 static void vmx_set_rvi(int vector)
6473 status = vmcs_read16(GUEST_INTR_STATUS);
6474 old = (u8)status & 0xff;
6475 if ((u8)vector != old) {
6477 status |= (u8)vector;
6478 vmcs_write16(GUEST_INTR_STATUS, status);
6482 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6485 * When running L2, updating RVI is only relevant when
6486 * vmcs12 virtual-interrupt-delivery enabled.
6487 * However, it can be enabled only when L1 also
6488 * intercepts external-interrupts and in that case
6489 * we should not update vmcs02 RVI but instead intercept
6490 * interrupt. Therefore, do nothing when running L2.
6492 if (!is_guest_mode(vcpu))
6493 vmx_set_rvi(max_irr);
6496 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6498 struct vcpu_vmx *vmx = to_vmx(vcpu);
6500 bool got_posted_interrupt;
6502 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6505 if (pi_test_on(&vmx->pi_desc)) {
6506 pi_clear_on(&vmx->pi_desc);
6508 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6509 * But on x86 this is just a compiler barrier anyway.
6511 smp_mb__after_atomic();
6512 got_posted_interrupt =
6513 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6515 max_irr = kvm_lapic_find_highest_irr(vcpu);
6516 got_posted_interrupt = false;
6520 * Newly recognized interrupts are injected via either virtual interrupt
6521 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6522 * disabled in two cases:
6524 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6525 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6526 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6527 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6528 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6530 * 2) If APICv is disabled for this vCPU, assigned devices may still
6531 * attempt to post interrupts. The posted interrupt vector will cause
6532 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6534 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6535 vmx_set_rvi(max_irr);
6536 else if (got_posted_interrupt)
6537 kvm_make_request(KVM_REQ_EVENT, vcpu);
6542 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6544 if (!kvm_vcpu_apicv_active(vcpu))
6547 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6548 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6549 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6550 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6553 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6555 struct vcpu_vmx *vmx = to_vmx(vcpu);
6557 pi_clear_on(&vmx->pi_desc);
6558 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6561 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6563 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6564 unsigned long entry)
6566 bool is_nmi = entry == (unsigned long)asm_exc_nmi_noist;
6568 kvm_before_interrupt(vcpu, is_nmi ? KVM_HANDLING_NMI : KVM_HANDLING_IRQ);
6569 vmx_do_interrupt_nmi_irqoff(entry);
6570 kvm_after_interrupt(vcpu);
6573 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6576 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6577 * MSR value is not clobbered by the host activity before the guest
6578 * has chance to consume it.
6580 * Do not blindly read xfd_err here, since this exception might
6581 * be caused by L1 interception on a platform which doesn't
6582 * support xfd at all.
6584 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6585 * only when xfd contains a non-zero value.
6587 * Queuing exception is done in vmx_handle_exit. See comment there.
6589 if (vcpu->arch.guest_fpu.fpstate->xfd)
6590 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6593 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6595 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6596 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6598 /* if exit due to PF check for async PF */
6599 if (is_page_fault(intr_info))
6600 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6601 /* if exit due to NM, handle before interrupts are enabled */
6602 else if (is_nm_fault(intr_info))
6603 handle_nm_fault_irqoff(&vmx->vcpu);
6604 /* Handle machine checks before interrupts are enabled */
6605 else if (is_machine_check(intr_info))
6606 kvm_machine_check();
6607 /* We need to handle NMIs before interrupts are enabled */
6608 else if (is_nmi(intr_info))
6609 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6612 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6614 u32 intr_info = vmx_get_intr_info(vcpu);
6615 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6616 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6618 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6619 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6622 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6623 vcpu->arch.at_instruction_boundary = true;
6626 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6628 struct vcpu_vmx *vmx = to_vmx(vcpu);
6630 if (vmx->emulation_required)
6633 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6634 handle_external_interrupt_irqoff(vcpu);
6635 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6636 handle_exception_nmi_irqoff(vmx);
6640 * The kvm parameter can be NULL (module initialization, or invocation before
6641 * VM creation). Be sure to check the kvm parameter before using it.
6643 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6646 case MSR_IA32_SMBASE:
6648 * We cannot do SMM unless we can run the guest in big
6651 return enable_unrestricted_guest || emulate_invalid_guest_state;
6652 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6654 case MSR_AMD64_VIRT_SPEC_CTRL:
6655 case MSR_AMD64_TSC_RATIO:
6656 /* This is AMD only. */
6663 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6668 bool idtv_info_valid;
6670 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6673 if (vmx->loaded_vmcs->nmi_known_unmasked)
6676 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6677 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6678 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6680 * SDM 3: 27.7.1.2 (September 2008)
6681 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6682 * a guest IRET fault.
6683 * SDM 3: 23.2.2 (September 2008)
6684 * Bit 12 is undefined in any of the following cases:
6685 * If the VM exit sets the valid bit in the IDT-vectoring
6686 * information field.
6687 * If the VM exit is due to a double fault.
6689 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6690 vector != DF_VECTOR && !idtv_info_valid)
6691 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6692 GUEST_INTR_STATE_NMI);
6694 vmx->loaded_vmcs->nmi_known_unmasked =
6695 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6696 & GUEST_INTR_STATE_NMI);
6697 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6698 vmx->loaded_vmcs->vnmi_blocked_time +=
6699 ktime_to_ns(ktime_sub(ktime_get(),
6700 vmx->loaded_vmcs->entry_time));
6703 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6704 u32 idt_vectoring_info,
6705 int instr_len_field,
6706 int error_code_field)
6710 bool idtv_info_valid;
6712 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6714 vcpu->arch.nmi_injected = false;
6715 kvm_clear_exception_queue(vcpu);
6716 kvm_clear_interrupt_queue(vcpu);
6718 if (!idtv_info_valid)
6721 kvm_make_request(KVM_REQ_EVENT, vcpu);
6723 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6724 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6727 case INTR_TYPE_NMI_INTR:
6728 vcpu->arch.nmi_injected = true;
6730 * SDM 3: 27.7.1.2 (September 2008)
6731 * Clear bit "block by NMI" before VM entry if a NMI
6734 vmx_set_nmi_mask(vcpu, false);
6736 case INTR_TYPE_SOFT_EXCEPTION:
6737 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6739 case INTR_TYPE_HARD_EXCEPTION:
6740 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6741 u32 err = vmcs_read32(error_code_field);
6742 kvm_requeue_exception_e(vcpu, vector, err);
6744 kvm_requeue_exception(vcpu, vector);
6746 case INTR_TYPE_SOFT_INTR:
6747 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6749 case INTR_TYPE_EXT_INTR:
6750 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6757 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6759 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6760 VM_EXIT_INSTRUCTION_LEN,
6761 IDT_VECTORING_ERROR_CODE);
6764 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6766 __vmx_complete_interrupts(vcpu,
6767 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6768 VM_ENTRY_INSTRUCTION_LEN,
6769 VM_ENTRY_EXCEPTION_ERROR_CODE);
6771 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6774 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6777 struct perf_guest_switch_msr *msrs;
6779 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6780 msrs = perf_guest_get_msrs(&nr_msrs);
6784 for (i = 0; i < nr_msrs; i++)
6785 if (msrs[i].host == msrs[i].guest)
6786 clear_atomic_switch_msr(vmx, msrs[i].msr);
6788 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6789 msrs[i].host, false);
6792 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6794 struct vcpu_vmx *vmx = to_vmx(vcpu);
6798 if (vmx->req_immediate_exit) {
6799 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6800 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6801 } else if (vmx->hv_deadline_tsc != -1) {
6803 if (vmx->hv_deadline_tsc > tscl)
6804 /* set_hv_timer ensures the delta fits in 32-bits */
6805 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6806 cpu_preemption_timer_multi);
6810 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6811 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6812 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6813 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6814 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6818 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6820 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6821 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6822 vmcs_writel(HOST_RSP, host_rsp);
6826 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6828 switch (to_vmx(vcpu)->exit_reason.basic) {
6829 case EXIT_REASON_MSR_WRITE:
6830 return handle_fastpath_set_msr_irqoff(vcpu);
6831 case EXIT_REASON_PREEMPTION_TIMER:
6832 return handle_fastpath_preemption_timer(vcpu);
6834 return EXIT_FASTPATH_NONE;
6838 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6839 struct vcpu_vmx *vmx,
6840 unsigned long flags)
6842 guest_state_enter_irqoff();
6844 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6845 if (static_branch_unlikely(&vmx_l1d_should_flush))
6846 vmx_l1d_flush(vcpu);
6847 else if (static_branch_unlikely(&mds_user_clear))
6848 mds_clear_cpu_buffers();
6849 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
6850 kvm_arch_has_assigned_device(vcpu->kvm))
6851 mds_clear_cpu_buffers();
6853 vmx_disable_fb_clear(vmx);
6855 if (vcpu->arch.cr2 != native_read_cr2())
6856 native_write_cr2(vcpu->arch.cr2);
6858 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6861 vcpu->arch.cr2 = native_read_cr2();
6863 vmx_enable_fb_clear(vmx);
6865 guest_state_exit_irqoff();
6868 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6870 struct vcpu_vmx *vmx = to_vmx(vcpu);
6871 unsigned long cr3, cr4;
6873 /* Record the guest's net vcpu time for enforced NMI injections. */
6874 if (unlikely(!enable_vnmi &&
6875 vmx->loaded_vmcs->soft_vnmi_blocked))
6876 vmx->loaded_vmcs->entry_time = ktime_get();
6879 * Don't enter VMX if guest state is invalid, let the exit handler
6880 * start emulation until we arrive back to a valid state. Synthesize a
6881 * consistency check VM-Exit due to invalid guest state and bail.
6883 if (unlikely(vmx->emulation_required)) {
6886 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
6887 vmx->exit_reason.failed_vmentry = 1;
6888 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
6889 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
6890 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
6891 vmx->exit_intr_info = 0;
6892 return EXIT_FASTPATH_NONE;
6895 trace_kvm_entry(vcpu);
6897 if (vmx->ple_window_dirty) {
6898 vmx->ple_window_dirty = false;
6899 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6903 * We did this in prepare_switch_to_guest, because it needs to
6904 * be within srcu_read_lock.
6906 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6908 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6909 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6910 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6911 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6912 vcpu->arch.regs_dirty = 0;
6915 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
6916 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
6917 * it switches back to the current->mm, which can occur in KVM context
6918 * when switching to a temporary mm to patch kernel code, e.g. if KVM
6919 * toggles a static key while handling a VM-Exit.
6921 cr3 = __get_current_cr3_fast();
6922 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6923 vmcs_writel(HOST_CR3, cr3);
6924 vmx->loaded_vmcs->host_state.cr3 = cr3;
6927 cr4 = cr4_read_shadow();
6928 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6929 vmcs_writel(HOST_CR4, cr4);
6930 vmx->loaded_vmcs->host_state.cr4 = cr4;
6933 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
6934 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
6935 set_debugreg(vcpu->arch.dr6, 6);
6937 /* When single-stepping over STI and MOV SS, we must clear the
6938 * corresponding interruptibility bits in the guest state. Otherwise
6939 * vmentry fails as it then expects bit 14 (BS) in pending debug
6940 * exceptions being set, but that's not correct for the guest debugging
6942 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6943 vmx_set_interrupt_shadow(vcpu, 0);
6945 kvm_load_guest_xsave_state(vcpu);
6947 pt_guest_enter(vmx);
6949 atomic_switch_perf_msrs(vmx);
6950 if (intel_pmu_lbr_is_enabled(vcpu))
6951 vmx_passthrough_lbr_msrs(vcpu);
6953 if (enable_preemption_timer)
6954 vmx_update_hv_timer(vcpu);
6956 kvm_wait_lapic_expire(vcpu);
6959 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6960 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6961 * is no need to worry about the conditional branch over the wrmsr
6962 * being speculatively taken.
6964 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6966 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6967 vmx_vcpu_enter_exit(vcpu, vmx, __vmx_vcpu_run_flags(vmx));
6970 * We do not use IBRS in the kernel. If this vCPU has used the
6971 * SPEC_CTRL MSR it may have left it on; save the value and
6972 * turn it off. This is much more efficient than blindly adding
6973 * it to the atomic save/restore list. Especially as the former
6974 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6976 * For non-nested case:
6977 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6981 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6984 if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
6985 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6987 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6989 /* All fields are clean at this point */
6990 if (static_branch_unlikely(&enable_evmcs)) {
6991 current_evmcs->hv_clean_fields |=
6992 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6994 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
6997 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6998 if (vmx->host_debugctlmsr)
6999 update_debugctlmsr(vmx->host_debugctlmsr);
7001 #ifndef CONFIG_X86_64
7003 * The sysexit path does not restore ds/es, so we must set them to
7004 * a reasonable value ourselves.
7006 * We can't defer this to vmx_prepare_switch_to_host() since that
7007 * function may be executed in interrupt context, which saves and
7008 * restore segments around it, nullifying its effect.
7010 loadsegment(ds, __USER_DS);
7011 loadsegment(es, __USER_DS);
7014 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7018 kvm_load_host_xsave_state(vcpu);
7020 if (is_guest_mode(vcpu)) {
7022 * Track VMLAUNCH/VMRESUME that have made past guest state
7025 if (vmx->nested.nested_run_pending &&
7026 !vmx->exit_reason.failed_vmentry)
7027 ++vcpu->stat.nested_run;
7029 vmx->nested.nested_run_pending = 0;
7032 vmx->idt_vectoring_info = 0;
7034 if (unlikely(vmx->fail)) {
7035 vmx->exit_reason.full = 0xdead;
7036 return EXIT_FASTPATH_NONE;
7039 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7040 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7041 kvm_machine_check();
7043 if (likely(!vmx->exit_reason.failed_vmentry))
7044 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7046 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7048 if (unlikely(vmx->exit_reason.failed_vmentry))
7049 return EXIT_FASTPATH_NONE;
7051 vmx->loaded_vmcs->launched = 1;
7053 vmx_recover_nmi_blocking(vmx);
7054 vmx_complete_interrupts(vmx);
7056 if (is_guest_mode(vcpu))
7057 return EXIT_FASTPATH_NONE;
7059 return vmx_exit_handlers_fastpath(vcpu);
7062 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7064 struct vcpu_vmx *vmx = to_vmx(vcpu);
7067 vmx_destroy_pml_buffer(vmx);
7068 free_vpid(vmx->vpid);
7069 nested_vmx_free_vcpu(vcpu);
7070 free_loaded_vmcs(vmx->loaded_vmcs);
7073 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7075 struct vmx_uret_msr *tsx_ctrl;
7076 struct vcpu_vmx *vmx;
7079 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7082 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7086 vmx->vpid = allocate_vpid();
7089 * If PML is turned on, failure on enabling PML just results in failure
7090 * of creating the vcpu, therefore we can simplify PML logic (by
7091 * avoiding dealing with cases, such as enabling PML partially on vcpus
7092 * for the guest), etc.
7095 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7100 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7101 vmx->guest_uret_msrs[i].mask = -1ull;
7102 if (boot_cpu_has(X86_FEATURE_RTM)) {
7104 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7105 * Keep the host value unchanged to avoid changing CPUID bits
7106 * under the host kernel's feet.
7108 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7110 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7113 err = alloc_loaded_vmcs(&vmx->vmcs01);
7118 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7119 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7120 * feature only for vmcs01, KVM currently isn't equipped to realize any
7121 * performance benefits from enabling it for vmcs02.
7123 if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs) &&
7124 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7125 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7127 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7130 /* The MSR bitmap starts with all ones */
7131 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7132 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7134 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7135 #ifdef CONFIG_X86_64
7136 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7137 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7138 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7140 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7141 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7142 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7143 if (kvm_cstate_in_guest(vcpu->kvm)) {
7144 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7145 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7146 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7147 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7150 vmx->loaded_vmcs = &vmx->vmcs01;
7152 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7153 err = alloc_apic_access_page(vcpu->kvm);
7158 if (enable_ept && !enable_unrestricted_guest) {
7159 err = init_rmode_identity_map(vcpu->kvm);
7167 free_loaded_vmcs(vmx->loaded_vmcs);
7169 vmx_destroy_pml_buffer(vmx);
7171 free_vpid(vmx->vpid);
7175 #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"
7176 #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"
7178 static int vmx_vm_init(struct kvm *kvm)
7181 kvm->arch.pause_in_guest = true;
7183 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7184 switch (l1tf_mitigation) {
7185 case L1TF_MITIGATION_OFF:
7186 case L1TF_MITIGATION_FLUSH_NOWARN:
7187 /* 'I explicitly don't care' is set */
7189 case L1TF_MITIGATION_FLUSH:
7190 case L1TF_MITIGATION_FLUSH_NOSMT:
7191 case L1TF_MITIGATION_FULL:
7193 * Warn upon starting the first VM in a potentially
7194 * insecure environment.
7196 if (sched_smt_active())
7197 pr_warn_once(L1TF_MSG_SMT);
7198 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7199 pr_warn_once(L1TF_MSG_L1D);
7201 case L1TF_MITIGATION_FULL_FORCE:
7202 /* Flush is enforced */
7209 static int __init vmx_check_processor_compat(void)
7211 struct vmcs_config vmcs_conf;
7212 struct vmx_capability vmx_cap;
7214 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7215 !this_cpu_has(X86_FEATURE_VMX)) {
7216 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7220 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7223 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7224 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7225 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7226 smp_processor_id());
7232 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7236 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7237 * memory aliases with conflicting memory types and sometimes MCEs.
7238 * We have to be careful as to what are honored and when.
7240 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7241 * UC. The effective memory type is UC or WC depending on guest PAT.
7242 * This was historically the source of MCEs and we want to be
7245 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7246 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7247 * EPT memory type is set to WB. The effective memory type is forced
7250 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7251 * EPT memory type is used to emulate guest CD/MTRR.
7255 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7257 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7258 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7260 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7261 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7262 cache = MTRR_TYPE_WRBACK;
7264 cache = MTRR_TYPE_UNCACHABLE;
7266 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7269 return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7272 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7275 * These bits in the secondary execution controls field
7276 * are dynamic, the others are mostly based on the hypervisor
7277 * architecture and the guest's CPUID. Do not touch the
7281 SECONDARY_EXEC_SHADOW_VMCS |
7282 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7283 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7284 SECONDARY_EXEC_DESC;
7286 u32 cur_ctl = secondary_exec_controls_get(vmx);
7288 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7292 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7293 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7295 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7297 struct vcpu_vmx *vmx = to_vmx(vcpu);
7298 struct kvm_cpuid_entry2 *entry;
7300 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7301 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7303 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7304 if (entry && (entry->_reg & (_cpuid_mask))) \
7305 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7308 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7309 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7310 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7311 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7312 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7313 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7314 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7315 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7316 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7317 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7318 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7319 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7320 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7321 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7322 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7324 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7325 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7326 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7327 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7328 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7329 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7330 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7332 #undef cr4_fixed1_update
7335 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7337 struct vcpu_vmx *vmx = to_vmx(vcpu);
7339 if (kvm_mpx_supported()) {
7340 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7343 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7344 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7346 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7347 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7352 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7354 struct vcpu_vmx *vmx = to_vmx(vcpu);
7355 struct kvm_cpuid_entry2 *best = NULL;
7358 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7359 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7362 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7363 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7364 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7365 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7368 /* Get the number of configurable Address Ranges for filtering */
7369 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7370 PT_CAP_num_address_ranges);
7372 /* Initialize and clear the no dependency bits */
7373 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7374 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7375 RTIT_CTL_BRANCH_EN);
7378 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7379 * will inject an #GP
7381 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7382 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7385 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7386 * PSBFreq can be set
7388 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7389 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7390 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7393 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7395 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7396 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7397 RTIT_CTL_MTC_RANGE);
7399 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7400 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7401 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7404 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7405 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7406 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7408 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7409 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7410 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7412 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7413 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7414 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7416 /* unmask address range configure area */
7417 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7418 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7421 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7423 struct vcpu_vmx *vmx = to_vmx(vcpu);
7425 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7426 vcpu->arch.xsaves_enabled = false;
7428 vmx_setup_uret_msrs(vmx);
7430 if (cpu_has_secondary_exec_ctrls())
7431 vmcs_set_secondary_exec_control(vmx,
7432 vmx_secondary_exec_control(vmx));
7434 if (nested_vmx_allowed(vcpu))
7435 vmx->msr_ia32_feature_control_valid_bits |=
7436 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7437 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7439 vmx->msr_ia32_feature_control_valid_bits &=
7440 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7441 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7443 if (nested_vmx_allowed(vcpu)) {
7444 nested_vmx_cr_fixed1_bits_update(vcpu);
7445 nested_vmx_entry_exit_ctls_update(vcpu);
7448 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7449 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7450 update_intel_pt_cfg(vcpu);
7452 if (boot_cpu_has(X86_FEATURE_RTM)) {
7453 struct vmx_uret_msr *msr;
7454 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7456 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7457 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7461 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7462 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7463 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7466 set_cr4_guest_host_mask(vmx);
7468 vmx_write_encls_bitmap(vcpu, NULL);
7469 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7470 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7472 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7474 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7475 vmx->msr_ia32_feature_control_valid_bits |=
7476 FEAT_CTL_SGX_LC_ENABLED;
7478 vmx->msr_ia32_feature_control_valid_bits &=
7479 ~FEAT_CTL_SGX_LC_ENABLED;
7481 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7482 vmx_update_exception_bitmap(vcpu);
7485 static __init void vmx_set_cpu_caps(void)
7491 kvm_cpu_cap_set(X86_FEATURE_VMX);
7494 if (kvm_mpx_supported())
7495 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7496 if (!cpu_has_vmx_invpcid())
7497 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7498 if (vmx_pt_mode_is_host_guest())
7499 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7502 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7503 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7504 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7505 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7508 if (vmx_umip_emulated())
7509 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7513 if (!cpu_has_vmx_xsaves())
7514 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7516 /* CPUID 0x80000001 and 0x7 (RDPID) */
7517 if (!cpu_has_vmx_rdtscp()) {
7518 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7519 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7522 if (cpu_has_vmx_waitpkg())
7523 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7526 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7528 to_vmx(vcpu)->req_immediate_exit = true;
7531 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7532 struct x86_instruction_info *info)
7534 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7535 unsigned short port;
7539 if (info->intercept == x86_intercept_in ||
7540 info->intercept == x86_intercept_ins) {
7541 port = info->src_val;
7542 size = info->dst_bytes;
7544 port = info->dst_val;
7545 size = info->src_bytes;
7549 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7550 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7553 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7555 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7556 intercept = nested_cpu_has(vmcs12,
7557 CPU_BASED_UNCOND_IO_EXITING);
7559 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7561 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7562 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7565 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7566 struct x86_instruction_info *info,
7567 enum x86_intercept_stage stage,
7568 struct x86_exception *exception)
7570 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7572 switch (info->intercept) {
7574 * RDPID causes #UD if disabled through secondary execution controls.
7575 * Because it is marked as EmulateOnUD, we need to intercept it here.
7576 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7578 case x86_intercept_rdpid:
7579 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7580 exception->vector = UD_VECTOR;
7581 exception->error_code_valid = false;
7582 return X86EMUL_PROPAGATE_FAULT;
7586 case x86_intercept_in:
7587 case x86_intercept_ins:
7588 case x86_intercept_out:
7589 case x86_intercept_outs:
7590 return vmx_check_intercept_io(vcpu, info);
7592 case x86_intercept_lgdt:
7593 case x86_intercept_lidt:
7594 case x86_intercept_lldt:
7595 case x86_intercept_ltr:
7596 case x86_intercept_sgdt:
7597 case x86_intercept_sidt:
7598 case x86_intercept_sldt:
7599 case x86_intercept_str:
7600 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7601 return X86EMUL_CONTINUE;
7603 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7606 /* TODO: check more intercepts... */
7611 return X86EMUL_UNHANDLEABLE;
7614 #ifdef CONFIG_X86_64
7615 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7616 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7617 u64 divisor, u64 *result)
7619 u64 low = a << shift, high = a >> (64 - shift);
7621 /* To avoid the overflow on divq */
7622 if (high >= divisor)
7625 /* Low hold the result, high hold rem which is discarded */
7626 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7627 "rm" (divisor), "0" (low), "1" (high));
7633 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7636 struct vcpu_vmx *vmx;
7637 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7638 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7642 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7643 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7644 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7645 ktimer->timer_advance_ns);
7647 if (delta_tsc > lapic_timer_advance_cycles)
7648 delta_tsc -= lapic_timer_advance_cycles;
7652 /* Convert to host delta tsc if tsc scaling is enabled */
7653 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7654 delta_tsc && u64_shl_div_u64(delta_tsc,
7655 kvm_tsc_scaling_ratio_frac_bits,
7656 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7660 * If the delta tsc can't fit in the 32 bit after the multi shift,
7661 * we can't use the preemption timer.
7662 * It's possible that it fits on later vmentries, but checking
7663 * on every vmentry is costly so we just use an hrtimer.
7665 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7668 vmx->hv_deadline_tsc = tscl + delta_tsc;
7669 *expired = !delta_tsc;
7673 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7675 to_vmx(vcpu)->hv_deadline_tsc = -1;
7679 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7681 if (!kvm_pause_in_guest(vcpu->kvm))
7682 shrink_ple_window(vcpu);
7685 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7687 struct vcpu_vmx *vmx = to_vmx(vcpu);
7689 if (is_guest_mode(vcpu)) {
7690 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7695 * Note, cpu_dirty_logging_count can be changed concurrent with this
7696 * code, but in that case another update request will be made and so
7697 * the guest will never run with a stale PML value.
7699 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7700 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7702 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7705 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7707 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7708 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7709 FEAT_CTL_LMCE_ENABLED;
7711 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7712 ~FEAT_CTL_LMCE_ENABLED;
7715 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7717 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7718 if (to_vmx(vcpu)->nested.nested_run_pending)
7720 return !is_smm(vcpu);
7723 static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7725 struct vcpu_vmx *vmx = to_vmx(vcpu);
7727 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7728 if (vmx->nested.smm.guest_mode)
7729 nested_vmx_vmexit(vcpu, -1, 0, 0);
7731 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7732 vmx->nested.vmxon = false;
7733 vmx_clear_hlt(vcpu);
7737 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7739 struct vcpu_vmx *vmx = to_vmx(vcpu);
7742 if (vmx->nested.smm.vmxon) {
7743 vmx->nested.vmxon = true;
7744 vmx->nested.smm.vmxon = false;
7747 if (vmx->nested.smm.guest_mode) {
7748 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7752 vmx->nested.nested_run_pending = 1;
7753 vmx->nested.smm.guest_mode = false;
7758 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7760 /* RSM will cause a vmexit anyway. */
7763 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7765 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7768 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7770 if (is_guest_mode(vcpu)) {
7771 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7773 if (hrtimer_try_to_cancel(timer) == 1)
7774 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7778 static void vmx_hardware_unsetup(void)
7780 kvm_set_posted_intr_wakeup_handler(NULL);
7783 nested_vmx_hardware_unsetup();
7788 static bool vmx_check_apicv_inhibit_reasons(enum kvm_apicv_inhibit reason)
7790 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7791 BIT(APICV_INHIBIT_REASON_ABSENT) |
7792 BIT(APICV_INHIBIT_REASON_HYPERV) |
7793 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |
7794 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |
7795 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
7797 return supported & BIT(reason);
7800 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7801 .name = "kvm_intel",
7803 .hardware_unsetup = vmx_hardware_unsetup,
7805 .hardware_enable = vmx_hardware_enable,
7806 .hardware_disable = vmx_hardware_disable,
7807 .has_emulated_msr = vmx_has_emulated_msr,
7809 .vm_size = sizeof(struct kvm_vmx),
7810 .vm_init = vmx_vm_init,
7812 .vcpu_create = vmx_vcpu_create,
7813 .vcpu_free = vmx_vcpu_free,
7814 .vcpu_reset = vmx_vcpu_reset,
7816 .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
7817 .vcpu_load = vmx_vcpu_load,
7818 .vcpu_put = vmx_vcpu_put,
7820 .update_exception_bitmap = vmx_update_exception_bitmap,
7821 .get_msr_feature = vmx_get_msr_feature,
7822 .get_msr = vmx_get_msr,
7823 .set_msr = vmx_set_msr,
7824 .get_segment_base = vmx_get_segment_base,
7825 .get_segment = vmx_get_segment,
7826 .set_segment = vmx_set_segment,
7827 .get_cpl = vmx_get_cpl,
7828 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7829 .set_cr0 = vmx_set_cr0,
7830 .is_valid_cr4 = vmx_is_valid_cr4,
7831 .set_cr4 = vmx_set_cr4,
7832 .set_efer = vmx_set_efer,
7833 .get_idt = vmx_get_idt,
7834 .set_idt = vmx_set_idt,
7835 .get_gdt = vmx_get_gdt,
7836 .set_gdt = vmx_set_gdt,
7837 .set_dr7 = vmx_set_dr7,
7838 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7839 .cache_reg = vmx_cache_reg,
7840 .get_rflags = vmx_get_rflags,
7841 .set_rflags = vmx_set_rflags,
7842 .get_if_flag = vmx_get_if_flag,
7844 .flush_tlb_all = vmx_flush_tlb_all,
7845 .flush_tlb_current = vmx_flush_tlb_current,
7846 .flush_tlb_gva = vmx_flush_tlb_gva,
7847 .flush_tlb_guest = vmx_flush_tlb_guest,
7849 .vcpu_pre_run = vmx_vcpu_pre_run,
7850 .vcpu_run = vmx_vcpu_run,
7851 .handle_exit = vmx_handle_exit,
7852 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7853 .update_emulated_instruction = vmx_update_emulated_instruction,
7854 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7855 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7856 .patch_hypercall = vmx_patch_hypercall,
7857 .inject_irq = vmx_inject_irq,
7858 .inject_nmi = vmx_inject_nmi,
7859 .queue_exception = vmx_queue_exception,
7860 .cancel_injection = vmx_cancel_injection,
7861 .interrupt_allowed = vmx_interrupt_allowed,
7862 .nmi_allowed = vmx_nmi_allowed,
7863 .get_nmi_mask = vmx_get_nmi_mask,
7864 .set_nmi_mask = vmx_set_nmi_mask,
7865 .enable_nmi_window = vmx_enable_nmi_window,
7866 .enable_irq_window = vmx_enable_irq_window,
7867 .update_cr8_intercept = vmx_update_cr8_intercept,
7868 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7869 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7870 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7871 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7872 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7873 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7874 .hwapic_irr_update = vmx_hwapic_irr_update,
7875 .hwapic_isr_update = vmx_hwapic_isr_update,
7876 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7877 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7878 .deliver_interrupt = vmx_deliver_interrupt,
7879 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7881 .set_tss_addr = vmx_set_tss_addr,
7882 .set_identity_map_addr = vmx_set_identity_map_addr,
7883 .get_mt_mask = vmx_get_mt_mask,
7885 .get_exit_info = vmx_get_exit_info,
7887 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7889 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7891 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
7892 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
7893 .write_tsc_offset = vmx_write_tsc_offset,
7894 .write_tsc_multiplier = vmx_write_tsc_multiplier,
7896 .load_mmu_pgd = vmx_load_mmu_pgd,
7898 .check_intercept = vmx_check_intercept,
7899 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7901 .request_immediate_exit = vmx_request_immediate_exit,
7903 .sched_in = vmx_sched_in,
7905 .cpu_dirty_log_size = PML_ENTITY_NUM,
7906 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
7908 .nested_ops = &vmx_nested_ops,
7910 .pi_update_irte = vmx_pi_update_irte,
7911 .pi_start_assignment = vmx_pi_start_assignment,
7913 #ifdef CONFIG_X86_64
7914 .set_hv_timer = vmx_set_hv_timer,
7915 .cancel_hv_timer = vmx_cancel_hv_timer,
7918 .setup_mce = vmx_setup_mce,
7920 .smi_allowed = vmx_smi_allowed,
7921 .enter_smm = vmx_enter_smm,
7922 .leave_smm = vmx_leave_smm,
7923 .enable_smi_window = vmx_enable_smi_window,
7925 .can_emulate_instruction = vmx_can_emulate_instruction,
7926 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7927 .migrate_timers = vmx_migrate_timers,
7929 .msr_filter_changed = vmx_msr_filter_changed,
7930 .complete_emulated_msr = kvm_complete_insn_gp,
7932 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7935 static unsigned int vmx_handle_intel_pt_intr(void)
7937 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
7939 /* '0' on failure so that the !PT case can use a RET0 static call. */
7940 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
7943 kvm_make_request(KVM_REQ_PMI, vcpu);
7944 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7945 (unsigned long *)&vcpu->arch.pmu.global_status);
7949 static __init void vmx_setup_user_return_msrs(void)
7953 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
7954 * will emulate SYSCALL in legacy mode if the vendor string in guest
7955 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
7956 * support this emulation, MSR_STAR is included in the list for i386,
7957 * but is never loaded into hardware. MSR_CSTAR is also never loaded
7958 * into hardware and is here purely for emulation purposes.
7960 const u32 vmx_uret_msrs_list[] = {
7961 #ifdef CONFIG_X86_64
7962 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
7964 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
7969 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
7971 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7972 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
7975 static void __init vmx_setup_me_spte_mask(void)
7980 * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
7981 * the former to avoid exposing shadow_phys_bits.
7983 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
7984 * shadow_phys_bits. On MKTME and/or TDX capable systems,
7985 * boot_cpu_data.x86_phys_bits holds the actual physical address
7986 * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
7987 * reported by CPUID. Those bits between are KeyID bits.
7989 if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
7990 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
7991 kvm_get_shadow_phys_bits() - 1);
7993 * Unlike SME, host kernel doesn't support setting up any
7994 * MKTME KeyID on Intel platforms. No memory encryption
7995 * bits should be included into the SPTE.
7997 kvm_mmu_set_me_spte_mask(0, me_mask);
8000 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8002 static __init int hardware_setup(void)
8004 unsigned long host_bndcfgs;
8009 host_idt_base = dt.address;
8011 vmx_setup_user_return_msrs();
8013 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8016 if (boot_cpu_has(X86_FEATURE_NX))
8017 kvm_enable_efer_bits(EFER_NX);
8019 if (boot_cpu_has(X86_FEATURE_MPX)) {
8020 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8021 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8024 if (!cpu_has_vmx_mpx())
8025 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8026 XFEATURE_MASK_BNDCSR);
8028 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8029 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8032 if (!cpu_has_vmx_ept() ||
8033 !cpu_has_vmx_ept_4levels() ||
8034 !cpu_has_vmx_ept_mt_wb() ||
8035 !cpu_has_vmx_invept_global())
8038 /* NX support is required for shadow paging. */
8039 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8040 pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
8044 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8045 enable_ept_ad_bits = 0;
8047 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8048 enable_unrestricted_guest = 0;
8050 if (!cpu_has_vmx_flexpriority())
8051 flexpriority_enabled = 0;
8053 if (!cpu_has_virtual_nmis())
8057 * set_apic_access_page_addr() is used to reload apic access
8058 * page upon invalidation. No need to do anything if not
8059 * using the APIC_ACCESS_ADDR VMCS field.
8061 if (!flexpriority_enabled)
8062 vmx_x86_ops.set_apic_access_page_addr = NULL;
8064 if (!cpu_has_vmx_tpr_shadow())
8065 vmx_x86_ops.update_cr8_intercept = NULL;
8067 #if IS_ENABLED(CONFIG_HYPERV)
8068 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8070 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8071 vmx_x86_ops.tlb_remote_flush_with_range =
8072 hv_remote_flush_tlb_with_range;
8076 if (!cpu_has_vmx_ple()) {
8079 ple_window_grow = 0;
8081 ple_window_shrink = 0;
8084 if (!cpu_has_vmx_apicv())
8087 vmx_x86_ops.sync_pir_to_irr = NULL;
8089 if (cpu_has_vmx_tsc_scaling())
8090 kvm_has_tsc_control = true;
8092 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8093 kvm_tsc_scaling_ratio_frac_bits = 48;
8094 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8096 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8099 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8100 cpu_has_vmx_ept_execute_only());
8103 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8104 * bits to shadow_zero_check.
8106 vmx_setup_me_spte_mask();
8108 kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
8109 ept_caps_to_lpage_level(vmx_capability.ept));
8112 * Only enable PML when hardware supports PML feature, and both EPT
8113 * and EPT A/D bit features are enabled -- PML depends on them to work.
8115 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8119 vmx_x86_ops.cpu_dirty_log_size = 0;
8121 if (!cpu_has_vmx_preemption_timer())
8122 enable_preemption_timer = false;
8124 if (enable_preemption_timer) {
8125 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8128 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8129 cpu_preemption_timer_multi =
8130 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8133 use_timer_freq = (u64)tsc_khz * 1000;
8134 use_timer_freq >>= cpu_preemption_timer_multi;
8137 * KVM "disables" the preemption timer by setting it to its max
8138 * value. Don't use the timer if it might cause spurious exits
8139 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8141 if (use_timer_freq > 0xffffffffu / 10)
8142 enable_preemption_timer = false;
8145 if (!enable_preemption_timer) {
8146 vmx_x86_ops.set_hv_timer = NULL;
8147 vmx_x86_ops.cancel_hv_timer = NULL;
8148 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8151 kvm_mce_cap_supported |= MCG_LMCE_P;
8153 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8155 if (!enable_ept || !cpu_has_vmx_intel_pt())
8156 pt_mode = PT_MODE_SYSTEM;
8157 if (pt_mode == PT_MODE_HOST_GUEST)
8158 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8160 vmx_init_ops.handle_intel_pt_intr = NULL;
8162 setup_default_sgx_lepubkeyhash();
8165 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8166 vmx_capability.ept);
8168 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8175 r = alloc_kvm_area();
8177 nested_vmx_hardware_unsetup();
8179 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8184 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8185 .cpu_has_kvm_support = cpu_has_kvm_support,
8186 .disabled_by_bios = vmx_disabled_by_bios,
8187 .check_processor_compatibility = vmx_check_processor_compat,
8188 .hardware_setup = hardware_setup,
8189 .handle_intel_pt_intr = NULL,
8191 .runtime_ops = &vmx_x86_ops,
8192 .pmu_ops = &intel_pmu_ops,
8195 static void vmx_cleanup_l1d_flush(void)
8197 if (vmx_l1d_flush_pages) {
8198 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8199 vmx_l1d_flush_pages = NULL;
8201 /* Restore state so sysfs ignores VMX */
8202 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8205 static void vmx_exit(void)
8207 #ifdef CONFIG_KEXEC_CORE
8208 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8214 #if IS_ENABLED(CONFIG_HYPERV)
8215 if (static_branch_unlikely(&enable_evmcs)) {
8217 struct hv_vp_assist_page *vp_ap;
8219 * Reset everything to support using non-enlightened VMCS
8220 * access later (e.g. when we reload the module with
8221 * enlightened_vmcs=0)
8223 for_each_online_cpu(cpu) {
8224 vp_ap = hv_get_vp_assist_page(cpu);
8229 vp_ap->nested_control.features.directhypercall = 0;
8230 vp_ap->current_nested_vmcs = 0;
8231 vp_ap->enlighten_vmentry = 0;
8234 static_branch_disable(&enable_evmcs);
8237 vmx_cleanup_l1d_flush();
8239 allow_smaller_maxphyaddr = false;
8241 module_exit(vmx_exit);
8243 static int __init vmx_init(void)
8247 #if IS_ENABLED(CONFIG_HYPERV)
8249 * Enlightened VMCS usage should be recommended and the host needs
8250 * to support eVMCS v1 or above. We can also disable eVMCS support
8251 * with module parameter.
8253 if (enlightened_vmcs &&
8254 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8255 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8256 KVM_EVMCS_VERSION) {
8258 /* Check that we have assist pages on all online CPUs */
8259 for_each_online_cpu(cpu) {
8260 if (!hv_get_vp_assist_page(cpu)) {
8261 enlightened_vmcs = false;
8266 if (enlightened_vmcs) {
8267 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8268 static_branch_enable(&enable_evmcs);
8271 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8272 vmx_x86_ops.enable_direct_tlbflush
8273 = hv_enable_direct_tlbflush;
8276 enlightened_vmcs = false;
8280 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8281 __alignof__(struct vcpu_vmx), THIS_MODULE);
8286 * Must be called after kvm_init() so enable_ept is properly set
8287 * up. Hand the parameter mitigation value in which was stored in
8288 * the pre module init parser. If no parameter was given, it will
8289 * contain 'auto' which will be turned into the default 'cond'
8292 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8298 vmx_setup_fb_clear_ctrl();
8300 for_each_possible_cpu(cpu) {
8301 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8306 #ifdef CONFIG_KEXEC_CORE
8307 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8308 crash_vmclear_local_loaded_vmcss);
8310 vmx_check_vmcs12_offsets();
8313 * Shadow paging doesn't have a (further) performance penalty
8314 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8318 allow_smaller_maxphyaddr = true;
8322 module_init(vmx_init);