1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/api.h>
39 #include <asm/fpu/xstate.h>
40 #include <asm/idtentry.h>
42 #include <asm/irq_remapping.h>
43 #include <asm/kexec.h>
44 #include <asm/perf_event.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/mwait.h>
48 #include <asm/spec-ctrl.h>
49 #include <asm/virtext.h>
52 #include "capabilities.h"
56 #include "kvm_onhyperv.h"
58 #include "kvm_cache_regs.h"
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
74 static const struct x86_cpu_id vmx_cpu_id[] = {
75 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
78 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
81 bool __read_mostly enable_vpid = 1;
82 module_param_named(vpid, enable_vpid, bool, 0444);
84 static bool __read_mostly enable_vnmi = 1;
85 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
87 bool __read_mostly flexpriority_enabled = 1;
88 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
90 bool __read_mostly enable_ept = 1;
91 module_param_named(ept, enable_ept, bool, S_IRUGO);
93 bool __read_mostly enable_unrestricted_guest = 1;
94 module_param_named(unrestricted_guest,
95 enable_unrestricted_guest, bool, S_IRUGO);
97 bool __read_mostly enable_ept_ad_bits = 1;
98 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
100 static bool __read_mostly emulate_invalid_guest_state = true;
101 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
103 static bool __read_mostly fasteoi = 1;
104 module_param(fasteoi, bool, S_IRUGO);
106 module_param(enable_apicv, bool, S_IRUGO);
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 = vmx_fb_clear_ctrl_available;
413 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
414 * at VMEntry. Skip the MSR read/write when a guest has no use case to
417 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
418 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
419 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
420 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
421 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
422 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
423 vmx->disable_fb_clear = false;
426 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
427 .set = vmentry_l1d_flush_set,
428 .get = vmentry_l1d_flush_get,
430 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
432 static u32 vmx_segment_access_rights(struct kvm_segment *var);
434 void vmx_vmexit(void);
436 #define vmx_insn_failed(fmt...) \
439 pr_warn_ratelimited(fmt); \
442 void vmread_error(unsigned long field, bool fault)
445 kvm_spurious_fault();
447 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
450 noinline void vmwrite_error(unsigned long field, unsigned long value)
452 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%u\n",
453 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
456 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
458 vmx_insn_failed("kvm: vmclear failed: %p/%llx err=%u\n",
459 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
462 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
464 vmx_insn_failed("kvm: vmptrld failed: %p/%llx err=%u\n",
465 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
468 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
470 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
474 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
476 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
480 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
481 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
483 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
484 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
486 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
488 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
489 static DEFINE_SPINLOCK(vmx_vpid_lock);
491 struct vmcs_config vmcs_config;
492 struct vmx_capability vmx_capability;
494 #define VMX_SEGMENT_FIELD(seg) \
495 [VCPU_SREG_##seg] = { \
496 .selector = GUEST_##seg##_SELECTOR, \
497 .base = GUEST_##seg##_BASE, \
498 .limit = GUEST_##seg##_LIMIT, \
499 .ar_bytes = GUEST_##seg##_AR_BYTES, \
502 static const struct kvm_vmx_segment_field {
507 } kvm_vmx_segment_fields[] = {
508 VMX_SEGMENT_FIELD(CS),
509 VMX_SEGMENT_FIELD(DS),
510 VMX_SEGMENT_FIELD(ES),
511 VMX_SEGMENT_FIELD(FS),
512 VMX_SEGMENT_FIELD(GS),
513 VMX_SEGMENT_FIELD(SS),
514 VMX_SEGMENT_FIELD(TR),
515 VMX_SEGMENT_FIELD(LDTR),
518 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
520 vmx->segment_cache.bitmask = 0;
523 static unsigned long host_idt_base;
525 #if IS_ENABLED(CONFIG_HYPERV)
526 static bool __read_mostly enlightened_vmcs = true;
527 module_param(enlightened_vmcs, bool, 0444);
529 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
531 struct hv_enlightened_vmcs *evmcs;
532 struct hv_partition_assist_pg **p_hv_pa_pg =
533 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
535 * Synthetic VM-Exit is not enabled in current code and so All
536 * evmcs in singe VM shares same assist page.
539 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
544 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
546 evmcs->partition_assist_page =
548 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
549 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
554 #endif /* IS_ENABLED(CONFIG_HYPERV) */
557 * Comment's format: document - errata name - stepping - processor name.
559 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
561 static u32 vmx_preemption_cpu_tfms[] = {
562 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
564 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
565 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
566 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
568 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
570 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
571 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
573 * 320767.pdf - AAP86 - B1 -
574 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
577 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
579 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
581 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
583 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
584 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
585 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
587 /* Xeon E3-1220 V2 */
591 static inline bool cpu_has_broken_vmx_preemption_timer(void)
593 u32 eax = cpuid_eax(0x00000001), i;
595 /* Clear the reserved bits */
596 eax &= ~(0x3U << 14 | 0xfU << 28);
597 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
598 if (eax == vmx_preemption_cpu_tfms[i])
604 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
606 return flexpriority_enabled && lapic_in_kernel(vcpu);
609 static int possible_passthrough_msr_slot(u32 msr)
613 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
614 if (vmx_possible_passthrough_msrs[i] == msr)
620 static bool is_valid_passthrough_msr(u32 msr)
625 case 0x800 ... 0x8ff:
626 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
628 case MSR_IA32_RTIT_STATUS:
629 case MSR_IA32_RTIT_OUTPUT_BASE:
630 case MSR_IA32_RTIT_OUTPUT_MASK:
631 case MSR_IA32_RTIT_CR3_MATCH:
632 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
633 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
636 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
637 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
638 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
639 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
640 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
641 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
645 r = possible_passthrough_msr_slot(msr) != -ENOENT;
647 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
652 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
656 i = kvm_find_user_return_msr(msr);
658 return &vmx->guest_uret_msrs[i];
662 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
663 struct vmx_uret_msr *msr, u64 data)
665 unsigned int slot = msr - vmx->guest_uret_msrs;
668 if (msr->load_into_hardware) {
670 ret = kvm_set_user_return_msr(slot, data, msr->mask);
678 #ifdef CONFIG_KEXEC_CORE
679 static void crash_vmclear_local_loaded_vmcss(void)
681 int cpu = raw_smp_processor_id();
682 struct loaded_vmcs *v;
684 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
685 loaded_vmcss_on_cpu_link)
688 #endif /* CONFIG_KEXEC_CORE */
690 static void __loaded_vmcs_clear(void *arg)
692 struct loaded_vmcs *loaded_vmcs = arg;
693 int cpu = raw_smp_processor_id();
695 if (loaded_vmcs->cpu != cpu)
696 return; /* vcpu migration can race with cpu offline */
697 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
698 per_cpu(current_vmcs, cpu) = NULL;
700 vmcs_clear(loaded_vmcs->vmcs);
701 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
702 vmcs_clear(loaded_vmcs->shadow_vmcs);
704 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
707 * Ensure all writes to loaded_vmcs, including deleting it from its
708 * current percpu list, complete before setting loaded_vmcs->cpu to
709 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
710 * and add loaded_vmcs to its percpu list before it's deleted from this
711 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
715 loaded_vmcs->cpu = -1;
716 loaded_vmcs->launched = 0;
719 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
721 int cpu = loaded_vmcs->cpu;
724 smp_call_function_single(cpu,
725 __loaded_vmcs_clear, loaded_vmcs, 1);
728 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
732 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
734 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
735 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
736 vmx->segment_cache.bitmask = 0;
738 ret = vmx->segment_cache.bitmask & mask;
739 vmx->segment_cache.bitmask |= mask;
743 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
745 u16 *p = &vmx->segment_cache.seg[seg].selector;
747 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
748 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
752 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
754 ulong *p = &vmx->segment_cache.seg[seg].base;
756 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
757 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
761 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
763 u32 *p = &vmx->segment_cache.seg[seg].limit;
765 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
766 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
770 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
772 u32 *p = &vmx->segment_cache.seg[seg].ar;
774 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
775 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
779 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
783 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
784 (1u << DB_VECTOR) | (1u << AC_VECTOR);
786 * Guest access to VMware backdoor ports could legitimately
787 * trigger #GP because of TSS I/O permission bitmap.
788 * We intercept those #GP and allow access to them anyway
791 if (enable_vmware_backdoor)
792 eb |= (1u << GP_VECTOR);
793 if ((vcpu->guest_debug &
794 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
795 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
796 eb |= 1u << BP_VECTOR;
797 if (to_vmx(vcpu)->rmode.vm86_active)
799 if (!vmx_need_pf_intercept(vcpu))
800 eb &= ~(1u << PF_VECTOR);
802 /* When we are running a nested L2 guest and L1 specified for it a
803 * certain exception bitmap, we must trap the same exceptions and pass
804 * them to L1. When running L2, we will only handle the exceptions
805 * specified above if L1 did not want them.
807 if (is_guest_mode(vcpu))
808 eb |= get_vmcs12(vcpu)->exception_bitmap;
810 int mask = 0, match = 0;
812 if (enable_ept && (eb & (1u << PF_VECTOR))) {
814 * If EPT is enabled, #PF is currently only intercepted
815 * if MAXPHYADDR is smaller on the guest than on the
816 * host. In that case we only care about present,
817 * non-reserved faults. For vmcs02, however, PFEC_MASK
818 * and PFEC_MATCH are set in prepare_vmcs02_rare.
820 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
821 match = PFERR_PRESENT_MASK;
823 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
824 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
828 * Disabling xfd interception indicates that dynamic xfeatures
829 * might be used in the guest. Always trap #NM in this case
830 * to save guest xfd_err timely.
832 if (vcpu->arch.xfd_no_write_intercept)
833 eb |= (1u << NM_VECTOR);
835 vmcs_write32(EXCEPTION_BITMAP, eb);
839 * Check if MSR is intercepted for currently loaded MSR bitmap.
841 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
843 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
846 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
849 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
851 unsigned int flags = 0;
853 if (vmx->loaded_vmcs->launched)
854 flags |= VMX_RUN_VMRESUME;
857 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
858 * to change it directly without causing a vmexit. In that case read
859 * it after vmexit and store it in vmx->spec_ctrl.
861 if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
862 flags |= VMX_RUN_SAVE_SPEC_CTRL;
867 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
868 unsigned long entry, unsigned long exit)
870 vm_entry_controls_clearbit(vmx, entry);
871 vm_exit_controls_clearbit(vmx, exit);
874 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
878 for (i = 0; i < m->nr; ++i) {
879 if (m->val[i].index == msr)
885 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
888 struct msr_autoload *m = &vmx->msr_autoload;
892 if (cpu_has_load_ia32_efer()) {
893 clear_atomic_switch_msr_special(vmx,
894 VM_ENTRY_LOAD_IA32_EFER,
895 VM_EXIT_LOAD_IA32_EFER);
899 case MSR_CORE_PERF_GLOBAL_CTRL:
900 if (cpu_has_load_perf_global_ctrl()) {
901 clear_atomic_switch_msr_special(vmx,
902 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
903 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
908 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
912 m->guest.val[i] = m->guest.val[m->guest.nr];
913 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
916 i = vmx_find_loadstore_msr_slot(&m->host, msr);
921 m->host.val[i] = m->host.val[m->host.nr];
922 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
925 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
926 unsigned long entry, unsigned long exit,
927 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
928 u64 guest_val, u64 host_val)
930 vmcs_write64(guest_val_vmcs, guest_val);
931 if (host_val_vmcs != HOST_IA32_EFER)
932 vmcs_write64(host_val_vmcs, host_val);
933 vm_entry_controls_setbit(vmx, entry);
934 vm_exit_controls_setbit(vmx, exit);
937 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
938 u64 guest_val, u64 host_val, bool entry_only)
941 struct msr_autoload *m = &vmx->msr_autoload;
945 if (cpu_has_load_ia32_efer()) {
946 add_atomic_switch_msr_special(vmx,
947 VM_ENTRY_LOAD_IA32_EFER,
948 VM_EXIT_LOAD_IA32_EFER,
951 guest_val, host_val);
955 case MSR_CORE_PERF_GLOBAL_CTRL:
956 if (cpu_has_load_perf_global_ctrl()) {
957 add_atomic_switch_msr_special(vmx,
958 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
959 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
960 GUEST_IA32_PERF_GLOBAL_CTRL,
961 HOST_IA32_PERF_GLOBAL_CTRL,
962 guest_val, host_val);
966 case MSR_IA32_PEBS_ENABLE:
967 /* PEBS needs a quiescent period after being disabled (to write
968 * a record). Disabling PEBS through VMX MSR swapping doesn't
969 * provide that period, so a CPU could write host's record into
972 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
975 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
977 j = vmx_find_loadstore_msr_slot(&m->host, msr);
979 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
980 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
981 printk_once(KERN_WARNING "Not enough msr switch entries. "
982 "Can't add msr %x\n", msr);
987 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
989 m->guest.val[i].index = msr;
990 m->guest.val[i].value = guest_val;
997 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
999 m->host.val[j].index = msr;
1000 m->host.val[j].value = host_val;
1003 static bool update_transition_efer(struct vcpu_vmx *vmx)
1005 u64 guest_efer = vmx->vcpu.arch.efer;
1006 u64 ignore_bits = 0;
1009 /* Shadow paging assumes NX to be available. */
1011 guest_efer |= EFER_NX;
1014 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1016 ignore_bits |= EFER_SCE;
1017 #ifdef CONFIG_X86_64
1018 ignore_bits |= EFER_LMA | EFER_LME;
1019 /* SCE is meaningful only in long mode on Intel */
1020 if (guest_efer & EFER_LMA)
1021 ignore_bits &= ~(u64)EFER_SCE;
1025 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1026 * On CPUs that support "load IA32_EFER", always switch EFER
1027 * atomically, since it's faster than switching it manually.
1029 if (cpu_has_load_ia32_efer() ||
1030 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1031 if (!(guest_efer & EFER_LMA))
1032 guest_efer &= ~EFER_LME;
1033 if (guest_efer != host_efer)
1034 add_atomic_switch_msr(vmx, MSR_EFER,
1035 guest_efer, host_efer, false);
1037 clear_atomic_switch_msr(vmx, MSR_EFER);
1041 i = kvm_find_user_return_msr(MSR_EFER);
1045 clear_atomic_switch_msr(vmx, MSR_EFER);
1047 guest_efer &= ~ignore_bits;
1048 guest_efer |= host_efer & ignore_bits;
1050 vmx->guest_uret_msrs[i].data = guest_efer;
1051 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1056 #ifdef CONFIG_X86_32
1058 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1059 * VMCS rather than the segment table. KVM uses this helper to figure
1060 * out the current bases to poke them into the VMCS before entry.
1062 static unsigned long segment_base(u16 selector)
1064 struct desc_struct *table;
1067 if (!(selector & ~SEGMENT_RPL_MASK))
1070 table = get_current_gdt_ro();
1072 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1073 u16 ldt_selector = kvm_read_ldt();
1075 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1078 table = (struct desc_struct *)segment_base(ldt_selector);
1080 v = get_desc_base(&table[selector >> 3]);
1085 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1087 return vmx_pt_mode_is_host_guest() &&
1088 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1091 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1093 /* The base must be 128-byte aligned and a legal physical address. */
1094 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1097 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1101 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1102 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1103 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1104 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1105 for (i = 0; i < addr_range; i++) {
1106 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1107 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1111 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1115 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1116 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1117 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1118 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1119 for (i = 0; i < addr_range; i++) {
1120 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1121 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1125 static void pt_guest_enter(struct vcpu_vmx *vmx)
1127 if (vmx_pt_mode_is_system())
1131 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1132 * Save host state before VM entry.
1134 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1135 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1136 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1137 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1138 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1142 static void pt_guest_exit(struct vcpu_vmx *vmx)
1144 if (vmx_pt_mode_is_system())
1147 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1148 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1149 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1153 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1154 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1156 if (vmx->pt_desc.host.ctl)
1157 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1160 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1161 unsigned long fs_base, unsigned long gs_base)
1163 if (unlikely(fs_sel != host->fs_sel)) {
1165 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1167 vmcs_write16(HOST_FS_SELECTOR, 0);
1168 host->fs_sel = fs_sel;
1170 if (unlikely(gs_sel != host->gs_sel)) {
1172 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1174 vmcs_write16(HOST_GS_SELECTOR, 0);
1175 host->gs_sel = gs_sel;
1177 if (unlikely(fs_base != host->fs_base)) {
1178 vmcs_writel(HOST_FS_BASE, fs_base);
1179 host->fs_base = fs_base;
1181 if (unlikely(gs_base != host->gs_base)) {
1182 vmcs_writel(HOST_GS_BASE, gs_base);
1183 host->gs_base = gs_base;
1187 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1189 struct vcpu_vmx *vmx = to_vmx(vcpu);
1190 struct vmcs_host_state *host_state;
1191 #ifdef CONFIG_X86_64
1192 int cpu = raw_smp_processor_id();
1194 unsigned long fs_base, gs_base;
1198 vmx->req_immediate_exit = false;
1201 * Note that guest MSRs to be saved/restored can also be changed
1202 * when guest state is loaded. This happens when guest transitions
1203 * to/from long-mode by setting MSR_EFER.LMA.
1205 if (!vmx->guest_uret_msrs_loaded) {
1206 vmx->guest_uret_msrs_loaded = true;
1207 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1208 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1211 kvm_set_user_return_msr(i,
1212 vmx->guest_uret_msrs[i].data,
1213 vmx->guest_uret_msrs[i].mask);
1217 if (vmx->nested.need_vmcs12_to_shadow_sync)
1218 nested_sync_vmcs12_to_shadow(vcpu);
1220 if (vmx->guest_state_loaded)
1223 host_state = &vmx->loaded_vmcs->host_state;
1226 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1227 * allow segment selectors with cpl > 0 or ti == 1.
1229 host_state->ldt_sel = kvm_read_ldt();
1231 #ifdef CONFIG_X86_64
1232 savesegment(ds, host_state->ds_sel);
1233 savesegment(es, host_state->es_sel);
1235 gs_base = cpu_kernelmode_gs_base(cpu);
1236 if (likely(is_64bit_mm(current->mm))) {
1237 current_save_fsgs();
1238 fs_sel = current->thread.fsindex;
1239 gs_sel = current->thread.gsindex;
1240 fs_base = current->thread.fsbase;
1241 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1243 savesegment(fs, fs_sel);
1244 savesegment(gs, gs_sel);
1245 fs_base = read_msr(MSR_FS_BASE);
1246 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1249 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1251 savesegment(fs, fs_sel);
1252 savesegment(gs, gs_sel);
1253 fs_base = segment_base(fs_sel);
1254 gs_base = segment_base(gs_sel);
1257 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1258 vmx->guest_state_loaded = true;
1261 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1263 struct vmcs_host_state *host_state;
1265 if (!vmx->guest_state_loaded)
1268 host_state = &vmx->loaded_vmcs->host_state;
1270 ++vmx->vcpu.stat.host_state_reload;
1272 #ifdef CONFIG_X86_64
1273 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1275 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1276 kvm_load_ldt(host_state->ldt_sel);
1277 #ifdef CONFIG_X86_64
1278 load_gs_index(host_state->gs_sel);
1280 loadsegment(gs, host_state->gs_sel);
1283 if (host_state->fs_sel & 7)
1284 loadsegment(fs, host_state->fs_sel);
1285 #ifdef CONFIG_X86_64
1286 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1287 loadsegment(ds, host_state->ds_sel);
1288 loadsegment(es, host_state->es_sel);
1291 invalidate_tss_limit();
1292 #ifdef CONFIG_X86_64
1293 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1295 load_fixmap_gdt(raw_smp_processor_id());
1296 vmx->guest_state_loaded = false;
1297 vmx->guest_uret_msrs_loaded = false;
1300 #ifdef CONFIG_X86_64
1301 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1304 if (vmx->guest_state_loaded)
1305 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1307 return vmx->msr_guest_kernel_gs_base;
1310 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1313 if (vmx->guest_state_loaded)
1314 wrmsrl(MSR_KERNEL_GS_BASE, data);
1316 vmx->msr_guest_kernel_gs_base = data;
1320 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1321 struct loaded_vmcs *buddy)
1323 struct vcpu_vmx *vmx = to_vmx(vcpu);
1324 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1327 if (!already_loaded) {
1328 loaded_vmcs_clear(vmx->loaded_vmcs);
1329 local_irq_disable();
1332 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1333 * this cpu's percpu list, otherwise it may not yet be deleted
1334 * from its previous cpu's percpu list. Pairs with the
1335 * smb_wmb() in __loaded_vmcs_clear().
1339 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1340 &per_cpu(loaded_vmcss_on_cpu, cpu));
1344 prev = per_cpu(current_vmcs, cpu);
1345 if (prev != vmx->loaded_vmcs->vmcs) {
1346 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1347 vmcs_load(vmx->loaded_vmcs->vmcs);
1350 * No indirect branch prediction barrier needed when switching
1351 * the active VMCS within a guest, e.g. on nested VM-Enter.
1352 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1354 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1355 indirect_branch_prediction_barrier();
1358 if (!already_loaded) {
1359 void *gdt = get_current_gdt_ro();
1362 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1363 * TLB entries from its previous association with the vCPU.
1365 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1368 * Linux uses per-cpu TSS and GDT, so set these when switching
1369 * processors. See 22.2.4.
1371 vmcs_writel(HOST_TR_BASE,
1372 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1373 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1375 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1377 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1378 (unsigned long)(cpu_entry_stack(cpu) + 1));
1381 vmx->loaded_vmcs->cpu = cpu;
1386 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1387 * vcpu mutex is already taken.
1389 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1391 struct vcpu_vmx *vmx = to_vmx(vcpu);
1393 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1395 vmx_vcpu_pi_load(vcpu, cpu);
1397 vmx->host_debugctlmsr = get_debugctlmsr();
1400 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1402 vmx_vcpu_pi_put(vcpu);
1404 vmx_prepare_switch_to_host(to_vmx(vcpu));
1407 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1409 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1412 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1414 struct vcpu_vmx *vmx = to_vmx(vcpu);
1415 unsigned long rflags, save_rflags;
1417 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1418 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1419 rflags = vmcs_readl(GUEST_RFLAGS);
1420 if (vmx->rmode.vm86_active) {
1421 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1422 save_rflags = vmx->rmode.save_rflags;
1423 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1425 vmx->rflags = rflags;
1430 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1432 struct vcpu_vmx *vmx = to_vmx(vcpu);
1433 unsigned long old_rflags;
1435 if (is_unrestricted_guest(vcpu)) {
1436 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1437 vmx->rflags = rflags;
1438 vmcs_writel(GUEST_RFLAGS, rflags);
1442 old_rflags = vmx_get_rflags(vcpu);
1443 vmx->rflags = rflags;
1444 if (vmx->rmode.vm86_active) {
1445 vmx->rmode.save_rflags = rflags;
1446 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1448 vmcs_writel(GUEST_RFLAGS, rflags);
1450 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1451 vmx->emulation_required = vmx_emulation_required(vcpu);
1454 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1456 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1459 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1461 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1464 if (interruptibility & GUEST_INTR_STATE_STI)
1465 ret |= KVM_X86_SHADOW_INT_STI;
1466 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1467 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1472 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1474 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1475 u32 interruptibility = interruptibility_old;
1477 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1479 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1480 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1481 else if (mask & KVM_X86_SHADOW_INT_STI)
1482 interruptibility |= GUEST_INTR_STATE_STI;
1484 if ((interruptibility != interruptibility_old))
1485 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1488 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1490 struct vcpu_vmx *vmx = to_vmx(vcpu);
1491 unsigned long value;
1494 * Any MSR write that attempts to change bits marked reserved will
1497 if (data & vmx->pt_desc.ctl_bitmask)
1501 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1502 * result in a #GP unless the same write also clears TraceEn.
1504 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1505 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1509 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1510 * and FabricEn would cause #GP, if
1511 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1513 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1514 !(data & RTIT_CTL_FABRIC_EN) &&
1515 !intel_pt_validate_cap(vmx->pt_desc.caps,
1516 PT_CAP_single_range_output))
1520 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1521 * utilize encodings marked reserved will cause a #GP fault.
1523 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1524 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1525 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1526 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1528 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1529 PT_CAP_cycle_thresholds);
1530 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1531 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1532 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1534 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1535 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1536 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1537 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1541 * If ADDRx_CFG is reserved or the encodings is >2 will
1542 * cause a #GP fault.
1544 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1545 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1547 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1548 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1550 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1551 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1553 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1554 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1560 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1561 void *insn, int insn_len)
1564 * Emulation of instructions in SGX enclaves is impossible as RIP does
1565 * not point at the failing instruction, and even if it did, the code
1566 * stream is inaccessible. Inject #UD instead of exiting to userspace
1567 * so that guest userspace can't DoS the guest simply by triggering
1568 * emulation (enclaves are CPL3 only).
1570 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1571 kvm_queue_exception(vcpu, UD_VECTOR);
1577 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1579 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1580 unsigned long rip, orig_rip;
1584 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1585 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1586 * set when EPT misconfig occurs. In practice, real hardware updates
1587 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1588 * (namely Hyper-V) don't set it due to it being undefined behavior,
1589 * i.e. we end up advancing IP with some random value.
1591 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1592 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1593 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1596 * Emulating an enclave's instructions isn't supported as KVM
1597 * cannot access the enclave's memory or its true RIP, e.g. the
1598 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1599 * the RIP that actually triggered the VM-Exit. But, because
1600 * most instructions that cause VM-Exit will #UD in an enclave,
1601 * most instruction-based VM-Exits simply do not occur.
1603 * There are a few exceptions, notably the debug instructions
1604 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1605 * and generate #DB/#BP as expected, which KVM might intercept.
1606 * But again, the CPU does the dirty work and saves an instr
1607 * length of zero so VMMs don't shoot themselves in the foot.
1608 * WARN if KVM tries to skip a non-zero length instruction on
1609 * a VM-Exit from an enclave.
1614 WARN(exit_reason.enclave_mode,
1615 "KVM: skipping instruction after SGX enclave VM-Exit");
1617 orig_rip = kvm_rip_read(vcpu);
1618 rip = orig_rip + instr_len;
1619 #ifdef CONFIG_X86_64
1621 * We need to mask out the high 32 bits of RIP if not in 64-bit
1622 * mode, but just finding out that we are in 64-bit mode is
1623 * quite expensive. Only do it if there was a carry.
1625 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1628 kvm_rip_write(vcpu, rip);
1630 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1635 /* skipping an emulated instruction also counts */
1636 vmx_set_interrupt_shadow(vcpu, 0);
1642 * Recognizes a pending MTF VM-exit and records the nested state for later
1645 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1647 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1648 struct vcpu_vmx *vmx = to_vmx(vcpu);
1650 if (!is_guest_mode(vcpu))
1654 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1655 * T-bit traps. As instruction emulation is completed (i.e. at the
1656 * instruction boundary), any #DB exception pending delivery must be a
1657 * debug-trap. Record the pending MTF state to be delivered in
1658 * vmx_check_nested_events().
1660 if (nested_cpu_has_mtf(vmcs12) &&
1661 (!vcpu->arch.exception.pending ||
1662 vcpu->arch.exception.nr == DB_VECTOR))
1663 vmx->nested.mtf_pending = true;
1665 vmx->nested.mtf_pending = false;
1668 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1670 vmx_update_emulated_instruction(vcpu);
1671 return skip_emulated_instruction(vcpu);
1674 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1677 * Ensure that we clear the HLT state in the VMCS. We don't need to
1678 * explicitly skip the instruction because if the HLT state is set,
1679 * then the instruction is already executing and RIP has already been
1682 if (kvm_hlt_in_guest(vcpu->kvm) &&
1683 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1684 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1687 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1689 struct vcpu_vmx *vmx = to_vmx(vcpu);
1690 unsigned nr = vcpu->arch.exception.nr;
1691 bool has_error_code = vcpu->arch.exception.has_error_code;
1692 u32 error_code = vcpu->arch.exception.error_code;
1693 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1695 kvm_deliver_exception_payload(vcpu);
1697 if (has_error_code) {
1699 * Despite the error code being architecturally defined as 32
1700 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1701 * VMX don't actually supporting setting bits 31:16. Hardware
1702 * will (should) never provide a bogus error code, but AMD CPUs
1703 * do generate error codes with bits 31:16 set, and so KVM's
1704 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1705 * the upper bits to avoid VM-Fail, losing information that
1706 * does't really exist is preferable to killing the VM.
1708 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code);
1709 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1712 if (vmx->rmode.vm86_active) {
1714 if (kvm_exception_is_soft(nr))
1715 inc_eip = vcpu->arch.event_exit_inst_len;
1716 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1720 WARN_ON_ONCE(vmx->emulation_required);
1722 if (kvm_exception_is_soft(nr)) {
1723 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1724 vmx->vcpu.arch.event_exit_inst_len);
1725 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1727 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1729 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1731 vmx_clear_hlt(vcpu);
1734 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1735 bool load_into_hardware)
1737 struct vmx_uret_msr *uret_msr;
1739 uret_msr = vmx_find_uret_msr(vmx, msr);
1743 uret_msr->load_into_hardware = load_into_hardware;
1747 * Configuring user return MSRs to automatically save, load, and restore MSRs
1748 * that need to be shoved into hardware when running the guest. Note, omitting
1749 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1750 * loaded into hardware when running the guest.
1752 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1754 #ifdef CONFIG_X86_64
1755 bool load_syscall_msrs;
1758 * The SYSCALL MSRs are only needed on long mode guests, and only
1759 * when EFER.SCE is set.
1761 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1762 (vmx->vcpu.arch.efer & EFER_SCE);
1764 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1765 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1766 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1768 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1770 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1771 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1772 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1775 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1776 * kernel and old userspace. If those guests run on a tsx=off host, do
1777 * allow guests to use TSX_CTRL, but don't change the value in hardware
1778 * so that TSX remains always disabled.
1780 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1783 * The set of MSRs to load may have changed, reload MSRs before the
1786 vmx->guest_uret_msrs_loaded = false;
1789 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1791 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1793 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1794 return vmcs12->tsc_offset;
1799 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1801 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1803 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1804 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1805 return vmcs12->tsc_multiplier;
1807 return kvm_caps.default_tsc_scaling_ratio;
1810 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1812 vmcs_write64(TSC_OFFSET, offset);
1815 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1817 vmcs_write64(TSC_MULTIPLIER, multiplier);
1821 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1822 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1823 * all guests if the "nested" module option is off, and can also be disabled
1824 * for a single guest by disabling its VMX cpuid bit.
1826 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1828 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1831 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1834 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1836 return !(val & ~valid_bits);
1839 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1841 switch (msr->index) {
1842 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1845 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1846 case MSR_IA32_PERF_CAPABILITIES:
1847 msr->data = vmx_get_perf_capabilities();
1850 return KVM_MSR_RET_INVALID;
1855 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1856 * Returns 0 on success, non-0 otherwise.
1857 * Assumes vcpu_load() was already called.
1859 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1861 struct vcpu_vmx *vmx = to_vmx(vcpu);
1862 struct vmx_uret_msr *msr;
1865 switch (msr_info->index) {
1866 #ifdef CONFIG_X86_64
1868 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1871 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1873 case MSR_KERNEL_GS_BASE:
1874 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1878 return kvm_get_msr_common(vcpu, msr_info);
1879 case MSR_IA32_TSX_CTRL:
1880 if (!msr_info->host_initiated &&
1881 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1884 case MSR_IA32_UMWAIT_CONTROL:
1885 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1888 msr_info->data = vmx->msr_ia32_umwait_control;
1890 case MSR_IA32_SPEC_CTRL:
1891 if (!msr_info->host_initiated &&
1892 !guest_has_spec_ctrl_msr(vcpu))
1895 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1897 case MSR_IA32_SYSENTER_CS:
1898 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1900 case MSR_IA32_SYSENTER_EIP:
1901 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1903 case MSR_IA32_SYSENTER_ESP:
1904 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1906 case MSR_IA32_BNDCFGS:
1907 if (!kvm_mpx_supported() ||
1908 (!msr_info->host_initiated &&
1909 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1911 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1913 case MSR_IA32_MCG_EXT_CTL:
1914 if (!msr_info->host_initiated &&
1915 !(vmx->msr_ia32_feature_control &
1916 FEAT_CTL_LMCE_ENABLED))
1918 msr_info->data = vcpu->arch.mcg_ext_ctl;
1920 case MSR_IA32_FEAT_CTL:
1921 msr_info->data = vmx->msr_ia32_feature_control;
1923 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1924 if (!msr_info->host_initiated &&
1925 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1927 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1928 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1930 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1931 if (!nested_vmx_allowed(vcpu))
1933 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1937 * Enlightened VMCS v1 doesn't have certain VMCS fields but
1938 * instead of just ignoring the features, different Hyper-V
1939 * versions are either trying to use them and fail or do some
1940 * sanity checking and refuse to boot. Filter all unsupported
1943 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
1944 nested_evmcs_filter_control_msr(vcpu, msr_info->index,
1947 case MSR_IA32_RTIT_CTL:
1948 if (!vmx_pt_mode_is_host_guest())
1950 msr_info->data = vmx->pt_desc.guest.ctl;
1952 case MSR_IA32_RTIT_STATUS:
1953 if (!vmx_pt_mode_is_host_guest())
1955 msr_info->data = vmx->pt_desc.guest.status;
1957 case MSR_IA32_RTIT_CR3_MATCH:
1958 if (!vmx_pt_mode_is_host_guest() ||
1959 !intel_pt_validate_cap(vmx->pt_desc.caps,
1960 PT_CAP_cr3_filtering))
1962 msr_info->data = vmx->pt_desc.guest.cr3_match;
1964 case MSR_IA32_RTIT_OUTPUT_BASE:
1965 if (!vmx_pt_mode_is_host_guest() ||
1966 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1967 PT_CAP_topa_output) &&
1968 !intel_pt_validate_cap(vmx->pt_desc.caps,
1969 PT_CAP_single_range_output)))
1971 msr_info->data = vmx->pt_desc.guest.output_base;
1973 case MSR_IA32_RTIT_OUTPUT_MASK:
1974 if (!vmx_pt_mode_is_host_guest() ||
1975 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1976 PT_CAP_topa_output) &&
1977 !intel_pt_validate_cap(vmx->pt_desc.caps,
1978 PT_CAP_single_range_output)))
1980 msr_info->data = vmx->pt_desc.guest.output_mask;
1982 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1983 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1984 if (!vmx_pt_mode_is_host_guest() ||
1985 (index >= 2 * vmx->pt_desc.num_address_ranges))
1988 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1990 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1992 case MSR_IA32_DEBUGCTLMSR:
1993 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1997 msr = vmx_find_uret_msr(vmx, msr_info->index);
1999 msr_info->data = msr->data;
2002 return kvm_get_msr_common(vcpu, msr_info);
2008 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2011 #ifdef CONFIG_X86_64
2012 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2015 return (unsigned long)data;
2018 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
2020 u64 debugctl = vmx_supported_debugctl();
2022 if (!intel_pmu_lbr_is_enabled(vcpu))
2023 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2025 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
2026 debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
2032 * Writes msr value into the appropriate "register".
2033 * Returns 0 on success, non-0 otherwise.
2034 * Assumes vcpu_load() was already called.
2036 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2038 struct vcpu_vmx *vmx = to_vmx(vcpu);
2039 struct vmx_uret_msr *msr;
2041 u32 msr_index = msr_info->index;
2042 u64 data = msr_info->data;
2045 switch (msr_index) {
2047 ret = kvm_set_msr_common(vcpu, msr_info);
2049 #ifdef CONFIG_X86_64
2051 vmx_segment_cache_clear(vmx);
2052 vmcs_writel(GUEST_FS_BASE, data);
2055 vmx_segment_cache_clear(vmx);
2056 vmcs_writel(GUEST_GS_BASE, data);
2058 case MSR_KERNEL_GS_BASE:
2059 vmx_write_guest_kernel_gs_base(vmx, data);
2062 ret = kvm_set_msr_common(vcpu, msr_info);
2064 * Always intercepting WRMSR could incur non-negligible
2065 * overhead given xfd might be changed frequently in
2066 * guest context switch. Disable write interception
2067 * upon the first write with a non-zero value (indicating
2068 * potential usage on dynamic xfeatures). Also update
2069 * exception bitmap to trap #NM for proper virtualization
2073 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2075 vcpu->arch.xfd_no_write_intercept = true;
2076 vmx_update_exception_bitmap(vcpu);
2080 case MSR_IA32_SYSENTER_CS:
2081 if (is_guest_mode(vcpu))
2082 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2083 vmcs_write32(GUEST_SYSENTER_CS, data);
2085 case MSR_IA32_SYSENTER_EIP:
2086 if (is_guest_mode(vcpu)) {
2087 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2088 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2090 vmcs_writel(GUEST_SYSENTER_EIP, data);
2092 case MSR_IA32_SYSENTER_ESP:
2093 if (is_guest_mode(vcpu)) {
2094 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2095 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2097 vmcs_writel(GUEST_SYSENTER_ESP, data);
2099 case MSR_IA32_DEBUGCTLMSR: {
2100 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2101 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2102 if (report_ignored_msrs)
2103 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2105 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2106 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2112 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2113 VM_EXIT_SAVE_DEBUG_CONTROLS)
2114 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2116 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2117 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2118 (data & DEBUGCTLMSR_LBR))
2119 intel_pmu_create_guest_lbr_event(vcpu);
2122 case MSR_IA32_BNDCFGS:
2123 if (!kvm_mpx_supported() ||
2124 (!msr_info->host_initiated &&
2125 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2127 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2128 (data & MSR_IA32_BNDCFGS_RSVD))
2131 if (is_guest_mode(vcpu) &&
2132 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2133 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2134 get_vmcs12(vcpu)->guest_bndcfgs = data;
2136 vmcs_write64(GUEST_BNDCFGS, data);
2138 case MSR_IA32_UMWAIT_CONTROL:
2139 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2142 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2143 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2146 vmx->msr_ia32_umwait_control = data;
2148 case MSR_IA32_SPEC_CTRL:
2149 if (!msr_info->host_initiated &&
2150 !guest_has_spec_ctrl_msr(vcpu))
2153 if (kvm_spec_ctrl_test_value(data))
2156 vmx->spec_ctrl = data;
2162 * When it's written (to non-zero) for the first time, pass
2166 * The handling of the MSR bitmap for L2 guests is done in
2167 * nested_vmx_prepare_msr_bitmap. We should not touch the
2168 * vmcs02.msr_bitmap here since it gets completely overwritten
2169 * in the merging. We update the vmcs01 here for L1 as well
2170 * since it will end up touching the MSR anyway now.
2172 vmx_disable_intercept_for_msr(vcpu,
2176 case MSR_IA32_TSX_CTRL:
2177 if (!msr_info->host_initiated &&
2178 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2180 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2183 case MSR_IA32_PRED_CMD:
2184 if (!msr_info->host_initiated &&
2185 !guest_has_pred_cmd_msr(vcpu))
2188 if (data & ~PRED_CMD_IBPB)
2190 if (!boot_cpu_has(X86_FEATURE_IBPB))
2195 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2199 * When it's written (to non-zero) for the first time, pass
2203 * The handling of the MSR bitmap for L2 guests is done in
2204 * nested_vmx_prepare_msr_bitmap. We should not touch the
2205 * vmcs02.msr_bitmap here since it gets completely overwritten
2208 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2210 case MSR_IA32_CR_PAT:
2211 if (!kvm_pat_valid(data))
2214 if (is_guest_mode(vcpu) &&
2215 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2216 get_vmcs12(vcpu)->guest_ia32_pat = data;
2218 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2219 vmcs_write64(GUEST_IA32_PAT, data);
2220 vcpu->arch.pat = data;
2223 ret = kvm_set_msr_common(vcpu, msr_info);
2225 case MSR_IA32_MCG_EXT_CTL:
2226 if ((!msr_info->host_initiated &&
2227 !(to_vmx(vcpu)->msr_ia32_feature_control &
2228 FEAT_CTL_LMCE_ENABLED)) ||
2229 (data & ~MCG_EXT_CTL_LMCE_EN))
2231 vcpu->arch.mcg_ext_ctl = data;
2233 case MSR_IA32_FEAT_CTL:
2234 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2235 (to_vmx(vcpu)->msr_ia32_feature_control &
2236 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2238 vmx->msr_ia32_feature_control = data;
2239 if (msr_info->host_initiated && data == 0)
2240 vmx_leave_nested(vcpu);
2242 /* SGX may be enabled/disabled by guest's firmware */
2243 vmx_write_encls_bitmap(vcpu, NULL);
2245 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2247 * On real hardware, the LE hash MSRs are writable before
2248 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2249 * at which point SGX related bits in IA32_FEATURE_CONTROL
2252 * KVM does not emulate SGX activation for simplicity, so
2253 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2254 * is unlocked. This is technically not architectural
2255 * behavior, but it's close enough.
2257 if (!msr_info->host_initiated &&
2258 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2259 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2260 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2262 vmx->msr_ia32_sgxlepubkeyhash
2263 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2265 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2266 if (!msr_info->host_initiated)
2267 return 1; /* they are read-only */
2268 if (!nested_vmx_allowed(vcpu))
2270 return vmx_set_vmx_msr(vcpu, msr_index, data);
2271 case MSR_IA32_RTIT_CTL:
2272 if (!vmx_pt_mode_is_host_guest() ||
2273 vmx_rtit_ctl_check(vcpu, data) ||
2276 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2277 vmx->pt_desc.guest.ctl = data;
2278 pt_update_intercept_for_msr(vcpu);
2280 case MSR_IA32_RTIT_STATUS:
2281 if (!pt_can_write_msr(vmx))
2283 if (data & MSR_IA32_RTIT_STATUS_MASK)
2285 vmx->pt_desc.guest.status = data;
2287 case MSR_IA32_RTIT_CR3_MATCH:
2288 if (!pt_can_write_msr(vmx))
2290 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2291 PT_CAP_cr3_filtering))
2293 vmx->pt_desc.guest.cr3_match = data;
2295 case MSR_IA32_RTIT_OUTPUT_BASE:
2296 if (!pt_can_write_msr(vmx))
2298 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2299 PT_CAP_topa_output) &&
2300 !intel_pt_validate_cap(vmx->pt_desc.caps,
2301 PT_CAP_single_range_output))
2303 if (!pt_output_base_valid(vcpu, data))
2305 vmx->pt_desc.guest.output_base = data;
2307 case MSR_IA32_RTIT_OUTPUT_MASK:
2308 if (!pt_can_write_msr(vmx))
2310 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2311 PT_CAP_topa_output) &&
2312 !intel_pt_validate_cap(vmx->pt_desc.caps,
2313 PT_CAP_single_range_output))
2315 vmx->pt_desc.guest.output_mask = data;
2317 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2318 if (!pt_can_write_msr(vmx))
2320 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2321 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2323 if (is_noncanonical_address(data, vcpu))
2326 vmx->pt_desc.guest.addr_b[index / 2] = data;
2328 vmx->pt_desc.guest.addr_a[index / 2] = data;
2330 case MSR_IA32_PERF_CAPABILITIES:
2331 if (data && !vcpu_to_pmu(vcpu)->version)
2333 if (data & PMU_CAP_LBR_FMT) {
2334 if ((data & PMU_CAP_LBR_FMT) !=
2335 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2337 if (!cpuid_model_is_consistent(vcpu))
2340 if (data & PERF_CAP_PEBS_FORMAT) {
2341 if ((data & PERF_CAP_PEBS_MASK) !=
2342 (vmx_get_perf_capabilities() & PERF_CAP_PEBS_MASK))
2344 if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2346 if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2348 if (!cpuid_model_is_consistent(vcpu))
2351 ret = kvm_set_msr_common(vcpu, msr_info);
2356 msr = vmx_find_uret_msr(vmx, msr_index);
2358 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2360 ret = kvm_set_msr_common(vcpu, msr_info);
2363 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2364 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2365 vmx_update_fb_clear_dis(vcpu, vmx);
2370 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2372 unsigned long guest_owned_bits;
2374 kvm_register_mark_available(vcpu, reg);
2378 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2381 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2383 case VCPU_EXREG_PDPTR:
2385 ept_save_pdptrs(vcpu);
2387 case VCPU_EXREG_CR0:
2388 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2390 vcpu->arch.cr0 &= ~guest_owned_bits;
2391 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2393 case VCPU_EXREG_CR3:
2395 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2396 * CR3 is loaded into hardware, not the guest's CR3.
2398 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2399 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2401 case VCPU_EXREG_CR4:
2402 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2404 vcpu->arch.cr4 &= ~guest_owned_bits;
2405 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2408 KVM_BUG_ON(1, vcpu->kvm);
2413 static __init int cpu_has_kvm_support(void)
2415 return cpu_has_vmx();
2418 static __init int vmx_disabled_by_bios(void)
2420 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2421 !boot_cpu_has(X86_FEATURE_VMX);
2424 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2428 cr4_set_bits(X86_CR4_VMXE);
2430 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2431 _ASM_EXTABLE(1b, %l[fault])
2432 : : [vmxon_pointer] "m"(vmxon_pointer)
2437 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2438 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2439 cr4_clear_bits(X86_CR4_VMXE);
2444 static int vmx_hardware_enable(void)
2446 int cpu = raw_smp_processor_id();
2447 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2450 if (cr4_read_shadow() & X86_CR4_VMXE)
2454 * This can happen if we hot-added a CPU but failed to allocate
2455 * VP assist page for it.
2457 if (static_branch_unlikely(&enable_evmcs) &&
2458 !hv_get_vp_assist_page(cpu))
2461 intel_pt_handle_vmx(1);
2463 r = kvm_cpu_vmxon(phys_addr);
2465 intel_pt_handle_vmx(0);
2475 static void vmclear_local_loaded_vmcss(void)
2477 int cpu = raw_smp_processor_id();
2478 struct loaded_vmcs *v, *n;
2480 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2481 loaded_vmcss_on_cpu_link)
2482 __loaded_vmcs_clear(v);
2485 static void vmx_hardware_disable(void)
2487 vmclear_local_loaded_vmcss();
2490 kvm_spurious_fault();
2492 intel_pt_handle_vmx(0);
2496 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2497 * directly instead of going through cpu_has(), to ensure KVM is trapping
2498 * ENCLS whenever it's supported in hardware. It does not matter whether
2499 * the host OS supports or has enabled SGX.
2501 static bool cpu_has_sgx(void)
2503 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2507 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2508 * can't be used due to errata where VM Exit may incorrectly clear
2509 * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2510 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2512 static bool cpu_has_perf_global_ctrl_bug(void)
2514 if (boot_cpu_data.x86 == 0x6) {
2515 switch (boot_cpu_data.x86_model) {
2516 case INTEL_FAM6_NEHALEM_EP: /* AAK155 */
2517 case INTEL_FAM6_NEHALEM: /* AAP115 */
2518 case INTEL_FAM6_WESTMERE: /* AAT100 */
2519 case INTEL_FAM6_WESTMERE_EP: /* BC86,AAY89,BD102 */
2520 case INTEL_FAM6_NEHALEM_EX: /* BA97 */
2530 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2531 u32 msr, u32 *result)
2533 u32 vmx_msr_low, vmx_msr_high;
2534 u32 ctl = ctl_min | ctl_opt;
2536 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2538 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2539 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2541 /* Ensure minimum (required) set of control bits are supported. */
2549 static __init u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2553 rdmsrl(msr, allowed);
2555 return ctl_opt & allowed;
2558 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2559 struct vmx_capability *vmx_cap)
2561 u32 vmx_msr_low, vmx_msr_high;
2562 u32 _pin_based_exec_control = 0;
2563 u32 _cpu_based_exec_control = 0;
2564 u32 _cpu_based_2nd_exec_control = 0;
2565 u64 _cpu_based_3rd_exec_control = 0;
2566 u32 _vmexit_control = 0;
2567 u32 _vmentry_control = 0;
2572 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2573 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2574 * intercepts writes to PAT and EFER, i.e. never enables those controls.
2579 } const vmcs_entry_exit_pairs[] = {
2580 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2581 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
2582 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
2583 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
2584 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
2587 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2589 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2590 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2591 MSR_IA32_VMX_PROCBASED_CTLS,
2592 &_cpu_based_exec_control))
2594 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2595 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2596 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2597 MSR_IA32_VMX_PROCBASED_CTLS2,
2598 &_cpu_based_2nd_exec_control))
2601 #ifndef CONFIG_X86_64
2602 if (!(_cpu_based_2nd_exec_control &
2603 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2604 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2607 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2608 _cpu_based_2nd_exec_control &= ~(
2609 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2610 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2611 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2613 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2614 &vmx_cap->ept, &vmx_cap->vpid);
2616 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2618 pr_warn_once("EPT CAP should not exist if not support "
2619 "1-setting enable EPT VM-execution control\n");
2621 if (error_on_inconsistent_vmcs_config)
2626 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2628 pr_warn_once("VPID CAP should not exist if not support "
2629 "1-setting enable VPID VM-execution control\n");
2631 if (error_on_inconsistent_vmcs_config)
2638 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2640 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2641 _cpu_based_3rd_exec_control =
2642 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2643 MSR_IA32_VMX_PROCBASED_CTLS3);
2645 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2646 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2647 MSR_IA32_VMX_EXIT_CTLS,
2651 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2652 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2653 MSR_IA32_VMX_PINBASED_CTLS,
2654 &_pin_based_exec_control))
2657 if (cpu_has_broken_vmx_preemption_timer())
2658 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2659 if (!(_cpu_based_2nd_exec_control &
2660 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2661 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2663 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2664 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2665 MSR_IA32_VMX_ENTRY_CTLS,
2669 for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2670 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2671 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2673 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2676 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2677 _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2679 if (error_on_inconsistent_vmcs_config)
2682 _vmentry_control &= ~n_ctrl;
2683 _vmexit_control &= ~x_ctrl;
2686 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2688 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2689 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2692 #ifdef CONFIG_X86_64
2693 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2694 if (vmx_msr_high & (1u<<16))
2698 /* Require Write-Back (WB) memory type for VMCS accesses. */
2699 if (((vmx_msr_high >> 18) & 15) != 6)
2702 rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2704 vmcs_conf->size = vmx_msr_high & 0x1fff;
2705 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2707 vmcs_conf->revision_id = vmx_msr_low;
2709 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2710 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2711 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2712 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2713 vmcs_conf->vmexit_ctrl = _vmexit_control;
2714 vmcs_conf->vmentry_ctrl = _vmentry_control;
2715 vmcs_conf->misc = misc_msr;
2720 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2722 int node = cpu_to_node(cpu);
2726 pages = __alloc_pages_node(node, flags, 0);
2729 vmcs = page_address(pages);
2730 memset(vmcs, 0, vmcs_config.size);
2732 /* KVM supports Enlightened VMCS v1 only */
2733 if (static_branch_unlikely(&enable_evmcs))
2734 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2736 vmcs->hdr.revision_id = vmcs_config.revision_id;
2739 vmcs->hdr.shadow_vmcs = 1;
2743 void free_vmcs(struct vmcs *vmcs)
2745 free_page((unsigned long)vmcs);
2749 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2751 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2753 if (!loaded_vmcs->vmcs)
2755 loaded_vmcs_clear(loaded_vmcs);
2756 free_vmcs(loaded_vmcs->vmcs);
2757 loaded_vmcs->vmcs = NULL;
2758 if (loaded_vmcs->msr_bitmap)
2759 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2760 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2763 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2765 loaded_vmcs->vmcs = alloc_vmcs(false);
2766 if (!loaded_vmcs->vmcs)
2769 vmcs_clear(loaded_vmcs->vmcs);
2771 loaded_vmcs->shadow_vmcs = NULL;
2772 loaded_vmcs->hv_timer_soft_disabled = false;
2773 loaded_vmcs->cpu = -1;
2774 loaded_vmcs->launched = 0;
2776 if (cpu_has_vmx_msr_bitmap()) {
2777 loaded_vmcs->msr_bitmap = (unsigned long *)
2778 __get_free_page(GFP_KERNEL_ACCOUNT);
2779 if (!loaded_vmcs->msr_bitmap)
2781 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2784 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2785 memset(&loaded_vmcs->controls_shadow, 0,
2786 sizeof(struct vmcs_controls_shadow));
2791 free_loaded_vmcs(loaded_vmcs);
2795 static void free_kvm_area(void)
2799 for_each_possible_cpu(cpu) {
2800 free_vmcs(per_cpu(vmxarea, cpu));
2801 per_cpu(vmxarea, cpu) = NULL;
2805 static __init int alloc_kvm_area(void)
2809 for_each_possible_cpu(cpu) {
2812 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2819 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2820 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2821 * revision_id reported by MSR_IA32_VMX_BASIC.
2823 * However, even though not explicitly documented by
2824 * TLFS, VMXArea passed as VMXON argument should
2825 * still be marked with revision_id reported by
2828 if (static_branch_unlikely(&enable_evmcs))
2829 vmcs->hdr.revision_id = vmcs_config.revision_id;
2831 per_cpu(vmxarea, cpu) = vmcs;
2836 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2837 struct kvm_segment *save)
2839 if (!emulate_invalid_guest_state) {
2841 * CS and SS RPL should be equal during guest entry according
2842 * to VMX spec, but in reality it is not always so. Since vcpu
2843 * is in the middle of the transition from real mode to
2844 * protected mode it is safe to assume that RPL 0 is a good
2847 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2848 save->selector &= ~SEGMENT_RPL_MASK;
2849 save->dpl = save->selector & SEGMENT_RPL_MASK;
2852 __vmx_set_segment(vcpu, save, seg);
2855 static void enter_pmode(struct kvm_vcpu *vcpu)
2857 unsigned long flags;
2858 struct vcpu_vmx *vmx = to_vmx(vcpu);
2861 * Update real mode segment cache. It may be not up-to-date if segment
2862 * register was written while vcpu was in a guest mode.
2864 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2865 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2866 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2867 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2868 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2869 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2871 vmx->rmode.vm86_active = 0;
2873 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2875 flags = vmcs_readl(GUEST_RFLAGS);
2876 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2877 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2878 vmcs_writel(GUEST_RFLAGS, flags);
2880 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2881 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2883 vmx_update_exception_bitmap(vcpu);
2885 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2886 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2887 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2888 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2889 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2890 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2893 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2895 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2896 struct kvm_segment var = *save;
2899 if (seg == VCPU_SREG_CS)
2902 if (!emulate_invalid_guest_state) {
2903 var.selector = var.base >> 4;
2904 var.base = var.base & 0xffff0;
2914 if (save->base & 0xf)
2915 printk_once(KERN_WARNING "kvm: segment base is not "
2916 "paragraph aligned when entering "
2917 "protected mode (seg=%d)", seg);
2920 vmcs_write16(sf->selector, var.selector);
2921 vmcs_writel(sf->base, var.base);
2922 vmcs_write32(sf->limit, var.limit);
2923 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2926 static void enter_rmode(struct kvm_vcpu *vcpu)
2928 unsigned long flags;
2929 struct vcpu_vmx *vmx = to_vmx(vcpu);
2930 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2932 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2933 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2934 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2935 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2936 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2937 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2938 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2940 vmx->rmode.vm86_active = 1;
2943 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2944 * vcpu. Warn the user that an update is overdue.
2946 if (!kvm_vmx->tss_addr)
2947 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2948 "called before entering vcpu\n");
2950 vmx_segment_cache_clear(vmx);
2952 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2953 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2954 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2956 flags = vmcs_readl(GUEST_RFLAGS);
2957 vmx->rmode.save_rflags = flags;
2959 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2961 vmcs_writel(GUEST_RFLAGS, flags);
2962 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2963 vmx_update_exception_bitmap(vcpu);
2965 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2966 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2967 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2968 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2969 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2970 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2973 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2975 struct vcpu_vmx *vmx = to_vmx(vcpu);
2977 /* Nothing to do if hardware doesn't support EFER. */
2978 if (!vmx_find_uret_msr(vmx, MSR_EFER))
2981 vcpu->arch.efer = efer;
2982 #ifdef CONFIG_X86_64
2983 if (efer & EFER_LMA)
2984 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
2986 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
2988 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
2992 vmx_setup_uret_msrs(vmx);
2996 #ifdef CONFIG_X86_64
2998 static void enter_lmode(struct kvm_vcpu *vcpu)
3002 vmx_segment_cache_clear(to_vmx(vcpu));
3004 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3005 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3006 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3008 vmcs_write32(GUEST_TR_AR_BYTES,
3009 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3010 | VMX_AR_TYPE_BUSY_64_TSS);
3012 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3015 static void exit_lmode(struct kvm_vcpu *vcpu)
3017 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3022 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3024 struct vcpu_vmx *vmx = to_vmx(vcpu);
3027 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3028 * the CPU is not required to invalidate guest-physical mappings on
3029 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3030 * associated with the root EPT structure and not any particular VPID
3031 * (INVVPID also isn't required to invalidate guest-physical mappings).
3035 } else if (enable_vpid) {
3036 if (cpu_has_vmx_invvpid_global()) {
3037 vpid_sync_vcpu_global();
3039 vpid_sync_vcpu_single(vmx->vpid);
3040 vpid_sync_vcpu_single(vmx->nested.vpid02);
3045 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3047 if (is_guest_mode(vcpu))
3048 return nested_get_vpid02(vcpu);
3049 return to_vmx(vcpu)->vpid;
3052 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3054 struct kvm_mmu *mmu = vcpu->arch.mmu;
3055 u64 root_hpa = mmu->root.hpa;
3057 /* No flush required if the current context is invalid. */
3058 if (!VALID_PAGE(root_hpa))
3062 ept_sync_context(construct_eptp(vcpu, root_hpa,
3063 mmu->root_role.level));
3065 vpid_sync_context(vmx_get_current_vpid(vcpu));
3068 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3071 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3072 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3074 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3077 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3080 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3081 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3082 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3083 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3084 * i.e. no explicit INVVPID is necessary.
3086 vpid_sync_context(vmx_get_current_vpid(vcpu));
3089 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3091 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3093 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3096 if (is_pae_paging(vcpu)) {
3097 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3098 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3099 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3100 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3104 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3106 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3108 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3111 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3112 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3113 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3114 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3116 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3119 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3120 CPU_BASED_CR3_STORE_EXITING)
3122 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3124 struct vcpu_vmx *vmx = to_vmx(vcpu);
3125 unsigned long hw_cr0, old_cr0_pg;
3128 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3130 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3131 if (is_unrestricted_guest(vcpu))
3132 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3134 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3136 hw_cr0 |= X86_CR0_WP;
3138 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3141 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3145 vmcs_writel(CR0_READ_SHADOW, cr0);
3146 vmcs_writel(GUEST_CR0, hw_cr0);
3147 vcpu->arch.cr0 = cr0;
3148 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3150 #ifdef CONFIG_X86_64
3151 if (vcpu->arch.efer & EFER_LME) {
3152 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3154 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3159 if (enable_ept && !is_unrestricted_guest(vcpu)) {
3161 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3162 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3163 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3164 * KVM's CR3 is installed.
3166 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3167 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3170 * When running with EPT but not unrestricted guest, KVM must
3171 * intercept CR3 accesses when paging is _disabled_. This is
3172 * necessary because restricted guests can't actually run with
3173 * paging disabled, and so KVM stuffs its own CR3 in order to
3174 * run the guest when identity mapped page tables.
3176 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3177 * update, it may be stale with respect to CR3 interception,
3178 * e.g. after nested VM-Enter.
3180 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3181 * stores to forward them to L1, even if KVM does not need to
3182 * intercept them to preserve its identity mapped page tables.
3184 if (!(cr0 & X86_CR0_PG)) {
3185 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3186 } else if (!is_guest_mode(vcpu)) {
3187 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3189 tmp = exec_controls_get(vmx);
3190 tmp &= ~CR3_EXITING_BITS;
3191 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3192 exec_controls_set(vmx, tmp);
3195 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3196 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3197 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3200 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3201 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3203 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3204 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3207 /* depends on vcpu->arch.cr0 to be set to a new value */
3208 vmx->emulation_required = vmx_emulation_required(vcpu);
3211 static int vmx_get_max_tdp_level(void)
3213 if (cpu_has_vmx_ept_5levels())
3218 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3220 u64 eptp = VMX_EPTP_MT_WB;
3222 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3224 if (enable_ept_ad_bits &&
3225 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3226 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3232 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3235 struct kvm *kvm = vcpu->kvm;
3236 bool update_guest_cr3 = true;
3237 unsigned long guest_cr3;
3241 eptp = construct_eptp(vcpu, root_hpa, root_level);
3242 vmcs_write64(EPT_POINTER, eptp);
3244 hv_track_root_tdp(vcpu, root_hpa);
3246 if (!enable_unrestricted_guest && !is_paging(vcpu))
3247 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3248 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3249 guest_cr3 = vcpu->arch.cr3;
3250 else /* vmcs.GUEST_CR3 is already up-to-date. */
3251 update_guest_cr3 = false;
3252 vmx_ept_load_pdptrs(vcpu);
3254 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3257 if (update_guest_cr3)
3258 vmcs_writel(GUEST_CR3, guest_cr3);
3262 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3265 * We operate under the default treatment of SMM, so VMX cannot be
3266 * enabled under SMM. Note, whether or not VMXE is allowed at all,
3267 * i.e. is a reserved bit, is handled by common x86 code.
3269 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3272 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3278 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3280 unsigned long old_cr4 = vcpu->arch.cr4;
3281 struct vcpu_vmx *vmx = to_vmx(vcpu);
3283 * Pass through host's Machine Check Enable value to hw_cr4, which
3284 * is in force while we are in guest mode. Do not let guests control
3285 * this bit, even if host CR4.MCE == 0.
3287 unsigned long hw_cr4;
3289 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3290 if (is_unrestricted_guest(vcpu))
3291 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3292 else if (vmx->rmode.vm86_active)
3293 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3295 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3297 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3298 if (cr4 & X86_CR4_UMIP) {
3299 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3300 hw_cr4 &= ~X86_CR4_UMIP;
3301 } else if (!is_guest_mode(vcpu) ||
3302 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3303 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3307 vcpu->arch.cr4 = cr4;
3308 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3310 if (!is_unrestricted_guest(vcpu)) {
3312 if (!is_paging(vcpu)) {
3313 hw_cr4 &= ~X86_CR4_PAE;
3314 hw_cr4 |= X86_CR4_PSE;
3315 } else if (!(cr4 & X86_CR4_PAE)) {
3316 hw_cr4 &= ~X86_CR4_PAE;
3321 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3322 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3323 * to be manually disabled when guest switches to non-paging
3326 * If !enable_unrestricted_guest, the CPU is always running
3327 * with CR0.PG=1 and CR4 needs to be modified.
3328 * If enable_unrestricted_guest, the CPU automatically
3329 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3331 if (!is_paging(vcpu))
3332 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3335 vmcs_writel(CR4_READ_SHADOW, cr4);
3336 vmcs_writel(GUEST_CR4, hw_cr4);
3338 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3339 kvm_update_cpuid_runtime(vcpu);
3342 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3344 struct vcpu_vmx *vmx = to_vmx(vcpu);
3347 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3348 *var = vmx->rmode.segs[seg];
3349 if (seg == VCPU_SREG_TR
3350 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3352 var->base = vmx_read_guest_seg_base(vmx, seg);
3353 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3356 var->base = vmx_read_guest_seg_base(vmx, seg);
3357 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3358 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3359 ar = vmx_read_guest_seg_ar(vmx, seg);
3360 var->unusable = (ar >> 16) & 1;
3361 var->type = ar & 15;
3362 var->s = (ar >> 4) & 1;
3363 var->dpl = (ar >> 5) & 3;
3365 * Some userspaces do not preserve unusable property. Since usable
3366 * segment has to be present according to VMX spec we can use present
3367 * property to amend userspace bug by making unusable segment always
3368 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3369 * segment as unusable.
3371 var->present = !var->unusable;
3372 var->avl = (ar >> 12) & 1;
3373 var->l = (ar >> 13) & 1;
3374 var->db = (ar >> 14) & 1;
3375 var->g = (ar >> 15) & 1;
3378 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3380 struct kvm_segment s;
3382 if (to_vmx(vcpu)->rmode.vm86_active) {
3383 vmx_get_segment(vcpu, &s, seg);
3386 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3389 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3391 struct vcpu_vmx *vmx = to_vmx(vcpu);
3393 if (unlikely(vmx->rmode.vm86_active))
3396 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3397 return VMX_AR_DPL(ar);
3401 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3405 if (var->unusable || !var->present)
3408 ar = var->type & 15;
3409 ar |= (var->s & 1) << 4;
3410 ar |= (var->dpl & 3) << 5;
3411 ar |= (var->present & 1) << 7;
3412 ar |= (var->avl & 1) << 12;
3413 ar |= (var->l & 1) << 13;
3414 ar |= (var->db & 1) << 14;
3415 ar |= (var->g & 1) << 15;
3421 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3423 struct vcpu_vmx *vmx = to_vmx(vcpu);
3424 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3426 vmx_segment_cache_clear(vmx);
3428 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3429 vmx->rmode.segs[seg] = *var;
3430 if (seg == VCPU_SREG_TR)
3431 vmcs_write16(sf->selector, var->selector);
3433 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3437 vmcs_writel(sf->base, var->base);
3438 vmcs_write32(sf->limit, var->limit);
3439 vmcs_write16(sf->selector, var->selector);
3442 * Fix the "Accessed" bit in AR field of segment registers for older
3444 * IA32 arch specifies that at the time of processor reset the
3445 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3446 * is setting it to 0 in the userland code. This causes invalid guest
3447 * state vmexit when "unrestricted guest" mode is turned on.
3448 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3449 * tree. Newer qemu binaries with that qemu fix would not need this
3452 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3453 var->type |= 0x1; /* Accessed */
3455 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3458 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3460 __vmx_set_segment(vcpu, var, seg);
3462 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3465 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3467 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3469 *db = (ar >> 14) & 1;
3470 *l = (ar >> 13) & 1;
3473 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3475 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3476 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3479 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3481 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3482 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3485 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3487 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3488 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3491 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3493 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3494 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3497 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3499 struct kvm_segment var;
3502 vmx_get_segment(vcpu, &var, seg);
3504 if (seg == VCPU_SREG_CS)
3506 ar = vmx_segment_access_rights(&var);
3508 if (var.base != (var.selector << 4))
3510 if (var.limit != 0xffff)
3518 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3520 struct kvm_segment cs;
3521 unsigned int cs_rpl;
3523 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3524 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3528 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3532 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3533 if (cs.dpl > cs_rpl)
3536 if (cs.dpl != cs_rpl)
3542 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3546 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3548 struct kvm_segment ss;
3549 unsigned int ss_rpl;
3551 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3552 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3556 if (ss.type != 3 && ss.type != 7)
3560 if (ss.dpl != ss_rpl) /* DPL != RPL */
3568 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3570 struct kvm_segment var;
3573 vmx_get_segment(vcpu, &var, seg);
3574 rpl = var.selector & SEGMENT_RPL_MASK;
3582 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3583 if (var.dpl < rpl) /* DPL < RPL */
3587 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3593 static bool tr_valid(struct kvm_vcpu *vcpu)
3595 struct kvm_segment tr;
3597 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3601 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3603 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3611 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3613 struct kvm_segment ldtr;
3615 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3619 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3629 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3631 struct kvm_segment cs, ss;
3633 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3634 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3636 return ((cs.selector & SEGMENT_RPL_MASK) ==
3637 (ss.selector & SEGMENT_RPL_MASK));
3641 * Check if guest state is valid. Returns true if valid, false if
3643 * We assume that registers are always usable
3645 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3647 /* real mode guest state checks */
3648 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3649 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3651 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3653 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3655 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3657 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3659 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3662 /* protected mode guest state checks */
3663 if (!cs_ss_rpl_check(vcpu))
3665 if (!code_segment_valid(vcpu))
3667 if (!stack_segment_valid(vcpu))
3669 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3671 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3673 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3675 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3677 if (!tr_valid(vcpu))
3679 if (!ldtr_valid(vcpu))
3683 * - Add checks on RIP
3684 * - Add checks on RFLAGS
3690 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3692 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3696 for (i = 0; i < 3; i++) {
3697 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3701 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3702 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3706 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3712 static int init_rmode_identity_map(struct kvm *kvm)
3714 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3719 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3720 mutex_lock(&kvm->slots_lock);
3722 if (likely(kvm_vmx->ept_identity_pagetable_done))
3725 if (!kvm_vmx->ept_identity_map_addr)
3726 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3728 uaddr = __x86_set_memory_region(kvm,
3729 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3730 kvm_vmx->ept_identity_map_addr,
3732 if (IS_ERR(uaddr)) {
3737 /* Set up identity-mapping pagetable for EPT in real mode */
3738 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3739 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3740 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3741 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3746 kvm_vmx->ept_identity_pagetable_done = true;
3749 mutex_unlock(&kvm->slots_lock);
3753 static void seg_setup(int seg)
3755 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3758 vmcs_write16(sf->selector, 0);
3759 vmcs_writel(sf->base, 0);
3760 vmcs_write32(sf->limit, 0xffff);
3762 if (seg == VCPU_SREG_CS)
3763 ar |= 0x08; /* code segment */
3765 vmcs_write32(sf->ar_bytes, ar);
3768 static int alloc_apic_access_page(struct kvm *kvm)
3774 mutex_lock(&kvm->slots_lock);
3775 if (kvm->arch.apic_access_memslot_enabled)
3777 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3778 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3784 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3785 if (is_error_page(page)) {
3791 * Do not pin the page in memory, so that memory hot-unplug
3792 * is able to migrate it.
3795 kvm->arch.apic_access_memslot_enabled = true;
3797 mutex_unlock(&kvm->slots_lock);
3801 int allocate_vpid(void)
3807 spin_lock(&vmx_vpid_lock);
3808 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3809 if (vpid < VMX_NR_VPIDS)
3810 __set_bit(vpid, vmx_vpid_bitmap);
3813 spin_unlock(&vmx_vpid_lock);
3817 void free_vpid(int vpid)
3819 if (!enable_vpid || vpid == 0)
3821 spin_lock(&vmx_vpid_lock);
3822 __clear_bit(vpid, vmx_vpid_bitmap);
3823 spin_unlock(&vmx_vpid_lock);
3826 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3829 * When KVM is a nested hypervisor on top of Hyper-V and uses
3830 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3831 * bitmap has changed.
3833 if (static_branch_unlikely(&enable_evmcs))
3834 evmcs_touch_msr_bitmap();
3836 vmx->nested.force_msr_bitmap_recalc = true;
3839 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3841 struct vcpu_vmx *vmx = to_vmx(vcpu);
3842 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3844 if (!cpu_has_vmx_msr_bitmap())
3847 vmx_msr_bitmap_l01_changed(vmx);
3850 * Mark the desired intercept state in shadow bitmap, this is needed
3851 * for resync when the MSR filters change.
3853 if (is_valid_passthrough_msr(msr)) {
3854 int idx = possible_passthrough_msr_slot(msr);
3856 if (idx != -ENOENT) {
3857 if (type & MSR_TYPE_R)
3858 clear_bit(idx, vmx->shadow_msr_intercept.read);
3859 if (type & MSR_TYPE_W)
3860 clear_bit(idx, vmx->shadow_msr_intercept.write);
3864 if ((type & MSR_TYPE_R) &&
3865 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3866 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3867 type &= ~MSR_TYPE_R;
3870 if ((type & MSR_TYPE_W) &&
3871 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3872 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3873 type &= ~MSR_TYPE_W;
3876 if (type & MSR_TYPE_R)
3877 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3879 if (type & MSR_TYPE_W)
3880 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3883 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3885 struct vcpu_vmx *vmx = to_vmx(vcpu);
3886 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3888 if (!cpu_has_vmx_msr_bitmap())
3891 vmx_msr_bitmap_l01_changed(vmx);
3894 * Mark the desired intercept state in shadow bitmap, this is needed
3895 * for resync when the MSR filter changes.
3897 if (is_valid_passthrough_msr(msr)) {
3898 int idx = possible_passthrough_msr_slot(msr);
3900 if (idx != -ENOENT) {
3901 if (type & MSR_TYPE_R)
3902 set_bit(idx, vmx->shadow_msr_intercept.read);
3903 if (type & MSR_TYPE_W)
3904 set_bit(idx, vmx->shadow_msr_intercept.write);
3908 if (type & MSR_TYPE_R)
3909 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3911 if (type & MSR_TYPE_W)
3912 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3915 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3917 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3918 unsigned long read_intercept;
3921 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3923 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3924 unsigned int read_idx = msr / BITS_PER_LONG;
3925 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3927 msr_bitmap[read_idx] = read_intercept;
3928 msr_bitmap[write_idx] = ~0ul;
3932 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
3934 struct vcpu_vmx *vmx = to_vmx(vcpu);
3937 if (!cpu_has_vmx_msr_bitmap())
3940 if (cpu_has_secondary_exec_ctrls() &&
3941 (secondary_exec_controls_get(vmx) &
3942 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3943 mode = MSR_BITMAP_MODE_X2APIC;
3944 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3945 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3950 if (mode == vmx->x2apic_msr_bitmap_mode)
3953 vmx->x2apic_msr_bitmap_mode = mode;
3955 vmx_reset_x2apic_msrs(vcpu, mode);
3958 * TPR reads and writes can be virtualized even if virtual interrupt
3959 * delivery is not in use.
3961 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3962 !(mode & MSR_BITMAP_MODE_X2APIC));
3964 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3965 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3966 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3967 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3969 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
3973 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3975 struct vcpu_vmx *vmx = to_vmx(vcpu);
3976 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3979 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3980 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3981 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3982 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3983 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
3984 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3985 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3989 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3991 struct vcpu_vmx *vmx = to_vmx(vcpu);
3996 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3997 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3998 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
4001 rvi = vmx_get_rvi();
4003 vapic_page = vmx->nested.virtual_apic_map.hva;
4004 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4006 return ((rvi & 0xf0) > (vppr & 0xf0));
4009 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4011 struct vcpu_vmx *vmx = to_vmx(vcpu);
4015 * Redo intercept permissions for MSRs that KVM is passing through to
4016 * the guest. Disabling interception will check the new MSR filter and
4017 * ensure that KVM enables interception if usersepace wants to filter
4018 * the MSR. MSRs that KVM is already intercepting don't need to be
4019 * refreshed since KVM is going to intercept them regardless of what
4022 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4023 u32 msr = vmx_possible_passthrough_msrs[i];
4025 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4026 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4028 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4029 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4032 /* PT MSRs can be passed through iff PT is exposed to the guest. */
4033 if (vmx_pt_mode_is_host_guest())
4034 pt_update_intercept_for_msr(vcpu);
4037 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4041 if (vcpu->mode == IN_GUEST_MODE) {
4043 * The vector of the virtual has already been set in the PIR.
4044 * Send a notification event to deliver the virtual interrupt
4045 * unless the vCPU is the currently running vCPU, i.e. the
4046 * event is being sent from a fastpath VM-Exit handler, in
4047 * which case the PIR will be synced to the vIRR before
4048 * re-entering the guest.
4050 * When the target is not the running vCPU, the following
4051 * possibilities emerge:
4053 * Case 1: vCPU stays in non-root mode. Sending a notification
4054 * event posts the interrupt to the vCPU.
4056 * Case 2: vCPU exits to root mode and is still runnable. The
4057 * PIR will be synced to the vIRR before re-entering the guest.
4058 * Sending a notification event is ok as the host IRQ handler
4059 * will ignore the spurious event.
4061 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4062 * has already synced PIR to vIRR and never blocks the vCPU if
4063 * the vIRR is not empty. Therefore, a blocked vCPU here does
4064 * not wait for any requested interrupts in PIR, and sending a
4065 * notification event also results in a benign, spurious event.
4068 if (vcpu != kvm_get_running_vcpu())
4069 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4074 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4075 * otherwise do nothing as KVM will grab the highest priority pending
4076 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4078 kvm_vcpu_wake_up(vcpu);
4081 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4084 struct vcpu_vmx *vmx = to_vmx(vcpu);
4086 if (is_guest_mode(vcpu) &&
4087 vector == vmx->nested.posted_intr_nv) {
4089 * If a posted intr is not recognized by hardware,
4090 * we will accomplish it in the next vmentry.
4092 vmx->nested.pi_pending = true;
4093 kvm_make_request(KVM_REQ_EVENT, vcpu);
4096 * This pairs with the smp_mb_*() after setting vcpu->mode in
4097 * vcpu_enter_guest() to guarantee the vCPU sees the event
4098 * request if triggering a posted interrupt "fails" because
4099 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4100 * the smb_wmb() in kvm_make_request() only ensures everything
4101 * done before making the request is visible when the request
4102 * is visible, it doesn't ensure ordering between the store to
4103 * vcpu->requests and the load from vcpu->mode.
4105 smp_mb__after_atomic();
4107 /* the PIR and ON have been set by L1. */
4108 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4114 * Send interrupt to vcpu via posted interrupt way.
4115 * 1. If target vcpu is running(non-root mode), send posted interrupt
4116 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4117 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4118 * interrupt from PIR in next vmentry.
4120 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4122 struct vcpu_vmx *vmx = to_vmx(vcpu);
4125 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4129 /* Note, this is called iff the local APIC is in-kernel. */
4130 if (!vcpu->arch.apic->apicv_active)
4133 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4136 /* If a previous notification has sent the IPI, nothing to do. */
4137 if (pi_test_and_set_on(&vmx->pi_desc))
4141 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4142 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4143 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4144 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4146 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4150 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4151 int trig_mode, int vector)
4153 struct kvm_vcpu *vcpu = apic->vcpu;
4155 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4156 kvm_lapic_set_irr(vector, apic);
4157 kvm_make_request(KVM_REQ_EVENT, vcpu);
4158 kvm_vcpu_kick(vcpu);
4160 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4166 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4167 * will not change in the lifetime of the guest.
4168 * Note that host-state that does change is set elsewhere. E.g., host-state
4169 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4171 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4175 unsigned long cr0, cr3, cr4;
4178 WARN_ON(cr0 & X86_CR0_TS);
4179 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4182 * Save the most likely value for this task's CR3 in the VMCS.
4183 * We can't use __get_current_cr3_fast() because we're not atomic.
4186 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4187 vmx->loaded_vmcs->host_state.cr3 = cr3;
4189 /* Save the most likely value for this task's CR4 in the VMCS. */
4190 cr4 = cr4_read_shadow();
4191 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4192 vmx->loaded_vmcs->host_state.cr4 = cr4;
4194 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4195 #ifdef CONFIG_X86_64
4197 * Load null selectors, so we can avoid reloading them in
4198 * vmx_prepare_switch_to_host(), in case userspace uses
4199 * the null selectors too (the expected case).
4201 vmcs_write16(HOST_DS_SELECTOR, 0);
4202 vmcs_write16(HOST_ES_SELECTOR, 0);
4204 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4205 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4207 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4208 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4210 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4212 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4214 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4215 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4218 * SYSENTER is used for 32-bit system calls on either 32-bit or
4219 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4220 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4221 * have already done so!).
4223 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4224 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4226 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4227 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4229 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4230 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4231 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4234 if (cpu_has_load_ia32_efer())
4235 vmcs_write64(HOST_IA32_EFER, host_efer);
4238 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4240 struct kvm_vcpu *vcpu = &vmx->vcpu;
4242 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4243 ~vcpu->arch.cr4_guest_rsvd_bits;
4245 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4246 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4248 if (is_guest_mode(&vmx->vcpu))
4249 vcpu->arch.cr4_guest_owned_bits &=
4250 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4251 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4254 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4256 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4258 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4259 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4262 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4264 if (!enable_preemption_timer)
4265 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4267 return pin_based_exec_ctrl;
4270 static u32 vmx_vmentry_ctrl(void)
4272 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4274 if (vmx_pt_mode_is_system())
4275 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4276 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4278 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4280 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4281 VM_ENTRY_LOAD_IA32_EFER |
4282 VM_ENTRY_IA32E_MODE);
4284 if (cpu_has_perf_global_ctrl_bug())
4285 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4287 return vmentry_ctrl;
4290 static u32 vmx_vmexit_ctrl(void)
4292 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4295 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4296 * nested virtualization and thus allowed to be set in vmcs12.
4298 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4299 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4301 if (vmx_pt_mode_is_system())
4302 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4303 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4305 if (cpu_has_perf_global_ctrl_bug())
4306 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4308 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4309 return vmexit_ctrl &
4310 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4313 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4315 struct vcpu_vmx *vmx = to_vmx(vcpu);
4317 if (is_guest_mode(vcpu)) {
4318 vmx->nested.update_vmcs01_apicv_status = true;
4322 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4324 if (kvm_vcpu_apicv_active(vcpu)) {
4325 secondary_exec_controls_setbit(vmx,
4326 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4327 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4329 tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4331 secondary_exec_controls_clearbit(vmx,
4332 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4333 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4335 tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4338 vmx_update_msr_bitmap_x2apic(vcpu);
4341 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4343 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4346 * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4347 * vmcs12 and propagated to vmcs02 when set in vmcs12.
4349 exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4350 CPU_BASED_USE_IO_BITMAPS |
4351 CPU_BASED_MONITOR_TRAP_FLAG |
4352 CPU_BASED_PAUSE_EXITING);
4354 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4355 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4356 CPU_BASED_NMI_WINDOW_EXITING);
4358 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4359 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4361 if (!cpu_need_tpr_shadow(&vmx->vcpu))
4362 exec_control &= ~CPU_BASED_TPR_SHADOW;
4364 #ifdef CONFIG_X86_64
4365 if (exec_control & CPU_BASED_TPR_SHADOW)
4366 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4367 CPU_BASED_CR8_STORE_EXITING);
4369 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4370 CPU_BASED_CR8_LOAD_EXITING;
4372 /* No need to intercept CR3 access or INVPLG when using EPT. */
4374 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4375 CPU_BASED_CR3_STORE_EXITING |
4376 CPU_BASED_INVLPG_EXITING);
4377 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4378 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4379 CPU_BASED_MONITOR_EXITING);
4380 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4381 exec_control &= ~CPU_BASED_HLT_EXITING;
4382 return exec_control;
4385 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4387 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4390 * IPI virtualization relies on APICv. Disable IPI virtualization if
4391 * APICv is inhibited.
4393 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4394 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4396 return exec_control;
4400 * Adjust a single secondary execution control bit to intercept/allow an
4401 * instruction in the guest. This is usually done based on whether or not a
4402 * feature has been exposed to the guest in order to correctly emulate faults.
4405 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4406 u32 control, bool enabled, bool exiting)
4409 * If the control is for an opt-in feature, clear the control if the
4410 * feature is not exposed to the guest, i.e. not enabled. If the
4411 * control is opt-out, i.e. an exiting control, clear the control if
4412 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4413 * disabled for the associated instruction. Note, the caller is
4414 * responsible presetting exec_control to set all supported bits.
4416 if (enabled == exiting)
4417 *exec_control &= ~control;
4420 * Update the nested MSR settings so that a nested VMM can/can't set
4421 * controls for features that are/aren't exposed to the guest.
4425 vmx->nested.msrs.secondary_ctls_high |= control;
4427 vmx->nested.msrs.secondary_ctls_high &= ~control;
4432 * Wrapper macro for the common case of adjusting a secondary execution control
4433 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4434 * verifies that the control is actually supported by KVM and hardware.
4436 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4440 if (cpu_has_vmx_##name()) { \
4441 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4442 X86_FEATURE_##feat_name); \
4443 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4444 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4448 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4449 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4450 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4452 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4453 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4455 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4457 struct kvm_vcpu *vcpu = &vmx->vcpu;
4459 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4461 if (vmx_pt_mode_is_system())
4462 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4463 if (!cpu_need_virtualize_apic_accesses(vcpu))
4464 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4466 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4468 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4469 enable_unrestricted_guest = 0;
4471 if (!enable_unrestricted_guest)
4472 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4473 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4474 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4475 if (!kvm_vcpu_apicv_active(vcpu))
4476 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4477 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4478 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4480 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4481 * in vmx_set_cr4. */
4482 exec_control &= ~SECONDARY_EXEC_DESC;
4484 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4486 We can NOT enable shadow_vmcs here because we don't have yet
4489 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4492 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4493 * it needs to be set here when dirty logging is already active, e.g.
4494 * if this vCPU was created after dirty logging was enabled.
4496 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4497 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4499 if (cpu_has_vmx_xsaves()) {
4500 /* Exposing XSAVES only when XSAVE is exposed */
4501 bool xsaves_enabled =
4502 boot_cpu_has(X86_FEATURE_XSAVE) &&
4503 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4504 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4506 vcpu->arch.xsaves_enabled = xsaves_enabled;
4508 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4509 SECONDARY_EXEC_XSAVES,
4510 xsaves_enabled, false);
4514 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4515 * feature is exposed to the guest. This creates a virtualization hole
4516 * if both are supported in hardware but only one is exposed to the
4517 * guest, but letting the guest execute RDTSCP or RDPID when either one
4518 * is advertised is preferable to emulating the advertised instruction
4519 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4521 if (cpu_has_vmx_rdtscp()) {
4522 bool rdpid_or_rdtscp_enabled =
4523 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4524 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4526 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4527 SECONDARY_EXEC_ENABLE_RDTSCP,
4528 rdpid_or_rdtscp_enabled, false);
4530 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4532 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4533 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4535 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4536 ENABLE_USR_WAIT_PAUSE, false);
4538 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4539 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4541 if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4542 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4544 return exec_control;
4547 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4549 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4552 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4555 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4557 if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4560 if (kvm_vmx->pid_table)
4563 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, vmx_get_pid_table_order(kvm));
4567 kvm_vmx->pid_table = (void *)page_address(pages);
4571 static int vmx_vcpu_precreate(struct kvm *kvm)
4573 return vmx_alloc_ipiv_pid_table(kvm);
4576 #define VMX_XSS_EXIT_BITMAP 0
4578 static void init_vmcs(struct vcpu_vmx *vmx)
4580 struct kvm *kvm = vmx->vcpu.kvm;
4581 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4584 nested_vmx_set_vmcs_shadowing_bitmap();
4586 if (cpu_has_vmx_msr_bitmap())
4587 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4589 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4592 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4594 exec_controls_set(vmx, vmx_exec_control(vmx));
4596 if (cpu_has_secondary_exec_ctrls())
4597 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4599 if (cpu_has_tertiary_exec_ctrls())
4600 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4602 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4603 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4604 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4605 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4606 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4608 vmcs_write16(GUEST_INTR_STATUS, 0);
4610 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4611 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4614 if (vmx_can_use_ipiv(&vmx->vcpu)) {
4615 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4616 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4619 if (!kvm_pause_in_guest(kvm)) {
4620 vmcs_write32(PLE_GAP, ple_gap);
4621 vmx->ple_window = ple_window;
4622 vmx->ple_window_dirty = true;
4625 if (kvm_notify_vmexit_enabled(kvm))
4626 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4628 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4629 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4630 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4632 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4633 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4634 vmx_set_constant_host_state(vmx);
4635 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4636 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4638 if (cpu_has_vmx_vmfunc())
4639 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4641 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4642 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4643 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4644 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4645 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4647 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4648 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4650 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4652 /* 22.2.1, 20.8.1 */
4653 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4655 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4656 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4658 set_cr4_guest_host_mask(vmx);
4661 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4663 if (cpu_has_vmx_xsaves())
4664 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4667 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4668 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4671 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4673 if (vmx_pt_mode_is_host_guest()) {
4674 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4675 /* Bit[6~0] are forced to 1, writes are ignored. */
4676 vmx->pt_desc.guest.output_mask = 0x7F;
4677 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4680 vmcs_write32(GUEST_SYSENTER_CS, 0);
4681 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4682 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4683 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4685 if (cpu_has_vmx_tpr_shadow()) {
4686 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4687 if (cpu_need_tpr_shadow(&vmx->vcpu))
4688 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4689 __pa(vmx->vcpu.arch.apic->regs));
4690 vmcs_write32(TPR_THRESHOLD, 0);
4693 vmx_setup_uret_msrs(vmx);
4696 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4698 struct vcpu_vmx *vmx = to_vmx(vcpu);
4703 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4705 vcpu_setup_sgx_lepubkeyhash(vcpu);
4707 vmx->nested.posted_intr_nv = -1;
4708 vmx->nested.vmxon_ptr = INVALID_GPA;
4709 vmx->nested.current_vmptr = INVALID_GPA;
4710 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4712 vcpu->arch.microcode_version = 0x100000000ULL;
4713 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4716 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4717 * or POSTED_INTR_WAKEUP_VECTOR.
4719 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4720 vmx->pi_desc.sn = 1;
4723 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4725 struct vcpu_vmx *vmx = to_vmx(vcpu);
4728 __vmx_vcpu_reset(vcpu);
4730 vmx->rmode.vm86_active = 0;
4733 vmx->msr_ia32_umwait_control = 0;
4735 vmx->hv_deadline_tsc = -1;
4736 kvm_set_cr8(vcpu, 0);
4738 vmx_segment_cache_clear(vmx);
4739 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4741 seg_setup(VCPU_SREG_CS);
4742 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4743 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4745 seg_setup(VCPU_SREG_DS);
4746 seg_setup(VCPU_SREG_ES);
4747 seg_setup(VCPU_SREG_FS);
4748 seg_setup(VCPU_SREG_GS);
4749 seg_setup(VCPU_SREG_SS);
4751 vmcs_write16(GUEST_TR_SELECTOR, 0);
4752 vmcs_writel(GUEST_TR_BASE, 0);
4753 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4754 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4756 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4757 vmcs_writel(GUEST_LDTR_BASE, 0);
4758 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4759 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4761 vmcs_writel(GUEST_GDTR_BASE, 0);
4762 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4764 vmcs_writel(GUEST_IDTR_BASE, 0);
4765 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4767 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4768 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4769 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4770 if (kvm_mpx_supported())
4771 vmcs_write64(GUEST_BNDCFGS, 0);
4773 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4775 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4777 vpid_sync_context(vmx->vpid);
4779 vmx_update_fb_clear_dis(vcpu, vmx);
4782 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4784 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4787 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4790 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4791 vmx_enable_irq_window(vcpu);
4795 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4798 static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4800 struct vcpu_vmx *vmx = to_vmx(vcpu);
4802 int irq = vcpu->arch.interrupt.nr;
4804 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4806 ++vcpu->stat.irq_injections;
4807 if (vmx->rmode.vm86_active) {
4809 if (vcpu->arch.interrupt.soft)
4810 inc_eip = vcpu->arch.event_exit_inst_len;
4811 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4814 intr = irq | INTR_INFO_VALID_MASK;
4815 if (vcpu->arch.interrupt.soft) {
4816 intr |= INTR_TYPE_SOFT_INTR;
4817 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4818 vmx->vcpu.arch.event_exit_inst_len);
4820 intr |= INTR_TYPE_EXT_INTR;
4821 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4823 vmx_clear_hlt(vcpu);
4826 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4828 struct vcpu_vmx *vmx = to_vmx(vcpu);
4832 * Tracking the NMI-blocked state in software is built upon
4833 * finding the next open IRQ window. This, in turn, depends on
4834 * well-behaving guests: They have to keep IRQs disabled at
4835 * least as long as the NMI handler runs. Otherwise we may
4836 * cause NMI nesting, maybe breaking the guest. But as this is
4837 * highly unlikely, we can live with the residual risk.
4839 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4840 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4843 ++vcpu->stat.nmi_injections;
4844 vmx->loaded_vmcs->nmi_known_unmasked = false;
4846 if (vmx->rmode.vm86_active) {
4847 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4851 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4852 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4854 vmx_clear_hlt(vcpu);
4857 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4859 struct vcpu_vmx *vmx = to_vmx(vcpu);
4863 return vmx->loaded_vmcs->soft_vnmi_blocked;
4864 if (vmx->loaded_vmcs->nmi_known_unmasked)
4866 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4867 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4871 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4873 struct vcpu_vmx *vmx = to_vmx(vcpu);
4876 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4877 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4878 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4881 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4883 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4884 GUEST_INTR_STATE_NMI);
4886 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4887 GUEST_INTR_STATE_NMI);
4891 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4893 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4896 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4899 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4900 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4901 GUEST_INTR_STATE_NMI));
4904 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4906 if (to_vmx(vcpu)->nested.nested_run_pending)
4909 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4910 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4913 return !vmx_nmi_blocked(vcpu);
4916 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4918 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4921 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4922 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4923 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4926 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4928 if (to_vmx(vcpu)->nested.nested_run_pending)
4932 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4933 * e.g. if the IRQ arrived asynchronously after checking nested events.
4935 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4938 return !vmx_interrupt_blocked(vcpu);
4941 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4945 if (enable_unrestricted_guest)
4948 mutex_lock(&kvm->slots_lock);
4949 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4951 mutex_unlock(&kvm->slots_lock);
4954 return PTR_ERR(ret);
4956 to_kvm_vmx(kvm)->tss_addr = addr;
4958 return init_rmode_tss(kvm, ret);
4961 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4963 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4967 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4972 * Update instruction length as we may reinject the exception
4973 * from user space while in guest debugging mode.
4975 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4976 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4977 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4981 return !(vcpu->guest_debug &
4982 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4996 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4997 int vec, u32 err_code)
5000 * Instruction with address size override prefix opcode 0x67
5001 * Cause the #SS fault with 0 error code in VM86 mode.
5003 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5004 if (kvm_emulate_instruction(vcpu, 0)) {
5005 if (vcpu->arch.halt_request) {
5006 vcpu->arch.halt_request = 0;
5007 return kvm_emulate_halt_noskip(vcpu);
5015 * Forward all other exceptions that are valid in real mode.
5016 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5017 * the required debugging infrastructure rework.
5019 kvm_queue_exception(vcpu, vec);
5023 static int handle_machine_check(struct kvm_vcpu *vcpu)
5025 /* handled by vmx_vcpu_run() */
5030 * If the host has split lock detection disabled, then #AC is
5031 * unconditionally injected into the guest, which is the pre split lock
5032 * detection behaviour.
5034 * If the host has split lock detection enabled then #AC is
5035 * only injected into the guest when:
5036 * - Guest CPL == 3 (user mode)
5037 * - Guest has #AC detection enabled in CR0
5038 * - Guest EFLAGS has AC bit set
5040 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5042 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5045 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
5046 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5049 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5051 struct vcpu_vmx *vmx = to_vmx(vcpu);
5052 struct kvm_run *kvm_run = vcpu->run;
5053 u32 intr_info, ex_no, error_code;
5054 unsigned long cr2, dr6;
5057 vect_info = vmx->idt_vectoring_info;
5058 intr_info = vmx_get_intr_info(vcpu);
5060 if (is_machine_check(intr_info) || is_nmi(intr_info))
5061 return 1; /* handled by handle_exception_nmi_irqoff() */
5064 * Queue the exception here instead of in handle_nm_fault_irqoff().
5065 * This ensures the nested_vmx check is not skipped so vmexit can
5066 * be reflected to L1 (when it intercepts #NM) before reaching this
5069 if (is_nm_fault(intr_info)) {
5070 kvm_queue_exception(vcpu, NM_VECTOR);
5074 if (is_invalid_opcode(intr_info))
5075 return handle_ud(vcpu);
5078 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5079 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5081 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5082 WARN_ON_ONCE(!enable_vmware_backdoor);
5085 * VMware backdoor emulation on #GP interception only handles
5086 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5087 * error code on #GP.
5090 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5093 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5097 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5098 * MMIO, it is better to report an internal error.
5099 * See the comments in vmx_handle_exit.
5101 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5102 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5103 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5104 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5105 vcpu->run->internal.ndata = 4;
5106 vcpu->run->internal.data[0] = vect_info;
5107 vcpu->run->internal.data[1] = intr_info;
5108 vcpu->run->internal.data[2] = error_code;
5109 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5113 if (is_page_fault(intr_info)) {
5114 cr2 = vmx_get_exit_qual(vcpu);
5115 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5117 * EPT will cause page fault only if we need to
5118 * detect illegal GPAs.
5120 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5121 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5124 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5127 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5129 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5130 return handle_rmode_exception(vcpu, ex_no, error_code);
5134 dr6 = vmx_get_exit_qual(vcpu);
5135 if (!(vcpu->guest_debug &
5136 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5138 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5139 * instruction. ICEBP generates a trap-like #DB, but
5140 * despite its interception control being tied to #DB,
5141 * is an instruction intercept, i.e. the VM-Exit occurs
5142 * on the ICEBP itself. Note, skipping ICEBP also
5143 * clears STI and MOVSS blocking.
5145 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5146 * if single-step is enabled in RFLAGS and STI or MOVSS
5147 * blocking is active, as the CPU doesn't set the bit
5148 * on VM-Exit due to #DB interception. VM-Entry has a
5149 * consistency check that a single-step #DB is pending
5150 * in this scenario as the previous instruction cannot
5151 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5152 * don't modify RFLAGS), therefore the one instruction
5153 * delay when activating single-step breakpoints must
5154 * have already expired. Note, the CPU sets/clears BS
5155 * as appropriate for all other VM-Exits types.
5157 if (is_icebp(intr_info))
5158 WARN_ON(!skip_emulated_instruction(vcpu));
5159 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5160 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5161 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5162 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5163 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5165 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5168 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5169 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5173 * Update instruction length as we may reinject #BP from
5174 * user space while in guest debugging mode. Reading it for
5175 * #DB as well causes no harm, it is not used in that case.
5177 vmx->vcpu.arch.event_exit_inst_len =
5178 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5179 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5180 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5181 kvm_run->debug.arch.exception = ex_no;
5184 if (vmx_guest_inject_ac(vcpu)) {
5185 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5190 * Handle split lock. Depending on detection mode this will
5191 * either warn and disable split lock detection for this
5192 * task or force SIGBUS on it.
5194 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5198 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5199 kvm_run->ex.exception = ex_no;
5200 kvm_run->ex.error_code = error_code;
5206 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5208 ++vcpu->stat.irq_exits;
5212 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5214 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5215 vcpu->mmio_needed = 0;
5219 static int handle_io(struct kvm_vcpu *vcpu)
5221 unsigned long exit_qualification;
5222 int size, in, string;
5225 exit_qualification = vmx_get_exit_qual(vcpu);
5226 string = (exit_qualification & 16) != 0;
5228 ++vcpu->stat.io_exits;
5231 return kvm_emulate_instruction(vcpu, 0);
5233 port = exit_qualification >> 16;
5234 size = (exit_qualification & 7) + 1;
5235 in = (exit_qualification & 8) != 0;
5237 return kvm_fast_pio(vcpu, size, port, in);
5241 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5244 * Patch in the VMCALL instruction:
5246 hypercall[0] = 0x0f;
5247 hypercall[1] = 0x01;
5248 hypercall[2] = 0xc1;
5251 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5252 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5254 if (is_guest_mode(vcpu)) {
5255 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5256 unsigned long orig_val = val;
5259 * We get here when L2 changed cr0 in a way that did not change
5260 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5261 * but did change L0 shadowed bits. So we first calculate the
5262 * effective cr0 value that L1 would like to write into the
5263 * hardware. It consists of the L2-owned bits from the new
5264 * value combined with the L1-owned bits from L1's guest_cr0.
5266 val = (val & ~vmcs12->cr0_guest_host_mask) |
5267 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5269 if (!nested_guest_cr0_valid(vcpu, val))
5272 if (kvm_set_cr0(vcpu, val))
5274 vmcs_writel(CR0_READ_SHADOW, orig_val);
5277 if (to_vmx(vcpu)->nested.vmxon &&
5278 !nested_host_cr0_valid(vcpu, val))
5281 return kvm_set_cr0(vcpu, val);
5285 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5287 if (is_guest_mode(vcpu)) {
5288 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5289 unsigned long orig_val = val;
5291 /* analogously to handle_set_cr0 */
5292 val = (val & ~vmcs12->cr4_guest_host_mask) |
5293 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5294 if (kvm_set_cr4(vcpu, val))
5296 vmcs_writel(CR4_READ_SHADOW, orig_val);
5299 return kvm_set_cr4(vcpu, val);
5302 static int handle_desc(struct kvm_vcpu *vcpu)
5304 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5305 return kvm_emulate_instruction(vcpu, 0);
5308 static int handle_cr(struct kvm_vcpu *vcpu)
5310 unsigned long exit_qualification, val;
5316 exit_qualification = vmx_get_exit_qual(vcpu);
5317 cr = exit_qualification & 15;
5318 reg = (exit_qualification >> 8) & 15;
5319 switch ((exit_qualification >> 4) & 3) {
5320 case 0: /* mov to cr */
5321 val = kvm_register_read(vcpu, reg);
5322 trace_kvm_cr_write(cr, val);
5325 err = handle_set_cr0(vcpu, val);
5326 return kvm_complete_insn_gp(vcpu, err);
5328 WARN_ON_ONCE(enable_unrestricted_guest);
5330 err = kvm_set_cr3(vcpu, val);
5331 return kvm_complete_insn_gp(vcpu, err);
5333 err = handle_set_cr4(vcpu, val);
5334 return kvm_complete_insn_gp(vcpu, err);
5336 u8 cr8_prev = kvm_get_cr8(vcpu);
5338 err = kvm_set_cr8(vcpu, cr8);
5339 ret = kvm_complete_insn_gp(vcpu, err);
5340 if (lapic_in_kernel(vcpu))
5342 if (cr8_prev <= cr8)
5345 * TODO: we might be squashing a
5346 * KVM_GUESTDBG_SINGLESTEP-triggered
5347 * KVM_EXIT_DEBUG here.
5349 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5355 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5357 case 1: /*mov from cr*/
5360 WARN_ON_ONCE(enable_unrestricted_guest);
5362 val = kvm_read_cr3(vcpu);
5363 kvm_register_write(vcpu, reg, val);
5364 trace_kvm_cr_read(cr, val);
5365 return kvm_skip_emulated_instruction(vcpu);
5367 val = kvm_get_cr8(vcpu);
5368 kvm_register_write(vcpu, reg, val);
5369 trace_kvm_cr_read(cr, val);
5370 return kvm_skip_emulated_instruction(vcpu);
5374 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5375 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5376 kvm_lmsw(vcpu, val);
5378 return kvm_skip_emulated_instruction(vcpu);
5382 vcpu->run->exit_reason = 0;
5383 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5384 (int)(exit_qualification >> 4) & 3, cr);
5388 static int handle_dr(struct kvm_vcpu *vcpu)
5390 unsigned long exit_qualification;
5394 exit_qualification = vmx_get_exit_qual(vcpu);
5395 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5397 /* First, if DR does not exist, trigger UD */
5398 if (!kvm_require_dr(vcpu, dr))
5401 if (vmx_get_cpl(vcpu) > 0)
5404 dr7 = vmcs_readl(GUEST_DR7);
5407 * As the vm-exit takes precedence over the debug trap, we
5408 * need to emulate the latter, either for the host or the
5409 * guest debugging itself.
5411 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5412 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5413 vcpu->run->debug.arch.dr7 = dr7;
5414 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5415 vcpu->run->debug.arch.exception = DB_VECTOR;
5416 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5419 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5424 if (vcpu->guest_debug == 0) {
5425 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5428 * No more DR vmexits; force a reload of the debug registers
5429 * and reenter on this instruction. The next vmexit will
5430 * retrieve the full state of the debug registers.
5432 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5436 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5437 if (exit_qualification & TYPE_MOV_FROM_DR) {
5440 kvm_get_dr(vcpu, dr, &val);
5441 kvm_register_write(vcpu, reg, val);
5444 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5448 return kvm_complete_insn_gp(vcpu, err);
5451 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5453 get_debugreg(vcpu->arch.db[0], 0);
5454 get_debugreg(vcpu->arch.db[1], 1);
5455 get_debugreg(vcpu->arch.db[2], 2);
5456 get_debugreg(vcpu->arch.db[3], 3);
5457 get_debugreg(vcpu->arch.dr6, 6);
5458 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5460 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5461 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5464 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5465 * a stale dr6 from the guest.
5467 set_debugreg(DR6_RESERVED, 6);
5470 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5472 vmcs_writel(GUEST_DR7, val);
5475 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5477 kvm_apic_update_ppr(vcpu);
5481 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5483 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5485 kvm_make_request(KVM_REQ_EVENT, vcpu);
5487 ++vcpu->stat.irq_window_exits;
5491 static int handle_invlpg(struct kvm_vcpu *vcpu)
5493 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5495 kvm_mmu_invlpg(vcpu, exit_qualification);
5496 return kvm_skip_emulated_instruction(vcpu);
5499 static int handle_apic_access(struct kvm_vcpu *vcpu)
5501 if (likely(fasteoi)) {
5502 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5503 int access_type, offset;
5505 access_type = exit_qualification & APIC_ACCESS_TYPE;
5506 offset = exit_qualification & APIC_ACCESS_OFFSET;
5508 * Sane guest uses MOV to write EOI, with written value
5509 * not cared. So make a short-circuit here by avoiding
5510 * heavy instruction emulation.
5512 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5513 (offset == APIC_EOI)) {
5514 kvm_lapic_set_eoi(vcpu);
5515 return kvm_skip_emulated_instruction(vcpu);
5518 return kvm_emulate_instruction(vcpu, 0);
5521 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5523 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5524 int vector = exit_qualification & 0xff;
5526 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5527 kvm_apic_set_eoi_accelerated(vcpu, vector);
5531 static int handle_apic_write(struct kvm_vcpu *vcpu)
5533 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5536 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5537 * hardware has done any necessary aliasing, offset adjustments, etc...
5538 * for the access. I.e. the correct value has already been written to
5539 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5540 * retrieve the register value and emulate the access.
5542 u32 offset = exit_qualification & 0xff0;
5544 kvm_apic_write_nodecode(vcpu, offset);
5548 static int handle_task_switch(struct kvm_vcpu *vcpu)
5550 struct vcpu_vmx *vmx = to_vmx(vcpu);
5551 unsigned long exit_qualification;
5552 bool has_error_code = false;
5555 int reason, type, idt_v, idt_index;
5557 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5558 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5559 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5561 exit_qualification = vmx_get_exit_qual(vcpu);
5563 reason = (u32)exit_qualification >> 30;
5564 if (reason == TASK_SWITCH_GATE && idt_v) {
5566 case INTR_TYPE_NMI_INTR:
5567 vcpu->arch.nmi_injected = false;
5568 vmx_set_nmi_mask(vcpu, true);
5570 case INTR_TYPE_EXT_INTR:
5571 case INTR_TYPE_SOFT_INTR:
5572 kvm_clear_interrupt_queue(vcpu);
5574 case INTR_TYPE_HARD_EXCEPTION:
5575 if (vmx->idt_vectoring_info &
5576 VECTORING_INFO_DELIVER_CODE_MASK) {
5577 has_error_code = true;
5579 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5582 case INTR_TYPE_SOFT_EXCEPTION:
5583 kvm_clear_exception_queue(vcpu);
5589 tss_selector = exit_qualification;
5591 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5592 type != INTR_TYPE_EXT_INTR &&
5593 type != INTR_TYPE_NMI_INTR))
5594 WARN_ON(!skip_emulated_instruction(vcpu));
5597 * TODO: What about debug traps on tss switch?
5598 * Are we supposed to inject them and update dr6?
5600 return kvm_task_switch(vcpu, tss_selector,
5601 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5602 reason, has_error_code, error_code);
5605 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5607 unsigned long exit_qualification;
5611 exit_qualification = vmx_get_exit_qual(vcpu);
5614 * EPT violation happened while executing iret from NMI,
5615 * "blocked by NMI" bit has to be set before next VM entry.
5616 * There are errata that may cause this bit to not be set:
5619 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5621 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5622 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5624 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5625 trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5627 /* Is it a read fault? */
5628 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5629 ? PFERR_USER_MASK : 0;
5630 /* Is it a write fault? */
5631 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5632 ? PFERR_WRITE_MASK : 0;
5633 /* Is it a fetch fault? */
5634 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5635 ? PFERR_FETCH_MASK : 0;
5636 /* ept page table entry is present? */
5637 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5638 ? PFERR_PRESENT_MASK : 0;
5640 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5641 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5643 vcpu->arch.exit_qualification = exit_qualification;
5646 * Check that the GPA doesn't exceed physical memory limits, as that is
5647 * a guest page fault. We have to emulate the instruction here, because
5648 * if the illegal address is that of a paging structure, then
5649 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5650 * would also use advanced VM-exit information for EPT violations to
5651 * reconstruct the page fault error code.
5653 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5654 return kvm_emulate_instruction(vcpu, 0);
5656 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5659 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5663 if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5667 * A nested guest cannot optimize MMIO vmexits, because we have an
5668 * nGPA here instead of the required GPA.
5670 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5671 if (!is_guest_mode(vcpu) &&
5672 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5673 trace_kvm_fast_mmio(gpa);
5674 return kvm_skip_emulated_instruction(vcpu);
5677 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5680 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5682 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5685 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5686 ++vcpu->stat.nmi_window_exits;
5687 kvm_make_request(KVM_REQ_EVENT, vcpu);
5692 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5694 struct vcpu_vmx *vmx = to_vmx(vcpu);
5696 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5697 (vcpu->arch.exception.pending || vcpu->arch.exception.injected);
5700 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5702 struct vcpu_vmx *vmx = to_vmx(vcpu);
5703 bool intr_window_requested;
5704 unsigned count = 130;
5706 intr_window_requested = exec_controls_get(vmx) &
5707 CPU_BASED_INTR_WINDOW_EXITING;
5709 while (vmx->emulation_required && count-- != 0) {
5710 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5711 return handle_interrupt_window(&vmx->vcpu);
5713 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5716 if (!kvm_emulate_instruction(vcpu, 0))
5719 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5720 kvm_prepare_emulation_failure_exit(vcpu);
5724 if (vcpu->arch.halt_request) {
5725 vcpu->arch.halt_request = 0;
5726 return kvm_emulate_halt_noskip(vcpu);
5730 * Note, return 1 and not 0, vcpu_run() will invoke
5731 * xfer_to_guest_mode() which will create a proper return
5734 if (__xfer_to_guest_mode_work_pending())
5741 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5743 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5744 kvm_prepare_emulation_failure_exit(vcpu);
5751 static void grow_ple_window(struct kvm_vcpu *vcpu)
5753 struct vcpu_vmx *vmx = to_vmx(vcpu);
5754 unsigned int old = vmx->ple_window;
5756 vmx->ple_window = __grow_ple_window(old, ple_window,
5760 if (vmx->ple_window != old) {
5761 vmx->ple_window_dirty = true;
5762 trace_kvm_ple_window_update(vcpu->vcpu_id,
5763 vmx->ple_window, old);
5767 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5769 struct vcpu_vmx *vmx = to_vmx(vcpu);
5770 unsigned int old = vmx->ple_window;
5772 vmx->ple_window = __shrink_ple_window(old, ple_window,
5776 if (vmx->ple_window != old) {
5777 vmx->ple_window_dirty = true;
5778 trace_kvm_ple_window_update(vcpu->vcpu_id,
5779 vmx->ple_window, old);
5784 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5785 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5787 static int handle_pause(struct kvm_vcpu *vcpu)
5789 if (!kvm_pause_in_guest(vcpu->kvm))
5790 grow_ple_window(vcpu);
5793 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5794 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5795 * never set PAUSE_EXITING and just set PLE if supported,
5796 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5798 kvm_vcpu_on_spin(vcpu, true);
5799 return kvm_skip_emulated_instruction(vcpu);
5802 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5807 static int handle_invpcid(struct kvm_vcpu *vcpu)
5809 u32 vmx_instruction_info;
5818 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5819 kvm_queue_exception(vcpu, UD_VECTOR);
5823 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5824 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5825 type = kvm_register_read(vcpu, gpr_index);
5827 /* According to the Intel instruction reference, the memory operand
5828 * is read even if it isn't needed (e.g., for type==all)
5830 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5831 vmx_instruction_info, false,
5832 sizeof(operand), &gva))
5835 return kvm_handle_invpcid(vcpu, type, gva);
5838 static int handle_pml_full(struct kvm_vcpu *vcpu)
5840 unsigned long exit_qualification;
5842 trace_kvm_pml_full(vcpu->vcpu_id);
5844 exit_qualification = vmx_get_exit_qual(vcpu);
5847 * PML buffer FULL happened while executing iret from NMI,
5848 * "blocked by NMI" bit has to be set before next VM entry.
5850 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5852 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5853 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5854 GUEST_INTR_STATE_NMI);
5857 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5858 * here.., and there's no userspace involvement needed for PML.
5863 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5865 struct vcpu_vmx *vmx = to_vmx(vcpu);
5867 if (!vmx->req_immediate_exit &&
5868 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5869 kvm_lapic_expired_hv_timer(vcpu);
5870 return EXIT_FASTPATH_REENTER_GUEST;
5873 return EXIT_FASTPATH_NONE;
5876 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5878 handle_fastpath_preemption_timer(vcpu);
5883 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5884 * are overwritten by nested_vmx_setup() when nested=1.
5886 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5888 kvm_queue_exception(vcpu, UD_VECTOR);
5892 #ifndef CONFIG_X86_SGX_KVM
5893 static int handle_encls(struct kvm_vcpu *vcpu)
5896 * SGX virtualization is disabled. There is no software enable bit for
5897 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5898 * the guest from executing ENCLS (when SGX is supported by hardware).
5900 kvm_queue_exception(vcpu, UD_VECTOR);
5903 #endif /* CONFIG_X86_SGX_KVM */
5905 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5908 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
5909 * VM-Exits. Unconditionally set the flag here and leave the handling to
5910 * vmx_handle_exit().
5912 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
5916 static int handle_notify(struct kvm_vcpu *vcpu)
5918 unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5919 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
5921 ++vcpu->stat.notify_window_exits;
5924 * Notify VM exit happened while executing iret from NMI,
5925 * "blocked by NMI" bit has to be set before next VM entry.
5927 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
5928 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5929 GUEST_INTR_STATE_NMI);
5931 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
5933 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
5934 vcpu->run->notify.flags = context_invalid ?
5935 KVM_NOTIFY_CONTEXT_INVALID : 0;
5943 * The exit handlers return 1 if the exit was handled fully and guest execution
5944 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5945 * to be done to userspace and return 0.
5947 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5948 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5949 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5950 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5951 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5952 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5953 [EXIT_REASON_CR_ACCESS] = handle_cr,
5954 [EXIT_REASON_DR_ACCESS] = handle_dr,
5955 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5956 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5957 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5958 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5959 [EXIT_REASON_HLT] = kvm_emulate_halt,
5960 [EXIT_REASON_INVD] = kvm_emulate_invd,
5961 [EXIT_REASON_INVLPG] = handle_invlpg,
5962 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5963 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5964 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5965 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5966 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5967 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5968 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5969 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5970 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5971 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5972 [EXIT_REASON_VMON] = handle_vmx_instruction,
5973 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5974 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5975 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5976 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5977 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5978 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5979 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5980 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5981 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5982 [EXIT_REASON_LDTR_TR] = handle_desc,
5983 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5984 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5985 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5986 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5987 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5988 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5989 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5990 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5991 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5992 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5993 [EXIT_REASON_PML_FULL] = handle_pml_full,
5994 [EXIT_REASON_INVPCID] = handle_invpcid,
5995 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5996 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5997 [EXIT_REASON_ENCLS] = handle_encls,
5998 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5999 [EXIT_REASON_NOTIFY] = handle_notify,
6002 static const int kvm_vmx_max_exit_handlers =
6003 ARRAY_SIZE(kvm_vmx_exit_handlers);
6005 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6006 u64 *info1, u64 *info2,
6007 u32 *intr_info, u32 *error_code)
6009 struct vcpu_vmx *vmx = to_vmx(vcpu);
6011 *reason = vmx->exit_reason.full;
6012 *info1 = vmx_get_exit_qual(vcpu);
6013 if (!(vmx->exit_reason.failed_vmentry)) {
6014 *info2 = vmx->idt_vectoring_info;
6015 *intr_info = vmx_get_intr_info(vcpu);
6016 if (is_exception_with_error_code(*intr_info))
6017 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6027 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6030 __free_page(vmx->pml_pg);
6035 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6037 struct vcpu_vmx *vmx = to_vmx(vcpu);
6041 pml_idx = vmcs_read16(GUEST_PML_INDEX);
6043 /* Do nothing if PML buffer is empty */
6044 if (pml_idx == (PML_ENTITY_NUM - 1))
6047 /* PML index always points to next available PML buffer entity */
6048 if (pml_idx >= PML_ENTITY_NUM)
6053 pml_buf = page_address(vmx->pml_pg);
6054 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6057 gpa = pml_buf[pml_idx];
6058 WARN_ON(gpa & (PAGE_SIZE - 1));
6059 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6062 /* reset PML index */
6063 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6066 static void vmx_dump_sel(char *name, uint32_t sel)
6068 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6069 name, vmcs_read16(sel),
6070 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6071 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6072 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6075 static void vmx_dump_dtsel(char *name, uint32_t limit)
6077 pr_err("%s limit=0x%08x, base=0x%016lx\n",
6078 name, vmcs_read32(limit),
6079 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6082 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6085 struct vmx_msr_entry *e;
6087 pr_err("MSR %s:\n", name);
6088 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6089 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6092 void dump_vmcs(struct kvm_vcpu *vcpu)
6094 struct vcpu_vmx *vmx = to_vmx(vcpu);
6095 u32 vmentry_ctl, vmexit_ctl;
6096 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6097 u64 tertiary_exec_control;
6101 if (!dump_invalid_vmcs) {
6102 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6106 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6107 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6108 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6109 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6110 cr4 = vmcs_readl(GUEST_CR4);
6112 if (cpu_has_secondary_exec_ctrls())
6113 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6115 secondary_exec_control = 0;
6117 if (cpu_has_tertiary_exec_ctrls())
6118 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6120 tertiary_exec_control = 0;
6122 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6123 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6124 pr_err("*** Guest State ***\n");
6125 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6126 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6127 vmcs_readl(CR0_GUEST_HOST_MASK));
6128 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6129 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6130 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6131 if (cpu_has_vmx_ept()) {
6132 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
6133 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6134 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
6135 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6137 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
6138 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6139 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
6140 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6141 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6142 vmcs_readl(GUEST_SYSENTER_ESP),
6143 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6144 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
6145 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
6146 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
6147 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
6148 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
6149 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
6150 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6151 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6152 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6153 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
6154 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6155 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6156 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6157 else if (efer_slot >= 0)
6158 pr_err("EFER= 0x%016llx (autoload)\n",
6159 vmx->msr_autoload.guest.val[efer_slot].value);
6160 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6161 pr_err("EFER= 0x%016llx (effective)\n",
6162 vcpu->arch.efer | (EFER_LMA | EFER_LME));
6164 pr_err("EFER= 0x%016llx (effective)\n",
6165 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6166 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6167 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6168 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
6169 vmcs_read64(GUEST_IA32_DEBUGCTL),
6170 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6171 if (cpu_has_load_perf_global_ctrl() &&
6172 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6173 pr_err("PerfGlobCtl = 0x%016llx\n",
6174 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6175 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6176 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6177 pr_err("Interruptibility = %08x ActivityState = %08x\n",
6178 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6179 vmcs_read32(GUEST_ACTIVITY_STATE));
6180 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6181 pr_err("InterruptStatus = %04x\n",
6182 vmcs_read16(GUEST_INTR_STATUS));
6183 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6184 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6185 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6186 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6188 pr_err("*** Host State ***\n");
6189 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6190 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6191 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6192 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6193 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6194 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6195 vmcs_read16(HOST_TR_SELECTOR));
6196 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6197 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6198 vmcs_readl(HOST_TR_BASE));
6199 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6200 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6201 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6202 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6203 vmcs_readl(HOST_CR4));
6204 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6205 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6206 vmcs_read32(HOST_IA32_SYSENTER_CS),
6207 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6208 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6209 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6210 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6211 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6212 if (cpu_has_load_perf_global_ctrl() &&
6213 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6214 pr_err("PerfGlobCtl = 0x%016llx\n",
6215 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6216 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6217 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6219 pr_err("*** Control State ***\n");
6220 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6221 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6222 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6223 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6224 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6225 vmcs_read32(EXCEPTION_BITMAP),
6226 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6227 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6228 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6229 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6230 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6231 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6232 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6233 vmcs_read32(VM_EXIT_INTR_INFO),
6234 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6235 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6236 pr_err(" reason=%08x qualification=%016lx\n",
6237 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6238 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6239 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6240 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6241 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6242 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6243 pr_err("TSC Multiplier = 0x%016llx\n",
6244 vmcs_read64(TSC_MULTIPLIER));
6245 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6246 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6247 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6248 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6250 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6251 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6252 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6253 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6255 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6256 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6257 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6258 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6259 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6260 pr_err("PLE Gap=%08x Window=%08x\n",
6261 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6262 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6263 pr_err("Virtual processor ID = 0x%04x\n",
6264 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6268 * The guest has exited. See if we can fix it or if we need userspace
6271 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6273 struct vcpu_vmx *vmx = to_vmx(vcpu);
6274 union vmx_exit_reason exit_reason = vmx->exit_reason;
6275 u32 vectoring_info = vmx->idt_vectoring_info;
6276 u16 exit_handler_index;
6279 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6280 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6281 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6282 * mode as if vcpus is in root mode, the PML buffer must has been
6283 * flushed already. Note, PML is never enabled in hardware while
6286 if (enable_pml && !is_guest_mode(vcpu))
6287 vmx_flush_pml_buffer(vcpu);
6290 * KVM should never reach this point with a pending nested VM-Enter.
6291 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6292 * invalid guest state should never happen as that means KVM knowingly
6293 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6295 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6298 if (is_guest_mode(vcpu)) {
6300 * PML is never enabled when running L2, bail immediately if a
6301 * PML full exit occurs as something is horribly wrong.
6303 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6304 goto unexpected_vmexit;
6307 * The host physical addresses of some pages of guest memory
6308 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6309 * Page). The CPU may write to these pages via their host
6310 * physical address while L2 is running, bypassing any
6311 * address-translation-based dirty tracking (e.g. EPT write
6314 * Mark them dirty on every exit from L2 to prevent them from
6315 * getting out of sync with dirty tracking.
6317 nested_mark_vmcs12_pages_dirty(vcpu);
6320 * Synthesize a triple fault if L2 state is invalid. In normal
6321 * operation, nested VM-Enter rejects any attempt to enter L2
6322 * with invalid state. However, those checks are skipped if
6323 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6324 * L2 state is invalid, it means either L1 modified SMRAM state
6325 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6326 * doing so is architecturally allowed in the RSM case, and is
6327 * the least awful solution for the userspace case without
6328 * risking false positives.
6330 if (vmx->emulation_required) {
6331 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6335 if (nested_vmx_reflect_vmexit(vcpu))
6339 /* If guest state is invalid, start emulating. L2 is handled above. */
6340 if (vmx->emulation_required)
6341 return handle_invalid_guest_state(vcpu);
6343 if (exit_reason.failed_vmentry) {
6345 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6346 vcpu->run->fail_entry.hardware_entry_failure_reason
6348 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6352 if (unlikely(vmx->fail)) {
6354 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6355 vcpu->run->fail_entry.hardware_entry_failure_reason
6356 = vmcs_read32(VM_INSTRUCTION_ERROR);
6357 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6363 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6364 * delivery event since it indicates guest is accessing MMIO.
6365 * The vm-exit can be triggered again after return to guest that
6366 * will cause infinite loop.
6368 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6369 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6370 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6371 exit_reason.basic != EXIT_REASON_PML_FULL &&
6372 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6373 exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6374 exit_reason.basic != EXIT_REASON_NOTIFY)) {
6377 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6378 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6379 vcpu->run->internal.data[0] = vectoring_info;
6380 vcpu->run->internal.data[1] = exit_reason.full;
6381 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6382 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6383 vcpu->run->internal.data[ndata++] =
6384 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6386 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6387 vcpu->run->internal.ndata = ndata;
6391 if (unlikely(!enable_vnmi &&
6392 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6393 if (!vmx_interrupt_blocked(vcpu)) {
6394 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6395 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6396 vcpu->arch.nmi_pending) {
6398 * This CPU don't support us in finding the end of an
6399 * NMI-blocked window if the guest runs with IRQs
6400 * disabled. So we pull the trigger after 1 s of
6401 * futile waiting, but inform the user about this.
6403 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6404 "state on VCPU %d after 1 s timeout\n",
6405 __func__, vcpu->vcpu_id);
6406 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6410 if (exit_fastpath != EXIT_FASTPATH_NONE)
6413 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6414 goto unexpected_vmexit;
6415 #ifdef CONFIG_RETPOLINE
6416 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6417 return kvm_emulate_wrmsr(vcpu);
6418 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6419 return handle_preemption_timer(vcpu);
6420 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6421 return handle_interrupt_window(vcpu);
6422 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6423 return handle_external_interrupt(vcpu);
6424 else if (exit_reason.basic == EXIT_REASON_HLT)
6425 return kvm_emulate_halt(vcpu);
6426 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6427 return handle_ept_misconfig(vcpu);
6430 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6431 kvm_vmx_max_exit_handlers);
6432 if (!kvm_vmx_exit_handlers[exit_handler_index])
6433 goto unexpected_vmexit;
6435 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6438 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6441 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6442 vcpu->run->internal.suberror =
6443 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6444 vcpu->run->internal.ndata = 2;
6445 vcpu->run->internal.data[0] = exit_reason.full;
6446 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6450 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6452 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6455 * Exit to user space when bus lock detected to inform that there is
6456 * a bus lock in guest.
6458 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6460 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6462 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6469 * Software based L1D cache flush which is used when microcode providing
6470 * the cache control MSR is not loaded.
6472 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6473 * flush it is required to read in 64 KiB because the replacement algorithm
6474 * is not exactly LRU. This could be sized at runtime via topology
6475 * information but as all relevant affected CPUs have 32KiB L1D cache size
6476 * there is no point in doing so.
6478 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6480 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6483 * This code is only executed when the flush mode is 'cond' or
6486 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6490 * Clear the per-vcpu flush bit, it gets set again
6491 * either from vcpu_run() or from one of the unsafe
6494 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6495 vcpu->arch.l1tf_flush_l1d = false;
6498 * Clear the per-cpu flush bit, it gets set again from
6499 * the interrupt handlers.
6501 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6502 kvm_clear_cpu_l1tf_flush_l1d();
6508 vcpu->stat.l1d_flush++;
6510 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6511 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6516 /* First ensure the pages are in the TLB */
6517 "xorl %%eax, %%eax\n"
6518 ".Lpopulate_tlb:\n\t"
6519 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6520 "addl $4096, %%eax\n\t"
6521 "cmpl %%eax, %[size]\n\t"
6522 "jne .Lpopulate_tlb\n\t"
6523 "xorl %%eax, %%eax\n\t"
6525 /* Now fill the cache */
6526 "xorl %%eax, %%eax\n"
6528 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6529 "addl $64, %%eax\n\t"
6530 "cmpl %%eax, %[size]\n\t"
6531 "jne .Lfill_cache\n\t"
6533 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6535 : "eax", "ebx", "ecx", "edx");
6538 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6540 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6543 if (is_guest_mode(vcpu) &&
6544 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6547 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6548 if (is_guest_mode(vcpu))
6549 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6551 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6554 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6556 struct vcpu_vmx *vmx = to_vmx(vcpu);
6557 u32 sec_exec_control;
6559 if (!lapic_in_kernel(vcpu))
6562 if (!flexpriority_enabled &&
6563 !cpu_has_vmx_virtualize_x2apic_mode())
6566 /* Postpone execution until vmcs01 is the current VMCS. */
6567 if (is_guest_mode(vcpu)) {
6568 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6572 sec_exec_control = secondary_exec_controls_get(vmx);
6573 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6574 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6576 switch (kvm_get_apic_mode(vcpu)) {
6577 case LAPIC_MODE_INVALID:
6578 WARN_ONCE(true, "Invalid local APIC state");
6580 case LAPIC_MODE_DISABLED:
6582 case LAPIC_MODE_XAPIC:
6583 if (flexpriority_enabled) {
6585 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6586 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6589 * Flush the TLB, reloading the APIC access page will
6590 * only do so if its physical address has changed, but
6591 * the guest may have inserted a non-APIC mapping into
6592 * the TLB while the APIC access page was disabled.
6594 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6597 case LAPIC_MODE_X2APIC:
6598 if (cpu_has_vmx_virtualize_x2apic_mode())
6600 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6603 secondary_exec_controls_set(vmx, sec_exec_control);
6605 vmx_update_msr_bitmap_x2apic(vcpu);
6608 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6612 /* Defer reload until vmcs01 is the current VMCS. */
6613 if (is_guest_mode(vcpu)) {
6614 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6618 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6619 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6622 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6623 if (is_error_page(page))
6626 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6627 vmx_flush_tlb_current(vcpu);
6630 * Do not pin apic access page in memory, the MMU notifier
6631 * will call us again if it is migrated or swapped out.
6636 static void vmx_hwapic_isr_update(int max_isr)
6644 status = vmcs_read16(GUEST_INTR_STATUS);
6646 if (max_isr != old) {
6648 status |= max_isr << 8;
6649 vmcs_write16(GUEST_INTR_STATUS, status);
6653 static void vmx_set_rvi(int vector)
6661 status = vmcs_read16(GUEST_INTR_STATUS);
6662 old = (u8)status & 0xff;
6663 if ((u8)vector != old) {
6665 status |= (u8)vector;
6666 vmcs_write16(GUEST_INTR_STATUS, status);
6670 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6673 * When running L2, updating RVI is only relevant when
6674 * vmcs12 virtual-interrupt-delivery enabled.
6675 * However, it can be enabled only when L1 also
6676 * intercepts external-interrupts and in that case
6677 * we should not update vmcs02 RVI but instead intercept
6678 * interrupt. Therefore, do nothing when running L2.
6680 if (!is_guest_mode(vcpu))
6681 vmx_set_rvi(max_irr);
6684 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6686 struct vcpu_vmx *vmx = to_vmx(vcpu);
6688 bool got_posted_interrupt;
6690 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6693 if (pi_test_on(&vmx->pi_desc)) {
6694 pi_clear_on(&vmx->pi_desc);
6696 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6697 * But on x86 this is just a compiler barrier anyway.
6699 smp_mb__after_atomic();
6700 got_posted_interrupt =
6701 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6703 max_irr = kvm_lapic_find_highest_irr(vcpu);
6704 got_posted_interrupt = false;
6708 * Newly recognized interrupts are injected via either virtual interrupt
6709 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6710 * disabled in two cases:
6712 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6713 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6714 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6715 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6716 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6718 * 2) If APICv is disabled for this vCPU, assigned devices may still
6719 * attempt to post interrupts. The posted interrupt vector will cause
6720 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6722 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6723 vmx_set_rvi(max_irr);
6724 else if (got_posted_interrupt)
6725 kvm_make_request(KVM_REQ_EVENT, vcpu);
6730 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6732 if (!kvm_vcpu_apicv_active(vcpu))
6735 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6736 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6737 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6738 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6741 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6743 struct vcpu_vmx *vmx = to_vmx(vcpu);
6745 pi_clear_on(&vmx->pi_desc);
6746 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6749 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6751 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6752 unsigned long entry)
6754 bool is_nmi = entry == (unsigned long)asm_exc_nmi_noist;
6756 kvm_before_interrupt(vcpu, is_nmi ? KVM_HANDLING_NMI : KVM_HANDLING_IRQ);
6757 vmx_do_interrupt_nmi_irqoff(entry);
6758 kvm_after_interrupt(vcpu);
6761 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6764 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6765 * MSR value is not clobbered by the host activity before the guest
6766 * has chance to consume it.
6768 * Do not blindly read xfd_err here, since this exception might
6769 * be caused by L1 interception on a platform which doesn't
6770 * support xfd at all.
6772 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6773 * only when xfd contains a non-zero value.
6775 * Queuing exception is done in vmx_handle_exit. See comment there.
6777 if (vcpu->arch.guest_fpu.fpstate->xfd)
6778 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6781 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6783 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6784 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6786 /* if exit due to PF check for async PF */
6787 if (is_page_fault(intr_info))
6788 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6789 /* if exit due to NM, handle before interrupts are enabled */
6790 else if (is_nm_fault(intr_info))
6791 handle_nm_fault_irqoff(&vmx->vcpu);
6792 /* Handle machine checks before interrupts are enabled */
6793 else if (is_machine_check(intr_info))
6794 kvm_machine_check();
6795 /* We need to handle NMIs before interrupts are enabled */
6796 else if (is_nmi(intr_info))
6797 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6800 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6802 u32 intr_info = vmx_get_intr_info(vcpu);
6803 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6804 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6806 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6807 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6810 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6811 vcpu->arch.at_instruction_boundary = true;
6814 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6816 struct vcpu_vmx *vmx = to_vmx(vcpu);
6818 if (vmx->emulation_required)
6821 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6822 handle_external_interrupt_irqoff(vcpu);
6823 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6824 handle_exception_nmi_irqoff(vmx);
6828 * The kvm parameter can be NULL (module initialization, or invocation before
6829 * VM creation). Be sure to check the kvm parameter before using it.
6831 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6834 case MSR_IA32_SMBASE:
6836 * We cannot do SMM unless we can run the guest in big
6839 return enable_unrestricted_guest || emulate_invalid_guest_state;
6840 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6842 case MSR_AMD64_VIRT_SPEC_CTRL:
6843 case MSR_AMD64_TSC_RATIO:
6844 /* This is AMD only. */
6851 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6856 bool idtv_info_valid;
6858 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6861 if (vmx->loaded_vmcs->nmi_known_unmasked)
6864 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6865 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6866 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6868 * SDM 3: 27.7.1.2 (September 2008)
6869 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6870 * a guest IRET fault.
6871 * SDM 3: 23.2.2 (September 2008)
6872 * Bit 12 is undefined in any of the following cases:
6873 * If the VM exit sets the valid bit in the IDT-vectoring
6874 * information field.
6875 * If the VM exit is due to a double fault.
6877 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6878 vector != DF_VECTOR && !idtv_info_valid)
6879 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6880 GUEST_INTR_STATE_NMI);
6882 vmx->loaded_vmcs->nmi_known_unmasked =
6883 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6884 & GUEST_INTR_STATE_NMI);
6885 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6886 vmx->loaded_vmcs->vnmi_blocked_time +=
6887 ktime_to_ns(ktime_sub(ktime_get(),
6888 vmx->loaded_vmcs->entry_time));
6891 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6892 u32 idt_vectoring_info,
6893 int instr_len_field,
6894 int error_code_field)
6898 bool idtv_info_valid;
6900 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6902 vcpu->arch.nmi_injected = false;
6903 kvm_clear_exception_queue(vcpu);
6904 kvm_clear_interrupt_queue(vcpu);
6906 if (!idtv_info_valid)
6909 kvm_make_request(KVM_REQ_EVENT, vcpu);
6911 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6912 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6915 case INTR_TYPE_NMI_INTR:
6916 vcpu->arch.nmi_injected = true;
6918 * SDM 3: 27.7.1.2 (September 2008)
6919 * Clear bit "block by NMI" before VM entry if a NMI
6922 vmx_set_nmi_mask(vcpu, false);
6924 case INTR_TYPE_SOFT_EXCEPTION:
6925 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6927 case INTR_TYPE_HARD_EXCEPTION:
6928 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6929 u32 err = vmcs_read32(error_code_field);
6930 kvm_requeue_exception_e(vcpu, vector, err);
6932 kvm_requeue_exception(vcpu, vector);
6934 case INTR_TYPE_SOFT_INTR:
6935 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6937 case INTR_TYPE_EXT_INTR:
6938 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6945 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6947 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6948 VM_EXIT_INSTRUCTION_LEN,
6949 IDT_VECTORING_ERROR_CODE);
6952 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6954 __vmx_complete_interrupts(vcpu,
6955 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6956 VM_ENTRY_INSTRUCTION_LEN,
6957 VM_ENTRY_EXCEPTION_ERROR_CODE);
6959 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6962 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6965 struct perf_guest_switch_msr *msrs;
6966 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
6968 pmu->host_cross_mapped_mask = 0;
6969 if (pmu->pebs_enable & pmu->global_ctrl)
6970 intel_pmu_cross_mapped_check(pmu);
6972 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6973 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
6977 for (i = 0; i < nr_msrs; i++)
6978 if (msrs[i].host == msrs[i].guest)
6979 clear_atomic_switch_msr(vmx, msrs[i].msr);
6981 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6982 msrs[i].host, false);
6985 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6987 struct vcpu_vmx *vmx = to_vmx(vcpu);
6991 if (vmx->req_immediate_exit) {
6992 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6993 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6994 } else if (vmx->hv_deadline_tsc != -1) {
6996 if (vmx->hv_deadline_tsc > tscl)
6997 /* set_hv_timer ensures the delta fits in 32-bits */
6998 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6999 cpu_preemption_timer_multi);
7003 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7004 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7005 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7006 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7007 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7011 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7013 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7014 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7015 vmcs_writel(HOST_RSP, host_rsp);
7019 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7022 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7024 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7027 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7028 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7031 * If the guest/host SPEC_CTRL values differ, restore the host value.
7033 * For legacy IBRS, the IBRS bit always needs to be written after
7034 * transitioning from a less privileged predictor mode, regardless of
7035 * whether the guest/host values differ.
7037 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7038 vmx->spec_ctrl != hostval)
7039 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7044 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
7046 switch (to_vmx(vcpu)->exit_reason.basic) {
7047 case EXIT_REASON_MSR_WRITE:
7048 return handle_fastpath_set_msr_irqoff(vcpu);
7049 case EXIT_REASON_PREEMPTION_TIMER:
7050 return handle_fastpath_preemption_timer(vcpu);
7052 return EXIT_FASTPATH_NONE;
7056 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7057 struct vcpu_vmx *vmx,
7058 unsigned long flags)
7060 guest_state_enter_irqoff();
7062 /* L1D Flush includes CPU buffer clear to mitigate MDS */
7063 if (static_branch_unlikely(&vmx_l1d_should_flush))
7064 vmx_l1d_flush(vcpu);
7065 else if (static_branch_unlikely(&mds_user_clear))
7066 mds_clear_cpu_buffers();
7067 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7068 kvm_arch_has_assigned_device(vcpu->kvm))
7069 mds_clear_cpu_buffers();
7071 vmx_disable_fb_clear(vmx);
7073 if (vcpu->arch.cr2 != native_read_cr2())
7074 native_write_cr2(vcpu->arch.cr2);
7076 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7079 vcpu->arch.cr2 = native_read_cr2();
7081 vmx_enable_fb_clear(vmx);
7083 guest_state_exit_irqoff();
7086 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
7088 struct vcpu_vmx *vmx = to_vmx(vcpu);
7089 unsigned long cr3, cr4;
7091 /* Record the guest's net vcpu time for enforced NMI injections. */
7092 if (unlikely(!enable_vnmi &&
7093 vmx->loaded_vmcs->soft_vnmi_blocked))
7094 vmx->loaded_vmcs->entry_time = ktime_get();
7097 * Don't enter VMX if guest state is invalid, let the exit handler
7098 * start emulation until we arrive back to a valid state. Synthesize a
7099 * consistency check VM-Exit due to invalid guest state and bail.
7101 if (unlikely(vmx->emulation_required)) {
7104 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7105 vmx->exit_reason.failed_vmentry = 1;
7106 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7107 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7108 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7109 vmx->exit_intr_info = 0;
7110 return EXIT_FASTPATH_NONE;
7113 trace_kvm_entry(vcpu);
7115 if (vmx->ple_window_dirty) {
7116 vmx->ple_window_dirty = false;
7117 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7121 * We did this in prepare_switch_to_guest, because it needs to
7122 * be within srcu_read_lock.
7124 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7126 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7127 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7128 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7129 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7130 vcpu->arch.regs_dirty = 0;
7133 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
7134 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7135 * it switches back to the current->mm, which can occur in KVM context
7136 * when switching to a temporary mm to patch kernel code, e.g. if KVM
7137 * toggles a static key while handling a VM-Exit.
7139 cr3 = __get_current_cr3_fast();
7140 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7141 vmcs_writel(HOST_CR3, cr3);
7142 vmx->loaded_vmcs->host_state.cr3 = cr3;
7145 cr4 = cr4_read_shadow();
7146 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7147 vmcs_writel(HOST_CR4, cr4);
7148 vmx->loaded_vmcs->host_state.cr4 = cr4;
7151 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
7152 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
7153 set_debugreg(vcpu->arch.dr6, 6);
7155 /* When single-stepping over STI and MOV SS, we must clear the
7156 * corresponding interruptibility bits in the guest state. Otherwise
7157 * vmentry fails as it then expects bit 14 (BS) in pending debug
7158 * exceptions being set, but that's not correct for the guest debugging
7160 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7161 vmx_set_interrupt_shadow(vcpu, 0);
7163 kvm_load_guest_xsave_state(vcpu);
7165 pt_guest_enter(vmx);
7167 atomic_switch_perf_msrs(vmx);
7168 if (intel_pmu_lbr_is_enabled(vcpu))
7169 vmx_passthrough_lbr_msrs(vcpu);
7171 if (enable_preemption_timer)
7172 vmx_update_hv_timer(vcpu);
7174 kvm_wait_lapic_expire(vcpu);
7176 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7177 vmx_vcpu_enter_exit(vcpu, vmx, __vmx_vcpu_run_flags(vmx));
7179 /* All fields are clean at this point */
7180 if (static_branch_unlikely(&enable_evmcs)) {
7181 current_evmcs->hv_clean_fields |=
7182 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7184 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7187 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7188 if (vmx->host_debugctlmsr)
7189 update_debugctlmsr(vmx->host_debugctlmsr);
7191 #ifndef CONFIG_X86_64
7193 * The sysexit path does not restore ds/es, so we must set them to
7194 * a reasonable value ourselves.
7196 * We can't defer this to vmx_prepare_switch_to_host() since that
7197 * function may be executed in interrupt context, which saves and
7198 * restore segments around it, nullifying its effect.
7200 loadsegment(ds, __USER_DS);
7201 loadsegment(es, __USER_DS);
7204 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7208 kvm_load_host_xsave_state(vcpu);
7210 if (is_guest_mode(vcpu)) {
7212 * Track VMLAUNCH/VMRESUME that have made past guest state
7215 if (vmx->nested.nested_run_pending &&
7216 !vmx->exit_reason.failed_vmentry)
7217 ++vcpu->stat.nested_run;
7219 vmx->nested.nested_run_pending = 0;
7222 vmx->idt_vectoring_info = 0;
7224 if (unlikely(vmx->fail)) {
7225 vmx->exit_reason.full = 0xdead;
7226 return EXIT_FASTPATH_NONE;
7229 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7230 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7231 kvm_machine_check();
7233 if (likely(!vmx->exit_reason.failed_vmentry))
7234 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7236 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7238 if (unlikely(vmx->exit_reason.failed_vmentry))
7239 return EXIT_FASTPATH_NONE;
7241 vmx->loaded_vmcs->launched = 1;
7243 vmx_recover_nmi_blocking(vmx);
7244 vmx_complete_interrupts(vmx);
7246 if (is_guest_mode(vcpu))
7247 return EXIT_FASTPATH_NONE;
7249 return vmx_exit_handlers_fastpath(vcpu);
7252 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7254 struct vcpu_vmx *vmx = to_vmx(vcpu);
7257 vmx_destroy_pml_buffer(vmx);
7258 free_vpid(vmx->vpid);
7259 nested_vmx_free_vcpu(vcpu);
7260 free_loaded_vmcs(vmx->loaded_vmcs);
7263 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7265 struct vmx_uret_msr *tsx_ctrl;
7266 struct vcpu_vmx *vmx;
7269 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7272 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7276 vmx->vpid = allocate_vpid();
7279 * If PML is turned on, failure on enabling PML just results in failure
7280 * of creating the vcpu, therefore we can simplify PML logic (by
7281 * avoiding dealing with cases, such as enabling PML partially on vcpus
7282 * for the guest), etc.
7285 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7290 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7291 vmx->guest_uret_msrs[i].mask = -1ull;
7292 if (boot_cpu_has(X86_FEATURE_RTM)) {
7294 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7295 * Keep the host value unchanged to avoid changing CPUID bits
7296 * under the host kernel's feet.
7298 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7300 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7303 err = alloc_loaded_vmcs(&vmx->vmcs01);
7308 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7309 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7310 * feature only for vmcs01, KVM currently isn't equipped to realize any
7311 * performance benefits from enabling it for vmcs02.
7313 if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs) &&
7314 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7315 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7317 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7320 /* The MSR bitmap starts with all ones */
7321 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7322 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7324 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7325 #ifdef CONFIG_X86_64
7326 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7327 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7328 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7330 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7331 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7332 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7333 if (kvm_cstate_in_guest(vcpu->kvm)) {
7334 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7335 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7336 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7337 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7340 vmx->loaded_vmcs = &vmx->vmcs01;
7342 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7343 err = alloc_apic_access_page(vcpu->kvm);
7348 if (enable_ept && !enable_unrestricted_guest) {
7349 err = init_rmode_identity_map(vcpu->kvm);
7354 if (vmx_can_use_ipiv(vcpu))
7355 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7356 __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7361 free_loaded_vmcs(vmx->loaded_vmcs);
7363 vmx_destroy_pml_buffer(vmx);
7365 free_vpid(vmx->vpid);
7369 #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"
7370 #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"
7372 static int vmx_vm_init(struct kvm *kvm)
7375 kvm->arch.pause_in_guest = true;
7377 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7378 switch (l1tf_mitigation) {
7379 case L1TF_MITIGATION_OFF:
7380 case L1TF_MITIGATION_FLUSH_NOWARN:
7381 /* 'I explicitly don't care' is set */
7383 case L1TF_MITIGATION_FLUSH:
7384 case L1TF_MITIGATION_FLUSH_NOSMT:
7385 case L1TF_MITIGATION_FULL:
7387 * Warn upon starting the first VM in a potentially
7388 * insecure environment.
7390 if (sched_smt_active())
7391 pr_warn_once(L1TF_MSG_SMT);
7392 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7393 pr_warn_once(L1TF_MSG_L1D);
7395 case L1TF_MITIGATION_FULL_FORCE:
7396 /* Flush is enforced */
7403 static int __init vmx_check_processor_compat(void)
7405 struct vmcs_config vmcs_conf;
7406 struct vmx_capability vmx_cap;
7408 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7409 !this_cpu_has(X86_FEATURE_VMX)) {
7410 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7414 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7417 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
7418 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7419 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7420 smp_processor_id());
7426 static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7430 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7431 * memory aliases with conflicting memory types and sometimes MCEs.
7432 * We have to be careful as to what are honored and when.
7434 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7435 * UC. The effective memory type is UC or WC depending on guest PAT.
7436 * This was historically the source of MCEs and we want to be
7439 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7440 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7441 * EPT memory type is set to WB. The effective memory type is forced
7444 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7445 * EPT memory type is used to emulate guest CD/MTRR.
7449 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7451 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7452 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7454 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7455 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7456 cache = MTRR_TYPE_WRBACK;
7458 cache = MTRR_TYPE_UNCACHABLE;
7460 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7463 return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7466 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7469 * These bits in the secondary execution controls field
7470 * are dynamic, the others are mostly based on the hypervisor
7471 * architecture and the guest's CPUID. Do not touch the
7475 SECONDARY_EXEC_SHADOW_VMCS |
7476 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7477 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7478 SECONDARY_EXEC_DESC;
7480 u32 cur_ctl = secondary_exec_controls_get(vmx);
7482 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7486 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7487 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7489 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7491 struct vcpu_vmx *vmx = to_vmx(vcpu);
7492 struct kvm_cpuid_entry2 *entry;
7494 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7495 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7497 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7498 if (entry && (entry->_reg & (_cpuid_mask))) \
7499 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7502 entry = kvm_find_cpuid_entry(vcpu, 0x1);
7503 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7504 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7505 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7506 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7507 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7508 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7509 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7510 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7511 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7512 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7513 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7514 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7515 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7516 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7518 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7519 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7520 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7521 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7522 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7523 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7524 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7526 #undef cr4_fixed1_update
7529 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7531 struct vcpu_vmx *vmx = to_vmx(vcpu);
7532 struct kvm_cpuid_entry2 *best = NULL;
7535 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7536 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7539 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7540 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7541 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7542 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7545 /* Get the number of configurable Address Ranges for filtering */
7546 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7547 PT_CAP_num_address_ranges);
7549 /* Initialize and clear the no dependency bits */
7550 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7551 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7552 RTIT_CTL_BRANCH_EN);
7555 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7556 * will inject an #GP
7558 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7559 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7562 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7563 * PSBFreq can be set
7565 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7566 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7567 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7570 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7572 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7573 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7574 RTIT_CTL_MTC_RANGE);
7576 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7577 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7578 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7581 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7582 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7583 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7585 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7586 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7587 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7589 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7590 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7591 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7593 /* unmask address range configure area */
7594 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7595 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7598 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7600 struct vcpu_vmx *vmx = to_vmx(vcpu);
7602 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7603 vcpu->arch.xsaves_enabled = false;
7605 vmx_setup_uret_msrs(vmx);
7607 if (cpu_has_secondary_exec_ctrls())
7608 vmcs_set_secondary_exec_control(vmx,
7609 vmx_secondary_exec_control(vmx));
7611 if (nested_vmx_allowed(vcpu))
7612 vmx->msr_ia32_feature_control_valid_bits |=
7613 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7614 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7616 vmx->msr_ia32_feature_control_valid_bits &=
7617 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7618 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7620 if (nested_vmx_allowed(vcpu))
7621 nested_vmx_cr_fixed1_bits_update(vcpu);
7623 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7624 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7625 update_intel_pt_cfg(vcpu);
7627 if (boot_cpu_has(X86_FEATURE_RTM)) {
7628 struct vmx_uret_msr *msr;
7629 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7631 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7632 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7636 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7637 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7638 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7641 set_cr4_guest_host_mask(vmx);
7643 vmx_write_encls_bitmap(vcpu, NULL);
7644 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7645 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7647 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7649 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7650 vmx->msr_ia32_feature_control_valid_bits |=
7651 FEAT_CTL_SGX_LC_ENABLED;
7653 vmx->msr_ia32_feature_control_valid_bits &=
7654 ~FEAT_CTL_SGX_LC_ENABLED;
7656 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7657 vmx_update_exception_bitmap(vcpu);
7660 static __init void vmx_set_cpu_caps(void)
7666 kvm_cpu_cap_set(X86_FEATURE_VMX);
7669 if (kvm_mpx_supported())
7670 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7671 if (!cpu_has_vmx_invpcid())
7672 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7673 if (vmx_pt_mode_is_host_guest())
7674 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7675 if (vmx_pebs_supported()) {
7676 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7677 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7681 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7684 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7685 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7686 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7687 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7690 if (vmx_umip_emulated())
7691 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7694 kvm_caps.supported_xss = 0;
7695 if (!cpu_has_vmx_xsaves())
7696 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7698 /* CPUID 0x80000001 and 0x7 (RDPID) */
7699 if (!cpu_has_vmx_rdtscp()) {
7700 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7701 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7704 if (cpu_has_vmx_waitpkg())
7705 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7708 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7710 to_vmx(vcpu)->req_immediate_exit = true;
7713 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7714 struct x86_instruction_info *info)
7716 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7717 unsigned short port;
7721 if (info->intercept == x86_intercept_in ||
7722 info->intercept == x86_intercept_ins) {
7723 port = info->src_val;
7724 size = info->dst_bytes;
7726 port = info->dst_val;
7727 size = info->src_bytes;
7731 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7732 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7735 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7737 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7738 intercept = nested_cpu_has(vmcs12,
7739 CPU_BASED_UNCOND_IO_EXITING);
7741 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7743 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7744 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7747 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7748 struct x86_instruction_info *info,
7749 enum x86_intercept_stage stage,
7750 struct x86_exception *exception)
7752 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7754 switch (info->intercept) {
7756 * RDPID causes #UD if disabled through secondary execution controls.
7757 * Because it is marked as EmulateOnUD, we need to intercept it here.
7758 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7760 case x86_intercept_rdpid:
7761 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7762 exception->vector = UD_VECTOR;
7763 exception->error_code_valid = false;
7764 return X86EMUL_PROPAGATE_FAULT;
7768 case x86_intercept_in:
7769 case x86_intercept_ins:
7770 case x86_intercept_out:
7771 case x86_intercept_outs:
7772 return vmx_check_intercept_io(vcpu, info);
7774 case x86_intercept_lgdt:
7775 case x86_intercept_lidt:
7776 case x86_intercept_lldt:
7777 case x86_intercept_ltr:
7778 case x86_intercept_sgdt:
7779 case x86_intercept_sidt:
7780 case x86_intercept_sldt:
7781 case x86_intercept_str:
7782 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7783 return X86EMUL_CONTINUE;
7785 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7788 /* TODO: check more intercepts... */
7793 return X86EMUL_UNHANDLEABLE;
7796 #ifdef CONFIG_X86_64
7797 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7798 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7799 u64 divisor, u64 *result)
7801 u64 low = a << shift, high = a >> (64 - shift);
7803 /* To avoid the overflow on divq */
7804 if (high >= divisor)
7807 /* Low hold the result, high hold rem which is discarded */
7808 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7809 "rm" (divisor), "0" (low), "1" (high));
7815 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7818 struct vcpu_vmx *vmx;
7819 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7820 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7824 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7825 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7826 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7827 ktimer->timer_advance_ns);
7829 if (delta_tsc > lapic_timer_advance_cycles)
7830 delta_tsc -= lapic_timer_advance_cycles;
7834 /* Convert to host delta tsc if tsc scaling is enabled */
7835 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
7836 delta_tsc && u64_shl_div_u64(delta_tsc,
7837 kvm_caps.tsc_scaling_ratio_frac_bits,
7838 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7842 * If the delta tsc can't fit in the 32 bit after the multi shift,
7843 * we can't use the preemption timer.
7844 * It's possible that it fits on later vmentries, but checking
7845 * on every vmentry is costly so we just use an hrtimer.
7847 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7850 vmx->hv_deadline_tsc = tscl + delta_tsc;
7851 *expired = !delta_tsc;
7855 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7857 to_vmx(vcpu)->hv_deadline_tsc = -1;
7861 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7863 if (!kvm_pause_in_guest(vcpu->kvm))
7864 shrink_ple_window(vcpu);
7867 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7869 struct vcpu_vmx *vmx = to_vmx(vcpu);
7871 if (is_guest_mode(vcpu)) {
7872 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7877 * Note, cpu_dirty_logging_count can be changed concurrent with this
7878 * code, but in that case another update request will be made and so
7879 * the guest will never run with a stale PML value.
7881 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7882 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7884 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7887 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7889 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7890 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7891 FEAT_CTL_LMCE_ENABLED;
7893 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7894 ~FEAT_CTL_LMCE_ENABLED;
7897 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7899 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7900 if (to_vmx(vcpu)->nested.nested_run_pending)
7902 return !is_smm(vcpu);
7905 static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7907 struct vcpu_vmx *vmx = to_vmx(vcpu);
7910 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
7911 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
7912 * SMI and RSM only modify state that is saved and restored via SMRAM.
7913 * E.g. most MSRs are left untouched, but many are modified by VM-Exit
7914 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
7916 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7917 if (vmx->nested.smm.guest_mode)
7918 nested_vmx_vmexit(vcpu, -1, 0, 0);
7920 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7921 vmx->nested.vmxon = false;
7922 vmx_clear_hlt(vcpu);
7926 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7928 struct vcpu_vmx *vmx = to_vmx(vcpu);
7931 if (vmx->nested.smm.vmxon) {
7932 vmx->nested.vmxon = true;
7933 vmx->nested.smm.vmxon = false;
7936 if (vmx->nested.smm.guest_mode) {
7937 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7941 vmx->nested.nested_run_pending = 1;
7942 vmx->nested.smm.guest_mode = false;
7947 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7949 /* RSM will cause a vmexit anyway. */
7952 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7954 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7957 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7959 if (is_guest_mode(vcpu)) {
7960 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7962 if (hrtimer_try_to_cancel(timer) == 1)
7963 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7967 static void vmx_hardware_unsetup(void)
7969 kvm_set_posted_intr_wakeup_handler(NULL);
7972 nested_vmx_hardware_unsetup();
7977 static bool vmx_check_apicv_inhibit_reasons(enum kvm_apicv_inhibit reason)
7979 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7980 BIT(APICV_INHIBIT_REASON_ABSENT) |
7981 BIT(APICV_INHIBIT_REASON_HYPERV) |
7982 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |
7983 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |
7984 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
7986 return supported & BIT(reason);
7989 static void vmx_vm_destroy(struct kvm *kvm)
7991 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
7993 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
7996 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7997 .name = "kvm_intel",
7999 .hardware_unsetup = vmx_hardware_unsetup,
8001 .hardware_enable = vmx_hardware_enable,
8002 .hardware_disable = vmx_hardware_disable,
8003 .has_emulated_msr = vmx_has_emulated_msr,
8005 .vm_size = sizeof(struct kvm_vmx),
8006 .vm_init = vmx_vm_init,
8007 .vm_destroy = vmx_vm_destroy,
8009 .vcpu_precreate = vmx_vcpu_precreate,
8010 .vcpu_create = vmx_vcpu_create,
8011 .vcpu_free = vmx_vcpu_free,
8012 .vcpu_reset = vmx_vcpu_reset,
8014 .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
8015 .vcpu_load = vmx_vcpu_load,
8016 .vcpu_put = vmx_vcpu_put,
8018 .update_exception_bitmap = vmx_update_exception_bitmap,
8019 .get_msr_feature = vmx_get_msr_feature,
8020 .get_msr = vmx_get_msr,
8021 .set_msr = vmx_set_msr,
8022 .get_segment_base = vmx_get_segment_base,
8023 .get_segment = vmx_get_segment,
8024 .set_segment = vmx_set_segment,
8025 .get_cpl = vmx_get_cpl,
8026 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8027 .set_cr0 = vmx_set_cr0,
8028 .is_valid_cr4 = vmx_is_valid_cr4,
8029 .set_cr4 = vmx_set_cr4,
8030 .set_efer = vmx_set_efer,
8031 .get_idt = vmx_get_idt,
8032 .set_idt = vmx_set_idt,
8033 .get_gdt = vmx_get_gdt,
8034 .set_gdt = vmx_set_gdt,
8035 .set_dr7 = vmx_set_dr7,
8036 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8037 .cache_reg = vmx_cache_reg,
8038 .get_rflags = vmx_get_rflags,
8039 .set_rflags = vmx_set_rflags,
8040 .get_if_flag = vmx_get_if_flag,
8042 .flush_tlb_all = vmx_flush_tlb_all,
8043 .flush_tlb_current = vmx_flush_tlb_current,
8044 .flush_tlb_gva = vmx_flush_tlb_gva,
8045 .flush_tlb_guest = vmx_flush_tlb_guest,
8047 .vcpu_pre_run = vmx_vcpu_pre_run,
8048 .vcpu_run = vmx_vcpu_run,
8049 .handle_exit = vmx_handle_exit,
8050 .skip_emulated_instruction = vmx_skip_emulated_instruction,
8051 .update_emulated_instruction = vmx_update_emulated_instruction,
8052 .set_interrupt_shadow = vmx_set_interrupt_shadow,
8053 .get_interrupt_shadow = vmx_get_interrupt_shadow,
8054 .patch_hypercall = vmx_patch_hypercall,
8055 .inject_irq = vmx_inject_irq,
8056 .inject_nmi = vmx_inject_nmi,
8057 .queue_exception = vmx_queue_exception,
8058 .cancel_injection = vmx_cancel_injection,
8059 .interrupt_allowed = vmx_interrupt_allowed,
8060 .nmi_allowed = vmx_nmi_allowed,
8061 .get_nmi_mask = vmx_get_nmi_mask,
8062 .set_nmi_mask = vmx_set_nmi_mask,
8063 .enable_nmi_window = vmx_enable_nmi_window,
8064 .enable_irq_window = vmx_enable_irq_window,
8065 .update_cr8_intercept = vmx_update_cr8_intercept,
8066 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
8067 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
8068 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
8069 .load_eoi_exitmap = vmx_load_eoi_exitmap,
8070 .apicv_post_state_restore = vmx_apicv_post_state_restore,
8071 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
8072 .hwapic_irr_update = vmx_hwapic_irr_update,
8073 .hwapic_isr_update = vmx_hwapic_isr_update,
8074 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
8075 .sync_pir_to_irr = vmx_sync_pir_to_irr,
8076 .deliver_interrupt = vmx_deliver_interrupt,
8077 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
8079 .set_tss_addr = vmx_set_tss_addr,
8080 .set_identity_map_addr = vmx_set_identity_map_addr,
8081 .get_mt_mask = vmx_get_mt_mask,
8083 .get_exit_info = vmx_get_exit_info,
8085 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
8087 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8089 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
8090 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
8091 .write_tsc_offset = vmx_write_tsc_offset,
8092 .write_tsc_multiplier = vmx_write_tsc_multiplier,
8094 .load_mmu_pgd = vmx_load_mmu_pgd,
8096 .check_intercept = vmx_check_intercept,
8097 .handle_exit_irqoff = vmx_handle_exit_irqoff,
8099 .request_immediate_exit = vmx_request_immediate_exit,
8101 .sched_in = vmx_sched_in,
8103 .cpu_dirty_log_size = PML_ENTITY_NUM,
8104 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
8106 .nested_ops = &vmx_nested_ops,
8108 .pi_update_irte = vmx_pi_update_irte,
8109 .pi_start_assignment = vmx_pi_start_assignment,
8111 #ifdef CONFIG_X86_64
8112 .set_hv_timer = vmx_set_hv_timer,
8113 .cancel_hv_timer = vmx_cancel_hv_timer,
8116 .setup_mce = vmx_setup_mce,
8118 .smi_allowed = vmx_smi_allowed,
8119 .enter_smm = vmx_enter_smm,
8120 .leave_smm = vmx_leave_smm,
8121 .enable_smi_window = vmx_enable_smi_window,
8123 .can_emulate_instruction = vmx_can_emulate_instruction,
8124 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8125 .migrate_timers = vmx_migrate_timers,
8127 .msr_filter_changed = vmx_msr_filter_changed,
8128 .complete_emulated_msr = kvm_complete_insn_gp,
8130 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
8133 static unsigned int vmx_handle_intel_pt_intr(void)
8135 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8137 /* '0' on failure so that the !PT case can use a RET0 static call. */
8138 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8141 kvm_make_request(KVM_REQ_PMI, vcpu);
8142 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8143 (unsigned long *)&vcpu->arch.pmu.global_status);
8147 static __init void vmx_setup_user_return_msrs(void)
8151 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8152 * will emulate SYSCALL in legacy mode if the vendor string in guest
8153 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8154 * support this emulation, MSR_STAR is included in the list for i386,
8155 * but is never loaded into hardware. MSR_CSTAR is also never loaded
8156 * into hardware and is here purely for emulation purposes.
8158 const u32 vmx_uret_msrs_list[] = {
8159 #ifdef CONFIG_X86_64
8160 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8162 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8167 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8169 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8170 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8173 static void __init vmx_setup_me_spte_mask(void)
8178 * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
8179 * the former to avoid exposing shadow_phys_bits.
8181 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8182 * shadow_phys_bits. On MKTME and/or TDX capable systems,
8183 * boot_cpu_data.x86_phys_bits holds the actual physical address
8184 * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
8185 * reported by CPUID. Those bits between are KeyID bits.
8187 if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
8188 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8189 kvm_get_shadow_phys_bits() - 1);
8191 * Unlike SME, host kernel doesn't support setting up any
8192 * MKTME KeyID on Intel platforms. No memory encryption
8193 * bits should be included into the SPTE.
8195 kvm_mmu_set_me_spte_mask(0, me_mask);
8198 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8200 static __init int hardware_setup(void)
8202 unsigned long host_bndcfgs;
8207 host_idt_base = dt.address;
8209 vmx_setup_user_return_msrs();
8211 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8214 if (cpu_has_perf_global_ctrl_bug())
8215 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8216 "does not work properly. Using workaround\n");
8218 if (boot_cpu_has(X86_FEATURE_NX))
8219 kvm_enable_efer_bits(EFER_NX);
8221 if (boot_cpu_has(X86_FEATURE_MPX)) {
8222 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8223 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8226 if (!cpu_has_vmx_mpx())
8227 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8228 XFEATURE_MASK_BNDCSR);
8230 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8231 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8234 if (!cpu_has_vmx_ept() ||
8235 !cpu_has_vmx_ept_4levels() ||
8236 !cpu_has_vmx_ept_mt_wb() ||
8237 !cpu_has_vmx_invept_global())
8240 /* NX support is required for shadow paging. */
8241 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8242 pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
8246 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8247 enable_ept_ad_bits = 0;
8249 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8250 enable_unrestricted_guest = 0;
8252 if (!cpu_has_vmx_flexpriority())
8253 flexpriority_enabled = 0;
8255 if (!cpu_has_virtual_nmis())
8259 * set_apic_access_page_addr() is used to reload apic access
8260 * page upon invalidation. No need to do anything if not
8261 * using the APIC_ACCESS_ADDR VMCS field.
8263 if (!flexpriority_enabled)
8264 vmx_x86_ops.set_apic_access_page_addr = NULL;
8266 if (!cpu_has_vmx_tpr_shadow())
8267 vmx_x86_ops.update_cr8_intercept = NULL;
8269 #if IS_ENABLED(CONFIG_HYPERV)
8270 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8272 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8273 vmx_x86_ops.tlb_remote_flush_with_range =
8274 hv_remote_flush_tlb_with_range;
8278 if (!cpu_has_vmx_ple()) {
8281 ple_window_grow = 0;
8283 ple_window_shrink = 0;
8286 if (!cpu_has_vmx_apicv())
8289 vmx_x86_ops.sync_pir_to_irr = NULL;
8291 if (!enable_apicv || !cpu_has_vmx_ipiv())
8292 enable_ipiv = false;
8294 if (cpu_has_vmx_tsc_scaling())
8295 kvm_caps.has_tsc_control = true;
8297 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8298 kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8299 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8300 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8302 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8305 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8306 cpu_has_vmx_ept_execute_only());
8309 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8310 * bits to shadow_zero_check.
8312 vmx_setup_me_spte_mask();
8314 kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
8315 ept_caps_to_lpage_level(vmx_capability.ept));
8318 * Only enable PML when hardware supports PML feature, and both EPT
8319 * and EPT A/D bit features are enabled -- PML depends on them to work.
8321 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8325 vmx_x86_ops.cpu_dirty_log_size = 0;
8327 if (!cpu_has_vmx_preemption_timer())
8328 enable_preemption_timer = false;
8330 if (enable_preemption_timer) {
8331 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8333 cpu_preemption_timer_multi =
8334 vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8337 use_timer_freq = (u64)tsc_khz * 1000;
8338 use_timer_freq >>= cpu_preemption_timer_multi;
8341 * KVM "disables" the preemption timer by setting it to its max
8342 * value. Don't use the timer if it might cause spurious exits
8343 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8345 if (use_timer_freq > 0xffffffffu / 10)
8346 enable_preemption_timer = false;
8349 if (!enable_preemption_timer) {
8350 vmx_x86_ops.set_hv_timer = NULL;
8351 vmx_x86_ops.cancel_hv_timer = NULL;
8352 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8355 kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8356 kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8358 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8360 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8361 pt_mode = PT_MODE_SYSTEM;
8362 if (pt_mode == PT_MODE_HOST_GUEST)
8363 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8365 vmx_init_ops.handle_intel_pt_intr = NULL;
8367 setup_default_sgx_lepubkeyhash();
8370 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8372 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8379 r = alloc_kvm_area();
8381 nested_vmx_hardware_unsetup();
8383 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8388 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8389 .cpu_has_kvm_support = cpu_has_kvm_support,
8390 .disabled_by_bios = vmx_disabled_by_bios,
8391 .check_processor_compatibility = vmx_check_processor_compat,
8392 .hardware_setup = hardware_setup,
8393 .handle_intel_pt_intr = NULL,
8395 .runtime_ops = &vmx_x86_ops,
8396 .pmu_ops = &intel_pmu_ops,
8399 static void vmx_cleanup_l1d_flush(void)
8401 if (vmx_l1d_flush_pages) {
8402 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8403 vmx_l1d_flush_pages = NULL;
8405 /* Restore state so sysfs ignores VMX */
8406 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8409 static void vmx_exit(void)
8411 #ifdef CONFIG_KEXEC_CORE
8412 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8418 #if IS_ENABLED(CONFIG_HYPERV)
8419 if (static_branch_unlikely(&enable_evmcs)) {
8421 struct hv_vp_assist_page *vp_ap;
8423 * Reset everything to support using non-enlightened VMCS
8424 * access later (e.g. when we reload the module with
8425 * enlightened_vmcs=0)
8427 for_each_online_cpu(cpu) {
8428 vp_ap = hv_get_vp_assist_page(cpu);
8433 vp_ap->nested_control.features.directhypercall = 0;
8434 vp_ap->current_nested_vmcs = 0;
8435 vp_ap->enlighten_vmentry = 0;
8438 static_branch_disable(&enable_evmcs);
8441 vmx_cleanup_l1d_flush();
8443 allow_smaller_maxphyaddr = false;
8445 module_exit(vmx_exit);
8447 static int __init vmx_init(void)
8451 #if IS_ENABLED(CONFIG_HYPERV)
8453 * Enlightened VMCS usage should be recommended and the host needs
8454 * to support eVMCS v1 or above. We can also disable eVMCS support
8455 * with module parameter.
8457 if (enlightened_vmcs &&
8458 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8459 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8460 KVM_EVMCS_VERSION) {
8462 /* Check that we have assist pages on all online CPUs */
8463 for_each_online_cpu(cpu) {
8464 if (!hv_get_vp_assist_page(cpu)) {
8465 enlightened_vmcs = false;
8470 if (enlightened_vmcs) {
8471 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8472 static_branch_enable(&enable_evmcs);
8475 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8476 vmx_x86_ops.enable_direct_tlbflush
8477 = hv_enable_direct_tlbflush;
8480 enlightened_vmcs = false;
8484 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8485 __alignof__(struct vcpu_vmx), THIS_MODULE);
8490 * Must be called after kvm_init() so enable_ept is properly set
8491 * up. Hand the parameter mitigation value in which was stored in
8492 * the pre module init parser. If no parameter was given, it will
8493 * contain 'auto' which will be turned into the default 'cond'
8496 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8502 vmx_setup_fb_clear_ctrl();
8504 for_each_possible_cpu(cpu) {
8505 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8510 #ifdef CONFIG_KEXEC_CORE
8511 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8512 crash_vmclear_local_loaded_vmcss);
8514 vmx_check_vmcs12_offsets();
8517 * Shadow paging doesn't have a (further) performance penalty
8518 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8522 allow_smaller_maxphyaddr = true;
8526 module_init(vmx_init);