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/reboot.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);
108 bool __read_mostly enable_ipiv = true;
109 module_param(enable_ipiv, bool, 0444);
112 * If nested=1, nested virtualization is supported, i.e., guests may use
113 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
114 * use VMX instructions.
116 static bool __read_mostly nested = 1;
117 module_param(nested, bool, S_IRUGO);
119 bool __read_mostly enable_pml = 1;
120 module_param_named(pml, enable_pml, bool, S_IRUGO);
122 static bool __read_mostly error_on_inconsistent_vmcs_config = true;
123 module_param(error_on_inconsistent_vmcs_config, bool, 0444);
125 static bool __read_mostly dump_invalid_vmcs = 0;
126 module_param(dump_invalid_vmcs, bool, 0644);
128 #define MSR_BITMAP_MODE_X2APIC 1
129 #define MSR_BITMAP_MODE_X2APIC_APICV 2
131 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
133 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
134 static int __read_mostly cpu_preemption_timer_multi;
135 static bool __read_mostly enable_preemption_timer = 1;
137 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
140 extern bool __read_mostly allow_smaller_maxphyaddr;
141 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
143 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
144 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
145 #define KVM_VM_CR0_ALWAYS_ON \
146 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
148 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
149 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
150 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
152 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
154 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
155 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
156 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
157 RTIT_STATUS_BYTECNT))
160 * List of MSRs that can be directly passed to the guest.
161 * In addition to these x2apic and PT MSRs are handled specially.
163 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
174 MSR_IA32_SYSENTER_CS,
175 MSR_IA32_SYSENTER_ESP,
176 MSR_IA32_SYSENTER_EIP,
178 MSR_CORE_C3_RESIDENCY,
179 MSR_CORE_C6_RESIDENCY,
180 MSR_CORE_C7_RESIDENCY,
184 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
185 * ple_gap: upper bound on the amount of time between two successive
186 * executions of PAUSE in a loop. Also indicate if ple enabled.
187 * According to test, this time is usually smaller than 128 cycles.
188 * ple_window: upper bound on the amount of time a guest is allowed to execute
189 * in a PAUSE loop. Tests indicate that most spinlocks are held for
190 * less than 2^12 cycles
191 * Time is measured based on a counter that runs at the same rate as the TSC,
192 * refer SDM volume 3b section 21.6.13 & 22.1.3.
194 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
195 module_param(ple_gap, uint, 0444);
197 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
198 module_param(ple_window, uint, 0444);
200 /* Default doubles per-vcpu window every exit. */
201 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
202 module_param(ple_window_grow, uint, 0444);
204 /* Default resets per-vcpu window every exit to ple_window. */
205 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
206 module_param(ple_window_shrink, uint, 0444);
208 /* Default is to compute the maximum so we can never overflow. */
209 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
210 module_param(ple_window_max, uint, 0444);
212 /* Default is SYSTEM mode, 1 for host-guest mode */
213 int __read_mostly pt_mode = PT_MODE_SYSTEM;
214 module_param(pt_mode, int, S_IRUGO);
216 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
217 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
218 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
220 /* Storage for pre module init parameter parsing */
221 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
223 static const struct {
226 } vmentry_l1d_param[] = {
227 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
228 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
229 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
230 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
231 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
232 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
235 #define L1D_CACHE_ORDER 4
236 static void *vmx_l1d_flush_pages;
238 /* Control for disabling CPU Fill buffer clear */
239 static bool __read_mostly vmx_fb_clear_ctrl_available;
241 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
246 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
247 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
252 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
256 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
259 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
260 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
261 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
266 /* If set to auto use the default l1tf mitigation method */
267 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
268 switch (l1tf_mitigation) {
269 case L1TF_MITIGATION_OFF:
270 l1tf = VMENTER_L1D_FLUSH_NEVER;
272 case L1TF_MITIGATION_FLUSH_NOWARN:
273 case L1TF_MITIGATION_FLUSH:
274 case L1TF_MITIGATION_FLUSH_NOSMT:
275 l1tf = VMENTER_L1D_FLUSH_COND;
277 case L1TF_MITIGATION_FULL:
278 case L1TF_MITIGATION_FULL_FORCE:
279 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
282 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
283 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
286 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
287 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
289 * This allocation for vmx_l1d_flush_pages is not tied to a VM
290 * lifetime and so should not be charged to a memcg.
292 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
295 vmx_l1d_flush_pages = page_address(page);
298 * Initialize each page with a different pattern in
299 * order to protect against KSM in the nested
300 * virtualization case.
302 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
303 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
308 l1tf_vmx_mitigation = l1tf;
310 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
311 static_branch_enable(&vmx_l1d_should_flush);
313 static_branch_disable(&vmx_l1d_should_flush);
315 if (l1tf == VMENTER_L1D_FLUSH_COND)
316 static_branch_enable(&vmx_l1d_flush_cond);
318 static_branch_disable(&vmx_l1d_flush_cond);
322 static int vmentry_l1d_flush_parse(const char *s)
327 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
328 if (vmentry_l1d_param[i].for_parse &&
329 sysfs_streq(s, vmentry_l1d_param[i].option))
336 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
340 l1tf = vmentry_l1d_flush_parse(s);
344 if (!boot_cpu_has(X86_BUG_L1TF))
348 * Has vmx_init() run already? If not then this is the pre init
349 * parameter parsing. In that case just store the value and let
350 * vmx_init() do the proper setup after enable_ept has been
353 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
354 vmentry_l1d_flush_param = l1tf;
358 mutex_lock(&vmx_l1d_flush_mutex);
359 ret = vmx_setup_l1d_flush(l1tf);
360 mutex_unlock(&vmx_l1d_flush_mutex);
364 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
366 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
367 return sprintf(s, "???\n");
369 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
372 static void vmx_setup_fb_clear_ctrl(void)
376 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
377 !boot_cpu_has_bug(X86_BUG_MDS) &&
378 !boot_cpu_has_bug(X86_BUG_TAA)) {
379 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
380 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
381 vmx_fb_clear_ctrl_available = true;
385 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
389 if (!vmx->disable_fb_clear)
392 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
394 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
395 /* Cache the MSR value to avoid reading it later */
396 vmx->msr_ia32_mcu_opt_ctrl = msr;
399 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
401 if (!vmx->disable_fb_clear)
404 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
405 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
408 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
410 vmx->disable_fb_clear = !cpu_feature_enabled(X86_FEATURE_CLEAR_CPU_BUF) &&
411 vmx_fb_clear_ctrl_available;
414 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
415 * at VMEntry. Skip the MSR read/write when a guest has no use case to
418 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
419 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
420 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
421 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
422 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
423 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
424 vmx->disable_fb_clear = false;
427 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
428 .set = vmentry_l1d_flush_set,
429 .get = vmentry_l1d_flush_get,
431 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
433 static u32 vmx_segment_access_rights(struct kvm_segment *var);
435 void vmx_vmexit(void);
437 #define vmx_insn_failed(fmt...) \
440 pr_warn_ratelimited(fmt); \
443 void vmread_error(unsigned long field, bool fault)
446 kvm_spurious_fault();
448 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
451 noinline void vmwrite_error(unsigned long field, unsigned long value)
453 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%u\n",
454 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
457 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
459 vmx_insn_failed("kvm: vmclear failed: %p/%llx err=%u\n",
460 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
463 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
465 vmx_insn_failed("kvm: vmptrld failed: %p/%llx err=%u\n",
466 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
469 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
471 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
475 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
477 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
481 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
482 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
484 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
485 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
487 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
489 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
490 static DEFINE_SPINLOCK(vmx_vpid_lock);
492 struct vmcs_config vmcs_config;
493 struct vmx_capability vmx_capability;
495 #define VMX_SEGMENT_FIELD(seg) \
496 [VCPU_SREG_##seg] = { \
497 .selector = GUEST_##seg##_SELECTOR, \
498 .base = GUEST_##seg##_BASE, \
499 .limit = GUEST_##seg##_LIMIT, \
500 .ar_bytes = GUEST_##seg##_AR_BYTES, \
503 static const struct kvm_vmx_segment_field {
508 } kvm_vmx_segment_fields[] = {
509 VMX_SEGMENT_FIELD(CS),
510 VMX_SEGMENT_FIELD(DS),
511 VMX_SEGMENT_FIELD(ES),
512 VMX_SEGMENT_FIELD(FS),
513 VMX_SEGMENT_FIELD(GS),
514 VMX_SEGMENT_FIELD(SS),
515 VMX_SEGMENT_FIELD(TR),
516 VMX_SEGMENT_FIELD(LDTR),
519 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
521 vmx->segment_cache.bitmask = 0;
524 static unsigned long host_idt_base;
526 #if IS_ENABLED(CONFIG_HYPERV)
527 static bool __read_mostly enlightened_vmcs = true;
528 module_param(enlightened_vmcs, bool, 0444);
530 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
532 struct hv_enlightened_vmcs *evmcs;
533 struct hv_partition_assist_pg **p_hv_pa_pg =
534 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
536 * Synthetic VM-Exit is not enabled in current code and so All
537 * evmcs in singe VM shares same assist page.
540 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
545 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
547 evmcs->partition_assist_page =
549 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
550 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
555 static void hv_reset_evmcs(void)
557 struct hv_vp_assist_page *vp_ap;
559 if (!static_branch_unlikely(&enable_evmcs))
563 * KVM should enable eVMCS if and only if all CPUs have a VP assist
564 * page, and should reject CPU onlining if eVMCS is enabled the CPU
565 * doesn't have a VP assist page allocated.
567 vp_ap = hv_get_vp_assist_page(smp_processor_id());
568 if (WARN_ON_ONCE(!vp_ap))
572 * Reset everything to support using non-enlightened VMCS access later
573 * (e.g. when we reload the module with enlightened_vmcs=0)
575 vp_ap->nested_control.features.directhypercall = 0;
576 vp_ap->current_nested_vmcs = 0;
577 vp_ap->enlighten_vmentry = 0;
580 #else /* IS_ENABLED(CONFIG_HYPERV) */
581 static void hv_reset_evmcs(void) {}
582 #endif /* IS_ENABLED(CONFIG_HYPERV) */
585 * Comment's format: document - errata name - stepping - processor name.
587 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
589 static u32 vmx_preemption_cpu_tfms[] = {
590 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
592 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
593 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
594 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
596 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
598 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
599 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
601 * 320767.pdf - AAP86 - B1 -
602 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
605 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
607 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
609 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
611 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
612 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
613 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
615 /* Xeon E3-1220 V2 */
619 static inline bool cpu_has_broken_vmx_preemption_timer(void)
621 u32 eax = cpuid_eax(0x00000001), i;
623 /* Clear the reserved bits */
624 eax &= ~(0x3U << 14 | 0xfU << 28);
625 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
626 if (eax == vmx_preemption_cpu_tfms[i])
632 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
634 return flexpriority_enabled && lapic_in_kernel(vcpu);
637 static int possible_passthrough_msr_slot(u32 msr)
641 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
642 if (vmx_possible_passthrough_msrs[i] == msr)
648 static bool is_valid_passthrough_msr(u32 msr)
653 case 0x800 ... 0x8ff:
654 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
656 case MSR_IA32_RTIT_STATUS:
657 case MSR_IA32_RTIT_OUTPUT_BASE:
658 case MSR_IA32_RTIT_OUTPUT_MASK:
659 case MSR_IA32_RTIT_CR3_MATCH:
660 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
661 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
664 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
665 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
666 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
667 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
668 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
669 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
673 r = possible_passthrough_msr_slot(msr) != -ENOENT;
675 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
680 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
684 i = kvm_find_user_return_msr(msr);
686 return &vmx->guest_uret_msrs[i];
690 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
691 struct vmx_uret_msr *msr, u64 data)
693 unsigned int slot = msr - vmx->guest_uret_msrs;
696 if (msr->load_into_hardware) {
698 ret = kvm_set_user_return_msr(slot, data, msr->mask);
706 static void crash_vmclear_local_loaded_vmcss(void)
708 int cpu = raw_smp_processor_id();
709 struct loaded_vmcs *v;
711 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
712 loaded_vmcss_on_cpu_link)
716 static void __loaded_vmcs_clear(void *arg)
718 struct loaded_vmcs *loaded_vmcs = arg;
719 int cpu = raw_smp_processor_id();
721 if (loaded_vmcs->cpu != cpu)
722 return; /* vcpu migration can race with cpu offline */
723 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
724 per_cpu(current_vmcs, cpu) = NULL;
726 vmcs_clear(loaded_vmcs->vmcs);
727 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
728 vmcs_clear(loaded_vmcs->shadow_vmcs);
730 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
733 * Ensure all writes to loaded_vmcs, including deleting it from its
734 * current percpu list, complete before setting loaded_vmcs->cpu to
735 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
736 * and add loaded_vmcs to its percpu list before it's deleted from this
737 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
741 loaded_vmcs->cpu = -1;
742 loaded_vmcs->launched = 0;
745 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
747 int cpu = loaded_vmcs->cpu;
750 smp_call_function_single(cpu,
751 __loaded_vmcs_clear, loaded_vmcs, 1);
754 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
758 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
760 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
761 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
762 vmx->segment_cache.bitmask = 0;
764 ret = vmx->segment_cache.bitmask & mask;
765 vmx->segment_cache.bitmask |= mask;
769 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
771 u16 *p = &vmx->segment_cache.seg[seg].selector;
773 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
774 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
778 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
780 ulong *p = &vmx->segment_cache.seg[seg].base;
782 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
783 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
787 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
789 u32 *p = &vmx->segment_cache.seg[seg].limit;
791 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
792 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
796 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
798 u32 *p = &vmx->segment_cache.seg[seg].ar;
800 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
801 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
805 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
809 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
810 (1u << DB_VECTOR) | (1u << AC_VECTOR);
812 * Guest access to VMware backdoor ports could legitimately
813 * trigger #GP because of TSS I/O permission bitmap.
814 * We intercept those #GP and allow access to them anyway
817 if (enable_vmware_backdoor)
818 eb |= (1u << GP_VECTOR);
819 if ((vcpu->guest_debug &
820 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
821 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
822 eb |= 1u << BP_VECTOR;
823 if (to_vmx(vcpu)->rmode.vm86_active)
825 if (!vmx_need_pf_intercept(vcpu))
826 eb &= ~(1u << PF_VECTOR);
828 /* When we are running a nested L2 guest and L1 specified for it a
829 * certain exception bitmap, we must trap the same exceptions and pass
830 * them to L1. When running L2, we will only handle the exceptions
831 * specified above if L1 did not want them.
833 if (is_guest_mode(vcpu))
834 eb |= get_vmcs12(vcpu)->exception_bitmap;
836 int mask = 0, match = 0;
838 if (enable_ept && (eb & (1u << PF_VECTOR))) {
840 * If EPT is enabled, #PF is currently only intercepted
841 * if MAXPHYADDR is smaller on the guest than on the
842 * host. In that case we only care about present,
843 * non-reserved faults. For vmcs02, however, PFEC_MASK
844 * and PFEC_MATCH are set in prepare_vmcs02_rare.
846 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
847 match = PFERR_PRESENT_MASK;
849 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
850 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
854 * Disabling xfd interception indicates that dynamic xfeatures
855 * might be used in the guest. Always trap #NM in this case
856 * to save guest xfd_err timely.
858 if (vcpu->arch.xfd_no_write_intercept)
859 eb |= (1u << NM_VECTOR);
861 vmcs_write32(EXCEPTION_BITMAP, eb);
865 * Check if MSR is intercepted for currently loaded MSR bitmap.
867 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
869 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
872 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
875 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
877 unsigned int flags = 0;
879 if (vmx->loaded_vmcs->launched)
880 flags |= VMX_RUN_VMRESUME;
883 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
884 * to change it directly without causing a vmexit. In that case read
885 * it after vmexit and store it in vmx->spec_ctrl.
887 if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
888 flags |= VMX_RUN_SAVE_SPEC_CTRL;
893 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
894 unsigned long entry, unsigned long exit)
896 vm_entry_controls_clearbit(vmx, entry);
897 vm_exit_controls_clearbit(vmx, exit);
900 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
904 for (i = 0; i < m->nr; ++i) {
905 if (m->val[i].index == msr)
911 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
914 struct msr_autoload *m = &vmx->msr_autoload;
918 if (cpu_has_load_ia32_efer()) {
919 clear_atomic_switch_msr_special(vmx,
920 VM_ENTRY_LOAD_IA32_EFER,
921 VM_EXIT_LOAD_IA32_EFER);
925 case MSR_CORE_PERF_GLOBAL_CTRL:
926 if (cpu_has_load_perf_global_ctrl()) {
927 clear_atomic_switch_msr_special(vmx,
928 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
929 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
934 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
938 m->guest.val[i] = m->guest.val[m->guest.nr];
939 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
942 i = vmx_find_loadstore_msr_slot(&m->host, msr);
947 m->host.val[i] = m->host.val[m->host.nr];
948 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
951 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
952 unsigned long entry, unsigned long exit,
953 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
954 u64 guest_val, u64 host_val)
956 vmcs_write64(guest_val_vmcs, guest_val);
957 if (host_val_vmcs != HOST_IA32_EFER)
958 vmcs_write64(host_val_vmcs, host_val);
959 vm_entry_controls_setbit(vmx, entry);
960 vm_exit_controls_setbit(vmx, exit);
963 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
964 u64 guest_val, u64 host_val, bool entry_only)
967 struct msr_autoload *m = &vmx->msr_autoload;
971 if (cpu_has_load_ia32_efer()) {
972 add_atomic_switch_msr_special(vmx,
973 VM_ENTRY_LOAD_IA32_EFER,
974 VM_EXIT_LOAD_IA32_EFER,
977 guest_val, host_val);
981 case MSR_CORE_PERF_GLOBAL_CTRL:
982 if (cpu_has_load_perf_global_ctrl()) {
983 add_atomic_switch_msr_special(vmx,
984 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
985 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
986 GUEST_IA32_PERF_GLOBAL_CTRL,
987 HOST_IA32_PERF_GLOBAL_CTRL,
988 guest_val, host_val);
992 case MSR_IA32_PEBS_ENABLE:
993 /* PEBS needs a quiescent period after being disabled (to write
994 * a record). Disabling PEBS through VMX MSR swapping doesn't
995 * provide that period, so a CPU could write host's record into
998 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1001 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1003 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1005 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1006 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1007 printk_once(KERN_WARNING "Not enough msr switch entries. "
1008 "Can't add msr %x\n", msr);
1013 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1015 m->guest.val[i].index = msr;
1016 m->guest.val[i].value = guest_val;
1023 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1025 m->host.val[j].index = msr;
1026 m->host.val[j].value = host_val;
1029 static bool update_transition_efer(struct vcpu_vmx *vmx)
1031 u64 guest_efer = vmx->vcpu.arch.efer;
1032 u64 ignore_bits = 0;
1035 /* Shadow paging assumes NX to be available. */
1037 guest_efer |= EFER_NX;
1040 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1042 ignore_bits |= EFER_SCE;
1043 #ifdef CONFIG_X86_64
1044 ignore_bits |= EFER_LMA | EFER_LME;
1045 /* SCE is meaningful only in long mode on Intel */
1046 if (guest_efer & EFER_LMA)
1047 ignore_bits &= ~(u64)EFER_SCE;
1051 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1052 * On CPUs that support "load IA32_EFER", always switch EFER
1053 * atomically, since it's faster than switching it manually.
1055 if (cpu_has_load_ia32_efer() ||
1056 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1057 if (!(guest_efer & EFER_LMA))
1058 guest_efer &= ~EFER_LME;
1059 if (guest_efer != host_efer)
1060 add_atomic_switch_msr(vmx, MSR_EFER,
1061 guest_efer, host_efer, false);
1063 clear_atomic_switch_msr(vmx, MSR_EFER);
1067 i = kvm_find_user_return_msr(MSR_EFER);
1071 clear_atomic_switch_msr(vmx, MSR_EFER);
1073 guest_efer &= ~ignore_bits;
1074 guest_efer |= host_efer & ignore_bits;
1076 vmx->guest_uret_msrs[i].data = guest_efer;
1077 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1082 #ifdef CONFIG_X86_32
1084 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1085 * VMCS rather than the segment table. KVM uses this helper to figure
1086 * out the current bases to poke them into the VMCS before entry.
1088 static unsigned long segment_base(u16 selector)
1090 struct desc_struct *table;
1093 if (!(selector & ~SEGMENT_RPL_MASK))
1096 table = get_current_gdt_ro();
1098 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1099 u16 ldt_selector = kvm_read_ldt();
1101 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1104 table = (struct desc_struct *)segment_base(ldt_selector);
1106 v = get_desc_base(&table[selector >> 3]);
1111 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1113 return vmx_pt_mode_is_host_guest() &&
1114 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1117 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1119 /* The base must be 128-byte aligned and a legal physical address. */
1120 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1123 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1127 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1128 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1129 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1130 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1131 for (i = 0; i < addr_range; i++) {
1132 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1133 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1137 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1141 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1142 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1143 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1144 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1145 for (i = 0; i < addr_range; i++) {
1146 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1147 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1151 static void pt_guest_enter(struct vcpu_vmx *vmx)
1153 if (vmx_pt_mode_is_system())
1157 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1158 * Save host state before VM entry.
1160 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1161 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1162 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1163 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1164 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1168 static void pt_guest_exit(struct vcpu_vmx *vmx)
1170 if (vmx_pt_mode_is_system())
1173 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1174 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1175 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1179 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1180 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1182 if (vmx->pt_desc.host.ctl)
1183 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1186 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1187 unsigned long fs_base, unsigned long gs_base)
1189 if (unlikely(fs_sel != host->fs_sel)) {
1191 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1193 vmcs_write16(HOST_FS_SELECTOR, 0);
1194 host->fs_sel = fs_sel;
1196 if (unlikely(gs_sel != host->gs_sel)) {
1198 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1200 vmcs_write16(HOST_GS_SELECTOR, 0);
1201 host->gs_sel = gs_sel;
1203 if (unlikely(fs_base != host->fs_base)) {
1204 vmcs_writel(HOST_FS_BASE, fs_base);
1205 host->fs_base = fs_base;
1207 if (unlikely(gs_base != host->gs_base)) {
1208 vmcs_writel(HOST_GS_BASE, gs_base);
1209 host->gs_base = gs_base;
1213 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1215 struct vcpu_vmx *vmx = to_vmx(vcpu);
1216 struct vmcs_host_state *host_state;
1217 #ifdef CONFIG_X86_64
1218 int cpu = raw_smp_processor_id();
1220 unsigned long fs_base, gs_base;
1224 vmx->req_immediate_exit = false;
1227 * Note that guest MSRs to be saved/restored can also be changed
1228 * when guest state is loaded. This happens when guest transitions
1229 * to/from long-mode by setting MSR_EFER.LMA.
1231 if (!vmx->guest_uret_msrs_loaded) {
1232 vmx->guest_uret_msrs_loaded = true;
1233 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1234 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1237 kvm_set_user_return_msr(i,
1238 vmx->guest_uret_msrs[i].data,
1239 vmx->guest_uret_msrs[i].mask);
1243 if (vmx->nested.need_vmcs12_to_shadow_sync)
1244 nested_sync_vmcs12_to_shadow(vcpu);
1246 if (vmx->guest_state_loaded)
1249 host_state = &vmx->loaded_vmcs->host_state;
1252 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1253 * allow segment selectors with cpl > 0 or ti == 1.
1255 host_state->ldt_sel = kvm_read_ldt();
1257 #ifdef CONFIG_X86_64
1258 savesegment(ds, host_state->ds_sel);
1259 savesegment(es, host_state->es_sel);
1261 gs_base = cpu_kernelmode_gs_base(cpu);
1262 if (likely(is_64bit_mm(current->mm))) {
1263 current_save_fsgs();
1264 fs_sel = current->thread.fsindex;
1265 gs_sel = current->thread.gsindex;
1266 fs_base = current->thread.fsbase;
1267 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1269 savesegment(fs, fs_sel);
1270 savesegment(gs, gs_sel);
1271 fs_base = read_msr(MSR_FS_BASE);
1272 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1275 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1277 savesegment(fs, fs_sel);
1278 savesegment(gs, gs_sel);
1279 fs_base = segment_base(fs_sel);
1280 gs_base = segment_base(gs_sel);
1283 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1284 vmx->guest_state_loaded = true;
1287 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1289 struct vmcs_host_state *host_state;
1291 if (!vmx->guest_state_loaded)
1294 host_state = &vmx->loaded_vmcs->host_state;
1296 ++vmx->vcpu.stat.host_state_reload;
1298 #ifdef CONFIG_X86_64
1299 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1301 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1302 kvm_load_ldt(host_state->ldt_sel);
1303 #ifdef CONFIG_X86_64
1304 load_gs_index(host_state->gs_sel);
1306 loadsegment(gs, host_state->gs_sel);
1309 if (host_state->fs_sel & 7)
1310 loadsegment(fs, host_state->fs_sel);
1311 #ifdef CONFIG_X86_64
1312 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1313 loadsegment(ds, host_state->ds_sel);
1314 loadsegment(es, host_state->es_sel);
1317 invalidate_tss_limit();
1318 #ifdef CONFIG_X86_64
1319 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1321 load_fixmap_gdt(raw_smp_processor_id());
1322 vmx->guest_state_loaded = false;
1323 vmx->guest_uret_msrs_loaded = false;
1326 #ifdef CONFIG_X86_64
1327 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1330 if (vmx->guest_state_loaded)
1331 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1333 return vmx->msr_guest_kernel_gs_base;
1336 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1339 if (vmx->guest_state_loaded)
1340 wrmsrl(MSR_KERNEL_GS_BASE, data);
1342 vmx->msr_guest_kernel_gs_base = data;
1346 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1347 struct loaded_vmcs *buddy)
1349 struct vcpu_vmx *vmx = to_vmx(vcpu);
1350 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1353 if (!already_loaded) {
1354 loaded_vmcs_clear(vmx->loaded_vmcs);
1355 local_irq_disable();
1358 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1359 * this cpu's percpu list, otherwise it may not yet be deleted
1360 * from its previous cpu's percpu list. Pairs with the
1361 * smb_wmb() in __loaded_vmcs_clear().
1365 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1366 &per_cpu(loaded_vmcss_on_cpu, cpu));
1370 prev = per_cpu(current_vmcs, cpu);
1371 if (prev != vmx->loaded_vmcs->vmcs) {
1372 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1373 vmcs_load(vmx->loaded_vmcs->vmcs);
1376 * No indirect branch prediction barrier needed when switching
1377 * the active VMCS within a vCPU, unless IBRS is advertised to
1378 * the vCPU. To minimize the number of IBPBs executed, KVM
1379 * performs IBPB on nested VM-Exit (a single nested transition
1380 * may switch the active VMCS multiple times).
1382 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1383 indirect_branch_prediction_barrier();
1386 if (!already_loaded) {
1387 void *gdt = get_current_gdt_ro();
1390 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1391 * TLB entries from its previous association with the vCPU.
1393 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1396 * Linux uses per-cpu TSS and GDT, so set these when switching
1397 * processors. See 22.2.4.
1399 vmcs_writel(HOST_TR_BASE,
1400 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1401 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1403 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1405 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1406 (unsigned long)(cpu_entry_stack(cpu) + 1));
1409 vmx->loaded_vmcs->cpu = cpu;
1414 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1415 * vcpu mutex is already taken.
1417 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1419 struct vcpu_vmx *vmx = to_vmx(vcpu);
1421 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1423 vmx_vcpu_pi_load(vcpu, cpu);
1425 vmx->host_debugctlmsr = get_debugctlmsr();
1428 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1430 vmx_vcpu_pi_put(vcpu);
1432 vmx_prepare_switch_to_host(to_vmx(vcpu));
1435 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1437 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1440 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1442 struct vcpu_vmx *vmx = to_vmx(vcpu);
1443 unsigned long rflags, save_rflags;
1445 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1446 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1447 rflags = vmcs_readl(GUEST_RFLAGS);
1448 if (vmx->rmode.vm86_active) {
1449 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1450 save_rflags = vmx->rmode.save_rflags;
1451 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1453 vmx->rflags = rflags;
1458 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1460 struct vcpu_vmx *vmx = to_vmx(vcpu);
1461 unsigned long old_rflags;
1464 * Unlike CR0 and CR4, RFLAGS handling requires checking if the vCPU
1465 * is an unrestricted guest in order to mark L2 as needing emulation
1466 * if L1 runs L2 as a restricted guest.
1468 if (is_unrestricted_guest(vcpu)) {
1469 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1470 vmx->rflags = rflags;
1471 vmcs_writel(GUEST_RFLAGS, rflags);
1475 old_rflags = vmx_get_rflags(vcpu);
1476 vmx->rflags = rflags;
1477 if (vmx->rmode.vm86_active) {
1478 vmx->rmode.save_rflags = rflags;
1479 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1481 vmcs_writel(GUEST_RFLAGS, rflags);
1483 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1484 vmx->emulation_required = vmx_emulation_required(vcpu);
1487 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1489 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1492 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1494 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1497 if (interruptibility & GUEST_INTR_STATE_STI)
1498 ret |= KVM_X86_SHADOW_INT_STI;
1499 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1500 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1505 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1507 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1508 u32 interruptibility = interruptibility_old;
1510 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1512 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1513 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1514 else if (mask & KVM_X86_SHADOW_INT_STI)
1515 interruptibility |= GUEST_INTR_STATE_STI;
1517 if ((interruptibility != interruptibility_old))
1518 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1521 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1523 struct vcpu_vmx *vmx = to_vmx(vcpu);
1524 unsigned long value;
1527 * Any MSR write that attempts to change bits marked reserved will
1530 if (data & vmx->pt_desc.ctl_bitmask)
1534 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1535 * result in a #GP unless the same write also clears TraceEn.
1537 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1538 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1542 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1543 * and FabricEn would cause #GP, if
1544 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1546 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1547 !(data & RTIT_CTL_FABRIC_EN) &&
1548 !intel_pt_validate_cap(vmx->pt_desc.caps,
1549 PT_CAP_single_range_output))
1553 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1554 * utilize encodings marked reserved will cause a #GP fault.
1556 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1557 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1558 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1559 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1561 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1562 PT_CAP_cycle_thresholds);
1563 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1564 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1565 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1567 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1568 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1569 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1570 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1574 * If ADDRx_CFG is reserved or the encodings is >2 will
1575 * cause a #GP fault.
1577 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1578 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1580 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1581 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1583 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1584 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1586 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1587 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1593 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1594 void *insn, int insn_len)
1597 * Emulation of instructions in SGX enclaves is impossible as RIP does
1598 * not point at the failing instruction, and even if it did, the code
1599 * stream is inaccessible. Inject #UD instead of exiting to userspace
1600 * so that guest userspace can't DoS the guest simply by triggering
1601 * emulation (enclaves are CPL3 only).
1603 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1604 kvm_queue_exception(vcpu, UD_VECTOR);
1610 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1612 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1613 unsigned long rip, orig_rip;
1617 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1618 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1619 * set when EPT misconfig occurs. In practice, real hardware updates
1620 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1621 * (namely Hyper-V) don't set it due to it being undefined behavior,
1622 * i.e. we end up advancing IP with some random value.
1624 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1625 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1626 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1629 * Emulating an enclave's instructions isn't supported as KVM
1630 * cannot access the enclave's memory or its true RIP, e.g. the
1631 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1632 * the RIP that actually triggered the VM-Exit. But, because
1633 * most instructions that cause VM-Exit will #UD in an enclave,
1634 * most instruction-based VM-Exits simply do not occur.
1636 * There are a few exceptions, notably the debug instructions
1637 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1638 * and generate #DB/#BP as expected, which KVM might intercept.
1639 * But again, the CPU does the dirty work and saves an instr
1640 * length of zero so VMMs don't shoot themselves in the foot.
1641 * WARN if KVM tries to skip a non-zero length instruction on
1642 * a VM-Exit from an enclave.
1647 WARN(exit_reason.enclave_mode,
1648 "KVM: skipping instruction after SGX enclave VM-Exit");
1650 orig_rip = kvm_rip_read(vcpu);
1651 rip = orig_rip + instr_len;
1652 #ifdef CONFIG_X86_64
1654 * We need to mask out the high 32 bits of RIP if not in 64-bit
1655 * mode, but just finding out that we are in 64-bit mode is
1656 * quite expensive. Only do it if there was a carry.
1658 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1661 kvm_rip_write(vcpu, rip);
1663 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1668 /* skipping an emulated instruction also counts */
1669 vmx_set_interrupt_shadow(vcpu, 0);
1675 * Recognizes a pending MTF VM-exit and records the nested state for later
1678 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1680 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1681 struct vcpu_vmx *vmx = to_vmx(vcpu);
1683 if (!is_guest_mode(vcpu))
1687 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1688 * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps
1689 * or ICEBP (in the emulator proper), and skipping of ICEBP after an
1690 * intercepted #DB deliberately avoids single-step #DB and MTF updates
1691 * as ICEBP is higher priority than both. As instruction emulation is
1692 * completed at this point (i.e. KVM is at the instruction boundary),
1693 * any #DB exception pending delivery must be a debug-trap of lower
1694 * priority than MTF. Record the pending MTF state to be delivered in
1695 * vmx_check_nested_events().
1697 if (nested_cpu_has_mtf(vmcs12) &&
1698 (!vcpu->arch.exception.pending ||
1699 vcpu->arch.exception.vector == DB_VECTOR) &&
1700 (!vcpu->arch.exception_vmexit.pending ||
1701 vcpu->arch.exception_vmexit.vector == DB_VECTOR)) {
1702 vmx->nested.mtf_pending = true;
1703 kvm_make_request(KVM_REQ_EVENT, vcpu);
1705 vmx->nested.mtf_pending = false;
1709 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1711 vmx_update_emulated_instruction(vcpu);
1712 return skip_emulated_instruction(vcpu);
1715 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1718 * Ensure that we clear the HLT state in the VMCS. We don't need to
1719 * explicitly skip the instruction because if the HLT state is set,
1720 * then the instruction is already executing and RIP has already been
1723 if (kvm_hlt_in_guest(vcpu->kvm) &&
1724 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1725 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1728 static void vmx_inject_exception(struct kvm_vcpu *vcpu)
1730 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1731 u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
1732 struct vcpu_vmx *vmx = to_vmx(vcpu);
1734 kvm_deliver_exception_payload(vcpu, ex);
1736 if (ex->has_error_code) {
1738 * Despite the error code being architecturally defined as 32
1739 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1740 * VMX don't actually supporting setting bits 31:16. Hardware
1741 * will (should) never provide a bogus error code, but AMD CPUs
1742 * do generate error codes with bits 31:16 set, and so KVM's
1743 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1744 * the upper bits to avoid VM-Fail, losing information that
1745 * does't really exist is preferable to killing the VM.
1747 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
1748 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1751 if (vmx->rmode.vm86_active) {
1753 if (kvm_exception_is_soft(ex->vector))
1754 inc_eip = vcpu->arch.event_exit_inst_len;
1755 kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
1759 WARN_ON_ONCE(vmx->emulation_required);
1761 if (kvm_exception_is_soft(ex->vector)) {
1762 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1763 vmx->vcpu.arch.event_exit_inst_len);
1764 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1766 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1768 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1770 vmx_clear_hlt(vcpu);
1773 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1774 bool load_into_hardware)
1776 struct vmx_uret_msr *uret_msr;
1778 uret_msr = vmx_find_uret_msr(vmx, msr);
1782 uret_msr->load_into_hardware = load_into_hardware;
1786 * Configuring user return MSRs to automatically save, load, and restore MSRs
1787 * that need to be shoved into hardware when running the guest. Note, omitting
1788 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1789 * loaded into hardware when running the guest.
1791 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1793 #ifdef CONFIG_X86_64
1794 bool load_syscall_msrs;
1797 * The SYSCALL MSRs are only needed on long mode guests, and only
1798 * when EFER.SCE is set.
1800 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1801 (vmx->vcpu.arch.efer & EFER_SCE);
1803 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1804 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1805 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1807 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1809 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1810 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1811 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1814 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1815 * kernel and old userspace. If those guests run on a tsx=off host, do
1816 * allow guests to use TSX_CTRL, but don't change the value in hardware
1817 * so that TSX remains always disabled.
1819 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1822 * The set of MSRs to load may have changed, reload MSRs before the
1825 vmx->guest_uret_msrs_loaded = false;
1828 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1830 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1832 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1833 return vmcs12->tsc_offset;
1838 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1840 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1842 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1843 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1844 return vmcs12->tsc_multiplier;
1846 return kvm_caps.default_tsc_scaling_ratio;
1849 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1851 vmcs_write64(TSC_OFFSET, offset);
1854 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1856 vmcs_write64(TSC_MULTIPLIER, multiplier);
1860 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1861 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1862 * all guests if the "nested" module option is off, and can also be disabled
1863 * for a single guest by disabling its VMX cpuid bit.
1865 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1867 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1870 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1873 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1875 return !(val & ~valid_bits);
1878 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1880 switch (msr->index) {
1881 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1884 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1885 case MSR_IA32_PERF_CAPABILITIES:
1886 msr->data = kvm_caps.supported_perf_cap;
1889 return KVM_MSR_RET_INVALID;
1894 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1895 * Returns 0 on success, non-0 otherwise.
1896 * Assumes vcpu_load() was already called.
1898 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1900 struct vcpu_vmx *vmx = to_vmx(vcpu);
1901 struct vmx_uret_msr *msr;
1904 switch (msr_info->index) {
1905 #ifdef CONFIG_X86_64
1907 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1910 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1912 case MSR_KERNEL_GS_BASE:
1913 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1917 return kvm_get_msr_common(vcpu, msr_info);
1918 case MSR_IA32_TSX_CTRL:
1919 if (!msr_info->host_initiated &&
1920 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1923 case MSR_IA32_UMWAIT_CONTROL:
1924 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1927 msr_info->data = vmx->msr_ia32_umwait_control;
1929 case MSR_IA32_SPEC_CTRL:
1930 if (!msr_info->host_initiated &&
1931 !guest_has_spec_ctrl_msr(vcpu))
1934 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1936 case MSR_IA32_SYSENTER_CS:
1937 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1939 case MSR_IA32_SYSENTER_EIP:
1940 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1942 case MSR_IA32_SYSENTER_ESP:
1943 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1945 case MSR_IA32_BNDCFGS:
1946 if (!kvm_mpx_supported() ||
1947 (!msr_info->host_initiated &&
1948 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1950 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1952 case MSR_IA32_MCG_EXT_CTL:
1953 if (!msr_info->host_initiated &&
1954 !(vmx->msr_ia32_feature_control &
1955 FEAT_CTL_LMCE_ENABLED))
1957 msr_info->data = vcpu->arch.mcg_ext_ctl;
1959 case MSR_IA32_FEAT_CTL:
1960 msr_info->data = vmx->msr_ia32_feature_control;
1962 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1963 if (!msr_info->host_initiated &&
1964 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1966 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1967 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1969 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1970 if (!nested_vmx_allowed(vcpu))
1972 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1976 * Enlightened VMCS v1 doesn't have certain VMCS fields but
1977 * instead of just ignoring the features, different Hyper-V
1978 * versions are either trying to use them and fail or do some
1979 * sanity checking and refuse to boot. Filter all unsupported
1982 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
1983 nested_evmcs_filter_control_msr(vcpu, msr_info->index,
1986 case MSR_IA32_RTIT_CTL:
1987 if (!vmx_pt_mode_is_host_guest())
1989 msr_info->data = vmx->pt_desc.guest.ctl;
1991 case MSR_IA32_RTIT_STATUS:
1992 if (!vmx_pt_mode_is_host_guest())
1994 msr_info->data = vmx->pt_desc.guest.status;
1996 case MSR_IA32_RTIT_CR3_MATCH:
1997 if (!vmx_pt_mode_is_host_guest() ||
1998 !intel_pt_validate_cap(vmx->pt_desc.caps,
1999 PT_CAP_cr3_filtering))
2001 msr_info->data = vmx->pt_desc.guest.cr3_match;
2003 case MSR_IA32_RTIT_OUTPUT_BASE:
2004 if (!vmx_pt_mode_is_host_guest() ||
2005 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2006 PT_CAP_topa_output) &&
2007 !intel_pt_validate_cap(vmx->pt_desc.caps,
2008 PT_CAP_single_range_output)))
2010 msr_info->data = vmx->pt_desc.guest.output_base;
2012 case MSR_IA32_RTIT_OUTPUT_MASK:
2013 if (!vmx_pt_mode_is_host_guest() ||
2014 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2015 PT_CAP_topa_output) &&
2016 !intel_pt_validate_cap(vmx->pt_desc.caps,
2017 PT_CAP_single_range_output)))
2019 msr_info->data = vmx->pt_desc.guest.output_mask;
2021 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2022 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2023 if (!vmx_pt_mode_is_host_guest() ||
2024 (index >= 2 * vmx->pt_desc.num_address_ranges))
2027 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
2029 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
2031 case MSR_IA32_DEBUGCTLMSR:
2032 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2036 msr = vmx_find_uret_msr(vmx, msr_info->index);
2038 msr_info->data = msr->data;
2041 return kvm_get_msr_common(vcpu, msr_info);
2047 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2050 #ifdef CONFIG_X86_64
2051 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2054 return (unsigned long)data;
2057 static u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated)
2061 if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) &&
2062 (host_initiated || guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT)))
2063 debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT;
2065 if ((kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT) &&
2066 (host_initiated || intel_pmu_lbr_is_enabled(vcpu)))
2067 debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI;
2073 * Writes msr value into the appropriate "register".
2074 * Returns 0 on success, non-0 otherwise.
2075 * Assumes vcpu_load() was already called.
2077 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2079 struct vcpu_vmx *vmx = to_vmx(vcpu);
2080 struct vmx_uret_msr *msr;
2082 u32 msr_index = msr_info->index;
2083 u64 data = msr_info->data;
2086 switch (msr_index) {
2088 ret = kvm_set_msr_common(vcpu, msr_info);
2090 #ifdef CONFIG_X86_64
2092 vmx_segment_cache_clear(vmx);
2093 vmcs_writel(GUEST_FS_BASE, data);
2096 vmx_segment_cache_clear(vmx);
2097 vmcs_writel(GUEST_GS_BASE, data);
2099 case MSR_KERNEL_GS_BASE:
2100 vmx_write_guest_kernel_gs_base(vmx, data);
2103 ret = kvm_set_msr_common(vcpu, msr_info);
2105 * Always intercepting WRMSR could incur non-negligible
2106 * overhead given xfd might be changed frequently in
2107 * guest context switch. Disable write interception
2108 * upon the first write with a non-zero value (indicating
2109 * potential usage on dynamic xfeatures). Also update
2110 * exception bitmap to trap #NM for proper virtualization
2114 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2116 vcpu->arch.xfd_no_write_intercept = true;
2117 vmx_update_exception_bitmap(vcpu);
2121 case MSR_IA32_SYSENTER_CS:
2122 if (is_guest_mode(vcpu))
2123 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2124 vmcs_write32(GUEST_SYSENTER_CS, data);
2126 case MSR_IA32_SYSENTER_EIP:
2127 if (is_guest_mode(vcpu)) {
2128 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2129 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2131 vmcs_writel(GUEST_SYSENTER_EIP, data);
2133 case MSR_IA32_SYSENTER_ESP:
2134 if (is_guest_mode(vcpu)) {
2135 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2136 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2138 vmcs_writel(GUEST_SYSENTER_ESP, data);
2140 case MSR_IA32_DEBUGCTLMSR: {
2143 invalid = data & ~vmx_get_supported_debugctl(vcpu, msr_info->host_initiated);
2144 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2145 if (report_ignored_msrs)
2146 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2148 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2149 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2155 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2156 VM_EXIT_SAVE_DEBUG_CONTROLS)
2157 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2159 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2160 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2161 (data & DEBUGCTLMSR_LBR))
2162 intel_pmu_create_guest_lbr_event(vcpu);
2165 case MSR_IA32_BNDCFGS:
2166 if (!kvm_mpx_supported() ||
2167 (!msr_info->host_initiated &&
2168 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2170 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2171 (data & MSR_IA32_BNDCFGS_RSVD))
2174 if (is_guest_mode(vcpu) &&
2175 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2176 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2177 get_vmcs12(vcpu)->guest_bndcfgs = data;
2179 vmcs_write64(GUEST_BNDCFGS, data);
2181 case MSR_IA32_UMWAIT_CONTROL:
2182 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2185 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2186 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2189 vmx->msr_ia32_umwait_control = data;
2191 case MSR_IA32_SPEC_CTRL:
2192 if (!msr_info->host_initiated &&
2193 !guest_has_spec_ctrl_msr(vcpu))
2196 if (kvm_spec_ctrl_test_value(data))
2199 vmx->spec_ctrl = data;
2205 * When it's written (to non-zero) for the first time, pass
2209 * The handling of the MSR bitmap for L2 guests is done in
2210 * nested_vmx_prepare_msr_bitmap. We should not touch the
2211 * vmcs02.msr_bitmap here since it gets completely overwritten
2212 * in the merging. We update the vmcs01 here for L1 as well
2213 * since it will end up touching the MSR anyway now.
2215 vmx_disable_intercept_for_msr(vcpu,
2219 case MSR_IA32_TSX_CTRL:
2220 if (!msr_info->host_initiated &&
2221 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2223 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2226 case MSR_IA32_PRED_CMD:
2227 if (!msr_info->host_initiated &&
2228 !guest_has_pred_cmd_msr(vcpu))
2231 if (data & ~PRED_CMD_IBPB)
2233 if (!boot_cpu_has(X86_FEATURE_IBPB))
2238 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2242 * When it's written (to non-zero) for the first time, pass
2246 * The handling of the MSR bitmap for L2 guests is done in
2247 * nested_vmx_prepare_msr_bitmap. We should not touch the
2248 * vmcs02.msr_bitmap here since it gets completely overwritten
2251 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2253 case MSR_IA32_CR_PAT:
2254 if (!kvm_pat_valid(data))
2257 if (is_guest_mode(vcpu) &&
2258 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2259 get_vmcs12(vcpu)->guest_ia32_pat = data;
2261 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2262 vmcs_write64(GUEST_IA32_PAT, data);
2263 vcpu->arch.pat = data;
2266 ret = kvm_set_msr_common(vcpu, msr_info);
2268 case MSR_IA32_MCG_EXT_CTL:
2269 if ((!msr_info->host_initiated &&
2270 !(to_vmx(vcpu)->msr_ia32_feature_control &
2271 FEAT_CTL_LMCE_ENABLED)) ||
2272 (data & ~MCG_EXT_CTL_LMCE_EN))
2274 vcpu->arch.mcg_ext_ctl = data;
2276 case MSR_IA32_FEAT_CTL:
2277 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2278 (to_vmx(vcpu)->msr_ia32_feature_control &
2279 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2281 vmx->msr_ia32_feature_control = data;
2282 if (msr_info->host_initiated && data == 0)
2283 vmx_leave_nested(vcpu);
2285 /* SGX may be enabled/disabled by guest's firmware */
2286 vmx_write_encls_bitmap(vcpu, NULL);
2288 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2290 * On real hardware, the LE hash MSRs are writable before
2291 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2292 * at which point SGX related bits in IA32_FEATURE_CONTROL
2295 * KVM does not emulate SGX activation for simplicity, so
2296 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2297 * is unlocked. This is technically not architectural
2298 * behavior, but it's close enough.
2300 if (!msr_info->host_initiated &&
2301 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2302 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2303 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2305 vmx->msr_ia32_sgxlepubkeyhash
2306 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2308 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2309 if (!msr_info->host_initiated)
2310 return 1; /* they are read-only */
2311 if (!nested_vmx_allowed(vcpu))
2313 return vmx_set_vmx_msr(vcpu, msr_index, data);
2314 case MSR_IA32_RTIT_CTL:
2315 if (!vmx_pt_mode_is_host_guest() ||
2316 vmx_rtit_ctl_check(vcpu, data) ||
2319 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2320 vmx->pt_desc.guest.ctl = data;
2321 pt_update_intercept_for_msr(vcpu);
2323 case MSR_IA32_RTIT_STATUS:
2324 if (!pt_can_write_msr(vmx))
2326 if (data & MSR_IA32_RTIT_STATUS_MASK)
2328 vmx->pt_desc.guest.status = data;
2330 case MSR_IA32_RTIT_CR3_MATCH:
2331 if (!pt_can_write_msr(vmx))
2333 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2334 PT_CAP_cr3_filtering))
2336 vmx->pt_desc.guest.cr3_match = data;
2338 case MSR_IA32_RTIT_OUTPUT_BASE:
2339 if (!pt_can_write_msr(vmx))
2341 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2342 PT_CAP_topa_output) &&
2343 !intel_pt_validate_cap(vmx->pt_desc.caps,
2344 PT_CAP_single_range_output))
2346 if (!pt_output_base_valid(vcpu, data))
2348 vmx->pt_desc.guest.output_base = data;
2350 case MSR_IA32_RTIT_OUTPUT_MASK:
2351 if (!pt_can_write_msr(vmx))
2353 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2354 PT_CAP_topa_output) &&
2355 !intel_pt_validate_cap(vmx->pt_desc.caps,
2356 PT_CAP_single_range_output))
2358 vmx->pt_desc.guest.output_mask = data;
2360 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2361 if (!pt_can_write_msr(vmx))
2363 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2364 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2366 if (is_noncanonical_address(data, vcpu))
2369 vmx->pt_desc.guest.addr_b[index / 2] = data;
2371 vmx->pt_desc.guest.addr_a[index / 2] = data;
2373 case MSR_IA32_PERF_CAPABILITIES:
2374 if (data && !vcpu_to_pmu(vcpu)->version)
2376 if (data & PMU_CAP_LBR_FMT) {
2377 if ((data & PMU_CAP_LBR_FMT) !=
2378 (kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT))
2380 if (!cpuid_model_is_consistent(vcpu))
2383 if (data & PERF_CAP_PEBS_FORMAT) {
2384 if ((data & PERF_CAP_PEBS_MASK) !=
2385 (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK))
2387 if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2389 if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2391 if (!cpuid_model_is_consistent(vcpu))
2394 ret = kvm_set_msr_common(vcpu, msr_info);
2399 msr = vmx_find_uret_msr(vmx, msr_index);
2401 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2403 ret = kvm_set_msr_common(vcpu, msr_info);
2406 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2407 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2408 vmx_update_fb_clear_dis(vcpu, vmx);
2413 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2415 unsigned long guest_owned_bits;
2417 kvm_register_mark_available(vcpu, reg);
2421 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2424 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2426 case VCPU_EXREG_PDPTR:
2428 ept_save_pdptrs(vcpu);
2430 case VCPU_EXREG_CR0:
2431 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2433 vcpu->arch.cr0 &= ~guest_owned_bits;
2434 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2436 case VCPU_EXREG_CR3:
2438 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2439 * CR3 is loaded into hardware, not the guest's CR3.
2441 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2442 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2444 case VCPU_EXREG_CR4:
2445 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2447 vcpu->arch.cr4 &= ~guest_owned_bits;
2448 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2451 KVM_BUG_ON(1, vcpu->kvm);
2456 static __init int cpu_has_kvm_support(void)
2458 return cpu_has_vmx();
2461 static __init int vmx_disabled_by_bios(void)
2463 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2464 !boot_cpu_has(X86_FEATURE_VMX);
2467 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2471 cr4_set_bits(X86_CR4_VMXE);
2473 asm goto("1: vmxon %[vmxon_pointer]\n\t"
2474 _ASM_EXTABLE(1b, %l[fault])
2475 : : [vmxon_pointer] "m"(vmxon_pointer)
2480 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2481 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2482 cr4_clear_bits(X86_CR4_VMXE);
2487 static int vmx_hardware_enable(void)
2489 int cpu = raw_smp_processor_id();
2490 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2493 if (cr4_read_shadow() & X86_CR4_VMXE)
2497 * This can happen if we hot-added a CPU but failed to allocate
2498 * VP assist page for it.
2500 if (static_branch_unlikely(&enable_evmcs) &&
2501 !hv_get_vp_assist_page(cpu))
2504 intel_pt_handle_vmx(1);
2506 r = kvm_cpu_vmxon(phys_addr);
2508 intel_pt_handle_vmx(0);
2518 static void vmclear_local_loaded_vmcss(void)
2520 int cpu = raw_smp_processor_id();
2521 struct loaded_vmcs *v, *n;
2523 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2524 loaded_vmcss_on_cpu_link)
2525 __loaded_vmcs_clear(v);
2528 static void vmx_hardware_disable(void)
2530 vmclear_local_loaded_vmcss();
2533 kvm_spurious_fault();
2537 intel_pt_handle_vmx(0);
2541 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2542 * directly instead of going through cpu_has(), to ensure KVM is trapping
2543 * ENCLS whenever it's supported in hardware. It does not matter whether
2544 * the host OS supports or has enabled SGX.
2546 static bool cpu_has_sgx(void)
2548 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2552 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2553 * can't be used due to errata where VM Exit may incorrectly clear
2554 * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2555 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2557 static bool cpu_has_perf_global_ctrl_bug(void)
2559 if (boot_cpu_data.x86 == 0x6) {
2560 switch (boot_cpu_data.x86_model) {
2561 case INTEL_FAM6_NEHALEM_EP: /* AAK155 */
2562 case INTEL_FAM6_NEHALEM: /* AAP115 */
2563 case INTEL_FAM6_WESTMERE: /* AAT100 */
2564 case INTEL_FAM6_WESTMERE_EP: /* BC86,AAY89,BD102 */
2565 case INTEL_FAM6_NEHALEM_EX: /* BA97 */
2575 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2576 u32 msr, u32 *result)
2578 u32 vmx_msr_low, vmx_msr_high;
2579 u32 ctl = ctl_min | ctl_opt;
2581 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2583 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2584 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2586 /* Ensure minimum (required) set of control bits are supported. */
2594 static __init u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2598 rdmsrl(msr, allowed);
2600 return ctl_opt & allowed;
2603 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2604 struct vmx_capability *vmx_cap)
2606 u32 vmx_msr_low, vmx_msr_high;
2607 u32 _pin_based_exec_control = 0;
2608 u32 _cpu_based_exec_control = 0;
2609 u32 _cpu_based_2nd_exec_control = 0;
2610 u64 _cpu_based_3rd_exec_control = 0;
2611 u32 _vmexit_control = 0;
2612 u32 _vmentry_control = 0;
2617 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2618 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2619 * intercepts writes to PAT and EFER, i.e. never enables those controls.
2624 } const vmcs_entry_exit_pairs[] = {
2625 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2626 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
2627 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
2628 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
2629 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
2632 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2634 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2635 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2636 MSR_IA32_VMX_PROCBASED_CTLS,
2637 &_cpu_based_exec_control))
2639 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2640 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2641 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2642 MSR_IA32_VMX_PROCBASED_CTLS2,
2643 &_cpu_based_2nd_exec_control))
2646 #ifndef CONFIG_X86_64
2647 if (!(_cpu_based_2nd_exec_control &
2648 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2649 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2652 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2653 _cpu_based_2nd_exec_control &= ~(
2654 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2655 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2656 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2658 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2659 &vmx_cap->ept, &vmx_cap->vpid);
2661 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2663 pr_warn_once("EPT CAP should not exist if not support "
2664 "1-setting enable EPT VM-execution control\n");
2666 if (error_on_inconsistent_vmcs_config)
2671 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2673 pr_warn_once("VPID CAP should not exist if not support "
2674 "1-setting enable VPID VM-execution control\n");
2676 if (error_on_inconsistent_vmcs_config)
2683 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2685 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2686 _cpu_based_3rd_exec_control =
2687 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2688 MSR_IA32_VMX_PROCBASED_CTLS3);
2690 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2691 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2692 MSR_IA32_VMX_EXIT_CTLS,
2696 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2697 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2698 MSR_IA32_VMX_PINBASED_CTLS,
2699 &_pin_based_exec_control))
2702 if (cpu_has_broken_vmx_preemption_timer())
2703 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2704 if (!(_cpu_based_2nd_exec_control &
2705 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2706 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2708 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2709 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2710 MSR_IA32_VMX_ENTRY_CTLS,
2714 for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2715 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2716 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2718 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2721 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2722 _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2724 if (error_on_inconsistent_vmcs_config)
2727 _vmentry_control &= ~n_ctrl;
2728 _vmexit_control &= ~x_ctrl;
2731 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2733 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2734 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2737 #ifdef CONFIG_X86_64
2738 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2739 if (vmx_msr_high & (1u<<16))
2743 /* Require Write-Back (WB) memory type for VMCS accesses. */
2744 if (((vmx_msr_high >> 18) & 15) != 6)
2747 rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2749 vmcs_conf->size = vmx_msr_high & 0x1fff;
2750 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2752 vmcs_conf->revision_id = vmx_msr_low;
2754 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2755 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2756 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2757 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2758 vmcs_conf->vmexit_ctrl = _vmexit_control;
2759 vmcs_conf->vmentry_ctrl = _vmentry_control;
2760 vmcs_conf->misc = misc_msr;
2765 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2767 int node = cpu_to_node(cpu);
2771 pages = __alloc_pages_node(node, flags, 0);
2774 vmcs = page_address(pages);
2775 memset(vmcs, 0, vmcs_config.size);
2777 /* KVM supports Enlightened VMCS v1 only */
2778 if (static_branch_unlikely(&enable_evmcs))
2779 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2781 vmcs->hdr.revision_id = vmcs_config.revision_id;
2784 vmcs->hdr.shadow_vmcs = 1;
2788 void free_vmcs(struct vmcs *vmcs)
2790 free_page((unsigned long)vmcs);
2794 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2796 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2798 if (!loaded_vmcs->vmcs)
2800 loaded_vmcs_clear(loaded_vmcs);
2801 free_vmcs(loaded_vmcs->vmcs);
2802 loaded_vmcs->vmcs = NULL;
2803 if (loaded_vmcs->msr_bitmap)
2804 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2805 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2808 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2810 loaded_vmcs->vmcs = alloc_vmcs(false);
2811 if (!loaded_vmcs->vmcs)
2814 vmcs_clear(loaded_vmcs->vmcs);
2816 loaded_vmcs->shadow_vmcs = NULL;
2817 loaded_vmcs->hv_timer_soft_disabled = false;
2818 loaded_vmcs->cpu = -1;
2819 loaded_vmcs->launched = 0;
2821 if (cpu_has_vmx_msr_bitmap()) {
2822 loaded_vmcs->msr_bitmap = (unsigned long *)
2823 __get_free_page(GFP_KERNEL_ACCOUNT);
2824 if (!loaded_vmcs->msr_bitmap)
2826 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2829 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2830 memset(&loaded_vmcs->controls_shadow, 0,
2831 sizeof(struct vmcs_controls_shadow));
2836 free_loaded_vmcs(loaded_vmcs);
2840 static void free_kvm_area(void)
2844 for_each_possible_cpu(cpu) {
2845 free_vmcs(per_cpu(vmxarea, cpu));
2846 per_cpu(vmxarea, cpu) = NULL;
2850 static __init int alloc_kvm_area(void)
2854 for_each_possible_cpu(cpu) {
2857 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2864 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2865 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2866 * revision_id reported by MSR_IA32_VMX_BASIC.
2868 * However, even though not explicitly documented by
2869 * TLFS, VMXArea passed as VMXON argument should
2870 * still be marked with revision_id reported by
2873 if (static_branch_unlikely(&enable_evmcs))
2874 vmcs->hdr.revision_id = vmcs_config.revision_id;
2876 per_cpu(vmxarea, cpu) = vmcs;
2881 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2882 struct kvm_segment *save)
2884 if (!emulate_invalid_guest_state) {
2886 * CS and SS RPL should be equal during guest entry according
2887 * to VMX spec, but in reality it is not always so. Since vcpu
2888 * is in the middle of the transition from real mode to
2889 * protected mode it is safe to assume that RPL 0 is a good
2892 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2893 save->selector &= ~SEGMENT_RPL_MASK;
2894 save->dpl = save->selector & SEGMENT_RPL_MASK;
2897 __vmx_set_segment(vcpu, save, seg);
2900 static void enter_pmode(struct kvm_vcpu *vcpu)
2902 unsigned long flags;
2903 struct vcpu_vmx *vmx = to_vmx(vcpu);
2906 * Update real mode segment cache. It may be not up-to-date if segment
2907 * register was written while vcpu was in a guest mode.
2909 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2910 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2911 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2912 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2913 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2914 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2916 vmx->rmode.vm86_active = 0;
2918 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2920 flags = vmcs_readl(GUEST_RFLAGS);
2921 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2922 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2923 vmcs_writel(GUEST_RFLAGS, flags);
2925 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2926 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2928 vmx_update_exception_bitmap(vcpu);
2930 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2931 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2932 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2933 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2934 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2935 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2938 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2940 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2941 struct kvm_segment var = *save;
2944 if (seg == VCPU_SREG_CS)
2947 if (!emulate_invalid_guest_state) {
2948 var.selector = var.base >> 4;
2949 var.base = var.base & 0xffff0;
2959 if (save->base & 0xf)
2960 printk_once(KERN_WARNING "kvm: segment base is not "
2961 "paragraph aligned when entering "
2962 "protected mode (seg=%d)", seg);
2965 vmcs_write16(sf->selector, var.selector);
2966 vmcs_writel(sf->base, var.base);
2967 vmcs_write32(sf->limit, var.limit);
2968 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2971 static void enter_rmode(struct kvm_vcpu *vcpu)
2973 unsigned long flags;
2974 struct vcpu_vmx *vmx = to_vmx(vcpu);
2975 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2978 * KVM should never use VM86 to virtualize Real Mode when L2 is active,
2979 * as using VM86 is unnecessary if unrestricted guest is enabled, and
2980 * if unrestricted guest is disabled, VM-Enter (from L1) with CR0.PG=0
2981 * should VM-Fail and KVM should reject userspace attempts to stuff
2982 * CR0.PG=0 when L2 is active.
2984 WARN_ON_ONCE(is_guest_mode(vcpu));
2986 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2987 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2988 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2989 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2990 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2991 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2992 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2994 vmx->rmode.vm86_active = 1;
2997 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2998 * vcpu. Warn the user that an update is overdue.
3000 if (!kvm_vmx->tss_addr)
3001 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3002 "called before entering vcpu\n");
3004 vmx_segment_cache_clear(vmx);
3006 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
3007 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3008 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3010 flags = vmcs_readl(GUEST_RFLAGS);
3011 vmx->rmode.save_rflags = flags;
3013 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3015 vmcs_writel(GUEST_RFLAGS, flags);
3016 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3017 vmx_update_exception_bitmap(vcpu);
3019 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3020 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3021 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3022 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3023 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3024 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3027 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3029 struct vcpu_vmx *vmx = to_vmx(vcpu);
3031 /* Nothing to do if hardware doesn't support EFER. */
3032 if (!vmx_find_uret_msr(vmx, MSR_EFER))
3035 vcpu->arch.efer = efer;
3036 #ifdef CONFIG_X86_64
3037 if (efer & EFER_LMA)
3038 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
3040 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
3042 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
3046 vmx_setup_uret_msrs(vmx);
3050 #ifdef CONFIG_X86_64
3052 static void enter_lmode(struct kvm_vcpu *vcpu)
3056 vmx_segment_cache_clear(to_vmx(vcpu));
3058 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3059 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3060 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3062 vmcs_write32(GUEST_TR_AR_BYTES,
3063 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3064 | VMX_AR_TYPE_BUSY_64_TSS);
3066 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3069 static void exit_lmode(struct kvm_vcpu *vcpu)
3071 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3076 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3078 struct vcpu_vmx *vmx = to_vmx(vcpu);
3081 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3082 * the CPU is not required to invalidate guest-physical mappings on
3083 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3084 * associated with the root EPT structure and not any particular VPID
3085 * (INVVPID also isn't required to invalidate guest-physical mappings).
3089 } else if (enable_vpid) {
3090 if (cpu_has_vmx_invvpid_global()) {
3091 vpid_sync_vcpu_global();
3093 vpid_sync_vcpu_single(vmx->vpid);
3094 vpid_sync_vcpu_single(vmx->nested.vpid02);
3099 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3101 if (is_guest_mode(vcpu))
3102 return nested_get_vpid02(vcpu);
3103 return to_vmx(vcpu)->vpid;
3106 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3108 struct kvm_mmu *mmu = vcpu->arch.mmu;
3109 u64 root_hpa = mmu->root.hpa;
3111 /* No flush required if the current context is invalid. */
3112 if (!VALID_PAGE(root_hpa))
3116 ept_sync_context(construct_eptp(vcpu, root_hpa,
3117 mmu->root_role.level));
3119 vpid_sync_context(vmx_get_current_vpid(vcpu));
3122 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3125 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3126 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3128 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3131 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3134 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3135 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3136 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3137 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3138 * i.e. no explicit INVVPID is necessary.
3140 vpid_sync_context(vmx_get_current_vpid(vcpu));
3143 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3145 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3147 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3150 if (is_pae_paging(vcpu)) {
3151 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3152 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3153 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3154 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3158 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3160 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3162 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3165 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3166 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3167 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3168 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3170 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3173 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3174 CPU_BASED_CR3_STORE_EXITING)
3176 static bool vmx_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3178 if (is_guest_mode(vcpu))
3179 return nested_guest_cr0_valid(vcpu, cr0);
3181 if (to_vmx(vcpu)->nested.vmxon)
3182 return nested_host_cr0_valid(vcpu, cr0);
3187 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3189 struct vcpu_vmx *vmx = to_vmx(vcpu);
3190 unsigned long hw_cr0, old_cr0_pg;
3193 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3195 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3196 if (enable_unrestricted_guest)
3197 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3199 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3201 hw_cr0 |= X86_CR0_WP;
3203 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3206 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3210 vmcs_writel(CR0_READ_SHADOW, cr0);
3211 vmcs_writel(GUEST_CR0, hw_cr0);
3212 vcpu->arch.cr0 = cr0;
3213 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3215 #ifdef CONFIG_X86_64
3216 if (vcpu->arch.efer & EFER_LME) {
3217 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3219 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3224 if (enable_ept && !enable_unrestricted_guest) {
3226 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3227 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3228 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3229 * KVM's CR3 is installed.
3231 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3232 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3235 * When running with EPT but not unrestricted guest, KVM must
3236 * intercept CR3 accesses when paging is _disabled_. This is
3237 * necessary because restricted guests can't actually run with
3238 * paging disabled, and so KVM stuffs its own CR3 in order to
3239 * run the guest when identity mapped page tables.
3241 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3242 * update, it may be stale with respect to CR3 interception,
3243 * e.g. after nested VM-Enter.
3245 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3246 * stores to forward them to L1, even if KVM does not need to
3247 * intercept them to preserve its identity mapped page tables.
3249 if (!(cr0 & X86_CR0_PG)) {
3250 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3251 } else if (!is_guest_mode(vcpu)) {
3252 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3254 tmp = exec_controls_get(vmx);
3255 tmp &= ~CR3_EXITING_BITS;
3256 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3257 exec_controls_set(vmx, tmp);
3260 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3261 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3262 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3265 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3266 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3268 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3269 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3272 /* depends on vcpu->arch.cr0 to be set to a new value */
3273 vmx->emulation_required = vmx_emulation_required(vcpu);
3276 static int vmx_get_max_tdp_level(void)
3278 if (cpu_has_vmx_ept_5levels())
3283 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3285 u64 eptp = VMX_EPTP_MT_WB;
3287 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3289 if (enable_ept_ad_bits &&
3290 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3291 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3297 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3300 struct kvm *kvm = vcpu->kvm;
3301 bool update_guest_cr3 = true;
3302 unsigned long guest_cr3;
3306 eptp = construct_eptp(vcpu, root_hpa, root_level);
3307 vmcs_write64(EPT_POINTER, eptp);
3309 hv_track_root_tdp(vcpu, root_hpa);
3311 if (!enable_unrestricted_guest && !is_paging(vcpu))
3312 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3313 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3314 guest_cr3 = vcpu->arch.cr3;
3315 else /* vmcs.GUEST_CR3 is already up-to-date. */
3316 update_guest_cr3 = false;
3317 vmx_ept_load_pdptrs(vcpu);
3319 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3322 if (update_guest_cr3)
3323 vmcs_writel(GUEST_CR3, guest_cr3);
3327 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3330 * We operate under the default treatment of SMM, so VMX cannot be
3331 * enabled under SMM. Note, whether or not VMXE is allowed at all,
3332 * i.e. is a reserved bit, is handled by common x86 code.
3334 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3337 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3343 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3345 unsigned long old_cr4 = vcpu->arch.cr4;
3346 struct vcpu_vmx *vmx = to_vmx(vcpu);
3348 * Pass through host's Machine Check Enable value to hw_cr4, which
3349 * is in force while we are in guest mode. Do not let guests control
3350 * this bit, even if host CR4.MCE == 0.
3352 unsigned long hw_cr4;
3354 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3355 if (enable_unrestricted_guest)
3356 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3357 else if (vmx->rmode.vm86_active)
3358 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3360 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3362 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3363 if (cr4 & X86_CR4_UMIP) {
3364 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3365 hw_cr4 &= ~X86_CR4_UMIP;
3366 } else if (!is_guest_mode(vcpu) ||
3367 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3368 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3372 vcpu->arch.cr4 = cr4;
3373 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3375 if (!enable_unrestricted_guest) {
3377 if (!is_paging(vcpu)) {
3378 hw_cr4 &= ~X86_CR4_PAE;
3379 hw_cr4 |= X86_CR4_PSE;
3380 } else if (!(cr4 & X86_CR4_PAE)) {
3381 hw_cr4 &= ~X86_CR4_PAE;
3386 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3387 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3388 * to be manually disabled when guest switches to non-paging
3391 * If !enable_unrestricted_guest, the CPU is always running
3392 * with CR0.PG=1 and CR4 needs to be modified.
3393 * If enable_unrestricted_guest, the CPU automatically
3394 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3396 if (!is_paging(vcpu))
3397 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3400 vmcs_writel(CR4_READ_SHADOW, cr4);
3401 vmcs_writel(GUEST_CR4, hw_cr4);
3403 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3404 kvm_update_cpuid_runtime(vcpu);
3407 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3409 struct vcpu_vmx *vmx = to_vmx(vcpu);
3412 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3413 *var = vmx->rmode.segs[seg];
3414 if (seg == VCPU_SREG_TR
3415 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3417 var->base = vmx_read_guest_seg_base(vmx, seg);
3418 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3421 var->base = vmx_read_guest_seg_base(vmx, seg);
3422 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3423 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3424 ar = vmx_read_guest_seg_ar(vmx, seg);
3425 var->unusable = (ar >> 16) & 1;
3426 var->type = ar & 15;
3427 var->s = (ar >> 4) & 1;
3428 var->dpl = (ar >> 5) & 3;
3430 * Some userspaces do not preserve unusable property. Since usable
3431 * segment has to be present according to VMX spec we can use present
3432 * property to amend userspace bug by making unusable segment always
3433 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3434 * segment as unusable.
3436 var->present = !var->unusable;
3437 var->avl = (ar >> 12) & 1;
3438 var->l = (ar >> 13) & 1;
3439 var->db = (ar >> 14) & 1;
3440 var->g = (ar >> 15) & 1;
3443 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3445 struct kvm_segment s;
3447 if (to_vmx(vcpu)->rmode.vm86_active) {
3448 vmx_get_segment(vcpu, &s, seg);
3451 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3454 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3456 struct vcpu_vmx *vmx = to_vmx(vcpu);
3458 if (unlikely(vmx->rmode.vm86_active))
3461 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3462 return VMX_AR_DPL(ar);
3466 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3470 ar = var->type & 15;
3471 ar |= (var->s & 1) << 4;
3472 ar |= (var->dpl & 3) << 5;
3473 ar |= (var->present & 1) << 7;
3474 ar |= (var->avl & 1) << 12;
3475 ar |= (var->l & 1) << 13;
3476 ar |= (var->db & 1) << 14;
3477 ar |= (var->g & 1) << 15;
3478 ar |= (var->unusable || !var->present) << 16;
3483 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3485 struct vcpu_vmx *vmx = to_vmx(vcpu);
3486 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3488 vmx_segment_cache_clear(vmx);
3490 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3491 vmx->rmode.segs[seg] = *var;
3492 if (seg == VCPU_SREG_TR)
3493 vmcs_write16(sf->selector, var->selector);
3495 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3499 vmcs_writel(sf->base, var->base);
3500 vmcs_write32(sf->limit, var->limit);
3501 vmcs_write16(sf->selector, var->selector);
3504 * Fix the "Accessed" bit in AR field of segment registers for older
3506 * IA32 arch specifies that at the time of processor reset the
3507 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3508 * is setting it to 0 in the userland code. This causes invalid guest
3509 * state vmexit when "unrestricted guest" mode is turned on.
3510 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3511 * tree. Newer qemu binaries with that qemu fix would not need this
3514 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3515 var->type |= 0x1; /* Accessed */
3517 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3520 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3522 __vmx_set_segment(vcpu, var, seg);
3524 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3527 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3529 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3531 *db = (ar >> 14) & 1;
3532 *l = (ar >> 13) & 1;
3535 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3537 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3538 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3541 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3543 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3544 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3547 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3549 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3550 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3553 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3555 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3556 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3559 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3561 struct kvm_segment var;
3564 vmx_get_segment(vcpu, &var, seg);
3566 if (seg == VCPU_SREG_CS)
3568 ar = vmx_segment_access_rights(&var);
3570 if (var.base != (var.selector << 4))
3572 if (var.limit != 0xffff)
3580 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3582 struct kvm_segment cs;
3583 unsigned int cs_rpl;
3585 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3586 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3590 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3594 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3595 if (cs.dpl > cs_rpl)
3598 if (cs.dpl != cs_rpl)
3604 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3608 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3610 struct kvm_segment ss;
3611 unsigned int ss_rpl;
3613 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3614 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3618 if (ss.type != 3 && ss.type != 7)
3622 if (ss.dpl != ss_rpl) /* DPL != RPL */
3630 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3632 struct kvm_segment var;
3635 vmx_get_segment(vcpu, &var, seg);
3636 rpl = var.selector & SEGMENT_RPL_MASK;
3644 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3645 if (var.dpl < rpl) /* DPL < RPL */
3649 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3655 static bool tr_valid(struct kvm_vcpu *vcpu)
3657 struct kvm_segment tr;
3659 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3663 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3665 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3673 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3675 struct kvm_segment ldtr;
3677 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3681 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3691 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3693 struct kvm_segment cs, ss;
3695 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3696 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3698 return ((cs.selector & SEGMENT_RPL_MASK) ==
3699 (ss.selector & SEGMENT_RPL_MASK));
3703 * Check if guest state is valid. Returns true if valid, false if
3705 * We assume that registers are always usable
3707 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3709 /* real mode guest state checks */
3710 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3711 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3713 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3715 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3717 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3719 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3721 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3724 /* protected mode guest state checks */
3725 if (!cs_ss_rpl_check(vcpu))
3727 if (!code_segment_valid(vcpu))
3729 if (!stack_segment_valid(vcpu))
3731 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3733 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3735 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3737 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3739 if (!tr_valid(vcpu))
3741 if (!ldtr_valid(vcpu))
3745 * - Add checks on RIP
3746 * - Add checks on RFLAGS
3752 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3754 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3758 for (i = 0; i < 3; i++) {
3759 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3763 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3764 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3768 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3774 static int init_rmode_identity_map(struct kvm *kvm)
3776 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3781 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3782 mutex_lock(&kvm->slots_lock);
3784 if (likely(kvm_vmx->ept_identity_pagetable_done))
3787 if (!kvm_vmx->ept_identity_map_addr)
3788 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3790 uaddr = __x86_set_memory_region(kvm,
3791 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3792 kvm_vmx->ept_identity_map_addr,
3794 if (IS_ERR(uaddr)) {
3799 /* Set up identity-mapping pagetable for EPT in real mode */
3800 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3801 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3802 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3803 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3808 kvm_vmx->ept_identity_pagetable_done = true;
3811 mutex_unlock(&kvm->slots_lock);
3815 static void seg_setup(int seg)
3817 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3820 vmcs_write16(sf->selector, 0);
3821 vmcs_writel(sf->base, 0);
3822 vmcs_write32(sf->limit, 0xffff);
3824 if (seg == VCPU_SREG_CS)
3825 ar |= 0x08; /* code segment */
3827 vmcs_write32(sf->ar_bytes, ar);
3830 static int alloc_apic_access_page(struct kvm *kvm)
3836 mutex_lock(&kvm->slots_lock);
3837 if (kvm->arch.apic_access_memslot_enabled)
3839 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3840 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3846 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3847 if (is_error_page(page)) {
3853 * Do not pin the page in memory, so that memory hot-unplug
3854 * is able to migrate it.
3857 kvm->arch.apic_access_memslot_enabled = true;
3859 mutex_unlock(&kvm->slots_lock);
3863 int allocate_vpid(void)
3869 spin_lock(&vmx_vpid_lock);
3870 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3871 if (vpid < VMX_NR_VPIDS)
3872 __set_bit(vpid, vmx_vpid_bitmap);
3875 spin_unlock(&vmx_vpid_lock);
3879 void free_vpid(int vpid)
3881 if (!enable_vpid || vpid == 0)
3883 spin_lock(&vmx_vpid_lock);
3884 __clear_bit(vpid, vmx_vpid_bitmap);
3885 spin_unlock(&vmx_vpid_lock);
3888 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3891 * When KVM is a nested hypervisor on top of Hyper-V and uses
3892 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3893 * bitmap has changed.
3895 if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs)) {
3896 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
3898 if (evmcs->hv_enlightenments_control.msr_bitmap)
3899 evmcs->hv_clean_fields &=
3900 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
3903 vmx->nested.force_msr_bitmap_recalc = true;
3906 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3908 struct vcpu_vmx *vmx = to_vmx(vcpu);
3909 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3911 if (!cpu_has_vmx_msr_bitmap())
3914 vmx_msr_bitmap_l01_changed(vmx);
3917 * Mark the desired intercept state in shadow bitmap, this is needed
3918 * for resync when the MSR filters change.
3920 if (is_valid_passthrough_msr(msr)) {
3921 int idx = possible_passthrough_msr_slot(msr);
3923 if (idx != -ENOENT) {
3924 if (type & MSR_TYPE_R)
3925 clear_bit(idx, vmx->shadow_msr_intercept.read);
3926 if (type & MSR_TYPE_W)
3927 clear_bit(idx, vmx->shadow_msr_intercept.write);
3931 if ((type & MSR_TYPE_R) &&
3932 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3933 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3934 type &= ~MSR_TYPE_R;
3937 if ((type & MSR_TYPE_W) &&
3938 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3939 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3940 type &= ~MSR_TYPE_W;
3943 if (type & MSR_TYPE_R)
3944 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3946 if (type & MSR_TYPE_W)
3947 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3950 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3952 struct vcpu_vmx *vmx = to_vmx(vcpu);
3953 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3955 if (!cpu_has_vmx_msr_bitmap())
3958 vmx_msr_bitmap_l01_changed(vmx);
3961 * Mark the desired intercept state in shadow bitmap, this is needed
3962 * for resync when the MSR filter changes.
3964 if (is_valid_passthrough_msr(msr)) {
3965 int idx = possible_passthrough_msr_slot(msr);
3967 if (idx != -ENOENT) {
3968 if (type & MSR_TYPE_R)
3969 set_bit(idx, vmx->shadow_msr_intercept.read);
3970 if (type & MSR_TYPE_W)
3971 set_bit(idx, vmx->shadow_msr_intercept.write);
3975 if (type & MSR_TYPE_R)
3976 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3978 if (type & MSR_TYPE_W)
3979 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3982 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3984 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3985 unsigned long read_intercept;
3988 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3990 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3991 unsigned int read_idx = msr / BITS_PER_LONG;
3992 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3994 msr_bitmap[read_idx] = read_intercept;
3995 msr_bitmap[write_idx] = ~0ul;
3999 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
4001 struct vcpu_vmx *vmx = to_vmx(vcpu);
4004 if (!cpu_has_vmx_msr_bitmap())
4007 if (cpu_has_secondary_exec_ctrls() &&
4008 (secondary_exec_controls_get(vmx) &
4009 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4010 mode = MSR_BITMAP_MODE_X2APIC;
4011 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4012 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4017 if (mode == vmx->x2apic_msr_bitmap_mode)
4020 vmx->x2apic_msr_bitmap_mode = mode;
4022 vmx_reset_x2apic_msrs(vcpu, mode);
4025 * TPR reads and writes can be virtualized even if virtual interrupt
4026 * delivery is not in use.
4028 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
4029 !(mode & MSR_BITMAP_MODE_X2APIC));
4031 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
4032 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
4033 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
4034 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
4036 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
4040 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
4042 struct vcpu_vmx *vmx = to_vmx(vcpu);
4043 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
4046 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
4047 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
4048 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
4049 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
4050 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
4051 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
4052 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
4056 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
4058 struct vcpu_vmx *vmx = to_vmx(vcpu);
4063 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
4064 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
4065 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
4068 rvi = vmx_get_rvi();
4070 vapic_page = vmx->nested.virtual_apic_map.hva;
4071 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4073 return ((rvi & 0xf0) > (vppr & 0xf0));
4076 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4078 struct vcpu_vmx *vmx = to_vmx(vcpu);
4082 * Redo intercept permissions for MSRs that KVM is passing through to
4083 * the guest. Disabling interception will check the new MSR filter and
4084 * ensure that KVM enables interception if usersepace wants to filter
4085 * the MSR. MSRs that KVM is already intercepting don't need to be
4086 * refreshed since KVM is going to intercept them regardless of what
4089 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4090 u32 msr = vmx_possible_passthrough_msrs[i];
4092 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4093 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4095 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4096 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4099 /* PT MSRs can be passed through iff PT is exposed to the guest. */
4100 if (vmx_pt_mode_is_host_guest())
4101 pt_update_intercept_for_msr(vcpu);
4104 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4108 if (vcpu->mode == IN_GUEST_MODE) {
4110 * The vector of the virtual has already been set in the PIR.
4111 * Send a notification event to deliver the virtual interrupt
4112 * unless the vCPU is the currently running vCPU, i.e. the
4113 * event is being sent from a fastpath VM-Exit handler, in
4114 * which case the PIR will be synced to the vIRR before
4115 * re-entering the guest.
4117 * When the target is not the running vCPU, the following
4118 * possibilities emerge:
4120 * Case 1: vCPU stays in non-root mode. Sending a notification
4121 * event posts the interrupt to the vCPU.
4123 * Case 2: vCPU exits to root mode and is still runnable. The
4124 * PIR will be synced to the vIRR before re-entering the guest.
4125 * Sending a notification event is ok as the host IRQ handler
4126 * will ignore the spurious event.
4128 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4129 * has already synced PIR to vIRR and never blocks the vCPU if
4130 * the vIRR is not empty. Therefore, a blocked vCPU here does
4131 * not wait for any requested interrupts in PIR, and sending a
4132 * notification event also results in a benign, spurious event.
4135 if (vcpu != kvm_get_running_vcpu())
4136 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4141 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4142 * otherwise do nothing as KVM will grab the highest priority pending
4143 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4145 kvm_vcpu_wake_up(vcpu);
4148 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4151 struct vcpu_vmx *vmx = to_vmx(vcpu);
4153 if (is_guest_mode(vcpu) &&
4154 vector == vmx->nested.posted_intr_nv) {
4156 * If a posted intr is not recognized by hardware,
4157 * we will accomplish it in the next vmentry.
4159 vmx->nested.pi_pending = true;
4160 kvm_make_request(KVM_REQ_EVENT, vcpu);
4163 * This pairs with the smp_mb_*() after setting vcpu->mode in
4164 * vcpu_enter_guest() to guarantee the vCPU sees the event
4165 * request if triggering a posted interrupt "fails" because
4166 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4167 * the smb_wmb() in kvm_make_request() only ensures everything
4168 * done before making the request is visible when the request
4169 * is visible, it doesn't ensure ordering between the store to
4170 * vcpu->requests and the load from vcpu->mode.
4172 smp_mb__after_atomic();
4174 /* the PIR and ON have been set by L1. */
4175 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4181 * Send interrupt to vcpu via posted interrupt way.
4182 * 1. If target vcpu is running(non-root mode), send posted interrupt
4183 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4184 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4185 * interrupt from PIR in next vmentry.
4187 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4189 struct vcpu_vmx *vmx = to_vmx(vcpu);
4192 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4196 /* Note, this is called iff the local APIC is in-kernel. */
4197 if (!vcpu->arch.apic->apicv_active)
4200 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4203 /* If a previous notification has sent the IPI, nothing to do. */
4204 if (pi_test_and_set_on(&vmx->pi_desc))
4208 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4209 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4210 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4211 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4213 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4217 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4218 int trig_mode, int vector)
4220 struct kvm_vcpu *vcpu = apic->vcpu;
4222 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4223 kvm_lapic_set_irr(vector, apic);
4224 kvm_make_request(KVM_REQ_EVENT, vcpu);
4225 kvm_vcpu_kick(vcpu);
4227 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4233 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4234 * will not change in the lifetime of the guest.
4235 * Note that host-state that does change is set elsewhere. E.g., host-state
4236 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4238 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4242 unsigned long cr0, cr3, cr4;
4245 WARN_ON(cr0 & X86_CR0_TS);
4246 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4249 * Save the most likely value for this task's CR3 in the VMCS.
4250 * We can't use __get_current_cr3_fast() because we're not atomic.
4253 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4254 vmx->loaded_vmcs->host_state.cr3 = cr3;
4256 /* Save the most likely value for this task's CR4 in the VMCS. */
4257 cr4 = cr4_read_shadow();
4258 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4259 vmx->loaded_vmcs->host_state.cr4 = cr4;
4261 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4262 #ifdef CONFIG_X86_64
4264 * Load null selectors, so we can avoid reloading them in
4265 * vmx_prepare_switch_to_host(), in case userspace uses
4266 * the null selectors too (the expected case).
4268 vmcs_write16(HOST_DS_SELECTOR, 0);
4269 vmcs_write16(HOST_ES_SELECTOR, 0);
4271 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4272 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4274 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4275 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4277 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4279 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4281 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4282 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4285 * SYSENTER is used for 32-bit system calls on either 32-bit or
4286 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4287 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4288 * have already done so!).
4290 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4291 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4293 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4294 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4296 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4297 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4298 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4301 if (cpu_has_load_ia32_efer())
4302 vmcs_write64(HOST_IA32_EFER, host_efer);
4305 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4307 struct kvm_vcpu *vcpu = &vmx->vcpu;
4309 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4310 ~vcpu->arch.cr4_guest_rsvd_bits;
4312 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4313 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4315 if (is_guest_mode(&vmx->vcpu))
4316 vcpu->arch.cr4_guest_owned_bits &=
4317 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4318 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4321 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4323 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4325 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4326 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4329 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4331 if (!enable_preemption_timer)
4332 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4334 return pin_based_exec_ctrl;
4337 static u32 vmx_vmentry_ctrl(void)
4339 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4341 if (vmx_pt_mode_is_system())
4342 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4343 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4345 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4347 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4348 VM_ENTRY_LOAD_IA32_EFER |
4349 VM_ENTRY_IA32E_MODE);
4351 if (cpu_has_perf_global_ctrl_bug())
4352 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4354 return vmentry_ctrl;
4357 static u32 vmx_vmexit_ctrl(void)
4359 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4362 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4363 * nested virtualization and thus allowed to be set in vmcs12.
4365 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4366 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4368 if (vmx_pt_mode_is_system())
4369 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4370 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4372 if (cpu_has_perf_global_ctrl_bug())
4373 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4375 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4376 return vmexit_ctrl &
4377 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4380 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4382 struct vcpu_vmx *vmx = to_vmx(vcpu);
4384 if (is_guest_mode(vcpu)) {
4385 vmx->nested.update_vmcs01_apicv_status = true;
4389 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4391 if (kvm_vcpu_apicv_active(vcpu)) {
4392 secondary_exec_controls_setbit(vmx,
4393 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4394 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4396 tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4398 secondary_exec_controls_clearbit(vmx,
4399 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4400 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4402 tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4405 vmx_update_msr_bitmap_x2apic(vcpu);
4408 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4410 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4413 * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4414 * vmcs12 and propagated to vmcs02 when set in vmcs12.
4416 exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4417 CPU_BASED_USE_IO_BITMAPS |
4418 CPU_BASED_MONITOR_TRAP_FLAG |
4419 CPU_BASED_PAUSE_EXITING);
4421 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4422 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4423 CPU_BASED_NMI_WINDOW_EXITING);
4425 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4426 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4428 if (!cpu_need_tpr_shadow(&vmx->vcpu))
4429 exec_control &= ~CPU_BASED_TPR_SHADOW;
4431 #ifdef CONFIG_X86_64
4432 if (exec_control & CPU_BASED_TPR_SHADOW)
4433 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4434 CPU_BASED_CR8_STORE_EXITING);
4436 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4437 CPU_BASED_CR8_LOAD_EXITING;
4439 /* No need to intercept CR3 access or INVPLG when using EPT. */
4441 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4442 CPU_BASED_CR3_STORE_EXITING |
4443 CPU_BASED_INVLPG_EXITING);
4444 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4445 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4446 CPU_BASED_MONITOR_EXITING);
4447 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4448 exec_control &= ~CPU_BASED_HLT_EXITING;
4449 return exec_control;
4452 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4454 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4457 * IPI virtualization relies on APICv. Disable IPI virtualization if
4458 * APICv is inhibited.
4460 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4461 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4463 return exec_control;
4467 * Adjust a single secondary execution control bit to intercept/allow an
4468 * instruction in the guest. This is usually done based on whether or not a
4469 * feature has been exposed to the guest in order to correctly emulate faults.
4472 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4473 u32 control, bool enabled, bool exiting)
4476 * If the control is for an opt-in feature, clear the control if the
4477 * feature is not exposed to the guest, i.e. not enabled. If the
4478 * control is opt-out, i.e. an exiting control, clear the control if
4479 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4480 * disabled for the associated instruction. Note, the caller is
4481 * responsible presetting exec_control to set all supported bits.
4483 if (enabled == exiting)
4484 *exec_control &= ~control;
4487 * Update the nested MSR settings so that a nested VMM can/can't set
4488 * controls for features that are/aren't exposed to the guest.
4492 vmx->nested.msrs.secondary_ctls_high |= control;
4494 vmx->nested.msrs.secondary_ctls_high &= ~control;
4499 * Wrapper macro for the common case of adjusting a secondary execution control
4500 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4501 * verifies that the control is actually supported by KVM and hardware.
4503 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4507 if (cpu_has_vmx_##name()) { \
4508 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4509 X86_FEATURE_##feat_name); \
4510 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4511 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4515 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4516 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4517 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4519 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4520 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4522 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4524 struct kvm_vcpu *vcpu = &vmx->vcpu;
4526 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4528 if (vmx_pt_mode_is_system())
4529 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4530 if (!cpu_need_virtualize_apic_accesses(vcpu))
4531 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4533 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4535 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4536 enable_unrestricted_guest = 0;
4538 if (!enable_unrestricted_guest)
4539 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4540 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4541 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4542 if (!kvm_vcpu_apicv_active(vcpu))
4543 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4544 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4545 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4547 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4548 * in vmx_set_cr4. */
4549 exec_control &= ~SECONDARY_EXEC_DESC;
4551 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4553 We can NOT enable shadow_vmcs here because we don't have yet
4556 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4559 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4560 * it needs to be set here when dirty logging is already active, e.g.
4561 * if this vCPU was created after dirty logging was enabled.
4563 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4564 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4566 if (cpu_has_vmx_xsaves()) {
4567 /* Exposing XSAVES only when XSAVE is exposed */
4568 bool xsaves_enabled =
4569 boot_cpu_has(X86_FEATURE_XSAVE) &&
4570 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4571 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4573 vcpu->arch.xsaves_enabled = xsaves_enabled;
4575 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4576 SECONDARY_EXEC_XSAVES,
4577 xsaves_enabled, false);
4581 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4582 * feature is exposed to the guest. This creates a virtualization hole
4583 * if both are supported in hardware but only one is exposed to the
4584 * guest, but letting the guest execute RDTSCP or RDPID when either one
4585 * is advertised is preferable to emulating the advertised instruction
4586 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4588 if (cpu_has_vmx_rdtscp()) {
4589 bool rdpid_or_rdtscp_enabled =
4590 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4591 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4593 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4594 SECONDARY_EXEC_ENABLE_RDTSCP,
4595 rdpid_or_rdtscp_enabled, false);
4597 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4599 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4600 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4602 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4603 ENABLE_USR_WAIT_PAUSE, false);
4605 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4606 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4608 if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4609 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4611 return exec_control;
4614 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4616 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4619 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4622 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4624 if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4627 if (kvm_vmx->pid_table)
4630 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, vmx_get_pid_table_order(kvm));
4634 kvm_vmx->pid_table = (void *)page_address(pages);
4638 static int vmx_vcpu_precreate(struct kvm *kvm)
4640 return vmx_alloc_ipiv_pid_table(kvm);
4643 #define VMX_XSS_EXIT_BITMAP 0
4645 static void init_vmcs(struct vcpu_vmx *vmx)
4647 struct kvm *kvm = vmx->vcpu.kvm;
4648 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4651 nested_vmx_set_vmcs_shadowing_bitmap();
4653 if (cpu_has_vmx_msr_bitmap())
4654 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4656 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4659 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4661 exec_controls_set(vmx, vmx_exec_control(vmx));
4663 if (cpu_has_secondary_exec_ctrls())
4664 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4666 if (cpu_has_tertiary_exec_ctrls())
4667 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4669 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4670 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4671 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4672 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4673 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4675 vmcs_write16(GUEST_INTR_STATUS, 0);
4677 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4678 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4681 if (vmx_can_use_ipiv(&vmx->vcpu)) {
4682 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4683 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4686 if (!kvm_pause_in_guest(kvm)) {
4687 vmcs_write32(PLE_GAP, ple_gap);
4688 vmx->ple_window = ple_window;
4689 vmx->ple_window_dirty = true;
4692 if (kvm_notify_vmexit_enabled(kvm))
4693 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4695 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4696 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4697 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4699 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4700 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4701 vmx_set_constant_host_state(vmx);
4702 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4703 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4705 if (cpu_has_vmx_vmfunc())
4706 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4708 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4709 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4710 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4711 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4712 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4714 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4715 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4717 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4719 /* 22.2.1, 20.8.1 */
4720 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4722 vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4723 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4725 set_cr4_guest_host_mask(vmx);
4728 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4730 if (cpu_has_vmx_xsaves())
4731 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4734 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4735 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4738 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4740 if (vmx_pt_mode_is_host_guest()) {
4741 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4742 /* Bit[6~0] are forced to 1, writes are ignored. */
4743 vmx->pt_desc.guest.output_mask = 0x7F;
4744 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4747 vmcs_write32(GUEST_SYSENTER_CS, 0);
4748 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4749 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4750 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4752 if (cpu_has_vmx_tpr_shadow()) {
4753 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4754 if (cpu_need_tpr_shadow(&vmx->vcpu))
4755 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4756 __pa(vmx->vcpu.arch.apic->regs));
4757 vmcs_write32(TPR_THRESHOLD, 0);
4760 vmx_setup_uret_msrs(vmx);
4763 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4765 struct vcpu_vmx *vmx = to_vmx(vcpu);
4770 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4772 vcpu_setup_sgx_lepubkeyhash(vcpu);
4774 vmx->nested.posted_intr_nv = -1;
4775 vmx->nested.vmxon_ptr = INVALID_GPA;
4776 vmx->nested.current_vmptr = INVALID_GPA;
4777 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4779 vcpu->arch.microcode_version = 0x100000000ULL;
4780 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4783 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4784 * or POSTED_INTR_WAKEUP_VECTOR.
4786 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4787 vmx->pi_desc.sn = 1;
4790 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4792 struct vcpu_vmx *vmx = to_vmx(vcpu);
4795 __vmx_vcpu_reset(vcpu);
4797 vmx->rmode.vm86_active = 0;
4800 vmx->msr_ia32_umwait_control = 0;
4802 vmx->hv_deadline_tsc = -1;
4803 kvm_set_cr8(vcpu, 0);
4805 vmx_segment_cache_clear(vmx);
4806 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4808 seg_setup(VCPU_SREG_CS);
4809 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4810 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4812 seg_setup(VCPU_SREG_DS);
4813 seg_setup(VCPU_SREG_ES);
4814 seg_setup(VCPU_SREG_FS);
4815 seg_setup(VCPU_SREG_GS);
4816 seg_setup(VCPU_SREG_SS);
4818 vmcs_write16(GUEST_TR_SELECTOR, 0);
4819 vmcs_writel(GUEST_TR_BASE, 0);
4820 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4821 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4823 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4824 vmcs_writel(GUEST_LDTR_BASE, 0);
4825 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4826 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4828 vmcs_writel(GUEST_GDTR_BASE, 0);
4829 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4831 vmcs_writel(GUEST_IDTR_BASE, 0);
4832 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4834 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4835 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4836 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4837 if (kvm_mpx_supported())
4838 vmcs_write64(GUEST_BNDCFGS, 0);
4840 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4842 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4844 vpid_sync_context(vmx->vpid);
4846 vmx_update_fb_clear_dis(vcpu, vmx);
4849 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4851 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4854 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4857 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4858 vmx_enable_irq_window(vcpu);
4862 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4865 static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4867 struct vcpu_vmx *vmx = to_vmx(vcpu);
4869 int irq = vcpu->arch.interrupt.nr;
4871 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4873 ++vcpu->stat.irq_injections;
4874 if (vmx->rmode.vm86_active) {
4876 if (vcpu->arch.interrupt.soft)
4877 inc_eip = vcpu->arch.event_exit_inst_len;
4878 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4881 intr = irq | INTR_INFO_VALID_MASK;
4882 if (vcpu->arch.interrupt.soft) {
4883 intr |= INTR_TYPE_SOFT_INTR;
4884 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4885 vmx->vcpu.arch.event_exit_inst_len);
4887 intr |= INTR_TYPE_EXT_INTR;
4888 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4890 vmx_clear_hlt(vcpu);
4893 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4895 struct vcpu_vmx *vmx = to_vmx(vcpu);
4899 * Tracking the NMI-blocked state in software is built upon
4900 * finding the next open IRQ window. This, in turn, depends on
4901 * well-behaving guests: They have to keep IRQs disabled at
4902 * least as long as the NMI handler runs. Otherwise we may
4903 * cause NMI nesting, maybe breaking the guest. But as this is
4904 * highly unlikely, we can live with the residual risk.
4906 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4907 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4910 ++vcpu->stat.nmi_injections;
4911 vmx->loaded_vmcs->nmi_known_unmasked = false;
4913 if (vmx->rmode.vm86_active) {
4914 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4918 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4919 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4921 vmx_clear_hlt(vcpu);
4924 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4926 struct vcpu_vmx *vmx = to_vmx(vcpu);
4930 return vmx->loaded_vmcs->soft_vnmi_blocked;
4931 if (vmx->loaded_vmcs->nmi_known_unmasked)
4933 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4934 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4938 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4940 struct vcpu_vmx *vmx = to_vmx(vcpu);
4943 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4944 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4945 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4948 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4950 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4951 GUEST_INTR_STATE_NMI);
4953 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4954 GUEST_INTR_STATE_NMI);
4958 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4960 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4963 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4966 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4967 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4968 GUEST_INTR_STATE_NMI));
4971 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4973 if (to_vmx(vcpu)->nested.nested_run_pending)
4976 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4977 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4980 return !vmx_nmi_blocked(vcpu);
4983 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4985 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4988 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4989 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4990 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4993 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4995 if (to_vmx(vcpu)->nested.nested_run_pending)
4999 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
5000 * e.g. if the IRQ arrived asynchronously after checking nested events.
5002 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5005 return !vmx_interrupt_blocked(vcpu);
5008 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5012 if (enable_unrestricted_guest)
5015 mutex_lock(&kvm->slots_lock);
5016 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5018 mutex_unlock(&kvm->slots_lock);
5021 return PTR_ERR(ret);
5023 to_kvm_vmx(kvm)->tss_addr = addr;
5025 return init_rmode_tss(kvm, ret);
5028 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5030 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
5034 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5039 * Update instruction length as we may reinject the exception
5040 * from user space while in guest debugging mode.
5042 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5043 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5044 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5048 return !(vcpu->guest_debug &
5049 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
5063 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5064 int vec, u32 err_code)
5067 * Instruction with address size override prefix opcode 0x67
5068 * Cause the #SS fault with 0 error code in VM86 mode.
5070 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5071 if (kvm_emulate_instruction(vcpu, 0)) {
5072 if (vcpu->arch.halt_request) {
5073 vcpu->arch.halt_request = 0;
5074 return kvm_emulate_halt_noskip(vcpu);
5082 * Forward all other exceptions that are valid in real mode.
5083 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5084 * the required debugging infrastructure rework.
5086 kvm_queue_exception(vcpu, vec);
5090 static int handle_machine_check(struct kvm_vcpu *vcpu)
5092 /* handled by vmx_vcpu_run() */
5097 * If the host has split lock detection disabled, then #AC is
5098 * unconditionally injected into the guest, which is the pre split lock
5099 * detection behaviour.
5101 * If the host has split lock detection enabled then #AC is
5102 * only injected into the guest when:
5103 * - Guest CPL == 3 (user mode)
5104 * - Guest has #AC detection enabled in CR0
5105 * - Guest EFLAGS has AC bit set
5107 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5109 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5112 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
5113 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5116 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5118 struct vcpu_vmx *vmx = to_vmx(vcpu);
5119 struct kvm_run *kvm_run = vcpu->run;
5120 u32 intr_info, ex_no, error_code;
5121 unsigned long cr2, dr6;
5124 vect_info = vmx->idt_vectoring_info;
5125 intr_info = vmx_get_intr_info(vcpu);
5127 if (is_machine_check(intr_info) || is_nmi(intr_info))
5128 return 1; /* handled by handle_exception_nmi_irqoff() */
5131 * Queue the exception here instead of in handle_nm_fault_irqoff().
5132 * This ensures the nested_vmx check is not skipped so vmexit can
5133 * be reflected to L1 (when it intercepts #NM) before reaching this
5136 if (is_nm_fault(intr_info)) {
5137 kvm_queue_exception(vcpu, NM_VECTOR);
5141 if (is_invalid_opcode(intr_info))
5142 return handle_ud(vcpu);
5145 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5146 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5148 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5149 WARN_ON_ONCE(!enable_vmware_backdoor);
5152 * VMware backdoor emulation on #GP interception only handles
5153 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5154 * error code on #GP.
5157 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5160 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5164 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5165 * MMIO, it is better to report an internal error.
5166 * See the comments in vmx_handle_exit.
5168 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5169 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5170 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5171 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5172 vcpu->run->internal.ndata = 4;
5173 vcpu->run->internal.data[0] = vect_info;
5174 vcpu->run->internal.data[1] = intr_info;
5175 vcpu->run->internal.data[2] = error_code;
5176 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5180 if (is_page_fault(intr_info)) {
5181 cr2 = vmx_get_exit_qual(vcpu);
5182 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5184 * EPT will cause page fault only if we need to
5185 * detect illegal GPAs.
5187 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5188 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5191 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5194 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5196 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5197 return handle_rmode_exception(vcpu, ex_no, error_code);
5201 dr6 = vmx_get_exit_qual(vcpu);
5202 if (!(vcpu->guest_debug &
5203 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5205 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5206 * instruction. ICEBP generates a trap-like #DB, but
5207 * despite its interception control being tied to #DB,
5208 * is an instruction intercept, i.e. the VM-Exit occurs
5209 * on the ICEBP itself. Use the inner "skip" helper to
5210 * avoid single-step #DB and MTF updates, as ICEBP is
5211 * higher priority. Note, skipping ICEBP still clears
5212 * STI and MOVSS blocking.
5214 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5215 * if single-step is enabled in RFLAGS and STI or MOVSS
5216 * blocking is active, as the CPU doesn't set the bit
5217 * on VM-Exit due to #DB interception. VM-Entry has a
5218 * consistency check that a single-step #DB is pending
5219 * in this scenario as the previous instruction cannot
5220 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5221 * don't modify RFLAGS), therefore the one instruction
5222 * delay when activating single-step breakpoints must
5223 * have already expired. Note, the CPU sets/clears BS
5224 * as appropriate for all other VM-Exits types.
5226 if (is_icebp(intr_info))
5227 WARN_ON(!skip_emulated_instruction(vcpu));
5228 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5229 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5230 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5231 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5232 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5234 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5237 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5238 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5242 * Update instruction length as we may reinject #BP from
5243 * user space while in guest debugging mode. Reading it for
5244 * #DB as well causes no harm, it is not used in that case.
5246 vmx->vcpu.arch.event_exit_inst_len =
5247 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5248 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5249 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5250 kvm_run->debug.arch.exception = ex_no;
5253 if (vmx_guest_inject_ac(vcpu)) {
5254 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5259 * Handle split lock. Depending on detection mode this will
5260 * either warn and disable split lock detection for this
5261 * task or force SIGBUS on it.
5263 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5267 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5268 kvm_run->ex.exception = ex_no;
5269 kvm_run->ex.error_code = error_code;
5275 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5277 ++vcpu->stat.irq_exits;
5281 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5283 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5284 vcpu->mmio_needed = 0;
5288 static int handle_io(struct kvm_vcpu *vcpu)
5290 unsigned long exit_qualification;
5291 int size, in, string;
5294 exit_qualification = vmx_get_exit_qual(vcpu);
5295 string = (exit_qualification & 16) != 0;
5297 ++vcpu->stat.io_exits;
5300 return kvm_emulate_instruction(vcpu, 0);
5302 port = exit_qualification >> 16;
5303 size = (exit_qualification & 7) + 1;
5304 in = (exit_qualification & 8) != 0;
5306 return kvm_fast_pio(vcpu, size, port, in);
5310 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5313 * Patch in the VMCALL instruction:
5315 hypercall[0] = 0x0f;
5316 hypercall[1] = 0x01;
5317 hypercall[2] = 0xc1;
5320 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5321 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5323 if (is_guest_mode(vcpu)) {
5324 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5325 unsigned long orig_val = val;
5328 * We get here when L2 changed cr0 in a way that did not change
5329 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5330 * but did change L0 shadowed bits. So we first calculate the
5331 * effective cr0 value that L1 would like to write into the
5332 * hardware. It consists of the L2-owned bits from the new
5333 * value combined with the L1-owned bits from L1's guest_cr0.
5335 val = (val & ~vmcs12->cr0_guest_host_mask) |
5336 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5338 if (kvm_set_cr0(vcpu, val))
5340 vmcs_writel(CR0_READ_SHADOW, orig_val);
5343 return kvm_set_cr0(vcpu, val);
5347 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5349 if (is_guest_mode(vcpu)) {
5350 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5351 unsigned long orig_val = val;
5353 /* analogously to handle_set_cr0 */
5354 val = (val & ~vmcs12->cr4_guest_host_mask) |
5355 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5356 if (kvm_set_cr4(vcpu, val))
5358 vmcs_writel(CR4_READ_SHADOW, orig_val);
5361 return kvm_set_cr4(vcpu, val);
5364 static int handle_desc(struct kvm_vcpu *vcpu)
5366 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5367 return kvm_emulate_instruction(vcpu, 0);
5370 static int handle_cr(struct kvm_vcpu *vcpu)
5372 unsigned long exit_qualification, val;
5378 exit_qualification = vmx_get_exit_qual(vcpu);
5379 cr = exit_qualification & 15;
5380 reg = (exit_qualification >> 8) & 15;
5381 switch ((exit_qualification >> 4) & 3) {
5382 case 0: /* mov to cr */
5383 val = kvm_register_read(vcpu, reg);
5384 trace_kvm_cr_write(cr, val);
5387 err = handle_set_cr0(vcpu, val);
5388 return kvm_complete_insn_gp(vcpu, err);
5390 WARN_ON_ONCE(enable_unrestricted_guest);
5392 err = kvm_set_cr3(vcpu, val);
5393 return kvm_complete_insn_gp(vcpu, err);
5395 err = handle_set_cr4(vcpu, val);
5396 return kvm_complete_insn_gp(vcpu, err);
5398 u8 cr8_prev = kvm_get_cr8(vcpu);
5400 err = kvm_set_cr8(vcpu, cr8);
5401 ret = kvm_complete_insn_gp(vcpu, err);
5402 if (lapic_in_kernel(vcpu))
5404 if (cr8_prev <= cr8)
5407 * TODO: we might be squashing a
5408 * KVM_GUESTDBG_SINGLESTEP-triggered
5409 * KVM_EXIT_DEBUG here.
5411 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5417 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5419 case 1: /*mov from cr*/
5422 WARN_ON_ONCE(enable_unrestricted_guest);
5424 val = kvm_read_cr3(vcpu);
5425 kvm_register_write(vcpu, reg, val);
5426 trace_kvm_cr_read(cr, val);
5427 return kvm_skip_emulated_instruction(vcpu);
5429 val = kvm_get_cr8(vcpu);
5430 kvm_register_write(vcpu, reg, val);
5431 trace_kvm_cr_read(cr, val);
5432 return kvm_skip_emulated_instruction(vcpu);
5436 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5437 trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
5438 kvm_lmsw(vcpu, val);
5440 return kvm_skip_emulated_instruction(vcpu);
5444 vcpu->run->exit_reason = 0;
5445 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5446 (int)(exit_qualification >> 4) & 3, cr);
5450 static int handle_dr(struct kvm_vcpu *vcpu)
5452 unsigned long exit_qualification;
5456 exit_qualification = vmx_get_exit_qual(vcpu);
5457 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5459 /* First, if DR does not exist, trigger UD */
5460 if (!kvm_require_dr(vcpu, dr))
5463 if (vmx_get_cpl(vcpu) > 0)
5466 dr7 = vmcs_readl(GUEST_DR7);
5469 * As the vm-exit takes precedence over the debug trap, we
5470 * need to emulate the latter, either for the host or the
5471 * guest debugging itself.
5473 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5474 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5475 vcpu->run->debug.arch.dr7 = dr7;
5476 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5477 vcpu->run->debug.arch.exception = DB_VECTOR;
5478 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5481 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5486 if (vcpu->guest_debug == 0) {
5487 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5490 * No more DR vmexits; force a reload of the debug registers
5491 * and reenter on this instruction. The next vmexit will
5492 * retrieve the full state of the debug registers.
5494 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5498 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5499 if (exit_qualification & TYPE_MOV_FROM_DR) {
5502 kvm_get_dr(vcpu, dr, &val);
5503 kvm_register_write(vcpu, reg, val);
5506 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5510 return kvm_complete_insn_gp(vcpu, err);
5513 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5515 get_debugreg(vcpu->arch.db[0], 0);
5516 get_debugreg(vcpu->arch.db[1], 1);
5517 get_debugreg(vcpu->arch.db[2], 2);
5518 get_debugreg(vcpu->arch.db[3], 3);
5519 get_debugreg(vcpu->arch.dr6, 6);
5520 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5522 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5523 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5526 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5527 * a stale dr6 from the guest.
5529 set_debugreg(DR6_RESERVED, 6);
5532 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5534 vmcs_writel(GUEST_DR7, val);
5537 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5539 kvm_apic_update_ppr(vcpu);
5543 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5545 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5547 kvm_make_request(KVM_REQ_EVENT, vcpu);
5549 ++vcpu->stat.irq_window_exits;
5553 static int handle_invlpg(struct kvm_vcpu *vcpu)
5555 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5557 kvm_mmu_invlpg(vcpu, exit_qualification);
5558 return kvm_skip_emulated_instruction(vcpu);
5561 static int handle_apic_access(struct kvm_vcpu *vcpu)
5563 if (likely(fasteoi)) {
5564 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5565 int access_type, offset;
5567 access_type = exit_qualification & APIC_ACCESS_TYPE;
5568 offset = exit_qualification & APIC_ACCESS_OFFSET;
5570 * Sane guest uses MOV to write EOI, with written value
5571 * not cared. So make a short-circuit here by avoiding
5572 * heavy instruction emulation.
5574 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5575 (offset == APIC_EOI)) {
5576 kvm_lapic_set_eoi(vcpu);
5577 return kvm_skip_emulated_instruction(vcpu);
5580 return kvm_emulate_instruction(vcpu, 0);
5583 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5585 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5586 int vector = exit_qualification & 0xff;
5588 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5589 kvm_apic_set_eoi_accelerated(vcpu, vector);
5593 static int handle_apic_write(struct kvm_vcpu *vcpu)
5595 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5598 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5599 * hardware has done any necessary aliasing, offset adjustments, etc...
5600 * for the access. I.e. the correct value has already been written to
5601 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5602 * retrieve the register value and emulate the access.
5604 u32 offset = exit_qualification & 0xff0;
5606 kvm_apic_write_nodecode(vcpu, offset);
5610 static int handle_task_switch(struct kvm_vcpu *vcpu)
5612 struct vcpu_vmx *vmx = to_vmx(vcpu);
5613 unsigned long exit_qualification;
5614 bool has_error_code = false;
5617 int reason, type, idt_v, idt_index;
5619 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5620 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5621 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5623 exit_qualification = vmx_get_exit_qual(vcpu);
5625 reason = (u32)exit_qualification >> 30;
5626 if (reason == TASK_SWITCH_GATE && idt_v) {
5628 case INTR_TYPE_NMI_INTR:
5629 vcpu->arch.nmi_injected = false;
5630 vmx_set_nmi_mask(vcpu, true);
5632 case INTR_TYPE_EXT_INTR:
5633 case INTR_TYPE_SOFT_INTR:
5634 kvm_clear_interrupt_queue(vcpu);
5636 case INTR_TYPE_HARD_EXCEPTION:
5637 if (vmx->idt_vectoring_info &
5638 VECTORING_INFO_DELIVER_CODE_MASK) {
5639 has_error_code = true;
5641 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5644 case INTR_TYPE_SOFT_EXCEPTION:
5645 kvm_clear_exception_queue(vcpu);
5651 tss_selector = exit_qualification;
5653 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5654 type != INTR_TYPE_EXT_INTR &&
5655 type != INTR_TYPE_NMI_INTR))
5656 WARN_ON(!skip_emulated_instruction(vcpu));
5659 * TODO: What about debug traps on tss switch?
5660 * Are we supposed to inject them and update dr6?
5662 return kvm_task_switch(vcpu, tss_selector,
5663 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5664 reason, has_error_code, error_code);
5667 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5669 unsigned long exit_qualification;
5673 exit_qualification = vmx_get_exit_qual(vcpu);
5676 * EPT violation happened while executing iret from NMI,
5677 * "blocked by NMI" bit has to be set before next VM entry.
5678 * There are errata that may cause this bit to not be set:
5681 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5683 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5684 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5686 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5687 trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5689 /* Is it a read fault? */
5690 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5691 ? PFERR_USER_MASK : 0;
5692 /* Is it a write fault? */
5693 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5694 ? PFERR_WRITE_MASK : 0;
5695 /* Is it a fetch fault? */
5696 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5697 ? PFERR_FETCH_MASK : 0;
5698 /* ept page table entry is present? */
5699 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5700 ? PFERR_PRESENT_MASK : 0;
5702 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5703 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5705 vcpu->arch.exit_qualification = exit_qualification;
5708 * Check that the GPA doesn't exceed physical memory limits, as that is
5709 * a guest page fault. We have to emulate the instruction here, because
5710 * if the illegal address is that of a paging structure, then
5711 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5712 * would also use advanced VM-exit information for EPT violations to
5713 * reconstruct the page fault error code.
5715 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5716 return kvm_emulate_instruction(vcpu, 0);
5718 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5721 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5725 if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5729 * A nested guest cannot optimize MMIO vmexits, because we have an
5730 * nGPA here instead of the required GPA.
5732 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5733 if (!is_guest_mode(vcpu) &&
5734 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5735 trace_kvm_fast_mmio(gpa);
5736 return kvm_skip_emulated_instruction(vcpu);
5739 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5742 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5744 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5747 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5748 ++vcpu->stat.nmi_window_exits;
5749 kvm_make_request(KVM_REQ_EVENT, vcpu);
5754 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5756 struct vcpu_vmx *vmx = to_vmx(vcpu);
5758 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5759 (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
5762 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5764 struct vcpu_vmx *vmx = to_vmx(vcpu);
5765 bool intr_window_requested;
5766 unsigned count = 130;
5768 intr_window_requested = exec_controls_get(vmx) &
5769 CPU_BASED_INTR_WINDOW_EXITING;
5771 while (vmx->emulation_required && count-- != 0) {
5772 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5773 return handle_interrupt_window(&vmx->vcpu);
5775 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5778 if (!kvm_emulate_instruction(vcpu, 0))
5781 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5782 kvm_prepare_emulation_failure_exit(vcpu);
5786 if (vcpu->arch.halt_request) {
5787 vcpu->arch.halt_request = 0;
5788 return kvm_emulate_halt_noskip(vcpu);
5792 * Note, return 1 and not 0, vcpu_run() will invoke
5793 * xfer_to_guest_mode() which will create a proper return
5796 if (__xfer_to_guest_mode_work_pending())
5803 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5805 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5806 kvm_prepare_emulation_failure_exit(vcpu);
5813 static void grow_ple_window(struct kvm_vcpu *vcpu)
5815 struct vcpu_vmx *vmx = to_vmx(vcpu);
5816 unsigned int old = vmx->ple_window;
5818 vmx->ple_window = __grow_ple_window(old, ple_window,
5822 if (vmx->ple_window != old) {
5823 vmx->ple_window_dirty = true;
5824 trace_kvm_ple_window_update(vcpu->vcpu_id,
5825 vmx->ple_window, old);
5829 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5831 struct vcpu_vmx *vmx = to_vmx(vcpu);
5832 unsigned int old = vmx->ple_window;
5834 vmx->ple_window = __shrink_ple_window(old, ple_window,
5838 if (vmx->ple_window != old) {
5839 vmx->ple_window_dirty = true;
5840 trace_kvm_ple_window_update(vcpu->vcpu_id,
5841 vmx->ple_window, old);
5846 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5847 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5849 static int handle_pause(struct kvm_vcpu *vcpu)
5851 if (!kvm_pause_in_guest(vcpu->kvm))
5852 grow_ple_window(vcpu);
5855 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5856 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5857 * never set PAUSE_EXITING and just set PLE if supported,
5858 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5860 kvm_vcpu_on_spin(vcpu, true);
5861 return kvm_skip_emulated_instruction(vcpu);
5864 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5869 static int handle_invpcid(struct kvm_vcpu *vcpu)
5871 u32 vmx_instruction_info;
5880 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5881 kvm_queue_exception(vcpu, UD_VECTOR);
5885 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5886 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5887 type = kvm_register_read(vcpu, gpr_index);
5889 /* According to the Intel instruction reference, the memory operand
5890 * is read even if it isn't needed (e.g., for type==all)
5892 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5893 vmx_instruction_info, false,
5894 sizeof(operand), &gva))
5897 return kvm_handle_invpcid(vcpu, type, gva);
5900 static int handle_pml_full(struct kvm_vcpu *vcpu)
5902 unsigned long exit_qualification;
5904 trace_kvm_pml_full(vcpu->vcpu_id);
5906 exit_qualification = vmx_get_exit_qual(vcpu);
5909 * PML buffer FULL happened while executing iret from NMI,
5910 * "blocked by NMI" bit has to be set before next VM entry.
5912 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5914 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5915 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5916 GUEST_INTR_STATE_NMI);
5919 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5920 * here.., and there's no userspace involvement needed for PML.
5925 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5927 struct vcpu_vmx *vmx = to_vmx(vcpu);
5929 if (!vmx->req_immediate_exit &&
5930 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5931 kvm_lapic_expired_hv_timer(vcpu);
5932 return EXIT_FASTPATH_REENTER_GUEST;
5935 return EXIT_FASTPATH_NONE;
5938 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5940 handle_fastpath_preemption_timer(vcpu);
5945 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5946 * are overwritten by nested_vmx_setup() when nested=1.
5948 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5950 kvm_queue_exception(vcpu, UD_VECTOR);
5954 #ifndef CONFIG_X86_SGX_KVM
5955 static int handle_encls(struct kvm_vcpu *vcpu)
5958 * SGX virtualization is disabled. There is no software enable bit for
5959 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5960 * the guest from executing ENCLS (when SGX is supported by hardware).
5962 kvm_queue_exception(vcpu, UD_VECTOR);
5965 #endif /* CONFIG_X86_SGX_KVM */
5967 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5970 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
5971 * VM-Exits. Unconditionally set the flag here and leave the handling to
5972 * vmx_handle_exit().
5974 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
5978 static int handle_notify(struct kvm_vcpu *vcpu)
5980 unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5981 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
5983 ++vcpu->stat.notify_window_exits;
5986 * Notify VM exit happened while executing iret from NMI,
5987 * "blocked by NMI" bit has to be set before next VM entry.
5989 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
5990 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5991 GUEST_INTR_STATE_NMI);
5993 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
5995 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
5996 vcpu->run->notify.flags = context_invalid ?
5997 KVM_NOTIFY_CONTEXT_INVALID : 0;
6005 * The exit handlers return 1 if the exit was handled fully and guest execution
6006 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
6007 * to be done to userspace and return 0.
6009 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6010 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
6011 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
6012 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
6013 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
6014 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
6015 [EXIT_REASON_CR_ACCESS] = handle_cr,
6016 [EXIT_REASON_DR_ACCESS] = handle_dr,
6017 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
6018 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
6019 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
6020 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
6021 [EXIT_REASON_HLT] = kvm_emulate_halt,
6022 [EXIT_REASON_INVD] = kvm_emulate_invd,
6023 [EXIT_REASON_INVLPG] = handle_invlpg,
6024 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
6025 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
6026 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
6027 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
6028 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
6029 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
6030 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
6031 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
6032 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
6033 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
6034 [EXIT_REASON_VMON] = handle_vmx_instruction,
6035 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
6036 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
6037 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
6038 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
6039 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
6040 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
6041 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
6042 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
6043 [EXIT_REASON_GDTR_IDTR] = handle_desc,
6044 [EXIT_REASON_LDTR_TR] = handle_desc,
6045 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
6046 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
6047 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
6048 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
6049 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
6050 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
6051 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
6052 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
6053 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
6054 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
6055 [EXIT_REASON_PML_FULL] = handle_pml_full,
6056 [EXIT_REASON_INVPCID] = handle_invpcid,
6057 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
6058 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
6059 [EXIT_REASON_ENCLS] = handle_encls,
6060 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
6061 [EXIT_REASON_NOTIFY] = handle_notify,
6064 static const int kvm_vmx_max_exit_handlers =
6065 ARRAY_SIZE(kvm_vmx_exit_handlers);
6067 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6068 u64 *info1, u64 *info2,
6069 u32 *intr_info, u32 *error_code)
6071 struct vcpu_vmx *vmx = to_vmx(vcpu);
6073 *reason = vmx->exit_reason.full;
6074 *info1 = vmx_get_exit_qual(vcpu);
6075 if (!(vmx->exit_reason.failed_vmentry)) {
6076 *info2 = vmx->idt_vectoring_info;
6077 *intr_info = vmx_get_intr_info(vcpu);
6078 if (is_exception_with_error_code(*intr_info))
6079 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6089 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6092 __free_page(vmx->pml_pg);
6097 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6099 struct vcpu_vmx *vmx = to_vmx(vcpu);
6103 pml_idx = vmcs_read16(GUEST_PML_INDEX);
6105 /* Do nothing if PML buffer is empty */
6106 if (pml_idx == (PML_ENTITY_NUM - 1))
6109 /* PML index always points to next available PML buffer entity */
6110 if (pml_idx >= PML_ENTITY_NUM)
6115 pml_buf = page_address(vmx->pml_pg);
6116 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6119 gpa = pml_buf[pml_idx];
6120 WARN_ON(gpa & (PAGE_SIZE - 1));
6121 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6124 /* reset PML index */
6125 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6128 static void vmx_dump_sel(char *name, uint32_t sel)
6130 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6131 name, vmcs_read16(sel),
6132 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6133 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6134 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6137 static void vmx_dump_dtsel(char *name, uint32_t limit)
6139 pr_err("%s limit=0x%08x, base=0x%016lx\n",
6140 name, vmcs_read32(limit),
6141 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6144 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6147 struct vmx_msr_entry *e;
6149 pr_err("MSR %s:\n", name);
6150 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6151 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6154 void dump_vmcs(struct kvm_vcpu *vcpu)
6156 struct vcpu_vmx *vmx = to_vmx(vcpu);
6157 u32 vmentry_ctl, vmexit_ctl;
6158 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6159 u64 tertiary_exec_control;
6163 if (!dump_invalid_vmcs) {
6164 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6168 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6169 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6170 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6171 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6172 cr4 = vmcs_readl(GUEST_CR4);
6174 if (cpu_has_secondary_exec_ctrls())
6175 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6177 secondary_exec_control = 0;
6179 if (cpu_has_tertiary_exec_ctrls())
6180 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6182 tertiary_exec_control = 0;
6184 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6185 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6186 pr_err("*** Guest State ***\n");
6187 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6188 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6189 vmcs_readl(CR0_GUEST_HOST_MASK));
6190 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6191 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6192 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6193 if (cpu_has_vmx_ept()) {
6194 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
6195 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6196 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
6197 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6199 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
6200 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6201 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
6202 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6203 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6204 vmcs_readl(GUEST_SYSENTER_ESP),
6205 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6206 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
6207 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
6208 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
6209 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
6210 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
6211 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
6212 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6213 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6214 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6215 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
6216 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6217 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6218 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6219 else if (efer_slot >= 0)
6220 pr_err("EFER= 0x%016llx (autoload)\n",
6221 vmx->msr_autoload.guest.val[efer_slot].value);
6222 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6223 pr_err("EFER= 0x%016llx (effective)\n",
6224 vcpu->arch.efer | (EFER_LMA | EFER_LME));
6226 pr_err("EFER= 0x%016llx (effective)\n",
6227 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6228 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6229 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6230 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
6231 vmcs_read64(GUEST_IA32_DEBUGCTL),
6232 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6233 if (cpu_has_load_perf_global_ctrl() &&
6234 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6235 pr_err("PerfGlobCtl = 0x%016llx\n",
6236 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6237 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6238 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6239 pr_err("Interruptibility = %08x ActivityState = %08x\n",
6240 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6241 vmcs_read32(GUEST_ACTIVITY_STATE));
6242 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6243 pr_err("InterruptStatus = %04x\n",
6244 vmcs_read16(GUEST_INTR_STATUS));
6245 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6246 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6247 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6248 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6250 pr_err("*** Host State ***\n");
6251 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6252 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6253 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6254 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6255 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6256 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6257 vmcs_read16(HOST_TR_SELECTOR));
6258 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6259 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6260 vmcs_readl(HOST_TR_BASE));
6261 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6262 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6263 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6264 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6265 vmcs_readl(HOST_CR4));
6266 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6267 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6268 vmcs_read32(HOST_IA32_SYSENTER_CS),
6269 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6270 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6271 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6272 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6273 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6274 if (cpu_has_load_perf_global_ctrl() &&
6275 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6276 pr_err("PerfGlobCtl = 0x%016llx\n",
6277 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6278 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6279 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6281 pr_err("*** Control State ***\n");
6282 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6283 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6284 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6285 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6286 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6287 vmcs_read32(EXCEPTION_BITMAP),
6288 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6289 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6290 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6291 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6292 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6293 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6294 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6295 vmcs_read32(VM_EXIT_INTR_INFO),
6296 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6297 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6298 pr_err(" reason=%08x qualification=%016lx\n",
6299 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6300 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6301 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6302 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6303 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6304 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6305 pr_err("TSC Multiplier = 0x%016llx\n",
6306 vmcs_read64(TSC_MULTIPLIER));
6307 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6308 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6309 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6310 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6312 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6313 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6314 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6315 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6317 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6318 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6319 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6320 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6321 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6322 pr_err("PLE Gap=%08x Window=%08x\n",
6323 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6324 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6325 pr_err("Virtual processor ID = 0x%04x\n",
6326 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6330 * The guest has exited. See if we can fix it or if we need userspace
6333 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6335 struct vcpu_vmx *vmx = to_vmx(vcpu);
6336 union vmx_exit_reason exit_reason = vmx->exit_reason;
6337 u32 vectoring_info = vmx->idt_vectoring_info;
6338 u16 exit_handler_index;
6341 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6342 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6343 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6344 * mode as if vcpus is in root mode, the PML buffer must has been
6345 * flushed already. Note, PML is never enabled in hardware while
6348 if (enable_pml && !is_guest_mode(vcpu))
6349 vmx_flush_pml_buffer(vcpu);
6352 * KVM should never reach this point with a pending nested VM-Enter.
6353 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6354 * invalid guest state should never happen as that means KVM knowingly
6355 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6357 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6360 if (is_guest_mode(vcpu)) {
6362 * PML is never enabled when running L2, bail immediately if a
6363 * PML full exit occurs as something is horribly wrong.
6365 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6366 goto unexpected_vmexit;
6369 * The host physical addresses of some pages of guest memory
6370 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6371 * Page). The CPU may write to these pages via their host
6372 * physical address while L2 is running, bypassing any
6373 * address-translation-based dirty tracking (e.g. EPT write
6376 * Mark them dirty on every exit from L2 to prevent them from
6377 * getting out of sync with dirty tracking.
6379 nested_mark_vmcs12_pages_dirty(vcpu);
6382 * Synthesize a triple fault if L2 state is invalid. In normal
6383 * operation, nested VM-Enter rejects any attempt to enter L2
6384 * with invalid state. However, those checks are skipped if
6385 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6386 * L2 state is invalid, it means either L1 modified SMRAM state
6387 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6388 * doing so is architecturally allowed in the RSM case, and is
6389 * the least awful solution for the userspace case without
6390 * risking false positives.
6392 if (vmx->emulation_required) {
6393 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6397 if (nested_vmx_reflect_vmexit(vcpu))
6401 /* If guest state is invalid, start emulating. L2 is handled above. */
6402 if (vmx->emulation_required)
6403 return handle_invalid_guest_state(vcpu);
6405 if (exit_reason.failed_vmentry) {
6407 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6408 vcpu->run->fail_entry.hardware_entry_failure_reason
6410 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6414 if (unlikely(vmx->fail)) {
6416 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6417 vcpu->run->fail_entry.hardware_entry_failure_reason
6418 = vmcs_read32(VM_INSTRUCTION_ERROR);
6419 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6425 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6426 * delivery event since it indicates guest is accessing MMIO.
6427 * The vm-exit can be triggered again after return to guest that
6428 * will cause infinite loop.
6430 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6431 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6432 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6433 exit_reason.basic != EXIT_REASON_PML_FULL &&
6434 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6435 exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6436 exit_reason.basic != EXIT_REASON_NOTIFY)) {
6439 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6440 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6441 vcpu->run->internal.data[0] = vectoring_info;
6442 vcpu->run->internal.data[1] = exit_reason.full;
6443 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6444 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6445 vcpu->run->internal.data[ndata++] =
6446 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6448 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6449 vcpu->run->internal.ndata = ndata;
6453 if (unlikely(!enable_vnmi &&
6454 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6455 if (!vmx_interrupt_blocked(vcpu)) {
6456 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6457 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6458 vcpu->arch.nmi_pending) {
6460 * This CPU don't support us in finding the end of an
6461 * NMI-blocked window if the guest runs with IRQs
6462 * disabled. So we pull the trigger after 1 s of
6463 * futile waiting, but inform the user about this.
6465 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6466 "state on VCPU %d after 1 s timeout\n",
6467 __func__, vcpu->vcpu_id);
6468 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6472 if (exit_fastpath != EXIT_FASTPATH_NONE)
6475 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6476 goto unexpected_vmexit;
6477 #ifdef CONFIG_RETPOLINE
6478 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6479 return kvm_emulate_wrmsr(vcpu);
6480 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6481 return handle_preemption_timer(vcpu);
6482 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6483 return handle_interrupt_window(vcpu);
6484 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6485 return handle_external_interrupt(vcpu);
6486 else if (exit_reason.basic == EXIT_REASON_HLT)
6487 return kvm_emulate_halt(vcpu);
6488 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6489 return handle_ept_misconfig(vcpu);
6492 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6493 kvm_vmx_max_exit_handlers);
6494 if (!kvm_vmx_exit_handlers[exit_handler_index])
6495 goto unexpected_vmexit;
6497 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6500 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6503 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6504 vcpu->run->internal.suberror =
6505 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6506 vcpu->run->internal.ndata = 2;
6507 vcpu->run->internal.data[0] = exit_reason.full;
6508 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6512 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6514 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6517 * Exit to user space when bus lock detected to inform that there is
6518 * a bus lock in guest.
6520 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6522 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6524 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6531 * Software based L1D cache flush which is used when microcode providing
6532 * the cache control MSR is not loaded.
6534 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6535 * flush it is required to read in 64 KiB because the replacement algorithm
6536 * is not exactly LRU. This could be sized at runtime via topology
6537 * information but as all relevant affected CPUs have 32KiB L1D cache size
6538 * there is no point in doing so.
6540 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6542 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6545 * This code is only executed when the flush mode is 'cond' or
6548 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6552 * Clear the per-vcpu flush bit, it gets set again
6553 * either from vcpu_run() or from one of the unsafe
6556 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6557 vcpu->arch.l1tf_flush_l1d = false;
6560 * Clear the per-cpu flush bit, it gets set again from
6561 * the interrupt handlers.
6563 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6564 kvm_clear_cpu_l1tf_flush_l1d();
6570 vcpu->stat.l1d_flush++;
6572 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6573 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6578 /* First ensure the pages are in the TLB */
6579 "xorl %%eax, %%eax\n"
6580 ".Lpopulate_tlb:\n\t"
6581 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6582 "addl $4096, %%eax\n\t"
6583 "cmpl %%eax, %[size]\n\t"
6584 "jne .Lpopulate_tlb\n\t"
6585 "xorl %%eax, %%eax\n\t"
6587 /* Now fill the cache */
6588 "xorl %%eax, %%eax\n"
6590 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6591 "addl $64, %%eax\n\t"
6592 "cmpl %%eax, %[size]\n\t"
6593 "jne .Lfill_cache\n\t"
6595 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6597 : "eax", "ebx", "ecx", "edx");
6600 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6602 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6605 if (is_guest_mode(vcpu) &&
6606 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6609 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6610 if (is_guest_mode(vcpu))
6611 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6613 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6616 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6618 struct vcpu_vmx *vmx = to_vmx(vcpu);
6619 u32 sec_exec_control;
6621 if (!lapic_in_kernel(vcpu))
6624 if (!flexpriority_enabled &&
6625 !cpu_has_vmx_virtualize_x2apic_mode())
6628 /* Postpone execution until vmcs01 is the current VMCS. */
6629 if (is_guest_mode(vcpu)) {
6630 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6634 sec_exec_control = secondary_exec_controls_get(vmx);
6635 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6636 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6638 switch (kvm_get_apic_mode(vcpu)) {
6639 case LAPIC_MODE_INVALID:
6640 WARN_ONCE(true, "Invalid local APIC state");
6642 case LAPIC_MODE_DISABLED:
6644 case LAPIC_MODE_XAPIC:
6645 if (flexpriority_enabled) {
6647 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6648 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6651 * Flush the TLB, reloading the APIC access page will
6652 * only do so if its physical address has changed, but
6653 * the guest may have inserted a non-APIC mapping into
6654 * the TLB while the APIC access page was disabled.
6656 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6659 case LAPIC_MODE_X2APIC:
6660 if (cpu_has_vmx_virtualize_x2apic_mode())
6662 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6665 secondary_exec_controls_set(vmx, sec_exec_control);
6667 vmx_update_msr_bitmap_x2apic(vcpu);
6670 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6674 /* Defer reload until vmcs01 is the current VMCS. */
6675 if (is_guest_mode(vcpu)) {
6676 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6680 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6681 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6684 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6685 if (is_error_page(page))
6688 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6689 vmx_flush_tlb_current(vcpu);
6692 * Do not pin apic access page in memory, the MMU notifier
6693 * will call us again if it is migrated or swapped out.
6698 static void vmx_hwapic_isr_update(int max_isr)
6706 status = vmcs_read16(GUEST_INTR_STATUS);
6708 if (max_isr != old) {
6710 status |= max_isr << 8;
6711 vmcs_write16(GUEST_INTR_STATUS, status);
6715 static void vmx_set_rvi(int vector)
6723 status = vmcs_read16(GUEST_INTR_STATUS);
6724 old = (u8)status & 0xff;
6725 if ((u8)vector != old) {
6727 status |= (u8)vector;
6728 vmcs_write16(GUEST_INTR_STATUS, status);
6732 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6735 * When running L2, updating RVI is only relevant when
6736 * vmcs12 virtual-interrupt-delivery enabled.
6737 * However, it can be enabled only when L1 also
6738 * intercepts external-interrupts and in that case
6739 * we should not update vmcs02 RVI but instead intercept
6740 * interrupt. Therefore, do nothing when running L2.
6742 if (!is_guest_mode(vcpu))
6743 vmx_set_rvi(max_irr);
6746 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6748 struct vcpu_vmx *vmx = to_vmx(vcpu);
6750 bool got_posted_interrupt;
6752 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6755 if (pi_test_on(&vmx->pi_desc)) {
6756 pi_clear_on(&vmx->pi_desc);
6758 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6759 * But on x86 this is just a compiler barrier anyway.
6761 smp_mb__after_atomic();
6762 got_posted_interrupt =
6763 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6765 max_irr = kvm_lapic_find_highest_irr(vcpu);
6766 got_posted_interrupt = false;
6770 * Newly recognized interrupts are injected via either virtual interrupt
6771 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6772 * disabled in two cases:
6774 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6775 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6776 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6777 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6778 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6780 * 2) If APICv is disabled for this vCPU, assigned devices may still
6781 * attempt to post interrupts. The posted interrupt vector will cause
6782 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6784 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6785 vmx_set_rvi(max_irr);
6786 else if (got_posted_interrupt)
6787 kvm_make_request(KVM_REQ_EVENT, vcpu);
6792 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6794 if (!kvm_vcpu_apicv_active(vcpu))
6797 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6798 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6799 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6800 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6803 static void vmx_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
6805 struct vcpu_vmx *vmx = to_vmx(vcpu);
6807 pi_clear_on(&vmx->pi_desc);
6808 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6811 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6813 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6814 unsigned long entry)
6816 bool is_nmi = entry == (unsigned long)asm_exc_nmi_noist;
6818 kvm_before_interrupt(vcpu, is_nmi ? KVM_HANDLING_NMI : KVM_HANDLING_IRQ);
6819 vmx_do_interrupt_nmi_irqoff(entry);
6820 kvm_after_interrupt(vcpu);
6823 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6826 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6827 * MSR value is not clobbered by the host activity before the guest
6828 * has chance to consume it.
6830 * Do not blindly read xfd_err here, since this exception might
6831 * be caused by L1 interception on a platform which doesn't
6832 * support xfd at all.
6834 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6835 * only when xfd contains a non-zero value.
6837 * Queuing exception is done in vmx_handle_exit. See comment there.
6839 if (vcpu->arch.guest_fpu.fpstate->xfd)
6840 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6843 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6845 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6846 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6848 /* if exit due to PF check for async PF */
6849 if (is_page_fault(intr_info))
6850 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6851 /* if exit due to NM, handle before interrupts are enabled */
6852 else if (is_nm_fault(intr_info))
6853 handle_nm_fault_irqoff(&vmx->vcpu);
6854 /* Handle machine checks before interrupts are enabled */
6855 else if (is_machine_check(intr_info))
6856 kvm_machine_check();
6857 /* We need to handle NMIs before interrupts are enabled */
6858 else if (is_nmi(intr_info))
6859 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6862 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6864 u32 intr_info = vmx_get_intr_info(vcpu);
6865 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6866 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6868 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6869 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6872 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6873 vcpu->arch.at_instruction_boundary = true;
6876 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6878 struct vcpu_vmx *vmx = to_vmx(vcpu);
6880 if (vmx->emulation_required)
6883 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6884 handle_external_interrupt_irqoff(vcpu);
6885 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6886 handle_exception_nmi_irqoff(vmx);
6890 * The kvm parameter can be NULL (module initialization, or invocation before
6891 * VM creation). Be sure to check the kvm parameter before using it.
6893 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6896 case MSR_IA32_SMBASE:
6898 * We cannot do SMM unless we can run the guest in big
6901 return enable_unrestricted_guest || emulate_invalid_guest_state;
6902 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6904 case MSR_AMD64_VIRT_SPEC_CTRL:
6905 case MSR_AMD64_TSC_RATIO:
6906 /* This is AMD only. */
6913 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6918 bool idtv_info_valid;
6920 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6923 if (vmx->loaded_vmcs->nmi_known_unmasked)
6926 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6927 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6928 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6930 * SDM 3: 27.7.1.2 (September 2008)
6931 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6932 * a guest IRET fault.
6933 * SDM 3: 23.2.2 (September 2008)
6934 * Bit 12 is undefined in any of the following cases:
6935 * If the VM exit sets the valid bit in the IDT-vectoring
6936 * information field.
6937 * If the VM exit is due to a double fault.
6939 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6940 vector != DF_VECTOR && !idtv_info_valid)
6941 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6942 GUEST_INTR_STATE_NMI);
6944 vmx->loaded_vmcs->nmi_known_unmasked =
6945 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6946 & GUEST_INTR_STATE_NMI);
6947 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6948 vmx->loaded_vmcs->vnmi_blocked_time +=
6949 ktime_to_ns(ktime_sub(ktime_get(),
6950 vmx->loaded_vmcs->entry_time));
6953 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6954 u32 idt_vectoring_info,
6955 int instr_len_field,
6956 int error_code_field)
6960 bool idtv_info_valid;
6962 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6964 vcpu->arch.nmi_injected = false;
6965 kvm_clear_exception_queue(vcpu);
6966 kvm_clear_interrupt_queue(vcpu);
6968 if (!idtv_info_valid)
6971 kvm_make_request(KVM_REQ_EVENT, vcpu);
6973 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6974 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6977 case INTR_TYPE_NMI_INTR:
6978 vcpu->arch.nmi_injected = true;
6980 * SDM 3: 27.7.1.2 (September 2008)
6981 * Clear bit "block by NMI" before VM entry if a NMI
6984 vmx_set_nmi_mask(vcpu, false);
6986 case INTR_TYPE_SOFT_EXCEPTION:
6987 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6989 case INTR_TYPE_HARD_EXCEPTION:
6990 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6991 u32 err = vmcs_read32(error_code_field);
6992 kvm_requeue_exception_e(vcpu, vector, err);
6994 kvm_requeue_exception(vcpu, vector);
6996 case INTR_TYPE_SOFT_INTR:
6997 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6999 case INTR_TYPE_EXT_INTR:
7000 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7007 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7009 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7010 VM_EXIT_INSTRUCTION_LEN,
7011 IDT_VECTORING_ERROR_CODE);
7014 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7016 __vmx_complete_interrupts(vcpu,
7017 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7018 VM_ENTRY_INSTRUCTION_LEN,
7019 VM_ENTRY_EXCEPTION_ERROR_CODE);
7021 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7024 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7027 struct perf_guest_switch_msr *msrs;
7028 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
7030 pmu->host_cross_mapped_mask = 0;
7031 if (pmu->pebs_enable & pmu->global_ctrl)
7032 intel_pmu_cross_mapped_check(pmu);
7034 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
7035 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
7039 for (i = 0; i < nr_msrs; i++)
7040 if (msrs[i].host == msrs[i].guest)
7041 clear_atomic_switch_msr(vmx, msrs[i].msr);
7043 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7044 msrs[i].host, false);
7047 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
7049 struct vcpu_vmx *vmx = to_vmx(vcpu);
7053 if (vmx->req_immediate_exit) {
7054 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
7055 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7056 } else if (vmx->hv_deadline_tsc != -1) {
7058 if (vmx->hv_deadline_tsc > tscl)
7059 /* set_hv_timer ensures the delta fits in 32-bits */
7060 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
7061 cpu_preemption_timer_multi);
7065 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7066 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7067 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7068 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7069 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7073 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7075 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7076 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7077 vmcs_writel(HOST_RSP, host_rsp);
7081 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7084 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7086 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7089 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7090 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7093 * If the guest/host SPEC_CTRL values differ, restore the host value.
7095 * For legacy IBRS, the IBRS bit always needs to be written after
7096 * transitioning from a less privileged predictor mode, regardless of
7097 * whether the guest/host values differ.
7099 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7100 vmx->spec_ctrl != hostval)
7101 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7106 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
7108 switch (to_vmx(vcpu)->exit_reason.basic) {
7109 case EXIT_REASON_MSR_WRITE:
7110 return handle_fastpath_set_msr_irqoff(vcpu);
7111 case EXIT_REASON_PREEMPTION_TIMER:
7112 return handle_fastpath_preemption_timer(vcpu);
7114 return EXIT_FASTPATH_NONE;
7118 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7119 struct vcpu_vmx *vmx,
7120 unsigned long flags)
7122 guest_state_enter_irqoff();
7125 * L1D Flush includes CPU buffer clear to mitigate MDS, but VERW
7126 * mitigation for MDS is done late in VMentry and is still
7127 * executed in spite of L1D Flush. This is because an extra VERW
7128 * should not matter much after the big hammer L1D Flush.
7130 if (static_branch_unlikely(&vmx_l1d_should_flush))
7131 vmx_l1d_flush(vcpu);
7132 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7133 kvm_arch_has_assigned_device(vcpu->kvm))
7134 mds_clear_cpu_buffers();
7136 vmx_disable_fb_clear(vmx);
7138 if (vcpu->arch.cr2 != native_read_cr2())
7139 native_write_cr2(vcpu->arch.cr2);
7141 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7144 vcpu->arch.cr2 = native_read_cr2();
7146 vmx_enable_fb_clear(vmx);
7148 guest_state_exit_irqoff();
7151 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
7153 struct vcpu_vmx *vmx = to_vmx(vcpu);
7154 unsigned long cr3, cr4;
7156 /* Record the guest's net vcpu time for enforced NMI injections. */
7157 if (unlikely(!enable_vnmi &&
7158 vmx->loaded_vmcs->soft_vnmi_blocked))
7159 vmx->loaded_vmcs->entry_time = ktime_get();
7162 * Don't enter VMX if guest state is invalid, let the exit handler
7163 * start emulation until we arrive back to a valid state. Synthesize a
7164 * consistency check VM-Exit due to invalid guest state and bail.
7166 if (unlikely(vmx->emulation_required)) {
7169 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7170 vmx->exit_reason.failed_vmentry = 1;
7171 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7172 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7173 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7174 vmx->exit_intr_info = 0;
7175 return EXIT_FASTPATH_NONE;
7178 trace_kvm_entry(vcpu);
7180 if (vmx->ple_window_dirty) {
7181 vmx->ple_window_dirty = false;
7182 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7186 * We did this in prepare_switch_to_guest, because it needs to
7187 * be within srcu_read_lock.
7189 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7191 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7192 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7193 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7194 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7195 vcpu->arch.regs_dirty = 0;
7198 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
7199 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7200 * it switches back to the current->mm, which can occur in KVM context
7201 * when switching to a temporary mm to patch kernel code, e.g. if KVM
7202 * toggles a static key while handling a VM-Exit.
7204 cr3 = __get_current_cr3_fast();
7205 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7206 vmcs_writel(HOST_CR3, cr3);
7207 vmx->loaded_vmcs->host_state.cr3 = cr3;
7210 cr4 = cr4_read_shadow();
7211 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7212 vmcs_writel(HOST_CR4, cr4);
7213 vmx->loaded_vmcs->host_state.cr4 = cr4;
7216 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
7217 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
7218 set_debugreg(vcpu->arch.dr6, 6);
7220 /* When single-stepping over STI and MOV SS, we must clear the
7221 * corresponding interruptibility bits in the guest state. Otherwise
7222 * vmentry fails as it then expects bit 14 (BS) in pending debug
7223 * exceptions being set, but that's not correct for the guest debugging
7225 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7226 vmx_set_interrupt_shadow(vcpu, 0);
7228 kvm_load_guest_xsave_state(vcpu);
7230 pt_guest_enter(vmx);
7232 atomic_switch_perf_msrs(vmx);
7233 if (intel_pmu_lbr_is_enabled(vcpu))
7234 vmx_passthrough_lbr_msrs(vcpu);
7236 if (enable_preemption_timer)
7237 vmx_update_hv_timer(vcpu);
7239 kvm_wait_lapic_expire(vcpu);
7241 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7242 vmx_vcpu_enter_exit(vcpu, vmx, __vmx_vcpu_run_flags(vmx));
7244 /* All fields are clean at this point */
7245 if (static_branch_unlikely(&enable_evmcs)) {
7246 current_evmcs->hv_clean_fields |=
7247 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7249 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7252 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7253 if (vmx->host_debugctlmsr)
7254 update_debugctlmsr(vmx->host_debugctlmsr);
7256 #ifndef CONFIG_X86_64
7258 * The sysexit path does not restore ds/es, so we must set them to
7259 * a reasonable value ourselves.
7261 * We can't defer this to vmx_prepare_switch_to_host() since that
7262 * function may be executed in interrupt context, which saves and
7263 * restore segments around it, nullifying its effect.
7265 loadsegment(ds, __USER_DS);
7266 loadsegment(es, __USER_DS);
7269 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7273 kvm_load_host_xsave_state(vcpu);
7275 if (is_guest_mode(vcpu)) {
7277 * Track VMLAUNCH/VMRESUME that have made past guest state
7280 if (vmx->nested.nested_run_pending &&
7281 !vmx->exit_reason.failed_vmentry)
7282 ++vcpu->stat.nested_run;
7284 vmx->nested.nested_run_pending = 0;
7287 vmx->idt_vectoring_info = 0;
7289 if (unlikely(vmx->fail)) {
7290 vmx->exit_reason.full = 0xdead;
7291 return EXIT_FASTPATH_NONE;
7294 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7295 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7296 kvm_machine_check();
7298 if (likely(!vmx->exit_reason.failed_vmentry))
7299 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7301 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7303 if (unlikely(vmx->exit_reason.failed_vmentry))
7304 return EXIT_FASTPATH_NONE;
7306 vmx->loaded_vmcs->launched = 1;
7308 vmx_recover_nmi_blocking(vmx);
7309 vmx_complete_interrupts(vmx);
7311 if (is_guest_mode(vcpu))
7312 return EXIT_FASTPATH_NONE;
7314 return vmx_exit_handlers_fastpath(vcpu);
7317 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7319 struct vcpu_vmx *vmx = to_vmx(vcpu);
7322 vmx_destroy_pml_buffer(vmx);
7323 free_vpid(vmx->vpid);
7324 nested_vmx_free_vcpu(vcpu);
7325 free_loaded_vmcs(vmx->loaded_vmcs);
7328 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7330 struct vmx_uret_msr *tsx_ctrl;
7331 struct vcpu_vmx *vmx;
7334 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7337 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7341 vmx->vpid = allocate_vpid();
7344 * If PML is turned on, failure on enabling PML just results in failure
7345 * of creating the vcpu, therefore we can simplify PML logic (by
7346 * avoiding dealing with cases, such as enabling PML partially on vcpus
7347 * for the guest), etc.
7350 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7355 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7356 vmx->guest_uret_msrs[i].mask = -1ull;
7357 if (boot_cpu_has(X86_FEATURE_RTM)) {
7359 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7360 * Keep the host value unchanged to avoid changing CPUID bits
7361 * under the host kernel's feet.
7363 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7365 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7368 err = alloc_loaded_vmcs(&vmx->vmcs01);
7373 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7374 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7375 * feature only for vmcs01, KVM currently isn't equipped to realize any
7376 * performance benefits from enabling it for vmcs02.
7378 if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs) &&
7379 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7380 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7382 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7385 /* The MSR bitmap starts with all ones */
7386 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7387 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7389 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7390 #ifdef CONFIG_X86_64
7391 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7392 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7393 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7395 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7396 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7397 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7398 if (kvm_cstate_in_guest(vcpu->kvm)) {
7399 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7400 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7401 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7402 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7405 vmx->loaded_vmcs = &vmx->vmcs01;
7407 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7408 err = alloc_apic_access_page(vcpu->kvm);
7413 if (enable_ept && !enable_unrestricted_guest) {
7414 err = init_rmode_identity_map(vcpu->kvm);
7419 if (vmx_can_use_ipiv(vcpu))
7420 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7421 __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7426 free_loaded_vmcs(vmx->loaded_vmcs);
7428 vmx_destroy_pml_buffer(vmx);
7430 free_vpid(vmx->vpid);
7434 #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"
7435 #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"
7437 static int vmx_vm_init(struct kvm *kvm)
7440 kvm->arch.pause_in_guest = true;
7442 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7443 switch (l1tf_mitigation) {
7444 case L1TF_MITIGATION_OFF:
7445 case L1TF_MITIGATION_FLUSH_NOWARN:
7446 /* 'I explicitly don't care' is set */
7448 case L1TF_MITIGATION_FLUSH:
7449 case L1TF_MITIGATION_FLUSH_NOSMT:
7450 case L1TF_MITIGATION_FULL:
7452 * Warn upon starting the first VM in a potentially
7453 * insecure environment.
7455 if (sched_smt_active())
7456 pr_warn_once(L1TF_MSG_SMT);
7457 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7458 pr_warn_once(L1TF_MSG_L1D);
7460 case L1TF_MITIGATION_FULL_FORCE:
7461 /* Flush is enforced */
7468 static int __init vmx_check_processor_compat(void)
7470 struct vmcs_config vmcs_conf;
7471 struct vmx_capability vmx_cap;
7473 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7474 !this_cpu_has(X86_FEATURE_VMX)) {
7475 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7479 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7482 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
7483 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7484 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7485 smp_processor_id());
7491 static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7495 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7496 * memory aliases with conflicting memory types and sometimes MCEs.
7497 * We have to be careful as to what are honored and when.
7499 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7500 * UC. The effective memory type is UC or WC depending on guest PAT.
7501 * This was historically the source of MCEs and we want to be
7504 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7505 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7506 * EPT memory type is set to WB. The effective memory type is forced
7509 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7510 * EPT memory type is used to emulate guest CD/MTRR.
7514 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7516 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7517 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7519 if (kvm_read_cr0_bits(vcpu, X86_CR0_CD)) {
7520 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7521 cache = MTRR_TYPE_WRBACK;
7523 cache = MTRR_TYPE_UNCACHABLE;
7525 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7528 return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7531 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7534 * These bits in the secondary execution controls field
7535 * are dynamic, the others are mostly based on the hypervisor
7536 * architecture and the guest's CPUID. Do not touch the
7540 SECONDARY_EXEC_SHADOW_VMCS |
7541 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7542 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7543 SECONDARY_EXEC_DESC;
7545 u32 cur_ctl = secondary_exec_controls_get(vmx);
7547 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7551 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7552 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7554 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7556 struct vcpu_vmx *vmx = to_vmx(vcpu);
7557 struct kvm_cpuid_entry2 *entry;
7559 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7560 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7562 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7563 if (entry && (entry->_reg & (_cpuid_mask))) \
7564 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7567 entry = kvm_find_cpuid_entry(vcpu, 0x1);
7568 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7569 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7570 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7571 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7572 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7573 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7574 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7575 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7576 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7577 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7578 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7579 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7580 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7581 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7583 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7584 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7585 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7586 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7587 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7588 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7589 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7591 #undef cr4_fixed1_update
7594 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7596 struct vcpu_vmx *vmx = to_vmx(vcpu);
7597 struct kvm_cpuid_entry2 *best = NULL;
7600 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7601 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7604 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7605 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7606 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7607 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7610 /* Get the number of configurable Address Ranges for filtering */
7611 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7612 PT_CAP_num_address_ranges);
7614 /* Initialize and clear the no dependency bits */
7615 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7616 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7617 RTIT_CTL_BRANCH_EN);
7620 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7621 * will inject an #GP
7623 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7624 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7627 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7628 * PSBFreq can be set
7630 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7631 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7632 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7635 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7637 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7638 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7639 RTIT_CTL_MTC_RANGE);
7641 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7642 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7643 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7646 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7647 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7648 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7650 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7651 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7652 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7654 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7655 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7656 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7658 /* unmask address range configure area */
7659 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7660 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7663 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7665 struct vcpu_vmx *vmx = to_vmx(vcpu);
7667 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7668 vcpu->arch.xsaves_enabled = false;
7670 vmx_setup_uret_msrs(vmx);
7672 if (cpu_has_secondary_exec_ctrls())
7673 vmcs_set_secondary_exec_control(vmx,
7674 vmx_secondary_exec_control(vmx));
7676 if (nested_vmx_allowed(vcpu))
7677 vmx->msr_ia32_feature_control_valid_bits |=
7678 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7679 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7681 vmx->msr_ia32_feature_control_valid_bits &=
7682 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7683 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7685 if (nested_vmx_allowed(vcpu))
7686 nested_vmx_cr_fixed1_bits_update(vcpu);
7688 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7689 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7690 update_intel_pt_cfg(vcpu);
7692 if (boot_cpu_has(X86_FEATURE_RTM)) {
7693 struct vmx_uret_msr *msr;
7694 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7696 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7697 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7701 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7702 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7703 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7706 set_cr4_guest_host_mask(vmx);
7708 vmx_write_encls_bitmap(vcpu, NULL);
7709 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7710 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7712 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7714 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7715 vmx->msr_ia32_feature_control_valid_bits |=
7716 FEAT_CTL_SGX_LC_ENABLED;
7718 vmx->msr_ia32_feature_control_valid_bits &=
7719 ~FEAT_CTL_SGX_LC_ENABLED;
7721 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7722 vmx_update_exception_bitmap(vcpu);
7725 static u64 vmx_get_perf_capabilities(void)
7727 u64 perf_cap = PMU_CAP_FW_WRITES;
7728 struct x86_pmu_lbr lbr;
7729 u64 host_perf_cap = 0;
7734 if (boot_cpu_has(X86_FEATURE_PDCM))
7735 rdmsrl(MSR_IA32_PERF_CAPABILITIES, host_perf_cap);
7737 if (!cpu_feature_enabled(X86_FEATURE_ARCH_LBR)) {
7738 x86_perf_get_lbr(&lbr);
7740 perf_cap |= host_perf_cap & PMU_CAP_LBR_FMT;
7743 if (vmx_pebs_supported()) {
7744 perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK;
7747 * Disallow adaptive PEBS as it is functionally broken, can be
7748 * used by the guest to read *host* LBRs, and can be used to
7749 * bypass userspace event filters. To correctly and safely
7750 * support adaptive PEBS, KVM needs to:
7752 * 1. Account for the ADAPTIVE flag when (re)programming fixed
7755 * 2. Gain support from perf (or take direct control of counter
7756 * programming) to support events without adaptive PEBS
7757 * enabled for the hardware counter.
7759 * 3. Ensure LBR MSRs cannot hold host data on VM-Entry with
7760 * adaptive PEBS enabled and MSR_PEBS_DATA_CFG.LBRS=1.
7762 * 4. Document which PMU events are effectively exposed to the
7763 * guest via adaptive PEBS, and make adaptive PEBS mutually
7764 * exclusive with KVM_SET_PMU_EVENT_FILTER if necessary.
7766 perf_cap &= ~PERF_CAP_PEBS_BASELINE;
7772 static __init void vmx_set_cpu_caps(void)
7778 kvm_cpu_cap_set(X86_FEATURE_VMX);
7781 if (kvm_mpx_supported())
7782 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7783 if (!cpu_has_vmx_invpcid())
7784 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7785 if (vmx_pt_mode_is_host_guest())
7786 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7787 if (vmx_pebs_supported()) {
7788 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7789 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7793 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7794 kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
7797 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7798 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7799 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7800 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7803 if (vmx_umip_emulated())
7804 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7807 kvm_caps.supported_xss = 0;
7808 if (!cpu_has_vmx_xsaves())
7809 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7811 /* CPUID 0x80000001 and 0x7 (RDPID) */
7812 if (!cpu_has_vmx_rdtscp()) {
7813 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7814 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7817 if (cpu_has_vmx_waitpkg())
7818 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7821 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7823 to_vmx(vcpu)->req_immediate_exit = true;
7826 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7827 struct x86_instruction_info *info)
7829 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7830 unsigned short port;
7834 if (info->intercept == x86_intercept_in ||
7835 info->intercept == x86_intercept_ins) {
7836 port = info->src_val;
7837 size = info->dst_bytes;
7839 port = info->dst_val;
7840 size = info->src_bytes;
7844 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7845 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7848 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7850 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7851 intercept = nested_cpu_has(vmcs12,
7852 CPU_BASED_UNCOND_IO_EXITING);
7854 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7856 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7857 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7860 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7861 struct x86_instruction_info *info,
7862 enum x86_intercept_stage stage,
7863 struct x86_exception *exception)
7865 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7867 switch (info->intercept) {
7869 * RDPID causes #UD if disabled through secondary execution controls.
7870 * Because it is marked as EmulateOnUD, we need to intercept it here.
7871 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7873 case x86_intercept_rdpid:
7874 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7875 exception->vector = UD_VECTOR;
7876 exception->error_code_valid = false;
7877 return X86EMUL_PROPAGATE_FAULT;
7881 case x86_intercept_in:
7882 case x86_intercept_ins:
7883 case x86_intercept_out:
7884 case x86_intercept_outs:
7885 return vmx_check_intercept_io(vcpu, info);
7887 case x86_intercept_lgdt:
7888 case x86_intercept_lidt:
7889 case x86_intercept_lldt:
7890 case x86_intercept_ltr:
7891 case x86_intercept_sgdt:
7892 case x86_intercept_sidt:
7893 case x86_intercept_sldt:
7894 case x86_intercept_str:
7895 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7896 return X86EMUL_CONTINUE;
7898 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7901 case x86_intercept_pause:
7903 * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides
7904 * with vanilla NOPs in the emulator. Apply the interception
7905 * check only to actual PAUSE instructions. Don't check
7906 * PAUSE-loop-exiting, software can't expect a given PAUSE to
7907 * exit, i.e. KVM is within its rights to allow L2 to execute
7910 if ((info->rep_prefix != REPE_PREFIX) ||
7911 !nested_cpu_has2(vmcs12, CPU_BASED_PAUSE_EXITING))
7912 return X86EMUL_CONTINUE;
7916 /* TODO: check more intercepts... */
7921 return X86EMUL_UNHANDLEABLE;
7924 #ifdef CONFIG_X86_64
7925 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7926 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7927 u64 divisor, u64 *result)
7929 u64 low = a << shift, high = a >> (64 - shift);
7931 /* To avoid the overflow on divq */
7932 if (high >= divisor)
7935 /* Low hold the result, high hold rem which is discarded */
7936 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7937 "rm" (divisor), "0" (low), "1" (high));
7943 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7946 struct vcpu_vmx *vmx;
7947 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7948 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7952 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7953 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7954 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7955 ktimer->timer_advance_ns);
7957 if (delta_tsc > lapic_timer_advance_cycles)
7958 delta_tsc -= lapic_timer_advance_cycles;
7962 /* Convert to host delta tsc if tsc scaling is enabled */
7963 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
7964 delta_tsc && u64_shl_div_u64(delta_tsc,
7965 kvm_caps.tsc_scaling_ratio_frac_bits,
7966 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7970 * If the delta tsc can't fit in the 32 bit after the multi shift,
7971 * we can't use the preemption timer.
7972 * It's possible that it fits on later vmentries, but checking
7973 * on every vmentry is costly so we just use an hrtimer.
7975 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7978 vmx->hv_deadline_tsc = tscl + delta_tsc;
7979 *expired = !delta_tsc;
7983 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7985 to_vmx(vcpu)->hv_deadline_tsc = -1;
7989 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7991 if (!kvm_pause_in_guest(vcpu->kvm))
7992 shrink_ple_window(vcpu);
7995 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7997 struct vcpu_vmx *vmx = to_vmx(vcpu);
7999 if (is_guest_mode(vcpu)) {
8000 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
8005 * Note, cpu_dirty_logging_count can be changed concurrent with this
8006 * code, but in that case another update request will be made and so
8007 * the guest will never run with a stale PML value.
8009 if (vcpu->kvm->arch.cpu_dirty_logging_count)
8010 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8012 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8015 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
8017 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
8018 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
8019 FEAT_CTL_LMCE_ENABLED;
8021 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
8022 ~FEAT_CTL_LMCE_ENABLED;
8025 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
8027 /* we need a nested vmexit to enter SMM, postpone if run is pending */
8028 if (to_vmx(vcpu)->nested.nested_run_pending)
8030 return !is_smm(vcpu);
8033 static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
8035 struct vcpu_vmx *vmx = to_vmx(vcpu);
8038 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
8039 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
8040 * SMI and RSM only modify state that is saved and restored via SMRAM.
8041 * E.g. most MSRs are left untouched, but many are modified by VM-Exit
8042 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
8044 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
8045 if (vmx->nested.smm.guest_mode)
8046 nested_vmx_vmexit(vcpu, -1, 0, 0);
8048 vmx->nested.smm.vmxon = vmx->nested.vmxon;
8049 vmx->nested.vmxon = false;
8050 vmx_clear_hlt(vcpu);
8054 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
8056 struct vcpu_vmx *vmx = to_vmx(vcpu);
8059 if (vmx->nested.smm.vmxon) {
8060 vmx->nested.vmxon = true;
8061 vmx->nested.smm.vmxon = false;
8064 if (vmx->nested.smm.guest_mode) {
8065 ret = nested_vmx_enter_non_root_mode(vcpu, false);
8069 vmx->nested.nested_run_pending = 1;
8070 vmx->nested.smm.guest_mode = false;
8075 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
8077 /* RSM will cause a vmexit anyway. */
8080 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
8082 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
8085 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
8087 if (is_guest_mode(vcpu)) {
8088 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
8090 if (hrtimer_try_to_cancel(timer) == 1)
8091 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
8095 static void vmx_hardware_unsetup(void)
8097 kvm_set_posted_intr_wakeup_handler(NULL);
8100 nested_vmx_hardware_unsetup();
8105 static bool vmx_check_apicv_inhibit_reasons(enum kvm_apicv_inhibit reason)
8107 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
8108 BIT(APICV_INHIBIT_REASON_ABSENT) |
8109 BIT(APICV_INHIBIT_REASON_HYPERV) |
8110 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |
8111 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |
8112 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
8114 return supported & BIT(reason);
8117 static void vmx_vm_destroy(struct kvm *kvm)
8119 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
8121 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
8124 static struct kvm_x86_ops vmx_x86_ops __initdata = {
8125 .name = "kvm_intel",
8127 .hardware_unsetup = vmx_hardware_unsetup,
8129 .hardware_enable = vmx_hardware_enable,
8130 .hardware_disable = vmx_hardware_disable,
8131 .has_emulated_msr = vmx_has_emulated_msr,
8133 .vm_size = sizeof(struct kvm_vmx),
8134 .vm_init = vmx_vm_init,
8135 .vm_destroy = vmx_vm_destroy,
8137 .vcpu_precreate = vmx_vcpu_precreate,
8138 .vcpu_create = vmx_vcpu_create,
8139 .vcpu_free = vmx_vcpu_free,
8140 .vcpu_reset = vmx_vcpu_reset,
8142 .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
8143 .vcpu_load = vmx_vcpu_load,
8144 .vcpu_put = vmx_vcpu_put,
8146 .update_exception_bitmap = vmx_update_exception_bitmap,
8147 .get_msr_feature = vmx_get_msr_feature,
8148 .get_msr = vmx_get_msr,
8149 .set_msr = vmx_set_msr,
8150 .get_segment_base = vmx_get_segment_base,
8151 .get_segment = vmx_get_segment,
8152 .set_segment = vmx_set_segment,
8153 .get_cpl = vmx_get_cpl,
8154 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8155 .is_valid_cr0 = vmx_is_valid_cr0,
8156 .set_cr0 = vmx_set_cr0,
8157 .is_valid_cr4 = vmx_is_valid_cr4,
8158 .set_cr4 = vmx_set_cr4,
8159 .set_efer = vmx_set_efer,
8160 .get_idt = vmx_get_idt,
8161 .set_idt = vmx_set_idt,
8162 .get_gdt = vmx_get_gdt,
8163 .set_gdt = vmx_set_gdt,
8164 .set_dr7 = vmx_set_dr7,
8165 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8166 .cache_reg = vmx_cache_reg,
8167 .get_rflags = vmx_get_rflags,
8168 .set_rflags = vmx_set_rflags,
8169 .get_if_flag = vmx_get_if_flag,
8171 .flush_tlb_all = vmx_flush_tlb_all,
8172 .flush_tlb_current = vmx_flush_tlb_current,
8173 .flush_tlb_gva = vmx_flush_tlb_gva,
8174 .flush_tlb_guest = vmx_flush_tlb_guest,
8176 .vcpu_pre_run = vmx_vcpu_pre_run,
8177 .vcpu_run = vmx_vcpu_run,
8178 .handle_exit = vmx_handle_exit,
8179 .skip_emulated_instruction = vmx_skip_emulated_instruction,
8180 .update_emulated_instruction = vmx_update_emulated_instruction,
8181 .set_interrupt_shadow = vmx_set_interrupt_shadow,
8182 .get_interrupt_shadow = vmx_get_interrupt_shadow,
8183 .patch_hypercall = vmx_patch_hypercall,
8184 .inject_irq = vmx_inject_irq,
8185 .inject_nmi = vmx_inject_nmi,
8186 .inject_exception = vmx_inject_exception,
8187 .cancel_injection = vmx_cancel_injection,
8188 .interrupt_allowed = vmx_interrupt_allowed,
8189 .nmi_allowed = vmx_nmi_allowed,
8190 .get_nmi_mask = vmx_get_nmi_mask,
8191 .set_nmi_mask = vmx_set_nmi_mask,
8192 .enable_nmi_window = vmx_enable_nmi_window,
8193 .enable_irq_window = vmx_enable_irq_window,
8194 .update_cr8_intercept = vmx_update_cr8_intercept,
8195 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
8196 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
8197 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
8198 .load_eoi_exitmap = vmx_load_eoi_exitmap,
8199 .apicv_pre_state_restore = vmx_apicv_pre_state_restore,
8200 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
8201 .hwapic_irr_update = vmx_hwapic_irr_update,
8202 .hwapic_isr_update = vmx_hwapic_isr_update,
8203 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
8204 .sync_pir_to_irr = vmx_sync_pir_to_irr,
8205 .deliver_interrupt = vmx_deliver_interrupt,
8206 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
8208 .set_tss_addr = vmx_set_tss_addr,
8209 .set_identity_map_addr = vmx_set_identity_map_addr,
8210 .get_mt_mask = vmx_get_mt_mask,
8212 .get_exit_info = vmx_get_exit_info,
8214 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
8216 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8218 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
8219 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
8220 .write_tsc_offset = vmx_write_tsc_offset,
8221 .write_tsc_multiplier = vmx_write_tsc_multiplier,
8223 .load_mmu_pgd = vmx_load_mmu_pgd,
8225 .check_intercept = vmx_check_intercept,
8226 .handle_exit_irqoff = vmx_handle_exit_irqoff,
8228 .request_immediate_exit = vmx_request_immediate_exit,
8230 .sched_in = vmx_sched_in,
8232 .cpu_dirty_log_size = PML_ENTITY_NUM,
8233 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
8235 .nested_ops = &vmx_nested_ops,
8237 .pi_update_irte = vmx_pi_update_irte,
8238 .pi_start_assignment = vmx_pi_start_assignment,
8240 #ifdef CONFIG_X86_64
8241 .set_hv_timer = vmx_set_hv_timer,
8242 .cancel_hv_timer = vmx_cancel_hv_timer,
8245 .setup_mce = vmx_setup_mce,
8247 .smi_allowed = vmx_smi_allowed,
8248 .enter_smm = vmx_enter_smm,
8249 .leave_smm = vmx_leave_smm,
8250 .enable_smi_window = vmx_enable_smi_window,
8252 .can_emulate_instruction = vmx_can_emulate_instruction,
8253 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8254 .migrate_timers = vmx_migrate_timers,
8256 .msr_filter_changed = vmx_msr_filter_changed,
8257 .complete_emulated_msr = kvm_complete_insn_gp,
8259 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
8262 static unsigned int vmx_handle_intel_pt_intr(void)
8264 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8266 /* '0' on failure so that the !PT case can use a RET0 static call. */
8267 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8270 kvm_make_request(KVM_REQ_PMI, vcpu);
8271 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8272 (unsigned long *)&vcpu->arch.pmu.global_status);
8276 static __init void vmx_setup_user_return_msrs(void)
8280 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8281 * will emulate SYSCALL in legacy mode if the vendor string in guest
8282 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8283 * support this emulation, MSR_STAR is included in the list for i386,
8284 * but is never loaded into hardware. MSR_CSTAR is also never loaded
8285 * into hardware and is here purely for emulation purposes.
8287 const u32 vmx_uret_msrs_list[] = {
8288 #ifdef CONFIG_X86_64
8289 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8291 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8296 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8298 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8299 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8302 static void __init vmx_setup_me_spte_mask(void)
8307 * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
8308 * the former to avoid exposing shadow_phys_bits.
8310 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8311 * shadow_phys_bits. On MKTME and/or TDX capable systems,
8312 * boot_cpu_data.x86_phys_bits holds the actual physical address
8313 * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
8314 * reported by CPUID. Those bits between are KeyID bits.
8316 if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
8317 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8318 kvm_get_shadow_phys_bits() - 1);
8320 * Unlike SME, host kernel doesn't support setting up any
8321 * MKTME KeyID on Intel platforms. No memory encryption
8322 * bits should be included into the SPTE.
8324 kvm_mmu_set_me_spte_mask(0, me_mask);
8327 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8329 static __init int hardware_setup(void)
8331 unsigned long host_bndcfgs;
8336 host_idt_base = dt.address;
8338 vmx_setup_user_return_msrs();
8340 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8343 if (cpu_has_perf_global_ctrl_bug())
8344 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8345 "does not work properly. Using workaround\n");
8347 if (boot_cpu_has(X86_FEATURE_NX))
8348 kvm_enable_efer_bits(EFER_NX);
8350 if (boot_cpu_has(X86_FEATURE_MPX)) {
8351 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8352 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8355 if (!cpu_has_vmx_mpx())
8356 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8357 XFEATURE_MASK_BNDCSR);
8359 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8360 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8363 if (!cpu_has_vmx_ept() ||
8364 !cpu_has_vmx_ept_4levels() ||
8365 !cpu_has_vmx_ept_mt_wb() ||
8366 !cpu_has_vmx_invept_global())
8369 /* NX support is required for shadow paging. */
8370 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8371 pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
8375 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8376 enable_ept_ad_bits = 0;
8378 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8379 enable_unrestricted_guest = 0;
8381 if (!cpu_has_vmx_flexpriority())
8382 flexpriority_enabled = 0;
8384 if (!cpu_has_virtual_nmis())
8387 #ifdef CONFIG_X86_SGX_KVM
8388 if (!cpu_has_vmx_encls_vmexit())
8393 * set_apic_access_page_addr() is used to reload apic access
8394 * page upon invalidation. No need to do anything if not
8395 * using the APIC_ACCESS_ADDR VMCS field.
8397 if (!flexpriority_enabled)
8398 vmx_x86_ops.set_apic_access_page_addr = NULL;
8400 if (!cpu_has_vmx_tpr_shadow())
8401 vmx_x86_ops.update_cr8_intercept = NULL;
8403 #if IS_ENABLED(CONFIG_HYPERV)
8404 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8406 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8407 vmx_x86_ops.tlb_remote_flush_with_range =
8408 hv_remote_flush_tlb_with_range;
8412 if (!cpu_has_vmx_ple()) {
8415 ple_window_grow = 0;
8417 ple_window_shrink = 0;
8420 if (!cpu_has_vmx_apicv())
8423 vmx_x86_ops.sync_pir_to_irr = NULL;
8425 if (!enable_apicv || !cpu_has_vmx_ipiv())
8426 enable_ipiv = false;
8428 if (cpu_has_vmx_tsc_scaling())
8429 kvm_caps.has_tsc_control = true;
8431 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8432 kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8433 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8434 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8436 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8439 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8440 cpu_has_vmx_ept_execute_only());
8443 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8444 * bits to shadow_zero_check.
8446 vmx_setup_me_spte_mask();
8448 kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
8449 ept_caps_to_lpage_level(vmx_capability.ept));
8452 * Only enable PML when hardware supports PML feature, and both EPT
8453 * and EPT A/D bit features are enabled -- PML depends on them to work.
8455 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8459 vmx_x86_ops.cpu_dirty_log_size = 0;
8461 if (!cpu_has_vmx_preemption_timer())
8462 enable_preemption_timer = false;
8464 if (enable_preemption_timer) {
8465 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8467 cpu_preemption_timer_multi =
8468 vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8471 use_timer_freq = (u64)tsc_khz * 1000;
8472 use_timer_freq >>= cpu_preemption_timer_multi;
8475 * KVM "disables" the preemption timer by setting it to its max
8476 * value. Don't use the timer if it might cause spurious exits
8477 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8479 if (use_timer_freq > 0xffffffffu / 10)
8480 enable_preemption_timer = false;
8483 if (!enable_preemption_timer) {
8484 vmx_x86_ops.set_hv_timer = NULL;
8485 vmx_x86_ops.cancel_hv_timer = NULL;
8486 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8489 kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8490 kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8492 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8494 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8495 pt_mode = PT_MODE_SYSTEM;
8496 if (pt_mode == PT_MODE_HOST_GUEST)
8497 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8499 vmx_init_ops.handle_intel_pt_intr = NULL;
8501 setup_default_sgx_lepubkeyhash();
8504 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8506 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8513 r = alloc_kvm_area();
8515 nested_vmx_hardware_unsetup();
8517 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8522 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8523 .cpu_has_kvm_support = cpu_has_kvm_support,
8524 .disabled_by_bios = vmx_disabled_by_bios,
8525 .check_processor_compatibility = vmx_check_processor_compat,
8526 .hardware_setup = hardware_setup,
8527 .handle_intel_pt_intr = NULL,
8529 .runtime_ops = &vmx_x86_ops,
8530 .pmu_ops = &intel_pmu_ops,
8533 static void vmx_cleanup_l1d_flush(void)
8535 if (vmx_l1d_flush_pages) {
8536 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8537 vmx_l1d_flush_pages = NULL;
8539 /* Restore state so sysfs ignores VMX */
8540 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8543 static void __vmx_exit(void)
8545 allow_smaller_maxphyaddr = false;
8547 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8550 vmx_cleanup_l1d_flush();
8553 static void vmx_exit(void)
8556 kvm_x86_vendor_exit();
8560 module_exit(vmx_exit);
8562 static int __init vmx_init(void)
8566 #if IS_ENABLED(CONFIG_HYPERV)
8568 * Enlightened VMCS usage should be recommended and the host needs
8569 * to support eVMCS v1 or above. We can also disable eVMCS support
8570 * with module parameter.
8572 if (enlightened_vmcs &&
8573 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8574 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8575 KVM_EVMCS_VERSION) {
8577 /* Check that we have assist pages on all online CPUs */
8578 for_each_online_cpu(cpu) {
8579 if (!hv_get_vp_assist_page(cpu)) {
8580 enlightened_vmcs = false;
8585 if (enlightened_vmcs) {
8586 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8587 static_branch_enable(&enable_evmcs);
8590 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8591 vmx_x86_ops.enable_direct_tlbflush
8592 = hv_enable_direct_tlbflush;
8595 enlightened_vmcs = false;
8599 r = kvm_x86_vendor_init(&vmx_init_ops);
8604 * Must be called after common x86 init so enable_ept is properly set
8605 * up. Hand the parameter mitigation value in which was stored in
8606 * the pre module init parser. If no parameter was given, it will
8607 * contain 'auto' which will be turned into the default 'cond'
8610 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8614 vmx_setup_fb_clear_ctrl();
8616 for_each_possible_cpu(cpu) {
8617 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8622 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8623 crash_vmclear_local_loaded_vmcss);
8625 vmx_check_vmcs12_offsets();
8628 * Shadow paging doesn't have a (further) performance penalty
8629 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8633 allow_smaller_maxphyaddr = true;
8636 * Common KVM initialization _must_ come last, after this, /dev/kvm is
8637 * exposed to userspace!
8639 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8640 __alignof__(struct vcpu_vmx), THIS_MODULE);
8649 kvm_x86_vendor_exit();
8652 module_init(vmx_init);